Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-8416 Prevent stale editor saves from undoing agent writes (#4142)

tim-inkeepca21ef991c74
diff --git a/.changeset/stale-external-write-rollback.md b/.changeset/stale-external-write-rollback.md
new file mode 100644
index 000000000..a8ea3fc3e
--- /dev/null
+++ b/.changeset/stale-external-write-rollback.md
@@ -0,0 +1,15 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fixes a bug where an agent write that Open Knowledge had already confirmed and saved could be silently undone by another program a moment later.
+
+An editor or script holding the older version of a file in its buffer, and saving it after the agent write landed, put the exact bytes that preceded the write back on disk. Open Knowledge saw a file whose content did not match what it last wrote, found the open document unchanged since that save, and concluded the file had been edited outside the app. It applied those bytes as an ordinary external edit, so the acknowledged write disappeared from the open document with nothing to indicate anything had gone wrong.
+
+The server now remembers, for a bounded window, which versions an acknowledged agent save displaced. It stores a local durability snapshot for only those recently displaced documents, including the acknowledged and rejected content needed to recover safely after an app restart. When a file on disk turns out to be one of those displaced versions while a newer save is the current one, the file is no longer applied. The document keeps the acknowledged content and is frozen with a `stale-external-write` conflict reason, so later agent writes fail explicitly instead of building on an unnoticed rollback. The existing conflict view and conflict tools expose both versions and can resolve the document by keeping either one or combining them. Until you choose, the file on disk is left exactly as the other program wrote it: Open Knowledge does not write over it, so there is no save fight between the two.
+
+External edits that do not exactly restore a version Open Knowledge itself displaced still reconcile the way they always have. An intentional exact restore of a recently displaced version is indistinguishable from a stale editor save, so it is surfaced for confirmation instead of being applied silently. The record of displaced versions is per branch and is dropped when a document is deleted. Its protection window expires after 30 minutes; expired text is removed from the recovery file only on a later state-persistence event, not by a timer or restart. Unresolved stale-write conflicts remain until they are resolved.
+
+Conflict resolutions can explicitly write an empty string to keep an empty file; only the separate `delete` strategy removes the file. The diff view preserves the selected bytes even when the current Git version in the editor differs from its committed stage.
+
+Recovery snapshots contain document text and are written with owner-only permissions. If a snapshot is corrupt, unreadable, or from an incompatible version, the server preserves it and stops opening the project with an actionable recovery message rather than discarding potentially unique edits. A write that discovers a stale file during its final flush returns a distinct 409: its collaborative edit and recovery snapshot are retained, but its disk write is skipped. Further external saves cannot discard that pending edit; explicit resolution is required. Resolve and re-read before retrying.
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index 3a7bf35ae..aa5e536cc 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -139,6 +139,8 @@ Click the badged tab or any row in the Conflicts section to focus the conflict.
You can't edit a page with conflicts until they're resolved; the same applies to agents writing over MCP.
+Conflicts can also happen with GitHub sync off: another app may save an older copy over an edit OpenKnowledge already saved. The diff view explains this stale-save conflict. **Current** is the protected OpenKnowledge version; **Incoming** is the older external save. Choose which to keep, then apply the resolution. Restoring an exact older version intentionally can trigger the same confirmation. Both versions remain recoverable after restarting the app.
+
## Work on multiple branches
In the desktop app you can open several branches of the same project at once, each in its own window. Click your project name in the bottom left and pick a branch or worktree from the project switcher (open worktrees also appear in the Command Palette); **New worktree** starts a fresh branch or checks out an existing one. Opening a branch that has no worktree yet creates one on demand under `.ok/worktrees/`, kept out of `git status`, so each window runs its own editor and server without touching your main working copy.
@@ -167,4 +169,3 @@ A few situations stop sync from completing successfully. In each case the sync s
### Temporary problems
- **Network or service hiccups.** Flaky Wi-Fi, a VPN drop, or a brief GitHub outage. OpenKnowledge retries automatically, slowing down progressively as described in [How often sync runs](#how-often-sync-runs). No action needed; a manual trigger from the sync indicator resets the backoff immediately if you want sync to run sooner.
-
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 7fe907347..30ee92ea1 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -35,8 +35,8 @@ To point an MCP client at this server, locally or over a tunnel from another mac
| `import` | Acquire a skill from a full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), `owner/repo[/subpath]`, a git URL, or a local / `file://` path into the vendor-neutral `.agents/skills/<name>/` hub as versioned content — live immediately, with cross-harness projection via `install`. Pass the required `add` array with at least one install location (an editor id, `agents`, or a custom root path). Use `skill` to choose one skill from a multi-skill source or a `skills({ query })` result. Records provenance in `.ok/skills-lock.json`; a name collision lands under `<name>-imported`; scripts are imported as content and never executed |
| `checkpoint` | Save a project-wide version snapshot — a single restore point. Returns its `version` |
| `restore_version` | Restore one `document` or `skill` to a historical `version` (the SHA from `history` or `checkpoint`) |
-| `conflicts` | Read GitHub-sync merge conflicts. `kind: "list"` enumerates tracked conflicts; `kind: "content"` returns one file's base / ours / theirs stages |
-| `resolve_conflict` | Write a chosen resolution (`mine` / `theirs` / `content` / `delete`) and commit |
+| `conflicts` | Read tracked conflicts (`conflictKind: "git"` or `"stale-external-write"`). `kind: "list"` enumerates them, including `variant: "working-tree"` for Git working-tree overlays; `kind: "content"` returns one file's base / ours / theirs versions |
+| `resolve_conflict` | Apply a chosen resolution (`mine` / `theirs` / `content` / `delete`). Git-index resolution stages files and commits after the final tracked conflict clears; local stale-save and working-tree overlay resolutions create no resolution commit |
## Output shape mirrors the input
@@ -64,16 +64,20 @@ Cap is 80 characters. Avoid secrets and PII; summaries persist to git history.
## Conflict-aware writes
-Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses to mutate a doc whose GitHub-sync state is `conflict`.
+Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses to mutate a doc whose lifecycle status is `conflict`, returning `urn:ok:error:doc-in-conflict` (409). This includes local stale-external-write conflicts with GitHub sync disabled.
-To recover, call `conflicts({ kind: "content", file })` to inspect the merge stages, then `resolve_conflict` with one of:
+To recover, call `conflicts({ kind: "list" })` to identify the `conflictKind` and any `variant: "working-tree"`, then `conflicts({ kind: "content", file })` to inspect both versions. The content response's `conflictKind: "git"` covers both Git-index conflicts and working-tree overlays; inspect the list entry to distinguish them. Call `resolve_conflict` with one of:
-- `mine`: resolve to your committed version (stage 2 — runs `git checkout --ours <file>` then `git add`).
-- `theirs`: resolve to their committed version (stage 3 — runs `git checkout --theirs <file>` then `git add`).
-- `content`: write the exact bytes you supply (for example, a merged result you composed by reading both stages).
-- `delete`: `git rm` the file (for delete-vs-modify shapes where one stage is missing).
+- `mine`: for Git-index conflicts, restore your committed version (stage 2); for working-tree overlays, keep the working-tree file; for stale external writes, keep the protected collaborative version, recovered from the local snapshot when needed.
+- `theirs`: for Git-index conflicts, restore their committed version (stage 3); for working-tree overlays, restore the pinned incoming blob; for stale external writes, accept the recorded older file version, including an intentional revert.
+- `content`: write the exact bytes you supply (for example, a merged result you composed by reading both stages). An explicit empty string keeps an empty file; omitting `content` is invalid. Use `delete` only to remove the file.
+- `delete`: remove the document (`git rm` for Git-index conflicts).
-To detect conflict state proactively without waiting for a 409, call `conflicts({ kind: "list" })`; each entry is `{ file, detectedAt, … }`. `conflicts({ kind: "content" })` adds the doc's `lifecycleStatus` alongside the merge stages.
+Git-index resolution stages the file and creates a merge commit after the final tracked conflict clears. Local stale-save and working-tree overlay resolutions create no resolution commit. A failed resolution remains tracked for retry; the disk, collaborative state, and index update are not one atomic transaction.
+
+A write that detects a stale file during its final disk flush returns the distinct `urn:ok:error:stale-external-write` (409): the edit reached collaborative state and the recovery snapshot, but the disk write was skipped. Resolve and re-read before retrying to avoid duplicating an already-applied append.
+
+To detect conflict state proactively without waiting for a 409, call `conflicts({ kind: "list" })`; each entry is `{ file, detectedAt, conflictKind, … }`. `conflicts({ kind: "content" })` adds the doc's `lifecycleStatus` alongside its versions.
## Preview links
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index b89c41204..4bb431000 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -113,6 +113,7 @@ The app runs a collaboration server for the open project. It writes runtime stat
| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server) | In-project, gitignored |
| `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored |
| `.ok/local/sync-state.json`, `.ok/local/conflicts.json` | GitHub-sync engine state | In-project, gitignored |
+| `.ok/local/stale-external-writes.json` | Private recovery snapshot containing full acknowledged, rejected, and retained document text for recently displaced writes. Protection expires after 30 minutes, but expired text is removed from disk only on a later state-persistence event, not by a timer or restart; unresolved conflicts remain until resolved | In-project, gitignored |
| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
| `.ok/local/last-server-exit.json` | Why the collaboration server the app started last exited — a timestamp, its process id, the exit code, the signal that ended it, and which part of the app was watching. One record, overwritten on each exit; a server the app only attached to, or one you started yourself with `ok start`, leaves none. No document content or paths | In-project, gitignored |
| `.ok/local/last-server-crash.json` | The collaboration server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Written by the server itself, so it covers `ok start` too. Holds the most recent crash only | In-project, gitignored |
@@ -234,6 +235,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a
| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server) | In-project, gitignored |
| `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored |
| `.ok/local/sync-state.json`, `.ok/local/conflicts.json` | GitHub-sync engine state | In-project, gitignored |
+| `.ok/local/stale-external-writes.json` | Private recovery snapshot containing full acknowledged, rejected, and retained document text for recently displaced writes. Protection expires after 30 minutes, but expired text is removed from disk only on a later state-persistence event, not by a timer or restart; unresolved conflicts remain until resolved | In-project, gitignored |
| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
| `.ok/local/last-server-crash.json` | The server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Holds the most recent crash only | In-project, gitignored |
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
diff --git a/packages/app/src/components/ConflictView.dom.test.tsx b/packages/app/src/components/ConflictView.dom.test.tsx
index 5cd0752b4..adfdee746 100644
--- a/packages/app/src/components/ConflictView.dom.test.tsx
+++ b/packages/app/src/components/ConflictView.dom.test.tsx
@@ -360,6 +360,133 @@ describe('ConflictView absent-stage banners — one fixture per kind', () => {
cleanup();
});
+ test('a restored base version remains an explicit incoming choice', async () => {
+ const onResolve = vi.fn();
+ render(
+ <ConflictView
+ fileName="notes/sync-engine.md"
+ conflictKind="stale-external-write"
+ ours={OUR_CONTENT}
+ base={THEIR_CONTENT}
+ theirs={THEIR_CONTENT}
+ onResolve={onResolve}
+ />,
+ );
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+
+ expect(screen.queryByRole('button', { name: 'Apply changes' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Show original' })).toBeNull();
+ expect(screen.getByRole('button', { name: /^Accept current/ })).toBeTruthy();
+ await act(async () => {
+ screen.getByRole('button', { name: /^Accept incoming/ }).click();
+ });
+ await act(async () => {
+ screen.getByRole('button', { name: 'Apply changes' }).click();
+ });
+ expect(onResolve).toHaveBeenCalledWith(THEIR_CONTENT, 'incoming');
+ });
+
+ test('Git still merges non-conflicting changes against its common base', async () => {
+ const onResolve = vi.fn();
+ render(
+ <ConflictView
+ fileName="notes/sync-engine.md"
+ conflictKind="git"
+ ours={OUR_CONTENT}
+ base={THEIR_CONTENT}
+ theirs={THEIR_CONTENT}
+ onResolve={onResolve}
+ />,
+ );
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+
+ expect(screen.queryByRole('button', { name: /^Accept current/ })).toBeNull();
+ expect(screen.getByRole('button', { name: 'Show original' })).toBeTruthy();
+ await act(async () => {
+ screen.getByRole('button', { name: 'Apply changes' }).click();
+ });
+ expect(onResolve).toHaveBeenCalledWith(OUR_CONTENT);
+ });
+
+ test.each([
+ { ours: '', theirs: '' },
+ { ours: 'Same content.\n', theirs: 'Same content.\n' },
+ { ours: OUR_CONTENT, theirs: THEIR_CONTENT },
+ ])('stale choice intent follows undo, replacement, and redo: %j', async ({ ours, theirs }) => {
+ const onResolve = vi.fn();
+ render(
+ <ConflictView
+ fileName="notes/sync-engine.md"
+ conflictKind="stale-external-write"
+ ours={ours}
+ base={theirs}
+ theirs={theirs}
+ onResolve={onResolve}
+ />,
+ );
+ const incoming = await screen.findByRole('button', { name: /^Accept incoming/ });
+ await act(async () => {
+ incoming.click();
+ });
+ await act(async () => {
+ screen.getByRole('button', { name: 'Undo' }).click();
+ });
+ expect(screen.queryByRole('button', { name: 'Apply changes' })).toBeNull();
+ expect(screen.getByText('Conflicts remaining: 1.')).toBeTruthy();
+ await act(async () => {
+ screen.getByRole('button', { name: /^Accept current/ }).click();
+ });
+ await act(async () => {
+ screen.getByRole('button', { name: 'Undo' }).click();
+ });
+ await act(async () => {
+ screen.getByRole('button', { name: 'Redo' }).click();
+ });
+ await act(async () => {
+ screen.getByRole('button', { name: 'Apply changes' }).click();
+ });
+ expect(onResolve).toHaveBeenCalledWith(ours, 'current');
+ });
+
+ test.each([
+ { ours: OUR_CONTENT, base: BASE_CONTENT, theirs: THEIR_CONTENT },
+ { ours: '', base: BASE_CONTENT, theirs: THEIR_CONTENT },
+ { ours: OUR_CONTENT, base: BASE_CONTENT, theirs: '' },
+ { ours: OUR_CONTENT, base: '', theirs: THEIR_CONTENT },
+ ])(
+ 'stale saves explain the versions without Git deletion or ancestor claims: %j',
+ async (sides) => {
+ render(
+ <ConflictView
+ fileName="notes/sync-engine.md"
+ conflictKind="stale-external-write"
+ {...sides}
+ onResolve={vi.fn()}
+ />,
+ );
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+
+ const alert = screen.getByRole('status');
+ expect(alert.textContent).toContain('The file was restored to an older version.');
+ expect(alert.textContent).toContain('Current is the version OpenKnowledge protected.');
+ expect(alert.textContent).toContain('Incoming is the restored version.');
+ expect(alert.textContent).toContain('Choose which version to keep, then apply your changes.');
+ expect(screen.queryByText(/This file was deleted/)).toBeNull();
+ expect(screen.queryByText(/No common ancestor/)).toBeNull();
+ },
+ );
+
+ test('Git conflicts do not show stale-save guidance', async () => {
+ await renderConflictView();
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
test('delete-modify (empty ours) shows the deleted-on-current-branch banner', async () => {
render(
<ConflictView
@@ -417,24 +544,28 @@ describe('ConflictView axe accessibility scan', () => {
cleanup();
});
- test('conflict surface has no detectable WCAG violations', async () => {
- render(
- <ConflictView
- fileName="notes/sync-engine.md"
- ours={OUR_CONTENT}
- base={BASE_CONTENT}
- theirs={THEIR_CONTENT}
- onResolve={vi.fn()}
- />,
- );
- await act(async () => {
- await new Promise<void>((resolve) => setTimeout(resolve, 0));
- });
- const results = await axe.run(document.body, {
- runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'] },
- });
- expect(results.violations).toEqual([]);
- });
+ test.each(['git', 'stale-external-write'] as const)(
+ 'conflict surface has no detectable WCAG violations: %s',
+ async (conflictKind) => {
+ render(
+ <ConflictView
+ fileName="notes/sync-engine.md"
+ conflictKind={conflictKind}
+ ours={OUR_CONTENT}
+ base={BASE_CONTENT}
+ theirs={THEIR_CONTENT}
+ onResolve={vi.fn()}
+ />,
+ );
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+ const results = await axe.run(document.body, {
+ runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'] },
+ });
+ expect(results.violations).toEqual([]);
+ },
+ );
});
describe('ConflictView — controls after undo', () => {
diff --git a/packages/app/src/components/ConflictView.tsx b/packages/app/src/components/ConflictView.tsx
index 1d2b01eb1..d2b78a7f5 100644
--- a/packages/app/src/components/ConflictView.tsx
+++ b/packages/app/src/components/ConflictView.tsx
@@ -1,4 +1,5 @@
import {
+ type SyncConflictContentSuccess,
type SynthesisedConflictRegion,
synthesiseConflictMarkersWithRegions,
} from '@inkeep/open-knowledge-core';
@@ -12,6 +13,7 @@ import type {
import { UnresolvedFile } from '@pierre/diffs';
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
+import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { useConflictFooterHeightVar } from '@/hooks/use-conflict-footer-height';
import { okPierreTheme } from '@/lib/pierre-theme';
@@ -20,10 +22,11 @@ import { ConflictHistory } from './conflict-history';
interface ConflictViewProps {
fileName: string;
+ conflictKind?: SyncConflictContentSuccess['conflictKind'];
ours: string;
base: string;
theirs: string;
- onResolve: (content: string) => void | Promise<void>;
+ onResolve: (content: string, selection?: MergeConflictResolution) => void | Promise<void>;
}
interface ConflictControl {
@@ -85,7 +88,14 @@ function isSnapshotAllResolved(snapshot: ConflictSnapshot): boolean {
return fileDiff.additionLines.join('') === fileDiff.deletionLines.join('');
}
-export function ConflictView({ fileName, ours, base, theirs, onResolve }: ConflictViewProps) {
+export function ConflictView({
+ fileName,
+ conflictKind = 'git',
+ ours,
+ base,
+ theirs,
+ onResolve,
+}: ConflictViewProps) {
const { t } = useLingui();
const containerRef = useRef<HTMLElement>(null);
const onResolveRef = useRef(onResolve);
@@ -95,6 +105,9 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
>(null);
const handleUndoRef = useRef<(() => void) | null>(null);
const handleRedoRef = useRef<(() => void) | null>(null);
+ const handleIdenticalChoiceRef = useRef<((selection: MergeConflictResolution) => void) | null>(
+ null,
+ );
const handleApplyRef = useRef<(() => void | Promise<void>) | null>(null);
const [controls, setControls] = useState<ConflictControl[]>([]);
const [canUndo, setCanUndo] = useState(false);
@@ -107,6 +120,7 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
const applyingRef = useRef(false);
const [isApplying, setIsApplying] = useState(false);
const [showBase, setShowBase] = useState(false);
+ const identicalStaleVersions = conflictKind === 'stale-external-write' && ours === theirs;
useEffect(() => {
onResolveRef.current = onResolve;
@@ -125,7 +139,7 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
const { text: markerText, regions: writtenRegions } = synthesiseConflictMarkersWithRegions(
ours,
- base || null,
+ conflictKind === 'stale-external-write' ? null : base || null,
theirs,
{
includeBaseSection: showBase,
@@ -140,11 +154,17 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
let verifyParse = true;
let parseMismatched = false;
- function syncState(resolved: boolean) {
+ function syncState(snapshot: ConflictSnapshot) {
+ const resolved =
+ isSnapshotAllResolved(snapshot) &&
+ (conflictKind !== 'stale-external-write' || snapshot.selection !== undefined);
setCanUndo(history.canUndo);
setCanRedo(history.canRedo);
setAllResolved(resolved);
- const remaining = remainingConflictCount(history.current.file.contents);
+ const remaining =
+ conflictKind === 'stale-external-write' && !resolved
+ ? 1
+ : remainingConflictCount(history.current.file.contents);
setLiveRemaining(resolved ? 'all-resolved' : remaining);
}
@@ -189,7 +209,13 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
if (!container) return;
verifyParse = false;
const scrollTop = container.scrollTop;
- inst.render({ ...snapshot, forceRender: true });
+ inst.render({
+ file: snapshot.file,
+ fileDiff: snapshot.fileDiff,
+ actions: snapshot.actions,
+ markerRows: snapshot.markerRows,
+ forceRender: true,
+ });
container.scrollTop = scrollTop;
container.focus();
}
@@ -221,11 +247,11 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
return;
}
- const snapshot: ConflictSnapshot = resolved;
+ const snapshot: ConflictSnapshot = { ...resolved, selection: resolution };
history.push(snapshot);
const done = isSnapshotAllResolved(snapshot);
- syncState(done);
+ syncState(snapshot);
if (done) setControls([]);
rerenderAndRestore(snapshot);
@@ -234,7 +260,7 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
handleUndoRef.current = () => {
const snapshot = history.undo();
if (!snapshot) return;
- syncState(isSnapshotAllResolved(snapshot));
+ syncState(snapshot);
rerenderAndRestore(snapshot);
};
@@ -242,13 +268,35 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
const snapshot = history.redo();
if (!snapshot) return;
const done = isSnapshotAllResolved(snapshot);
- syncState(done);
+ syncState(snapshot);
if (done) setControls([]);
rerenderAndRestore(snapshot);
};
- handleApplyRef.current = () =>
- onResolveRef.current(matchTrailingNewline(history.current.file.contents, ours, theirs));
+ handleIdenticalChoiceRef.current = (selection) => {
+ if (parseMismatched) {
+ console.warn(
+ JSON.stringify({
+ event: 'conflict-action-refused-parse-mismatch',
+ 'doc.name': fileName,
+ resolution: selection,
+ }),
+ );
+ setLiveRemaining('unavailable');
+ return;
+ }
+ const snapshot: ConflictSnapshot = { ...history.current, selection };
+ history.push(snapshot);
+ syncState(snapshot);
+ rerenderAndRestore(snapshot);
+ };
+
+ handleApplyRef.current = () => {
+ const content = matchTrailingNewline(history.current.file.contents, ours, theirs);
+ return conflictKind === 'stale-external-write'
+ ? onResolveRef.current(content, history.current.selection)
+ : onResolveRef.current(content);
+ };
inst.render({
file: { name: fileName, contents: markerText },
@@ -272,7 +320,7 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
markerRows: initCache.markerRows,
};
history.reset(initial);
- setAllResolved(isSnapshotAllResolved(initial));
+ setAllResolved(conflictKind !== 'stale-external-write' && isSnapshotAllResolved(initial));
}
return () => {
@@ -280,6 +328,7 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
handleActionRef.current = null;
handleUndoRef.current = null;
handleRedoRef.current = null;
+ handleIdenticalChoiceRef.current = null;
handleApplyRef.current = null;
setControls([]);
setCanUndo(false);
@@ -287,18 +336,33 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
setAllResolved(false);
setParseMismatch(false);
};
- }, [fileName, ours, base, theirs, showBase]);
+ }, [fileName, ours, base, theirs, showBase, conflictKind]);
- const absentStageBanner = !ours
- ? t`This file was deleted on the current branch (delete-modify conflict).`
- : !theirs
- ? t`This file was deleted on the incoming branch (modify-delete conflict).`
- : !base
- ? t`No common ancestor — both branches added this file (add/add conflict).`
- : null;
+ const absentStageBanner =
+ conflictKind === 'stale-external-write'
+ ? null
+ : !ours
+ ? t`This file was deleted on the current branch (delete-modify conflict).`
+ : !theirs
+ ? t`This file was deleted on the incoming branch (modify-delete conflict).`
+ : !base
+ ? t`No common ancestor — both branches added this file (add/add conflict).`
+ : null;
return (
<div className="flex h-full flex-col">
+ {conflictKind === 'stale-external-write' && (
+ <div className="shrink-0 px-3 py-2">
+ <Alert role="status">
+ <AlertDescription>
+ {t`The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes.`}
+ {identicalStaleVersions
+ ? ` ${t`Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off.`}`
+ : null}
+ </AlertDescription>
+ </Alert>
+ </div>
+ )}
{}
{absentStageBanner && (
<p role="status" className="shrink-0 border-b px-3 py-2 text-xs text-muted-foreground">
@@ -339,7 +403,7 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
>
{t`Redo`}
</Button>
- {base ? (
+ {base && conflictKind !== 'stale-external-write' ? (
<Button
type="button"
size="xs"
@@ -354,6 +418,13 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
</Button>
) : null}
</div>
+ {identicalStaleVersions && !parseMismatch && !allResolved && (
+ <div className="shrink-0 px-3 py-2">
+ <ConflictActions
+ onSelect={(selection) => handleIdenticalChoiceRef.current?.(selection)}
+ />
+ </div>
+ )}
<section
ref={containerRef}
// biome-ignore lint/a11y/noNoninteractiveTabindex: keyboard-focusable scroll container — Chromium doesn't make overflow:auto elements focusable without tabIndex, and axe's scrollable-region-focusable requires the stop. Same pattern as SyncStatusBadge's scroll container.
@@ -389,35 +460,10 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
{!parseMismatch &&
controls.map((control) =>
createPortal(
- <div className="flex items-center gap-1">
- <Button
- type="button"
- size="xs"
- variant="outline"
- aria-label={t`Accept current version for conflict ${control.conflict.conflictIndex + 1}`}
- onClick={() => handleActionRef.current?.(control.conflict, 'current')}
- >
- {t`Accept current`}
- </Button>
- <Button
- type="button"
- size="xs"
- variant="outline"
- aria-label={t`Accept incoming version for conflict ${control.conflict.conflictIndex + 1}`}
- onClick={() => handleActionRef.current?.(control.conflict, 'incoming')}
- >
- {t`Accept incoming`}
- </Button>
- <Button
- type="button"
- size="xs"
- variant="outline"
- aria-label={t`Accept both versions for conflict ${control.conflict.conflictIndex + 1}`}
- onClick={() => handleActionRef.current?.(control.conflict, 'both')}
- >
- {t`Accept both`}
- </Button>
- </div>,
+ <ConflictActions
+ conflictIndex={control.conflict.conflictIndex}
+ onSelect={(selection) => handleActionRef.current?.(control.conflict, selection)}
+ />,
control.host,
control.key,
),
@@ -425,3 +471,54 @@ export function ConflictView({ fileName, ours, base, theirs, onResolve }: Confli
</div>
);
}
+
+function ConflictActions({
+ conflictIndex,
+ onSelect,
+}: {
+ conflictIndex?: number;
+ onSelect: (selection: MergeConflictResolution) => void;
+}) {
+ const { t } = useLingui();
+ return (
+ <div className="flex items-center gap-1">
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ aria-label={
+ conflictIndex === undefined
+ ? undefined
+ : t`Accept current version for conflict ${conflictIndex + 1}`
+ }
+ onClick={() => onSelect('current')}
+ >
+ {t`Accept current`}
+ </Button>
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ aria-label={
+ conflictIndex === undefined
+ ? undefined
+ : t`Accept incoming version for conflict ${conflictIndex + 1}`
+ }
+ onClick={() => onSelect('incoming')}
+ >
+ {t`Accept incoming`}
+ </Button>
+ {conflictIndex !== undefined && (
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ aria-label={t`Accept both versions for conflict ${conflictIndex + 1}`}
+ onClick={() => onSelect('both')}
+ >
+ {t`Accept both`}
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/ConflictsSection.dom.test.tsx b/packages/app/src/components/ConflictsSection.dom.test.tsx
index 4fc76517a..350253cee 100644
--- a/packages/app/src/components/ConflictsSection.dom.test.tsx
+++ b/packages/app/src/components/ConflictsSection.dom.test.tsx
@@ -2,7 +2,11 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
interface MockConflictsResult {
- conflicts: Array<{ file: string; detectedAt: string }>;
+ conflicts: Array<{
+ file: string;
+ detectedAt: string;
+ conflictKind?: 'git' | 'stale-external-write';
+ }>;
loading: boolean;
error: 'network' | 'server' | null;
}
@@ -79,6 +83,35 @@ describe('ConflictsSection', () => {
expect(window.location.hash).toBe('#/docs/page');
});
+ test('explains stale external writes without labeling Git conflicts as external edits', () => {
+ mockResult = {
+ conflicts: [
+ {
+ file: 'docs/stale.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ conflictKind: 'stale-external-write',
+ },
+ {
+ file: 'docs/git.md',
+ detectedAt: '2026-05-20T10:01:00.000Z',
+ conflictKind: 'git',
+ },
+ ],
+ loading: false,
+ error: null,
+ };
+
+ render(<ConflictsSection />);
+
+ const rows = screen.getAllByTestId('conflicts-section-row');
+ expect(rows[0]?.textContent).toContain(
+ 'The file was restored to an older version. Open it to choose which version to keep.',
+ );
+ expect(rows[1]?.textContent).not.toContain('Another app');
+ expect(rows[0]?.getAttribute('data-conflict-kind')).toBe('stale-external-write');
+ expect(rows[1]?.getAttribute('data-conflict-kind')).toBe('git');
+ });
+
test('section has NO quick-action buttons ([Keep mine] / [Keep theirs])', () => {
mockResult = {
conflicts: [{ file: 'docs/notes.md', detectedAt: '2026-05-20T10:00:00.000Z' }],
diff --git a/packages/app/src/components/ConflictsSection.tsx b/packages/app/src/components/ConflictsSection.tsx
index fedb98766..ab0478260 100644
--- a/packages/app/src/components/ConflictsSection.tsx
+++ b/packages/app/src/components/ConflictsSection.tsx
@@ -67,12 +67,23 @@ export function ConflictsSection() {
size="sm"
data-testid="conflicts-section-row"
data-file={entry.file}
+ data-conflict-kind={entry.conflictKind}
title={entry.file}
- className="h-7 w-full justify-start gap-1.5 px-2 font-normal text-[13px] text-amber-800 hover:bg-amber-100/60 hover:text-amber-900 dark:text-amber-300 dark:hover:bg-amber-900/30 dark:hover:text-amber-200"
+ className="h-auto min-h-7 w-full items-start justify-start gap-1.5 px-2 py-1.5 font-normal text-[13px] text-amber-800 hover:bg-amber-100/60 hover:text-amber-900 dark:text-amber-300 dark:hover:bg-amber-900/30 dark:hover:text-amber-200"
onClick={() => navigateToConflictedDoc(entry.file)}
>
- <AlertTriangle aria-hidden="true" className="size-3.5 shrink-0" />
- <span className="min-w-0 truncate">{entry.file}</span>
+ <AlertTriangle aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
+ <span className="min-w-0 text-start">
+ <span className="block truncate">{entry.file}</span>
+ {entry.conflictKind === 'stale-external-write' ? (
+ <span className="block text-pretty text-[11px] leading-4 text-amber-700/80 dark:text-amber-400/80">
+ <Trans>
+ The file was restored to an older version. Open it to choose which version to
+ keep.
+ </Trans>
+ </span>
+ ) : null}
+ </span>
</Button>
</li>
))}
diff --git a/packages/app/src/components/DiffViewBoundary.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.dom.test.tsx
index b3f1934b2..3c701928c 100644
--- a/packages/app/src/components/DiffViewBoundary.dom.test.tsx
+++ b/packages/app/src/components/DiffViewBoundary.dom.test.tsx
@@ -1,3 +1,4 @@
+import { SyncResolveConflictRequestSchema } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
@@ -70,7 +71,7 @@ function strategyFetch(kind: ConflictKind, resolvePending?: Promise<unknown>) {
function lastResolveBody(): { file?: string; strategy?: string } {
const call = fetchCalls.find((c) => c.url === '/api/sync/resolve-conflict');
- return JSON.parse(String(call?.init?.body ?? '{}'));
+ return SyncResolveConflictRequestSchema.parse(JSON.parse(String(call?.init?.body ?? '{}')));
}
describe('DiffViewBoundary (Tier-3 mount)', () => {
@@ -135,6 +136,209 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
expect(screen.queryByText(/Couldn't load conflict content/i)).toBeNull();
});
+ test('carries the stale-save kind from conflict content into the diff view', async () => {
+ globalThis.fetch = (input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input.toString();
+ const body =
+ url === '/api/sync/conflicts'
+ ? { conflicts: [{ file: 'foo.md', detectedAt: '2026-05-20T00:00:00.000Z' }] }
+ : {
+ file: 'foo.md',
+ base: '',
+ ours: 'Protected current version.\n',
+ theirs: 'Blocked older save.\n',
+ kind: 'both-modified',
+ conflictKind: 'stale-external-write',
+ lifecycleStatus: 'conflict',
+ };
+ return Promise.resolve(Response.json(body));
+ };
+ render(
+ <DiffViewBoundary docName="foo" provider={makeProvider('Protected current version.\n')} />,
+ );
+
+ const alert = await screen.findByRole('status');
+ expect(alert.textContent).toContain('Current is the version OpenKnowledge protected.');
+ expect(alert.textContent).toContain('Incoming is the restored version.');
+ expect(screen.queryByText(/No common ancestor/)).toBeNull();
+ });
+
+ test.each([undefined, 'git', 'future-conflict'])(
+ 'diagnoses only an unrecognized conflict discriminator: %j',
+ async (conflictKind) => {
+ globalThis.fetch = (input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input.toString();
+ return Promise.resolve(
+ Response.json(
+ url === '/api/sync/conflicts'
+ ? { conflicts: [{ file: 'foo.md', detectedAt: '2026-05-20T00:00:00.000Z' }] }
+ : {
+ file: 'foo.md',
+ base: 'Original content.\n',
+ ours: 'Current content.\n',
+ theirs: 'Incoming content.\n',
+ kind: 'both-modified',
+ conflictKind,
+ lifecycleStatus: 'conflict',
+ },
+ ),
+ );
+ };
+ render(<DiffViewBoundary docName="foo" provider={makeProvider('Current content.\n')} />);
+ expect(await screen.findByRole('button', { name: /^Accept current/ })).toBeTruthy();
+ const diagnostics = consoleWarnSpy.mock.calls
+ .map(([message]) => JSON.parse(String(message)))
+ .filter((event) => event.event === 'conflict-discriminator-unrecognized');
+ expect(diagnostics).toEqual(
+ conflictKind === 'future-conflict'
+ ? [
+ {
+ event: 'conflict-discriminator-unrecognized',
+ file: 'foo.md',
+ receivedConflictKind: conflictKind,
+ },
+ ]
+ : [],
+ );
+ },
+ );
+
+ test.each([
+ {
+ conflictKind: 'stale-external-write',
+ ours: '',
+ theirs: 'Older content.\n',
+ choice: 'current',
+ strategy: 'content',
+ content: '',
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: 'Current content.\n',
+ theirs: '',
+ choice: 'incoming',
+ strategy: 'theirs',
+ content: undefined,
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: 'Current content.\n',
+ theirs: 'Older content.\n',
+ choice: 'current',
+ strategy: 'content',
+ content: 'Current content.\n',
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: 'Current content.\n',
+ theirs: 'Older content.\n',
+ choice: 'incoming',
+ strategy: 'theirs',
+ content: undefined,
+ },
+ {
+ conflictKind: 'git',
+ ours: '',
+ theirs: 'Older content.\n',
+ choice: 'current',
+ strategy: 'content',
+ content: '',
+ },
+ {
+ conflictKind: 'git',
+ ours: 'Current content.\n',
+ theirs: '',
+ choice: 'incoming',
+ strategy: 'content',
+ content: '',
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: '',
+ theirs: '',
+ choice: 'current',
+ strategy: 'content',
+ content: '',
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: '',
+ theirs: '',
+ choice: 'incoming',
+ strategy: 'theirs',
+ content: undefined,
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: 'Same content.\n',
+ theirs: 'Same content.\n',
+ choice: 'incoming',
+ strategy: 'theirs',
+ content: undefined,
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: 'Same content.\n',
+ theirs: 'Same content.\n',
+ choice: 'current',
+ strategy: 'content',
+ content: 'Same content.\n',
+ },
+ {
+ conflictKind: 'stale-external-write',
+ ours: 'Current content.\n',
+ theirs: 'Older content.\n',
+ choice: 'both',
+ strategy: 'content',
+ content: 'Current content.\nOlder content.\n',
+ },
+ ])(
+ 'resolves $conflictKind $choice via $strategy without changing selected bytes',
+ async ({ conflictKind, ours, theirs, choice, strategy, content }) => {
+ globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = typeof input === 'string' ? input : input.toString();
+ fetchCalls.push({ url, init });
+ if (url === '/api/sync/conflicts') {
+ return Promise.resolve(
+ Response.json({
+ conflicts: [{ file: 'foo.md', detectedAt: '2026-05-20T00:00:00.000Z', conflictKind }],
+ }),
+ );
+ }
+ if (url.startsWith('/api/sync/conflict-content')) {
+ return Promise.resolve(
+ Response.json({
+ file: 'foo.md',
+ base: conflictKind === 'stale-external-write' ? theirs : 'Original content.\n',
+ ours,
+ theirs,
+ kind: 'both-modified',
+ conflictKind,
+ lifecycleStatus: 'conflict',
+ }),
+ );
+ }
+ return Promise.resolve(Response.json({}));
+ };
+ render(<DiffViewBoundary docName="foo" provider={makeProvider(ours)} />);
+
+ const choiceButton = await screen.findByRole('button', {
+ name: new RegExp(`^Accept ${choice}`),
+ });
+ expect(screen.queryByRole('button', { name: 'Apply changes' })).toBeNull();
+ fireEvent.click(choiceButton);
+ fireEvent.click(await screen.findByRole('button', { name: 'Apply changes' }));
+
+ await waitFor(() => {
+ expect(lastResolveBody()).toEqual({
+ file: 'foo.md',
+ strategy,
+ ...(content === undefined ? {} : { content }),
+ });
+ });
+ },
+ );
+
test('emits editor-area-swap-to-diffview on mount and -from on unmount', async () => {
const provider = makeProvider('seed\n');
const { unmount } = render(<DiffViewBoundary docName="logs/entry" provider={provider} />);
diff --git a/packages/app/src/components/DiffViewBoundary.tsx b/packages/app/src/components/DiffViewBoundary.tsx
index bad14b3a4..665930ca0 100644
--- a/packages/app/src/components/DiffViewBoundary.tsx
+++ b/packages/app/src/components/DiffViewBoundary.tsx
@@ -3,7 +3,9 @@
* precedent #18(b) stays intact.
*/
import type { HocuspocusProvider } from '@hocuspocus/provider';
+import type { SyncConflictContentSuccess } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
+import type { MergeConflictResolution } from '@pierre/diffs';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
@@ -26,13 +28,14 @@ interface DiffViewBoundaryProps {
provider: HocuspocusProvider;
}
-type ConflictKind = 'both-modified' | 'delete-modify' | 'modify-delete';
+type ConflictKind = SyncConflictContentSuccess['kind'];
interface ConflictSides {
base: string;
ours: string;
theirs: string;
kind: ConflictKind;
+ conflictKind: SyncConflictContentSuccess['conflictKind'];
}
async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
@@ -57,7 +60,9 @@ async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
);
return null;
}
- const data = (await res.json()) as Partial<ConflictSides>;
+ const data = (await res.json()) as Partial<Omit<ConflictSides, 'conflictKind'>> & {
+ conflictKind?: unknown;
+ };
const kind: ConflictKind =
data.kind === 'delete-modify' ||
data.kind === 'modify-delete' ||
@@ -73,11 +78,25 @@ async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
}),
);
}
+ if (
+ data.conflictKind !== undefined &&
+ data.conflictKind !== 'git' &&
+ data.conflictKind !== 'stale-external-write'
+ ) {
+ console.warn(
+ JSON.stringify({
+ event: 'conflict-discriminator-unrecognized',
+ file,
+ receivedConflictKind: data.conflictKind,
+ }),
+ );
+ }
return {
base: data.base ?? '',
ours: data.ours ?? '',
theirs: data.theirs ?? '',
kind,
+ conflictKind: data.conflictKind === 'stale-external-write' ? 'stale-external-write' : 'git',
};
} catch (err) {
console.warn(
@@ -127,6 +146,7 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
? null
: [
conflictEntry.detectedAt,
+ conflictEntry.conflictKind ?? 'git',
conflictEntry.baseSha ?? '',
conflictEntry.oursSha ?? '',
conflictEntry.theirsSha ?? '',
@@ -151,8 +171,10 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
};
}, [filePath, deferFetch, conflictSignature]);
- async function handleResolve(content: string) {
- const result = await resolveConflictContent(filePath, content);
+ async function handleResolve(content: string, selection?: MergeConflictResolution) {
+ const result = await (sides?.conflictKind === 'stale-external-write' && selection === 'incoming'
+ ? resolveConflictTheirs(filePath)
+ : resolveConflictContent(filePath, content));
if (!result.ok) {
toast.error(t`Couldn't save the resolution for ${filePath}.`, { description: result.detail });
}
@@ -295,6 +317,7 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
return (
<ConflictView
fileName={filePath}
+ conflictKind={sides.conflictKind}
ours={sides.ours}
base={sides.base}
theirs={sides.theirs}
diff --git a/packages/app/src/components/conflict-history.ts b/packages/app/src/components/conflict-history.ts
index 2a66b465f..111639e7b 100644
--- a/packages/app/src/components/conflict-history.ts
+++ b/packages/app/src/components/conflict-history.ts
@@ -2,6 +2,7 @@ import type {
FileContents,
FileDiffMetadata,
MergeConflictMarkerRow,
+ MergeConflictResolution,
UnresolvedFile,
} from '@pierre/diffs';
@@ -12,6 +13,7 @@ export interface ConflictSnapshot {
fileDiff?: FileDiffMetadata;
actions?: ResolveReturn['actions'];
markerRows?: MergeConflictMarkerRow[];
+ selection?: MergeConflictResolution;
}
const MAX_DEPTH = 50;
diff --git a/packages/app/src/components/conflict-view-regressions.dom.test.tsx b/packages/app/src/components/conflict-view-regressions.dom.test.tsx
index 7ba658988..db08110c8 100644
--- a/packages/app/src/components/conflict-view-regressions.dom.test.tsx
+++ b/packages/app/src/components/conflict-view-regressions.dom.test.tsx
@@ -31,12 +31,14 @@ async function mount(props: {
ours: string;
base: string;
theirs: string;
+ conflictKind?: 'git' | 'stale-external-write';
onResolve?: (content: string) => void | Promise<void>;
}) {
const onResolve = props.onResolve ?? vi.fn();
render(
<ConflictView
fileName="notes/plan.md"
+ conflictKind={props.conflictKind}
ours={props.ours}
base={props.base}
theirs={props.theirs}
@@ -47,6 +49,8 @@ async function mount(props: {
return onResolve;
}
+const IDENTICAL_WITH_MARKERS = 'intro\n<<<<<<< OURS\na\n=======\nb\n>>>>>>> THEIRS\ntail\n';
+
test('a conflict the three-way merge resolves cleanly still offers Apply', async () => {
await mount({
base: 'alpha\nbeta\ngamma\n',
@@ -159,6 +163,50 @@ test('a marker-lookalike line in the content withholds every control', async ()
expect(onResolve).not.toHaveBeenCalled();
});
+test('identical stale versions label their choice without a conflict index', async () => {
+ await mount({
+ conflictKind: 'stale-external-write',
+ base: '',
+ ours: 'same bytes\n',
+ theirs: 'same bytes\n',
+ });
+
+ expect(screen.getByRole('button', { name: 'Accept current' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Accept incoming' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /for conflict/ })).toBeNull();
+ expect(screen.getByText(/Both versions are identical/)).toBeTruthy();
+});
+
+test('the identical-versions banner maps each button to its protection outcome', async () => {
+ await mount({
+ conflictKind: 'stale-external-write',
+ base: '',
+ ours: 'same bytes\n',
+ theirs: 'same bytes\n',
+ });
+
+ const banner = screen.getByText(/Both versions are identical/).textContent ?? '';
+ expect(banner).toContain("Accept current leaves OpenKnowledge's protection on");
+ expect(banner).toContain('Accept incoming turns that protection off');
+});
+
+test('identical stale versions withhold the choice when the shared content misparses', async () => {
+ const onResolve = vi.fn();
+ await mount({
+ conflictKind: 'stale-external-write',
+ base: '',
+ ours: IDENTICAL_WITH_MARKERS,
+ theirs: IDENTICAL_WITH_MARKERS,
+ onResolve,
+ });
+
+ expect(screen.getByText(/look like conflict markers/)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /^Accept current/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: /^Accept incoming/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Apply changes' })).toBeNull();
+ expect(onResolve).not.toHaveBeenCalled();
+});
+
test('an ordinary conflict is unaffected by the parse check', async () => {
await mount({
base: 'intro\n\nBASE\n',
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 289dd0609..e45ea57e9 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -1061,6 +1061,9 @@
]
],
"ALhMYW": ["الطرفية"],
+ "AMU00p": [
+ "النسختان متطابقتان. اختيار قبول الحالي يُبقي حماية OpenKnowledge مفعّلة، لذا سيُرفض مجددًا أي حفظ آخر للنسخة الأقدم. اختيار قبول الوارد يوقف تلك الحماية."
+ ],
"AN-UPd": [
"يجب أن تكون terminal.shell في .ok/local/config.yml مسار Windows مطلقًا. سيتم استخدام صدفة Windows متاحة بدلًا منها."
],
@@ -3246,6 +3249,9 @@
"تعذّرت إعادة تشغيل الخادم — عملية أخرى تملكه. أغلق نوافذ OpenKnowledge الأخرى لهذا المشروع، ثم أعد المحاولة."
],
"Xv_ijG": ["https://github.com/owner/repo أو owner/repo"],
+ "XwZiq2": [
+ "تمت استعادة الملف إلى إصدار أقدم. الحالي هو الإصدار الذي حماه OpenKnowledge. الوارد هو الإصدار المستعاد. اختر الإصدار الذي تريد الاحتفاظ به، ثم طبّق تغييراتك."
+ ],
"XzL7x7": ["أعد فتح ", ["filePath"], " لمواصلة التحرير."],
"Xzy0s0": ["إزالة ", ["fullLabel"], " من السياق"],
"Y-Urt2": ["معادلة رياضية بكتلة مستقلة تُعرض بواسطة KaTeX من نص مصدري بصيغة LaTeX."],
@@ -5121,6 +5127,7 @@
"q2kXMG": ["رياضيات مضمَّنة"],
"q3TWG7": ["النقل إلى المهملات"],
"q3W2nd": ["تعذّرت إضافة ذلك التعليق: ", ["0"]],
+ "q3sP3v": ["تمت استعادة الملف إلى إصدار أقدم. افتحه لاختيار الإصدار الذي تريد الاحتفاظ به."],
"q4YJl_": ["انتهت جلسة الطرفية (رمز الخروج ", ["0"], ")."],
"q4efaG": [["filePath"], " لم يعد ضمن هذه المهارة"],
"q5uZbJ": ["تُفهرس الصفحات المتبقية عند البحث. ابحث مرة أخرى للحصول على نتائج أكثر اكتمالًا."],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index 722d676ef..ca04a3fd1 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -1432,7 +1432,7 @@ msgstr "أعلى"
msgid "Accept both"
msgstr "قبول كليهما"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "قبول كلتا النسختين للتعارض {0}"
@@ -1441,7 +1441,7 @@ msgstr "قبول كلتا النسختين للتعارض {0}"
msgid "Accept current"
msgstr "قبول الحالي"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "قبول النسخة الحالية للتعارض {0}"
@@ -1450,7 +1450,7 @@ msgstr "قبول النسخة الحالية للتعارض {0}"
msgid "Accept incoming"
msgstr "قبول الوارد"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "قبول النسخة الواردة للتعارض {0}"
@@ -2382,6 +2382,10 @@ msgstr "كلاهما"
msgid "Both agents end up reading everything in {keep}."
msgstr "سيقرأ الوكيلان في النهاية كل ما في {keep}."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "النسختان متطابقتان. اختيار قبول الحالي يُبقي حماية OpenKnowledge مفعّلة، لذا سيُرفض مجددًا أي حفظ آخر للنسخة الأقدم. اختيار قبول الوارد يوقف تلك الحماية."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "فرع"
@@ -13644,6 +13648,14 @@ msgstr "الملف موجود في {trashNoun}؛ سيقوم مراقب المل
msgid "The file on disk, and the id agents use."
msgstr "الملف على القرص، والمعرّف الذي يستخدمه الوكلاء."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "تمت استعادة الملف إلى إصدار أقدم. الحالي هو الإصدار الذي حماه OpenKnowledge. الوارد هو الإصدار المستعاد. اختر الإصدار الذي تريد الاحتفاظ به، ثم طبّق تغييراتك."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "تمت استعادة الملف إلى إصدار أقدم. افتحه لاختيار الإصدار الذي تريد الاحتفاظ به."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "المجلد على القرص والمعرّف الذي يستخدمه الوكلاء لاستدعاء هذه المهارة."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index b223faebb..3e3eb6399 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -862,6 +862,9 @@
"AJ7_B2": ["নতুন থিম তৈরি করুন"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ওয়ার্কট্রি"], "other": ["ওয়ার্কট্রি"] }]],
"ALhMYW": ["টার্মিনাল"],
+ "AMU00p": [
+ "দুটি সংস্করণ অভিন্ন। বর্তমানটি গ্রহণ করুন বেছে নিলে OpenKnowledge-এর সুরক্ষা চালু থাকে, ফলে পুরোনো সংস্করণের আরেকটি সেভ আবার প্রত্যাখ্যান করা হবে। আগতটি গ্রহণ করুন বেছে নিলে সেই সুরক্ষা বন্ধ হয়ে যায়।"
+ ],
"AN-UPd": [
".ok/local/config.yml-এ terminal.shell অবশ্যই একটি সম্পূর্ণ Windows পাথ হতে হবে। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"
],
@@ -2724,6 +2727,9 @@
"সার্ভার পুনরায় চালু করা যায়নি — অন্য একটি প্রক্রিয়া এর মালিক। এই প্রকল্পের অন্য OpenKnowledge জানালাগুলো বন্ধ করে আবার চেষ্টা করুন।"
],
"Xv_ijG": ["https://github.com/owner/repo বা owner/repo"],
+ "XwZiq2": [
+ "ফাইলটি একটি পুরোনো সংস্করণে ফিরিয়ে আনা হয়েছে। বর্তমানটি হলো OpenKnowledge যে সংস্করণটি সুরক্ষিত রেখেছে। আগতটি হলো ফিরিয়ে আনা সংস্করণ। কোন সংস্করণটি রাখবেন তা বেছে নিন, তারপর আপনার পরিবর্তনগুলি প্রয়োগ করুন।"
+ ],
"XzL7x7": ["সম্পাদনা চালিয়ে যেতে ", ["filePath"], " আবার খুলুন।"],
"Xzy0s0": [["fullLabel"], " প্রসঙ্গ থেকে সরান"],
"Y-Urt2": ["একটি LaTeX সোর্স স্ট্রিং থেকে KaTeX দিয়ে রেন্ডার করা ব্লক গাণিতিক সমীকরণ।"],
@@ -4352,6 +4358,7 @@
"q2kXMG": ["ইনলাইন গণিত"],
"q3TWG7": ["ট্র্যাশে পাঠান"],
"q3W2nd": ["ওই মন্তব্যটি যোগ করা যায়নি: ", ["0"]],
+ "q3sP3v": ["ফাইলটি একটি পুরোনো সংস্করণে ফিরিয়ে আনা হয়েছে। কোন সংস্করণটি রাখবেন তা বেছে নিতে এটি খুলুন।"],
"q4YJl_": ["টার্মিনাল সেশন শেষ হয়েছে (প্রস্থান কোড ", ["0"], ")।"],
"q4efaG": [["filePath"], " আর এই স্কিলে নেই"],
"q5uZbJ": ["বাকি পৃষ্ঠাগুলো অনুসন্ধান করার সময় ইনডেক্স করা হয়। আরও সম্পূর্ণ ফলাফলের জন্য আবার অনুসন্ধান করুন।"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index b31d73050..fb207da2d 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -1428,7 +1428,7 @@ msgstr "উপরে"
msgid "Accept both"
msgstr "দুটোই গ্রহণ করুন"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "কনফ্লিক্ট {0}-এর জন্য উভয় সংস্করণ গ্রহণ করুন"
@@ -1437,7 +1437,7 @@ msgstr "কনফ্লিক্ট {0}-এর জন্য উভয় সং
msgid "Accept current"
msgstr "বর্তমানটি গ্রহণ করুন"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "কনফ্লিক্ট {0}-এর জন্য বর্তমান সংস্করণ গ্রহণ করুন"
@@ -1446,7 +1446,7 @@ msgstr "কনফ্লিক্ট {0}-এর জন্য বর্তমা
msgid "Accept incoming"
msgstr "আগতটি গ্রহণ করুন"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "কনফ্লিক্ট {0}-এর জন্য আগত সংস্করণ গ্রহণ করুন"
@@ -2378,6 +2378,10 @@ msgstr "দুটোই"
msgid "Both agents end up reading everything in {keep}."
msgstr "শেষমেশ দুই এজেন্টই {keep}-এর সবকিছু পড়বে।"
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "দুটি সংস্করণ অভিন্ন। বর্তমানটি গ্রহণ করুন বেছে নিলে OpenKnowledge-এর সুরক্ষা চালু থাকে, ফলে পুরোনো সংস্করণের আরেকটি সেভ আবার প্রত্যাখ্যান করা হবে। আগতটি গ্রহণ করুন বেছে নিলে সেই সুরক্ষা বন্ধ হয়ে যায়।"
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "ব্রাঞ্চ"
@@ -13640,6 +13644,14 @@ msgstr "ফাইলটি আপনার {trashNoun}-এ আছে; ফাই
msgid "The file on disk, and the id agents use."
msgstr "ডিস্কের ফাইলটি, এবং এজেন্টরা যে id ব্যবহার করে।"
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "ফাইলটি একটি পুরোনো সংস্করণে ফিরিয়ে আনা হয়েছে। বর্তমানটি হলো OpenKnowledge যে সংস্করণটি সুরক্ষিত রেখেছে। আগতটি হলো ফিরিয়ে আনা সংস্করণ। কোন সংস্করণটি রাখবেন তা বেছে নিন, তারপর আপনার পরিবর্তনগুলি প্রয়োগ করুন।"
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "ফাইলটি একটি পুরোনো সংস্করণে ফিরিয়ে আনা হয়েছে। কোন সংস্করণটি রাখবেন তা বেছে নিতে এটি খুলুন।"
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "ডিস্কের ফোল্ডার এবং এজেন্টরা এই স্কিলটি ডাকতে যে id ব্যবহার করে।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 1b54966ce..3759b3e7f 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -884,6 +884,9 @@
"AJ7_B2": ["Create new theme"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["worktree"], "other": ["worktrees"] }]],
"ALhMYW": ["Terminal"],
+ "AMU00p": [
+ "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+ ],
"AN-UPd": [
"terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."
],
@@ -2790,6 +2793,9 @@
"Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again."
],
"Xv_ijG": ["https://github.com/owner/repo or owner/repo"],
+ "XwZiq2": [
+ "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+ ],
"XzL7x7": ["Reopen ", ["filePath"], " to keep editing."],
"Xzy0s0": ["Remove ", ["fullLabel"], " from context"],
"Y-Urt2": ["Block math equation rendered with KaTeX from a LaTeX source string."],
@@ -4486,6 +4492,9 @@
"q2kXMG": ["Inline Math"],
"q3TWG7": ["Move to Trash"],
"q3W2nd": ["Couldn't add that comment: ", ["0"]],
+ "q3sP3v": [
+ "The file was restored to an older version. Open it to choose which version to keep."
+ ],
"q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],
"q4efaG": [["filePath"], " is no longer in this skill"],
"q5uZbJ": ["Missing pages are indexed when you search. Search again for fuller results."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 2c638cc2d..04e2002d0 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1432,7 +1432,7 @@ msgstr "Above"
msgid "Accept both"
msgstr "Accept both"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "Accept both versions for conflict {0}"
@@ -1441,7 +1441,7 @@ msgstr "Accept both versions for conflict {0}"
msgid "Accept current"
msgstr "Accept current"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "Accept current version for conflict {0}"
@@ -1450,7 +1450,7 @@ msgstr "Accept current version for conflict {0}"
msgid "Accept incoming"
msgstr "Accept incoming"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "Accept incoming version for conflict {0}"
@@ -2382,6 +2382,10 @@ msgstr "Both"
msgid "Both agents end up reading everything in {keep}."
msgstr "Both agents end up reading everything in {keep}."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "Branch"
@@ -13644,6 +13648,14 @@ msgstr "The file is in your {trashNoun}; the file-watcher will reconcile."
msgid "The file on disk, and the id agents use."
msgstr "The file on disk, and the id agents use."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "The file was restored to an older version. Open it to choose which version to keep."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "The folder on disk and the id agents use to invoke this skill."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index 46d828a2c..b34572844 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -1051,6 +1051,9 @@
]
],
"ALhMYW": ["Terminal"],
+ "AMU00p": [
+ "Las dos versiones son idénticas. Elegir Aceptar actual mantiene activa la protección de OpenKnowledge, así que otro guardado de la versión anterior se rechazará de nuevo. Elegir Aceptar entrante desactiva esa protección."
+ ],
"AN-UPd": [
"terminal.shell en .ok/local/config.yml debe ser una ruta absoluta de Windows. Se usará un shell de Windows disponible."
],
@@ -3258,6 +3261,9 @@
"No se pudo reiniciar el servidor: otro proceso lo tiene. Cierra las demás ventanas de OpenKnowledge de este proyecto e inténtalo de nuevo."
],
"Xv_ijG": ["https://github.com/propietario/repo o propietario/repo"],
+ "XwZiq2": [
+ "El archivo se restauró a una versión anterior. Actual es la versión que OpenKnowledge protegió. Entrante es la versión restaurada. Elige qué versión conservar y luego aplica los cambios."
+ ],
"XzL7x7": ["Vuelve a abrir ", ["filePath"], " para seguir editando."],
"Xzy0s0": ["Quitar ", ["fullLabel"], " del contexto"],
"Y-Urt2": ["Ecuación matemática en bloque renderizada con KaTeX a partir de código LaTeX."],
@@ -5175,6 +5181,9 @@
"q2kXMG": ["Fórmula en línea"],
"q3TWG7": ["Mover a la Papelera"],
"q3W2nd": ["No se pudo añadir ese comentario: ", ["0"]],
+ "q3sP3v": [
+ "El archivo se restauró a una versión anterior. Ábrelo para elegir qué versión conservar."
+ ],
"q4YJl_": ["La sesión de terminal terminó (código de salida ", ["0"], ")."],
"q4efaG": [["filePath"], " ya no está en esta skill"],
"q5uZbJ": [
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 587c1be23..8fa36956e 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -1432,7 +1432,7 @@ msgstr "Arriba"
msgid "Accept both"
msgstr "Aceptar ambos"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "Aceptar ambas versiones para el conflicto {0}"
@@ -1441,7 +1441,7 @@ msgstr "Aceptar ambas versiones para el conflicto {0}"
msgid "Accept current"
msgstr "Aceptar actual"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "Aceptar la versión actual para el conflicto {0}"
@@ -1450,7 +1450,7 @@ msgstr "Aceptar la versión actual para el conflicto {0}"
msgid "Accept incoming"
msgstr "Aceptar entrante"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "Aceptar la versión entrante para el conflicto {0}"
@@ -2382,6 +2382,10 @@ msgstr "Ambos"
msgid "Both agents end up reading everything in {keep}."
msgstr "Ambos agentes acaban leyendo todo lo que hay en {keep}."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "Las dos versiones son idénticas. Elegir Aceptar actual mantiene activa la protección de OpenKnowledge, así que otro guardado de la versión anterior se rechazará de nuevo. Elegir Aceptar entrante desactiva esa protección."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "Rama"
@@ -13644,6 +13648,14 @@ msgstr "El archivo está en tu {trashNoun}; el observador de archivos lo reconci
msgid "The file on disk, and the id agents use."
msgstr "El archivo en el disco, y el id que usan los agentes."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "El archivo se restauró a una versión anterior. Actual es la versión que OpenKnowledge protegió. Entrante es la versión restaurada. Elige qué versión conservar y luego aplica los cambios."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "El archivo se restauró a una versión anterior. Ábrelo para elegir qué versión conservar."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "La carpeta en el disco y el id con el que los agentes invocan esta habilidad."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 0d00c6f1e..8ce9dbbb5 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -1078,6 +1078,9 @@
]
],
"ALhMYW": ["Terminal"],
+ "AMU00p": [
+ "Les deux versions sont identiques. Choisir Accepter l’actuel laisse la protection d’OpenKnowledge activée : un nouvel enregistrement de la version antérieure sera de nouveau refusé. Choisir Accepter l’entrant désactive cette protection."
+ ],
"AN-UPd": [
"terminal.shell dans .ok/local/config.yml doit être un chemin Windows absolu. Un shell Windows disponible sera utilisé à la place."
],
@@ -3299,6 +3302,9 @@
"Impossible de redémarrer le serveur — un autre processus le détient. Quittez les autres fenêtres OpenKnowledge de ce projet, puis réessayez."
],
"Xv_ijG": ["https://github.com/owner/repo ou owner/repo"],
+ "XwZiq2": [
+ "Le fichier a été restauré dans une version antérieure. L’actuel est la version protégée par OpenKnowledge. L’entrant est la version restaurée. Choisissez la version à conserver, puis appliquez vos modifications."
+ ],
"XzL7x7": ["Rouvrez ", ["filePath"], " pour continuer à modifier."],
"Xzy0s0": ["Retirer ", ["fullLabel"], " du contexte"],
"Y-Urt2": ["Équation mathématique en bloc rendue avec KaTeX à partir d'une source LaTeX."],
@@ -5238,6 +5244,9 @@
"q2kXMG": ["Formule en ligne"],
"q3TWG7": ["Mettre à la corbeille"],
"q3W2nd": ["Impossible d'ajouter ce commentaire : ", ["0"]],
+ "q3sP3v": [
+ "Le fichier a été restauré dans une version antérieure. Ouvrez-le pour choisir la version à conserver."
+ ],
"q4YJl_": ["La session de terminal s'est terminée (code de sortie ", ["0"], ")."],
"q4efaG": [["filePath"], " ne fait plus partie de cette compétence"],
"q5uZbJ": [
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index d4da10cfa..4d28db961 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -1432,7 +1432,7 @@ msgstr "Au-dessus"
msgid "Accept both"
msgstr "Accepter les deux"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "Accepter les deux versions pour le conflit {0}"
@@ -1441,7 +1441,7 @@ msgstr "Accepter les deux versions pour le conflit {0}"
msgid "Accept current"
msgstr "Accepter l’actuel"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "Accepter la version actuelle pour le conflit {0}"
@@ -1450,7 +1450,7 @@ msgstr "Accepter la version actuelle pour le conflit {0}"
msgid "Accept incoming"
msgstr "Accepter l’entrant"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "Accepter la version entrante pour le conflit {0}"
@@ -2382,6 +2382,10 @@ msgstr "Les deux"
msgid "Both agents end up reading everything in {keep}."
msgstr "Les deux agents liront tout ce qui se trouve dans {keep}."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "Les deux versions sont identiques. Choisir Accepter l’actuel laisse la protection d’OpenKnowledge activée : un nouvel enregistrement de la version antérieure sera de nouveau refusé. Choisir Accepter l’entrant désactive cette protection."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "Branche"
@@ -13644,6 +13648,14 @@ msgstr "Le fichier est dans votre {trashNoun} ; l'observateur de fichiers fera l
msgid "The file on disk, and the id agents use."
msgstr "Le fichier sur le disque, et l'id qu'utilisent les agents."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "Le fichier a été restauré dans une version antérieure. L’actuel est la version protégée par OpenKnowledge. L’entrant est la version restaurée. Choisissez la version à conserver, puis appliquez vos modifications."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "Le fichier a été restauré dans une version antérieure. Ouvrez-le pour choisir la version à conserver."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "Le dossier sur le disque et l'id que les agents utilisent pour invoquer cette compétence."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index c2b9f6694..514d4ce69 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -866,6 +866,9 @@
"AJ7_B2": ["नई थीम बनाएँ"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["वर्कट्री"], "other": ["वर्कट्री"] }]],
"ALhMYW": ["टर्मिनल"],
+ "AMU00p": [
+ "दोनों संस्करण एक जैसे हैं। वर्तमान स्वीकारें चुनने पर OpenKnowledge की सुरक्षा चालू रहती है, इसलिए पुराने संस्करण का एक और सेव फिर से अस्वीकार कर दिया जाएगा। आने वाला स्वीकारें चुनने पर वह सुरक्षा बंद हो जाती है।"
+ ],
"AN-UPd": [
".ok/local/config.yml में terminal.shell एक निरपेक्ष Windows पथ होना चाहिए। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"
],
@@ -2716,6 +2719,9 @@
"सर्वर पुनः आरंभ नहीं किया जा सका — कोई दूसरी प्रक्रिया उस पर अधिकार रखती है। इस प्रोजेक्ट की बाकी OpenKnowledge विंडो बंद करें, फिर कोशिश करें।"
],
"Xv_ijG": ["https://github.com/owner/repo या owner/repo"],
+ "XwZiq2": [
+ "फ़ाइल को पुराने संस्करण में बहाल किया गया है। वर्तमान वह संस्करण है जिसे OpenKnowledge ने सुरक्षित रखा है। आने वाला बहाल किया गया संस्करण है। कौन सा संस्करण रखना है, यह चुनें, फिर अपने बदलाव लागू करें।"
+ ],
"XzL7x7": ["संपादन जारी रखने के लिए ", ["filePath"], " फिर से खोलें।"],
"Xzy0s0": [["fullLabel"], " को संदर्भ से हटाएँ"],
"Y-Urt2": ["एक LaTeX स्रोत स्ट्रिंग से KaTeX द्वारा रेंडर किया गया ब्लॉक गणित समीकरण।"],
@@ -4344,6 +4350,7 @@
"q2kXMG": ["इनलाइन गणित"],
"q3TWG7": ["ट्रैश में ले जाएँ"],
"q3W2nd": ["वह टिप्पणी नहीं जोड़ी जा सकी: ", ["0"]],
+ "q3sP3v": ["फ़ाइल को पुराने संस्करण में बहाल किया गया है। कौन सा संस्करण रखना है, यह चुनने के लिए इसे खोलें।"],
"q4YJl_": ["टर्मिनल सत्र समाप्त हो गया (निकास कोड ", ["0"], ")।"],
"q4efaG": [["filePath"], " अब इस स्किल में नहीं है"],
"q5uZbJ": ["बाकी पेज खोज करते समय इंडेक्स किए जाते हैं। अधिक पूर्ण परिणामों के लिए फिर से खोजें।"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 9596652b2..d8628e177 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -1428,7 +1428,7 @@ msgstr "ऊपर"
msgid "Accept both"
msgstr "दोनों स्वीकारें"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "कॉन्फ़्लिक्ट {0} के लिए दोनों संस्करण स्वीकारें"
@@ -1437,7 +1437,7 @@ msgstr "कॉन्फ़्लिक्ट {0} के लिए दोनो
msgid "Accept current"
msgstr "वर्तमान स्वीकारें"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "कॉन्फ़्लिक्ट {0} के लिए मौजूदा संस्करण स्वीकारें"
@@ -1446,7 +1446,7 @@ msgstr "कॉन्फ़्लिक्ट {0} के लिए मौजू
msgid "Accept incoming"
msgstr "आने वाला स्वीकारें"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "कॉन्फ़्लिक्ट {0} के लिए आने वाला संस्करण स्वीकारें"
@@ -2378,6 +2378,10 @@ msgstr "दोनों"
msgid "Both agents end up reading everything in {keep}."
msgstr "दोनों एजेंट अंत में {keep} की हर चीज़ पढ़ेंगे।"
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "दोनों संस्करण एक जैसे हैं। वर्तमान स्वीकारें चुनने पर OpenKnowledge की सुरक्षा चालू रहती है, इसलिए पुराने संस्करण का एक और सेव फिर से अस्वीकार कर दिया जाएगा। आने वाला स्वीकारें चुनने पर वह सुरक्षा बंद हो जाती है।"
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "ब्रांच"
@@ -13640,6 +13644,14 @@ msgstr "फ़ाइल आपके {trashNoun} में है; फ़ाइ
msgid "The file on disk, and the id agents use."
msgstr "डिस्क की फ़ाइल, और वह id जो एजेंट उपयोग करते हैं।"
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "फ़ाइल को पुराने संस्करण में बहाल किया गया है। वर्तमान वह संस्करण है जिसे OpenKnowledge ने सुरक्षित रखा है। आने वाला बहाल किया गया संस्करण है। कौन सा संस्करण रखना है, यह चुनें, फिर अपने बदलाव लागू करें।"
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "फ़ाइल को पुराने संस्करण में बहाल किया गया है। कौन सा संस्करण रखना है, यह चुनने के लिए इसे खोलें।"
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "डिस्क का फ़ोल्डर और वह id जिससे एजेंट इस स्किल को बुलाते हैं।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index b9c11223e..1fd3035ec 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -896,6 +896,9 @@
"AJ7_B2": ["Buat tema baru"],
"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["worktree"] }]],
"ALhMYW": ["Terminal"],
+ "AMU00p": [
+ "Kedua versi identik. Memilih Terima yang sekarang membuat perlindungan OpenKnowledge tetap aktif, sehingga penyimpanan versi lama berikutnya akan ditolak lagi. Memilih Terima yang masuk menonaktifkan perlindungan tersebut."
+ ],
"AN-UPd": [
"terminal.shell di .ok/local/config.yml harus berupa jalur Windows absolut. Shell Windows yang tersedia akan digunakan sebagai gantinya."
],
@@ -2813,6 +2816,9 @@
"Server tidak bisa dimulai ulang — proses lain menguasainya. Tutup jendela OpenKnowledge lain untuk proyek ini, lalu coba lagi."
],
"Xv_ijG": ["https://github.com/pemilik/repo atau pemilik/repo"],
+ "XwZiq2": [
+ "Berkas dipulihkan ke versi yang lebih lama. Yang sekarang adalah versi yang dilindungi OpenKnowledge. Yang masuk adalah versi yang dipulihkan. Pilih versi yang ingin dipertahankan, lalu terapkan perubahan Anda."
+ ],
"XzL7x7": ["Buka kembali ", ["filePath"], " untuk melanjutkan penyuntingan."],
"Xzy0s0": ["Hapus ", ["fullLabel"], " dari konteks"],
"Y-Urt2": ["Persamaan matematika blok yang dirender dengan KaTeX dari sumber LaTeX."],
@@ -4515,6 +4521,9 @@
"q2kXMG": ["Matematika Sebaris"],
"q3TWG7": ["Pindahkan ke Tempat Sampah"],
"q3W2nd": ["Komentar itu tidak bisa ditambahkan: ", ["0"]],
+ "q3sP3v": [
+ "Berkas dipulihkan ke versi yang lebih lama. Buka berkas untuk memilih versi yang ingin dipertahankan."
+ ],
"q4YJl_": ["Sesi terminal berakhir (kode keluar ", ["0"], ")."],
"q4efaG": [["filePath"], " sudah tidak ada di skill ini"],
"q5uZbJ": [
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 077854feb..7bff5f4cb 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -1428,7 +1428,7 @@ msgstr "Di atas"
msgid "Accept both"
msgstr "Terima keduanya"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "Terima kedua versi untuk konflik {0}"
@@ -1437,7 +1437,7 @@ msgstr "Terima kedua versi untuk konflik {0}"
msgid "Accept current"
msgstr "Terima yang sekarang"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "Terima versi saat ini untuk konflik {0}"
@@ -1446,7 +1446,7 @@ msgstr "Terima versi saat ini untuk konflik {0}"
msgid "Accept incoming"
msgstr "Terima yang masuk"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "Terima versi masuk untuk konflik {0}"
@@ -2378,6 +2378,10 @@ msgstr "Keduanya"
msgid "Both agents end up reading everything in {keep}."
msgstr "Kedua agen akhirnya membaca semua yang ada di {keep}."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "Kedua versi identik. Memilih Terima yang sekarang membuat perlindungan OpenKnowledge tetap aktif, sehingga penyimpanan versi lama berikutnya akan ditolak lagi. Memilih Terima yang masuk menonaktifkan perlindungan tersebut."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "Cabang"
@@ -13640,6 +13644,14 @@ msgstr "Berkas ada di {trashNoun} Anda; pengawas berkas akan menyelaraskannya."
msgid "The file on disk, and the id agents use."
msgstr "Berkas di disk, dan id yang dipakai agen."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "Berkas dipulihkan ke versi yang lebih lama. Yang sekarang adalah versi yang dilindungi OpenKnowledge. Yang masuk adalah versi yang dipulihkan. Pilih versi yang ingin dipertahankan, lalu terapkan perubahan Anda."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "Berkas dipulihkan ke versi yang lebih lama. Buka berkas untuk memilih versi yang ingin dipertahankan."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "Folder di disk dan id yang dipakai agen untuk memanggil keterampilan ini."
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 4b662d218..3c24d580d 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -859,6 +859,9 @@
"AJ7_B2": ["새 테마 만들기"],
"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["워크트리"] }]],
"ALhMYW": ["터미널"],
+ "AMU00p": [
+ "두 버전이 동일합니다. 현재 항목 적용을 선택하면 OpenKnowledge의 보호가 켜진 상태로 유지되어 이전 버전의 또 다른 저장이 다시 거부됩니다. 수신 항목 적용을 선택하면 그 보호가 해제됩니다."
+ ],
"AN-UPd": [
".ok/local/config.yml의 terminal.shell은 Windows 절대 경로여야 합니다. 대신 사용 가능한 Windows 셸을 사용합니다."
],
@@ -2697,6 +2700,9 @@
"서버를 다시 시작할 수 없습니다. 다른 프로세스가 사용 중입니다. 이 프로젝트의 다른 OpenKnowledge 창을 닫은 후 다시 시도하세요."
],
"Xv_ijG": ["https://github.com/owner/repo 또는 owner/repo"],
+ "XwZiq2": [
+ "파일이 이전 버전으로 복원되었습니다. 현재 항목은 OpenKnowledge가 보호한 버전입니다. 수신 항목은 복원된 버전입니다. 유지할 버전을 선택한 다음 변경 사항을 적용하세요."
+ ],
"XzL7x7": ["계속 편집하려면 ", ["filePath"], "을(를) 다시 여세요."],
"Xzy0s0": ["현재 내용에서 ", ["fullLabel"], " 제거"],
"Y-Urt2": ["LaTeX 소스 문자열에서 KaTeX로 렌더링되는 블록 수식입니다."],
@@ -4316,6 +4322,7 @@
"q2kXMG": ["인라인 수식"],
"q3TWG7": ["휴지통으로 이동"],
"q3W2nd": ["댓글 추가에 실패했습니다: ", ["0"]],
+ "q3sP3v": ["파일이 이전 버전으로 복원되었습니다. 유지할 버전을 선택하려면 파일을 여세요."],
"q4YJl_": ["터미널 세션 종료(종료 코드 ", ["0"], ")."],
"q4efaG": [["filePath"], "이 이 스킬에서 제거되었습니다"],
"q5uZbJ": [
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 77c10a76f..3b2f873a4 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -1432,7 +1432,7 @@ msgstr "위"
msgid "Accept both"
msgstr "둘 다 적용"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "충돌 {0}에 두 버전 모두 적용"
@@ -1441,7 +1441,7 @@ msgstr "충돌 {0}에 두 버전 모두 적용"
msgid "Accept current"
msgstr "현재 항목 적용"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "충돌 {0}에 현재 버전 적용"
@@ -1450,7 +1450,7 @@ msgstr "충돌 {0}에 현재 버전 적용"
msgid "Accept incoming"
msgstr "수신 항목 적용"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "충돌 {0}에 수신 버전 적용"
@@ -2382,6 +2382,10 @@ msgstr "둘 다"
msgid "Both agents end up reading everything in {keep}."
msgstr "두 에이전트 모두 결국 {keep}의 모든 항목을 읽게 됩니다."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "두 버전이 동일합니다. 현재 항목 적용을 선택하면 OpenKnowledge의 보호가 켜진 상태로 유지되어 이전 버전의 또 다른 저장이 다시 거부됩니다. 수신 항목 적용을 선택하면 그 보호가 해제됩니다."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "브랜치"
@@ -13644,6 +13648,14 @@ msgstr "파일이 {trashNoun}에 있습니다. 파일 감시자가 상태를 조
msgid "The file on disk, and the id agents use."
msgstr "디스크의 파일과 에이전트가 사용하는 ID입니다."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "파일이 이전 버전으로 복원되었습니다. 현재 항목은 OpenKnowledge가 보호한 버전입니다. 수신 항목은 복원된 버전입니다. 유지할 버전을 선택한 다음 변경 사항을 적용하세요."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "파일이 이전 버전으로 복원되었습니다. 유지할 버전을 선택하려면 파일을 여세요."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "디스크의 폴더와 에이전트가 이 스킬을 호출할 때 사용하는 ID입니다."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 39f19b84d..550e29a9a 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -884,6 +884,9 @@
"AJ7_B2": ["Ćŕēàţē ńēŵ ţĥēḿē"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ŵōŕķţŕēē"], "other": ["ŵōŕķţŕēēś"] }]],
"ALhMYW": ["Ţēŕḿĩńàĺ"],
+ "AMU00p": [
+ "ßōţĥ vēŕśĩōńś àŕē ĩďēńţĩćàĺ. Ćĥōōśĩńĝ Àććēƥţ ćũŕŕēńţ ĺēàvēś ŌƥēńĶńōŵĺēďĝē'ś ƥŕōţēćţĩōń ōń, śō àńōţĥēŕ śàvē ōƒ ţĥē ōĺďēŕ vēŕśĩōń ĩś ŕēƒũśēď àĝàĩń. Ćĥōōśĩńĝ Àććēƥţ ĩńćōḿĩńĝ ţũŕńś ţĥàţ ƥŕōţēćţĩōń ōƒƒ."
+ ],
"AN-UPd": [
"ţēŕḿĩńàĺ.śĥēĺĺ ĩń .ōķ/ĺōćàĺ/ćōńƒĩĝ.ŷḿĺ ḿũśţ ƀē àń àƀśōĺũţē Ŵĩńďōŵś ƥàţĥ. Ũśĩńĝ àń àvàĩĺàƀĺē Ŵĩńďōŵś śĥēĺĺ ĩńśţēàď."
],
@@ -2790,6 +2793,9 @@
"Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ — àńōţĥēŕ ƥŕōćēśś ōŵńś ĩţ. Ǫũĩţ ōţĥēŕ ŌƥēńĶńōŵĺēďĝē ŵĩńďōŵś ƒōŕ ţĥĩś ƥŕōĴēćţ, ţĥēń ţŕŷ àĝàĩń."
],
"Xv_ijG": ["ĥţţƥś://ĝĩţĥũƀ.ćōḿ/ōŵńēŕ/ŕēƥō ōŕ ōŵńēŕ/ŕēƥō"],
+ "XwZiq2": [
+ "Ţĥē ƒĩĺē ŵàś ŕēśţōŕēď ţō àń ōĺďēŕ vēŕśĩōń. Ćũŕŕēńţ ĩś ţĥē vēŕśĩōń ŌƥēńĶńōŵĺēďĝē ƥŕōţēćţēď. Ĩńćōḿĩńĝ ĩś ţĥē ŕēśţōŕēď vēŕśĩōń. Ćĥōōśē ŵĥĩćĥ vēŕśĩōń ţō ķēēƥ, ţĥēń àƥƥĺŷ ŷōũŕ ćĥàńĝēś."
+ ],
"XzL7x7": ["Ŕēōƥēń ", ["filePath"], " ţō ķēēƥ ēďĩţĩńĝ."],
"Xzy0s0": ["Ŕēḿōvē ", ["fullLabel"], " ƒŕōḿ ćōńţēxţ"],
"Y-Urt2": ["ßĺōćķ ḿàţĥ ēǫũàţĩōń ŕēńďēŕēď ŵĩţĥ ĶàŢēX ƒŕōḿ à ĹàŢēX śōũŕćē śţŕĩńĝ."],
@@ -4486,6 +4492,9 @@
"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],
"q3TWG7": ["Ḿōvē ţō Ţŕàśĥ"],
"q3W2nd": ["Ćōũĺďń'ţ àďď ţĥàţ ćōḿḿēńţ: ", ["0"]],
+ "q3sP3v": [
+ "Ţĥē ƒĩĺē ŵàś ŕēśţōŕēď ţō àń ōĺďēŕ vēŕśĩōń. Ōƥēń ĩţ ţō ćĥōōśē ŵĥĩćĥ vēŕśĩōń ţō ķēēƥ."
+ ],
"q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],
"q4efaG": [["filePath"], " ĩś ńō ĺōńĝēŕ ĩń ţĥĩś śķĩĺĺ"],
"q5uZbJ": ["Ḿĩśśĩńĝ ƥàĝēś àŕē ĩńďēxēď ŵĥēń ŷōũ śēàŕćĥ. Śēàŕćĥ àĝàĩń ƒōŕ ƒũĺĺēŕ ŕēśũĺţś."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index e0fa206b3..a161ddb15 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1428,7 +1428,7 @@ msgstr ""
msgid "Accept both"
msgstr ""
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr ""
@@ -1437,7 +1437,7 @@ msgstr ""
msgid "Accept current"
msgstr ""
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr ""
@@ -1446,7 +1446,7 @@ msgstr ""
msgid "Accept incoming"
msgstr ""
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr ""
@@ -2378,6 +2378,10 @@ msgstr ""
msgid "Both agents end up reading everything in {keep}."
msgstr ""
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr ""
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr ""
@@ -13640,6 +13644,14 @@ msgstr ""
msgid "The file on disk, and the id agents use."
msgstr ""
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr ""
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr ""
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index e9158623f..35e9190c4 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -1041,6 +1041,9 @@
]
],
"ALhMYW": ["Terminal"],
+ "AMU00p": [
+ "As duas versões são idênticas. Escolher Aceitar atual mantém a proteção do OpenKnowledge ativada, então outro salvamento da versão mais antiga será recusado novamente. Escolher Aceitar recebido desativa essa proteção."
+ ],
"AN-UPd": [
"terminal.shell em .ok/local/config.yml deve ser um caminho absoluto do Windows. Um shell do Windows disponível será usado."
],
@@ -3208,6 +3211,9 @@
"Não deu para reiniciar o servidor — outro processo está com ele. Feche as outras janelas do OpenKnowledge deste projeto e tente de novo."
],
"Xv_ijG": ["https://github.com/dono/repo ou dono/repo"],
+ "XwZiq2": [
+ "O arquivo foi restaurado para uma versão mais antiga. Atual é a versão que o OpenKnowledge protegeu. Recebido é a versão restaurada. Escolha qual versão manter e aplique suas alterações."
+ ],
"XzL7x7": ["Reabra ", ["filePath"], " para continuar editando."],
"Xzy0s0": ["Remover ", ["fullLabel"], " do contexto"],
"Y-Urt2": ["Equação matemática em bloco renderizada com KaTeX a partir de código LaTeX."],
@@ -5079,6 +5085,9 @@
"q2kXMG": ["Fórmula em linha"],
"q3TWG7": ["Mover para o Lixo"],
"q3W2nd": ["Não deu para adicionar esse comentário: ", ["0"]],
+ "q3sP3v": [
+ "O arquivo foi restaurado para uma versão mais antiga. Abra-o para escolher qual versão manter."
+ ],
"q4YJl_": ["A sessão de terminal terminou (código de saída ", ["0"], ")."],
"q4efaG": [["filePath"], " não está mais nesta skill"],
"q5uZbJ": [
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 8429cbf50..7e3d059e8 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -1428,7 +1428,7 @@ msgstr "Acima"
msgid "Accept both"
msgstr "Aceitar ambos"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "Aceitar ambas as versões para o conflito {0}"
@@ -1437,7 +1437,7 @@ msgstr "Aceitar ambas as versões para o conflito {0}"
msgid "Accept current"
msgstr "Aceitar atual"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "Aceitar a versão atual para o conflito {0}"
@@ -1446,7 +1446,7 @@ msgstr "Aceitar a versão atual para o conflito {0}"
msgid "Accept incoming"
msgstr "Aceitar recebido"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "Aceitar a versão recebida para o conflito {0}"
@@ -2378,6 +2378,10 @@ msgstr "Ambos"
msgid "Both agents end up reading everything in {keep}."
msgstr "Os dois agentes passam a ler tudo o que está em {keep}."
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "As duas versões são idênticas. Escolher Aceitar atual mantém a proteção do OpenKnowledge ativada, então outro salvamento da versão mais antiga será recusado novamente. Escolher Aceitar recebido desativa essa proteção."
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "Ramo"
@@ -13640,6 +13644,14 @@ msgstr "O arquivo está no seu {trashNoun}; o observador de arquivos vai reconci
msgid "The file on disk, and the id agents use."
msgstr "O arquivo no disco, e o id que os agentes usam."
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "O arquivo foi restaurado para uma versão mais antiga. Atual é a versão que o OpenKnowledge protegeu. Recebido é a versão restaurada. Escolha qual versão manter e aplique suas alterações."
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "O arquivo foi restaurado para uma versão mais antiga. Abra-o para escolher qual versão manter."
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "A pasta no disco e o id que os agentes usam para invocar esta habilidade."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 01c0b8e59..b8e267601 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -900,6 +900,9 @@
"AJ7_B2": ["نئی تھیم بنائیں"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ورک ٹری"], "other": ["ورک ٹریز"] }]],
"ALhMYW": ["ٹرمینل"],
+ "AMU00p": [
+ "دونوں ورژن یکساں ہیں۔ موجودہ قبول کریں منتخب کرنے سے OpenKnowledge کا تحفظ فعال رہتا ہے، اس لیے پرانے ورژن کا ایک اور سیو دوبارہ مسترد کر دیا جائے گا۔ آنے والا قبول کریں منتخب کرنے سے وہ تحفظ بند ہو جاتا ہے۔"
+ ],
"AN-UPd": [
".ok/local/config.yml میں terminal.shell کا مکمل Windows پاتھ ہونا ضروری ہے۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"
],
@@ -2854,6 +2857,9 @@
"سرور دوبارہ نہیں چل سکا — کوئی اور عمل اس کا مالک ہے۔ اس پروجیکٹ کے لیے OpenKnowledge کی دیگر ونڈوز بند کریں، پھر دوبارہ کوشش کریں۔"
],
"Xv_ijG": ["https://github.com/owner/repo یا owner/repo"],
+ "XwZiq2": [
+ "فائل کو ایک پرانے ورژن پر بحال کیا گیا ہے۔ موجودہ وہ ورژن ہے جسے OpenKnowledge نے محفوظ رکھا۔ آنے والا بحال کیا گیا ورژن ہے۔ منتخب کریں کہ کون سا ورژن رکھنا ہے، پھر اپنی تبدیلیاں لاگو کریں۔"
+ ],
"XzL7x7": ["ترمیم جاری رکھنے کے لیے ", ["filePath"], " دوبارہ کھولیں۔"],
"Xzy0s0": [["fullLabel"], " کو سیاق سے ہٹائیں"],
"Y-Urt2": ["LaTeX سورس سٹرنگ سے KaTeX کے ذریعے رینڈر کی گئی بلاک ریاضی مساوات۔"],
@@ -4582,6 +4588,9 @@
"q2kXMG": ["اِن لائن ریاضی"],
"q3TWG7": ["ردی میں منتقل کریں"],
"q3W2nd": ["وہ تبصرہ شامل نہیں ہو سکا: ", ["0"]],
+ "q3sP3v": [
+ "فائل کو ایک پرانے ورژن پر بحال کیا گیا ہے۔ یہ منتخب کرنے کے لیے اسے کھولیں کہ کون سا ورژن رکھنا ہے۔"
+ ],
"q4YJl_": ["ٹرمینل کا سیشن ختم ہو گیا (خروج کوڈ ", ["0"], ")۔"],
"q4efaG": [["filePath"], " اب اس اسکل میں نہیں ہے"],
"q5uZbJ": [
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index d35eb16c9..80ab765a8 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -1432,7 +1432,7 @@ msgstr "اوپر"
msgid "Accept both"
msgstr "دونوں قبول کریں"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "کنفلکٹ {0} کے لیے دونوں ورژن قبول کریں"
@@ -1441,7 +1441,7 @@ msgstr "کنفلکٹ {0} کے لیے دونوں ورژن قبول کریں"
msgid "Accept current"
msgstr "موجودہ قبول کریں"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "کنفلکٹ {0} کے لیے موجودہ ورژن قبول کریں"
@@ -1450,7 +1450,7 @@ msgstr "کنفلکٹ {0} کے لیے موجودہ ورژن قبول کریں"
msgid "Accept incoming"
msgstr "آنے والا قبول کریں"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "کنفلکٹ {0} کے لیے آنے والا ورژن قبول کریں"
@@ -2382,6 +2382,10 @@ msgstr "دونوں"
msgid "Both agents end up reading everything in {keep}."
msgstr "دونوں ایجنٹس بالآخر {keep} کی ہر چیز پڑھیں گے۔"
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "دونوں ورژن یکساں ہیں۔ موجودہ قبول کریں منتخب کرنے سے OpenKnowledge کا تحفظ فعال رہتا ہے، اس لیے پرانے ورژن کا ایک اور سیو دوبارہ مسترد کر دیا جائے گا۔ آنے والا قبول کریں منتخب کرنے سے وہ تحفظ بند ہو جاتا ہے۔"
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "برانچ"
@@ -13644,6 +13648,14 @@ msgstr "فائل آپ کے {trashNoun} میں ہے؛ فائل واچر ہم آہ
msgid "The file on disk, and the id agents use."
msgstr "ڈسک پر موجود فائل، اور وہ شناخت جو ایجنٹس استعمال کرتے ہیں۔"
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "فائل کو ایک پرانے ورژن پر بحال کیا گیا ہے۔ موجودہ وہ ورژن ہے جسے OpenKnowledge نے محفوظ رکھا۔ آنے والا بحال کیا گیا ورژن ہے۔ منتخب کریں کہ کون سا ورژن رکھنا ہے، پھر اپنی تبدیلیاں لاگو کریں۔"
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "فائل کو ایک پرانے ورژن پر بحال کیا گیا ہے۔ یہ منتخب کرنے کے لیے اسے کھولیں کہ کون سا ورژن رکھنا ہے۔"
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "ڈسک پر موجود فولڈر اور وہ شناخت جو ایجنٹس اس مہارت کو بلانے کے لیے استعمال کرتے ہیں۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 5605df857..55ad10604 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -783,6 +783,9 @@
"AJ7_B2": ["创建新主题"],
"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["worktree"] }]],
"ALhMYW": ["终端"],
+ "AMU00p": [
+ "两个版本完全相同。选择“采用当前”会让 OpenKnowledge 的保护保持开启,因此再次保存较旧的版本仍会被拒绝。选择“采用传入”会关闭该保护。"
+ ],
"AN-UPd": [
".ok/local/config.yml 中的 terminal.shell 必须是 Windows 绝对路径,将改用可用的 Windows shell。"
],
@@ -2446,6 +2449,9 @@
"无法重启服务器——它被另一个进程占用。请关闭这个项目的其他 OpenKnowledge 窗口后重试。"
],
"Xv_ijG": ["https://github.com/owner/repo 或 owner/repo"],
+ "XwZiq2": [
+ "文件已恢复为较旧的版本。当前版本是 OpenKnowledge 保护的版本。传入版本是恢复的版本。请选择要保留的版本,然后应用更改。"
+ ],
"XzL7x7": ["重新打开 ", ["filePath"], " 以继续编辑。"],
"Xzy0s0": ["把 ", ["fullLabel"], " 从上下文中移除"],
"Y-Urt2": ["由 LaTeX 源码经 KaTeX 渲染的独立数学公式。"],
@@ -3921,6 +3927,7 @@
"q2kXMG": ["行内公式"],
"q3TWG7": ["移到废纸篓"],
"q3W2nd": ["无法添加那条评论:", ["0"]],
+ "q3sP3v": ["文件已恢复为较旧的版本。打开它以选择要保留的版本。"],
"q4YJl_": ["终端会话已结束(退出码 ", ["0"], ")。"],
"q4efaG": [["filePath"], " 已不在此技能中"],
"q5uZbJ": ["尚未建立索引的页面会在搜索时建立索引。再次搜索可获得更完整的结果。"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 19be3ab72..e9f8f72f3 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -1432,7 +1432,7 @@ msgstr "上方"
msgid "Accept both"
msgstr "两者都采用"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "对冲突 {0} 同时采用两个版本"
@@ -1441,7 +1441,7 @@ msgstr "对冲突 {0} 同时采用两个版本"
msgid "Accept current"
msgstr "采用当前"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "对冲突 {0} 采用当前版本"
@@ -1450,7 +1450,7 @@ msgstr "对冲突 {0} 采用当前版本"
msgid "Accept incoming"
msgstr "采用传入"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "对冲突 {0} 采用传入版本"
@@ -2382,6 +2382,10 @@ msgstr "两者"
msgid "Both agents end up reading everything in {keep}."
msgstr "两个智能体最终都会读取 {keep} 中的全部内容。"
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "两个版本完全相同。选择“采用当前”会让 OpenKnowledge 的保护保持开启,因此再次保存较旧的版本仍会被拒绝。选择“采用传入”会关闭该保护。"
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "分支"
@@ -13644,6 +13648,14 @@ msgstr "文件已在你的{trashNoun}中;文件监视器将进行同步。"
msgid "The file on disk, and the id agents use."
msgstr "磁盘上的文件,以及智能体使用的 id。"
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "文件已恢复为较旧的版本。当前版本是 OpenKnowledge 保护的版本。传入版本是恢复的版本。请选择要保留的版本,然后应用更改。"
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "文件已恢复为较旧的版本。打开它以选择要保留的版本。"
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "磁盘上的文件夹,以及智能体调用这个技能时使用的 id。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index a1d05299b..d562a4e47 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -785,6 +785,9 @@
"AJ7_B2": ["建立新主題"],
"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["worktree"] }]],
"ALhMYW": ["終端機"],
+ "AMU00p": [
+ "兩個版本完全相同。選擇「採用目前」會讓 OpenKnowledge 的保護保持開啟,因此再次儲存較舊的版本仍會被拒絕。選擇「採用傳入」會關閉該保護。"
+ ],
"AN-UPd": [
".ok/local/config.yml 中的 terminal.shell 必須是 Windows 絕對路徑,將改用可用的 Windows shell。"
],
@@ -2470,6 +2473,9 @@
"無法重新啟動伺服器——它被另一個處理程序佔用。請關閉這個專案的其他 OpenKnowledge 視窗,然後再試一次。"
],
"Xv_ijG": ["https://github.com/owner/repo 或 owner/repo"],
+ "XwZiq2": [
+ "檔案已還原為較舊的版本。目前版本是 OpenKnowledge 保護的版本。傳入版本是還原的版本。請選擇要保留的版本,然後套用變更。"
+ ],
"XzL7x7": ["重新開啟 ", ["filePath"], " 以繼續編輯。"],
"Xzy0s0": ["把 ", ["fullLabel"], " 從脈絡中移除"],
"Y-Urt2": ["由 LaTeX 原始碼經 KaTeX 顯示的獨立數學公式。"],
@@ -3951,6 +3957,7 @@
"q2kXMG": ["行內公式"],
"q3TWG7": ["移到垃圾桶"],
"q3W2nd": ["無法加上那則註解:", ["0"]],
+ "q3sP3v": ["檔案已還原為較舊的版本。開啟它以選擇要保留的版本。"],
"q4YJl_": ["終端機工作階段已結束(結束代碼 ", ["0"], ")。"],
"q4efaG": [["filePath"], " 已不在此技能中"],
"q5uZbJ": ["尚未建立索引的頁面會在搜尋時建立索引。再次搜尋可取得更完整的結果。"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 68c653eed..2a77a1654 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -1432,7 +1432,7 @@ msgstr "上方"
msgid "Accept both"
msgstr "兩者都採用"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept both versions for conflict {0}"
msgstr "對衝突 {0} 同時採用兩個版本"
@@ -1441,7 +1441,7 @@ msgstr "對衝突 {0} 同時採用兩個版本"
msgid "Accept current"
msgstr "採用目前"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept current version for conflict {0}"
msgstr "對衝突 {0} 採用目前版本"
@@ -1450,7 +1450,7 @@ msgstr "對衝突 {0} 採用目前版本"
msgid "Accept incoming"
msgstr "採用傳入"
-#. placeholder {0}: control.conflict.conflictIndex + 1
+#. placeholder {0}: conflictIndex + 1
#: src/components/ConflictView.tsx
msgid "Accept incoming version for conflict {0}"
msgstr "對衝突 {0} 採用傳入版本"
@@ -2382,6 +2382,10 @@ msgstr "兩者"
msgid "Both agents end up reading everything in {keep}."
msgstr "兩個代理最後都會讀到 {keep} 裡的全部內容。"
+#: src/components/ConflictView.tsx
+msgid "Both versions are identical. Choosing Accept current leaves OpenKnowledge's protection on, so another save of the older version is refused again. Choosing Accept incoming turns that protection off."
+msgstr "兩個版本完全相同。選擇「採用目前」會讓 OpenKnowledge 的保護保持開啟,因此再次儲存較舊的版本仍會被拒絕。選擇「採用傳入」會關閉該保護。"
+
#: src/components/share-metadata-rows.tsx
msgid "Branch"
msgstr "分支"
@@ -13644,6 +13648,14 @@ msgstr "檔案已在你的{trashNoun}中;檔案監看程式會進行同步。"
msgid "The file on disk, and the id agents use."
msgstr "磁碟上的檔案,以及代理使用的 id。"
+#: src/components/ConflictView.tsx
+msgid "The file was restored to an older version. Current is the version OpenKnowledge protected. Incoming is the restored version. Choose which version to keep, then apply your changes."
+msgstr "檔案已還原為較舊的版本。目前版本是 OpenKnowledge 保護的版本。傳入版本是還原的版本。請選擇要保留的版本,然後套用變更。"
+
+#: src/components/ConflictsSection.tsx
+msgid "The file was restored to an older version. Open it to choose which version to keep."
+msgstr "檔案已還原為較舊的版本。開啟它以選擇要保留的版本。"
+
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "磁碟上的資料夾,以及代理呼叫這個技能時使用的 id。"
diff --git a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
index fb5b738e2..b4bf82702 100644
--- a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
+++ b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
@@ -3,10 +3,9 @@ import { existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } fr
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
-import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
-import { createTestServer, pollUntil, type TestServer } from './test-harness';
+import { createTestClient, createTestServer, pollUntil, type TestServer } from './test-harness';
const execFileAsync = promisify(execFile);
@@ -207,29 +206,15 @@ describe("POST /api/sync/resolve-conflict { strategy: 'content', content: '' }",
await server.cleanup();
});
- test("empty content NEVER produces a 500 with the misleading 'requires content parameter' detail", async () => {
+ test('explicit empty content keeps an empty file rather than deleting it', async () => {
const res = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file: 'foo.md', strategy: 'content', content: '' }),
});
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
-
- if (res.status === 500) {
- const detail = typeof body.detail === 'string' ? body.detail : '';
- expect(detail).not.toContain("strategy 'content' requires content parameter");
- }
-
- expect([200, 400]).toContain(res.status);
-
- if (res.status === 400) {
- const parsed = ProblemDetailsSchema.safeParse(body);
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(parsed.data.type).toBe('urn:ok:error:invalid-request');
- }
- }
+ expect(res.status).toBe(200);
+ expect(readFileSync(join(server.contentDir, 'foo.md'), 'utf-8')).toBe('');
});
});
@@ -288,4 +273,38 @@ describe('both-modified conflict — backward compatibility', () => {
const baseFile = readFileSync(join(server.contentDir, 'foo.md'), 'utf-8');
expect(baseFile).toContain('<<<<<<<');
});
+
+ test('resolves the selected empty live Y.Text instead of the nonempty Git ours stage', async () => {
+ const client = await createTestClient(server.port, 'foo');
+ try {
+ client.doc.transact(() => client.ytext.delete(0, client.ytext.length));
+ await pollUntil(
+ () => server.instance.hocuspocus.documents.get('foo')?.getText('source').toString() === '',
+ );
+ const response = await fetch(
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=foo.md&source=ytext`,
+ );
+ expect(response.status).toBe(200);
+ const sides = (await response.json()) as { ours: string; conflictKind: string };
+ expect(sides.ours).toBe('');
+ expect(sides.conflictKind).toBe('git');
+ expect((await execFileAsync('git', ['show', ':2:foo.md'], { cwd: contentDir })).stdout).toBe(
+ 'ours\n',
+ );
+ const resolved = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ file: 'foo.md', strategy: 'content', content: sides.ours }),
+ });
+ expect(resolved.status).toBe(200);
+ expect(existsSync(join(contentDir, 'foo.md'))).toBe(true);
+ expect(readFileSync(join(contentDir, 'foo.md'), 'utf-8')).toBe('');
+ expect(
+ (await execFileAsync('git', ['show', 'HEAD:foo.md'], { cwd: contentDir })).stdout,
+ ).toBe('');
+ expect(client.ytext.toString()).toBe('');
+ } finally {
+ await client.cleanup();
+ }
+ });
});
diff --git a/packages/app/tests/integration/durable-store-snapshot.test.ts b/packages/app/tests/integration/durable-store-snapshot.test.ts
new file mode 100644
index 000000000..fd184943d
--- /dev/null
+++ b/packages/app/tests/integration/durable-store-snapshot.test.ts
@@ -0,0 +1,41 @@
+import { readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, expect, test } from 'vitest';
+import { agentWriteMd, createTestServer, readTestDoc, type TestServer } from './test-harness';
+
+let server: TestServer | undefined;
+let contentDir: string | undefined;
+
+afterEach(async () => {
+ await server?.cleanup();
+ server = undefined;
+ if (contentDir) rmSync(contentDir, { recursive: true, force: true });
+ contentDir = undefined;
+});
+
+test('HTTP save acknowledges a snapshot containing the new base and displaced version before restart', async () => {
+ server = await createTestServer({ keepContentDir: true, debounce: 50, maxDebounce: 200 });
+ contentDir = server.contentDir;
+ const docName = 'durable-store';
+ await agentWriteMd(server.port, 'original body\n', { docName, position: 'replace' });
+ const original = readTestDoc(contentDir, docName);
+
+ await agentWriteMd(server.port, 'acknowledged addition\n', { docName, position: 'append' });
+
+ const acknowledged = readTestDoc(contentDir, docName);
+ expect(acknowledged).toContain('acknowledged addition');
+ expect(server.instance.durabilityState.getReconciledBase(docName)).toBe(acknowledged);
+ expect(server.instance.durabilityState.isDisplacedVersion(docName, original)).toBe(true);
+ const snapshot = readFileSync(
+ join(server.instance.lockDir, 'stale-external-writes.json'),
+ 'utf8',
+ );
+ expect(snapshot).toContain('acknowledged addition');
+ await server.cleanup();
+ server = undefined;
+ server = await createTestServer({ contentDir, keepContentDir: true });
+
+ expect(server.instance.durabilityState.getReconciledBase(docName)).toBe(acknowledged);
+ expect(server.instance.durabilityState.isDisplacedVersion(docName, original)).toBe(true);
+ expect(readTestDoc(contentDir, docName)).toBe(acknowledged);
+});
diff --git a/packages/app/tests/integration/stale-external-write-http.test.ts b/packages/app/tests/integration/stale-external-write-http.test.ts
new file mode 100644
index 000000000..234aea966
--- /dev/null
+++ b/packages/app/tests/integration/stale-external-write-http.test.ts
@@ -0,0 +1,129 @@
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { AgentWriteBatchSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
+import { writeTracker } from '../../../server/src/file-watcher';
+import { contentHash } from '../../../server/src/version-hash';
+import {
+ agentWriteMd,
+ createTestServer,
+ getServerState,
+ pollUntil,
+ type TestServer,
+} from './test-harness';
+
+const APPLIED_MARKER = 'applied-before-final-disk-read';
+let server: TestServer | undefined;
+let projectDir: string | undefined;
+
+afterEach(async () => {
+ await server?.cleanup();
+ server = undefined;
+ if (projectDir) rmSync(projectDir, { recursive: true, force: true });
+ projectDir = undefined;
+});
+
+async function prepareRace(extension: '.md' | '.mdx') {
+ projectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-stale-http-')));
+ const contentDir = join(projectDir, 'notes');
+ mkdirSync(contentDir);
+ const docName = `race-${randomUUID()}`;
+ const file = `${docName}${extension}`;
+ const path = join(contentDir, file);
+ writeFileSync(path, '# Original\n\noriginal-body\n');
+ const target = await createTestServer({ contentDir, projectDir, debounce: 50, maxDebounce: 200 });
+ server = target;
+ const stale = readFileSync(path, 'utf-8');
+ await agentWriteMd(target.port, 'acknowledged-body\n', { docName, position: 'append' });
+ await pollUntil(
+ () => !writeTracker.get(path)?.some((entry) => entry.hash === contentHash(stale)),
+ );
+ const source = getServerState(target, docName)?.ytext;
+ if (!source) throw new Error('Expected a loaded document after the acknowledged write');
+ const restoreAfterEdit = () => {
+ if (!source.toString().includes(APPLIED_MARKER)) return;
+ source.unobserve(restoreAfterEdit);
+ writeFileSync(path, stale);
+ };
+ source.observe(restoreAfterEdit);
+ return { target, docName, file: `notes/${file}`, path, stale, source };
+}
+
+function expectRetainedEdit(race: Awaited<ReturnType<typeof prepareRace>>): void {
+ expect(readFileSync(race.path, 'utf-8')).toBe(race.stale);
+ expect(race.source.toString()).toContain(APPLIED_MARKER);
+ expect(race.source.toString()).toContain('acknowledged-body');
+ expect(
+ race.target.instance.durabilityState.getStaleExternalWrite(race.docName)?.retainedContent,
+ ).toBe(race.source.toString());
+ expect(
+ readFileSync(join(race.target.instance.lockDir, 'stale-external-writes.json'), 'utf-8'),
+ ).toContain(APPLIED_MARKER);
+}
+
+function expectStaleDetails(error: unknown, file: string): void {
+ expect(error).toMatchObject({
+ type: 'urn:ok:error:stale-external-write',
+ title: 'Edit retained; disk write blocked by a stale external-write conflict.',
+ detail: expect.stringContaining('recovery snapshot'),
+ file,
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ });
+ expect(error).toMatchObject({ detail: expect.stringContaining('Do not repeat this edit') });
+}
+
+describe('stale external write discovered by the final HTTP disk flush', () => {
+ test.each(['.md', '.mdx'] as const)(
+ 'single write returns actionable conflict details for %s',
+ async (extension) => {
+ const race = await prepareRace(extension);
+ const response = await fetch(`${race.target.baseUrl}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName: race.docName,
+ markdown: `${APPLIED_MARKER}\n`,
+ position: 'append',
+ }),
+ });
+ expect(response.status).toBe(409);
+ expect(response.headers.get('content-type')).toBe('application/problem+json');
+ const body: unknown = await response.json();
+ expect(ProblemDetailsSchema.safeParse(body).success).toBe(true);
+ expectStaleDetails(body, race.file);
+ expectRetainedEdit(race);
+ const conflicts = await (await fetch(`${race.target.baseUrl}/api/sync/conflicts`)).json();
+ expect(conflicts.conflicts).toContainEqual(expect.objectContaining({ file: race.file }));
+ },
+ );
+
+ test('batch retains per-document conflict details and independent successful writes', async () => {
+ const race = await prepareRace('.mdx');
+ const otherDoc = `other-${randomUUID()}`;
+ const response = await fetch(`${race.target.baseUrl}/api/agent-write-batch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docs: [
+ { docName: race.docName, markdown: `${APPLIED_MARKER}\n`, position: 'append' },
+ { docName: otherDoc, markdown: '# Independent\n', position: 'replace' },
+ ],
+ }),
+ });
+ expect(response.status).toBe(200);
+ const body = AgentWriteBatchSuccessSchema.parse(await response.json());
+ expect(body.written).toBe(1);
+ expect(body.failed).toBe(1);
+ const failed = body.results[0];
+ expect(failed.status).toBe('error');
+ if (failed.status !== 'error') throw new Error('Expected the restored document to conflict');
+ expectStaleDetails(failed.error, race.file);
+ expect(body.results[1]).toMatchObject({ status: 'written', docName: otherDoc });
+ expect(readFileSync(join(race.target.contentDir, `${otherDoc}.md`), 'utf-8')).toBe(
+ '# Independent\n',
+ );
+ expectRetainedEdit(race);
+ });
+});
diff --git a/packages/app/tests/integration/stale-external-write-rollback.test.ts b/packages/app/tests/integration/stale-external-write-rollback.test.ts
new file mode 100644
index 000000000..ea99b4159
--- /dev/null
+++ b/packages/app/tests/integration/stale-external-write-rollback.test.ts
@@ -0,0 +1,585 @@
+import { randomUUID } from 'node:crypto';
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { DocumentDurabilityStateError } from '../../../server/src/document-durability-state';
+import { writeTracker } from '../../../server/src/file-watcher';
+import { contentHash } from '../../../server/src/version-hash';
+import {
+ agentWriteMd,
+ createTestClient,
+ createTestServer,
+ getServerState,
+ pollUntil,
+ readTestDoc,
+ type TestServer,
+ wait,
+} from './test-harness';
+
+const ACK_MARKER = 'ACK-APPEND-MARKER';
+const STALE_WRITE_DELAY_MS = 200;
+
+let server: TestServer | undefined;
+let ownedProjectDir: string | undefined;
+
+afterEach(async () => {
+ if (server) {
+ await server.cleanup();
+ server = undefined;
+ }
+ if (ownedProjectDir) {
+ rmSync(ownedProjectDir, { recursive: true, force: true });
+ ownedProjectDir = undefined;
+ }
+});
+
+async function acknowledgeWrite(
+ target: TestServer,
+ docName: string,
+): Promise<{ stale: string; acknowledged: string }> {
+ await agentWriteMd(
+ target.port,
+ '---\ntags: [stale-write-test]\n---\n\n# Doc\n\noriginal-body\n',
+ { docName, position: 'replace' },
+ );
+ await pollUntil(() => readTestDoc(target.contentDir, docName).includes('original-body'));
+ const stale = readTestDoc(target.contentDir, docName);
+ await agentWriteMd(target.port, `${ACK_MARKER}\n`, { docName, position: 'append' });
+ await pollUntil(() => readTestDoc(target.contentDir, docName).includes(ACK_MARKER));
+ const file = join(target.contentDir, `${docName}.md`);
+ await pollUntil(
+ () => !writeTracker.get(file)?.some((entry) => entry.hash === contentHash(stale)),
+ );
+ return { stale, acknowledged: readTestDoc(target.contentDir, docName) };
+}
+
+async function restoreStale(target: TestServer, docName: string, stale: string): Promise<void> {
+ writeFileSync(join(target.contentDir, `${docName}.md`), stale, 'utf-8');
+ await pollUntil(
+ () => target.instance.durabilityState.getStaleExternalWrite(docName) !== undefined,
+ );
+}
+
+async function resolveConflict(
+ target: TestServer,
+ file: string,
+ strategy: string,
+ content?: string,
+): Promise<Response> {
+ return fetch(`${target.baseUrl}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ file, strategy, content }),
+ });
+}
+
+async function unloadDocument(target: TestServer, docName: string): Promise<void> {
+ await target.instance.sessionManager.closeAllForDoc(docName);
+ const hocuspocus = target.instance.hocuspocus;
+ const document = hocuspocus.documents.get(docName);
+ if (!document) throw new Error(`document ${docName} not loaded`);
+ const shouldUnload = hocuspocus.shouldUnloadDocument;
+ hocuspocus.shouldUnloadDocument = (candidate) =>
+ candidate === document || shouldUnload.call(hocuspocus, candidate);
+ try {
+ await hocuspocus.unloadDocument(document);
+ } finally {
+ hocuspocus.shouldUnloadDocument = shouldUnload;
+ }
+}
+
+function lifecycleOf(target: TestServer, docName: string): { status?: unknown; reason?: unknown } {
+ const document = target.instance.hocuspocus.documents.get(docName);
+ if (!document) throw new Error(`document ${docName} not loaded`);
+ const lifecycle = document.getMap('lifecycle');
+ return { status: lifecycle.get('status'), reason: lifecycle.get('reason') };
+}
+
+describe('stale external write does not roll back an acknowledged agent write', () => {
+ test.each([false, true])(
+ 'resolves nonempty stale sides to an explicit empty file (unloaded=%s)',
+ async (unloaded) => {
+ server = await createTestServer();
+ const docName = 'explicit-empty';
+ const { stale } = await acknowledgeWrite(server, docName);
+ await restoreStale(server, docName, stale);
+ if (unloaded) await unloadDocument(server, docName);
+ const response = await resolveConflict(server, `${docName}.md`, 'content', '');
+ expect(response.status).toBe(200);
+ expect(existsSync(join(server.contentDir, `${docName}.md`))).toBe(true);
+ expect(readTestDoc(server.contentDir, docName)).toBe('');
+ expect(server.instance.durabilityState.getStaleExternalWrite(docName)).toBeUndefined();
+ const client = await createTestClient(server.port, docName);
+ try {
+ expect(client.ytext.toString()).toBe('');
+ } finally {
+ await client.cleanup();
+ }
+ },
+ );
+ test('a corrupt recovery snapshot stops startup with actionable diagnostics and preserves bytes', async () => {
+ ownedProjectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-stale-boot-')));
+ const snapshot = join(ownedProjectDir, '.ok', 'local', 'stale-external-writes.json');
+ mkdirSync(join(ownedProjectDir, '.ok', 'local'), { recursive: true });
+ const raw = '{protected edits, truncated';
+ writeFileSync(snapshot, raw);
+ await expect(
+ createTestServer({ contentDir: ownedProjectDir, configHomedirOverride: ownedProjectDir }),
+ ).rejects.toThrow(DocumentDurabilityStateError);
+ expect(readFileSync(snapshot, 'utf-8')).toBe(raw);
+ });
+
+ test('a shareable template stale conflict can be listed, read and resolved', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = '.ok/templates/stale-template';
+ const file = `${docName}.md`;
+ mkdirSync(join(server.contentDir, '.ok', 'templates'), { recursive: true });
+ writeFileSync(join(server.contentDir, file), 'rejected\n');
+ const state = server.instance.durabilityState;
+ state.setReconciledBase(docName, 'acknowledged\n');
+ state.recordStaleExternalWrite(docName, 'rejected\n');
+ const list = await (await fetch(`${server.baseUrl}/api/sync/conflicts`)).json();
+ expect(list.conflicts).toContainEqual(expect.objectContaining({ file }));
+ const response = await fetch(
+ `${server.baseUrl}/api/sync/conflict-content?file=${encodeURIComponent(file)}`,
+ );
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ ours: 'acknowledged\n', theirs: 'rejected\n' });
+ expect((await resolveConflict(server, file, 'mine')).status).toBe(200);
+ expect(readFileSync(join(server.contentDir, file), 'utf-8')).toBe('acknowledged\n');
+ expect(state.getStaleExternalWrite(docName)).toBeUndefined();
+ });
+
+ test('an unloaded late-write snapshot exposes and restores the retained candidate', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `retained-${randomUUID()}`;
+ const state = server.instance.durabilityState;
+ const retained = 'acknowledged\n\nnext edit retained\n';
+ writeFileSync(join(server.contentDir, `${docName}.md`), 'rejected\n');
+ state.setReconciledBase(docName, 'acknowledged\n');
+ state.recordStaleExternalWrite(docName, 'rejected\n', retained);
+ const sides = await (
+ await fetch(`${server.baseUrl}/api/sync/conflict-content?file=${docName}.md`)
+ ).json();
+ expect(sides.ours).toBe(retained);
+ expect((await resolveConflict(server, `${docName}.md`, 'mine')).status).toBe(200);
+ expect(readTestDoc(server.contentDir, docName)).toBe(retained);
+ });
+ test.each(['mine', 'content'])(
+ 'a repeated stale save after %s remains protected',
+ async (strategy) => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `repeat-${randomUUID()}`;
+ const { stale, acknowledged } = await acknowledgeWrite(server, docName);
+ await restoreStale(server, docName, stale);
+ expect((await resolveConflict(server, `${docName}.md`, strategy, acknowledged)).status).toBe(
+ 200,
+ );
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+ await restoreStale(server, docName, stale);
+ expect(lifecycleOf(server, docName).status).toBe('conflict');
+ expect(getServerState(server, docName)?.ytext.toString()).toBe(acknowledged);
+ },
+ );
+
+ test.each(['theirs', 'delete'])(
+ '%s resolves the stale conflict and updates disk and lifecycle',
+ async (strategy) => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `resolve-${randomUUID()}`;
+ const { stale } = await acknowledgeWrite(server, docName);
+ await restoreStale(server, docName, stale);
+ expect((await resolveConflict(server, `${docName}.md`, strategy)).status).toBe(200);
+ expect(server.instance.durabilityState.listStaleExternalWrites()).toEqual([]);
+ expect(server.instance.durabilityState.isDisplacedVersion(docName, stale)).toBe(false);
+ if (strategy === 'delete') {
+ expect(existsSync(join(server.contentDir, `${docName}.md`))).toBe(false);
+ expect(lifecycleOf(server, docName).status).toBe('deleted-upstream');
+ const tags = await (await fetch(`${server.baseUrl}/api/tags/stale-write-test`)).json();
+ expect(tags.docs.map((entry: { docName: string }) => entry.docName)).not.toContain(docName);
+ } else {
+ expect(readTestDoc(server.contentDir, docName)).toBe(stale);
+ expect(getServerState(server, docName)?.ytext.toString()).toBe(stale);
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+ }
+ },
+ );
+
+ test('an unloaded stale write is listed, and delete then restore starts fresh', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `unloaded-${randomUUID()}`;
+ const { stale, acknowledged } = await acknowledgeWrite(server, docName);
+ await unloadDocument(server, docName);
+ await restoreStale(server, docName, stale);
+ expect(server.instance.hocuspocus.documents.has(docName)).toBe(false);
+ const conflicts = await (await fetch(`${server.baseUrl}/api/sync/conflicts`)).json();
+ expect(conflicts.conflicts).toContainEqual(expect.objectContaining({ file: `${docName}.md` }));
+ const sides = await (
+ await fetch(`${server.baseUrl}/api/sync/conflict-content?file=${docName}.md`)
+ ).json();
+ expect(sides.ours).toBe(acknowledged);
+ unlinkSync(join(server.contentDir, `${docName}.md`));
+ await pollUntil(
+ () => server?.instance.durabilityState.getReconciledBase(docName) === undefined,
+ );
+ expect(server.instance.durabilityState.listStaleExternalWrites()).toEqual([]);
+ writeFileSync(join(server.contentDir, `${docName}.md`), stale, 'utf-8');
+ const client = await createTestClient(server.port, docName);
+ try {
+ expect(client.ytext.toString()).toBe(stale);
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+ expect(server.instance.durabilityState.getReconciledBase(docName)).toBe(stale);
+ await pollUntil(async () => {
+ const tags = await (await fetch(`${server?.baseUrl}/api/tags/stale-write-test`)).json();
+ return tags.docs.some((entry: { docName: string }) => entry.docName === docName);
+ });
+ } finally {
+ await client.cleanup();
+ }
+ });
+
+ test('conflict paths round-trip when content is a project subdirectory', async () => {
+ ownedProjectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-stale-subdir-')));
+ const contentDir = join(ownedProjectDir, 'notes');
+ mkdirSync(contentDir);
+ server = await createTestServer({
+ contentDir,
+ projectDir: ownedProjectDir,
+ debounce: 50,
+ maxDebounce: 200,
+ });
+ const docName = `subdir-${randomUUID()}`;
+ const { stale } = await acknowledgeWrite(server, docName);
+ await restoreStale(server, docName, stale);
+ const list = await (await fetch(`${server.baseUrl}/api/sync/conflicts`)).json();
+ const file = `notes/${docName}.md`;
+ expect(list.conflicts).toContainEqual(expect.objectContaining({ file }));
+ const response = await fetch(
+ `${server.baseUrl}/api/sync/conflict-content?file=${encodeURIComponent(file)}`,
+ );
+ expect(response.status).toBe(200);
+ expect((await response.json()).ours).toContain(ACK_MARKER);
+ expect((await resolveConflict(server, file, 'mine')).status).toBe(200);
+ expect(readTestDoc(contentDir, docName)).toContain(ACK_MARKER);
+ });
+
+ test('resolution preserves an in-tree symlink and restores a missing file from recorded theirs', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `alias-${randomUUID()}`;
+ const target = join(server.contentDir, `${docName}-target.md`);
+ const alias = join(server.contentDir, `${docName}.md`);
+ writeFileSync(target, 'stale\n');
+ symlinkSync(target, alias);
+ const state = server.instance.durabilityState;
+ state.setReconciledBase(docName, 'acknowledged\n');
+ state.recordDisplacedVersion(docName, 'stale\n');
+ state.recordStaleExternalWrite(docName, 'stale\n');
+ expect((await resolveConflict(server, `${docName}.md`, 'mine')).status).toBe(200);
+ expect(lstatSync(alias).isSymbolicLink()).toBe(true);
+ expect(readFileSync(target, 'utf-8')).toBe('acknowledged\n');
+ const missingDoc = `missing-${randomUUID()}`;
+ state.setReconciledBase(missingDoc, 'acknowledged\n');
+ state.recordStaleExternalWrite(missingDoc, 'stale\n');
+ expect((await resolveConflict(server, `${missingDoc}.md`, 'theirs')).status).toBe(200);
+ expect(readTestDoc(server.contentDir, missingDoc)).toBe('stale\n');
+ const danglingDoc = `dangling-${randomUUID()}`;
+ const danglingTarget = join(server.contentDir, `${danglingDoc}-target.md`);
+ const danglingAlias = join(server.contentDir, `${danglingDoc}.md`);
+ symlinkSync(danglingTarget, danglingAlias);
+ state.setReconciledBase(danglingDoc, 'acknowledged\n');
+ state.recordStaleExternalWrite(danglingDoc, 'stale\n');
+ expect((await resolveConflict(server, `${danglingDoc}.md`, 'theirs')).status).toBe(200);
+ expect(lstatSync(danglingAlias).isSymbolicLink()).toBe(true);
+ expect(readFileSync(danglingTarget, 'utf-8')).toBe('stale\n');
+ expect(state.listStaleExternalWrites()).toEqual([]);
+ });
+
+ test('a failed disk write leaves the acknowledged document and conflict unchanged', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `directory-${randomUUID()}`;
+ const file = join(server.contentDir, `${docName}.md`);
+ mkdirSync(file);
+ const state = server.instance.durabilityState;
+ state.setReconciledBase(docName, 'acknowledged\n');
+ state.recordStaleExternalWrite(docName, 'stale\n');
+ const failed = await resolveConflict(server, `${docName}.md`, 'content', 'replacement\n');
+ expect(failed.status).toBe(500);
+ expect(state.getReconciledBase(docName)).toBe('acknowledged\n');
+ expect(state.getStaleExternalWrite(docName)?.diskContent).toBe('stale\n');
+ expect(lstatSync(file).isDirectory()).toBe(true);
+ rmSync(file, { recursive: true });
+ expect((await resolveConflict(server, `${docName}.md`, 'mine')).status).toBe(200);
+ expect(readTestDoc(server.contentDir, docName)).toBe('acknowledged\n');
+ });
+
+ test.each(['mine', 'delete'])(
+ 'a durability filesystem failure during %s keeps the conflict retryable',
+ async (strategy) => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `retry-${randomUUID()}`;
+ const { stale, acknowledged } = await acknowledgeWrite(server, docName);
+ await restoreStale(server, docName, stale);
+ const statePath = join(server.instance.lockDir, 'stale-external-writes.json');
+ renameSync(statePath, `${statePath}.backup`);
+ mkdirSync(statePath);
+ const failed = await resolveConflict(server, `${docName}.md`, strategy);
+ expect(failed.status).toBe(500);
+ expect((await failed.json()).detail).toBeTruthy();
+ expect(server.instance.durabilityState.getStaleExternalWrite(docName)).toBeDefined();
+ expect(lifecycleOf(server, docName).status).toBe('conflict');
+ if (strategy === 'mine') expect(readTestDoc(server.contentDir, docName)).toBe(acknowledged);
+ else expect(existsSync(join(server.contentDir, `${docName}.md`))).toBe(false);
+ rmSync(statePath, { recursive: true });
+ renameSync(`${statePath}.backup`, statePath);
+ expect((await resolveConflict(server, `${docName}.md`, 'mine')).status).toBe(200);
+ expect(server.instance.durabilityState.getStaleExternalWrite(docName)).toBeUndefined();
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+ },
+ );
+
+ test('resolution refuses an escaping symlink without modifying its target', async () => {
+ ownedProjectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-stale-outside-')));
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `escape-${randomUUID()}`;
+ const outside = join(ownedProjectDir, 'outside.md');
+ writeFileSync(outside, 'outside\n');
+ symlinkSync(outside, join(server.contentDir, `${docName}.md`));
+ const state = server.instance.durabilityState;
+ state.setReconciledBase(docName, 'acknowledged\n');
+ state.recordStaleExternalWrite(docName, 'stale\n');
+ for (const strategy of ['mine', 'theirs', 'content', 'delete']) {
+ const response = await resolveConflict(server, `${docName}.md`, strategy, 'replacement\n');
+ expect(response.status).toBe(400);
+ expect(await response.json()).toMatchObject({
+ status: 400,
+ type: 'urn:ok:error:path-escape',
+ });
+ expect(readFileSync(outside, 'utf-8')).toBe('outside\n');
+ expect(state.getStaleExternalWrite(docName)).toBeDefined();
+ }
+ });
+ test('exact pre-write bytes restored on disk keep the acknowledged append and conflict the doc', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const { port, contentDir } = server;
+ const docName = `stale-rollback-${randomUUID()}`;
+
+ await agentWriteMd(port, '# Doc\n\noriginal-body\n', { docName, position: 'replace' });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes('original-body'));
+ const staleBytes = readTestDoc(contentDir, docName);
+
+ await agentWriteMd(port, `${ACK_MARKER}\n`, { docName, position: 'append' });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes(ACK_MARKER));
+
+ await wait(STALE_WRITE_DELAY_MS);
+ writeFileSync(join(contentDir, `${docName}.md`), staleBytes, 'utf-8');
+
+ await pollUntil(
+ () => lifecycleOf(server as TestServer, docName).status === 'conflict',
+ 10_000,
+ 100,
+ 'stale-write lifecycle conflict',
+ );
+
+ expect(lifecycleOf(server, docName).reason).toBe('stale-external-write');
+ expect(getServerState(server, docName)?.ytext.toString()).toContain(ACK_MARKER);
+
+ const retry = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, markdown: 'retry\n', position: 'append' }),
+ });
+ expect(retry.status).toBe(409);
+
+ const conflictsResponse = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`);
+ const conflicts = (await conflictsResponse.json()) as {
+ conflicts: Array<{
+ file: string;
+ detectedAt: string;
+ conflictKind?: 'git' | 'stale-external-write';
+ }>;
+ };
+ expect(conflicts.conflicts).toContainEqual({
+ file: `${docName}.md`,
+ detectedAt: expect.any(String),
+ conflictKind: 'stale-external-write',
+ });
+
+ const contentResponse = await fetch(
+ `http://127.0.0.1:${port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
+ );
+ const sides = (await contentResponse.json()) as {
+ ours: string;
+ theirs: string;
+ conflictKind?: 'git' | 'stale-external-write';
+ };
+ expect(sides.ours).toContain(ACK_MARKER);
+ expect(sides.theirs).toBe(staleBytes);
+ expect(sides.conflictKind).toBe('stale-external-write');
+
+ for (const request of [
+ { file: docName, strategy: 'mine' },
+ {
+ file: docName,
+ strategy: 'content',
+ content: '<<<<<<< current\ndraft\n=======\nstill unresolved\n>>>>>>> incoming\n',
+ },
+ ]) {
+ const aliasResolution = await fetch(`http://127.0.0.1:${port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ });
+ expect(aliasResolution.status).toBe(404);
+ expect(await aliasResolution.json()).toMatchObject({
+ type: 'urn:ok:error:no-conflict-tracked',
+ });
+ expect(lifecycleOf(server, docName).status).toBe('conflict');
+ expect(readTestDoc(contentDir, docName)).toBe(staleBytes);
+ expect(getServerState(server, docName)?.ytext.toString()).toContain(ACK_MARKER);
+ }
+
+ const markerResolution = await fetch(`http://127.0.0.1:${port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ file: `${docName}.md`,
+ strategy: 'content',
+ content: '<<<<<<< current\ndraft\n=======\nstill unresolved\n>>>>>>> incoming\n',
+ }),
+ });
+ expect(markerResolution.status).toBe(422);
+ expect(lifecycleOf(server, docName).status).toBe('conflict');
+
+ const resolution = await fetch(`http://127.0.0.1:${port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ file: `${docName}.md`,
+ strategy: 'content',
+ content: sides.ours,
+ }),
+ });
+ expect(resolution.status).toBe(200);
+ expect(readTestDoc(contentDir, docName)).toContain(ACK_MARKER);
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+
+ writeFileSync(join(contentDir, `${docName}.md`), staleBytes, 'utf-8');
+ await pollUntil(
+ () => lifecycleOf(server as TestServer, docName).status === 'conflict',
+ 10_000,
+ 100,
+ 'repeated stale-write lifecycle conflict',
+ );
+
+ const repeatedResolution = await fetch(`http://127.0.0.1:${port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ file: `${docName}.md`,
+ strategy: 'mine',
+ }),
+ });
+ expect(repeatedResolution.status).toBe(200);
+
+ await agentWriteMd(port, 'retry-after-resolution\n', { docName, position: 'append' });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes('retry-after-resolution'));
+ });
+
+ test('content resolution accepts a Setext heading and preserves the submitted bytes', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const docName = `setext-resolution-${randomUUID()}`;
+ const { stale, acknowledged } = await acknowledgeWrite(server, docName);
+ await restoreStale(server, docName, stale);
+
+ const content = `Release notes\n=======\n\n${acknowledged}`;
+ const response = await resolveConflict(server, `${docName}.md`, 'content', content);
+
+ expect(response.status).toBe(200);
+ expect(readTestDoc(server.contentDir, docName)).toBe(content);
+ expect(getServerState(server, docName)?.ytext.toString()).toBe(content);
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+ expect(server.instance.durabilityState.getStaleExternalWrite(docName)).toBeUndefined();
+ });
+
+ test('an unrelated external edit still reconciles into the Y.Doc', async () => {
+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ const { port, contentDir } = server;
+ const docName = `unrelated-external-${randomUUID()}`;
+
+ await agentWriteMd(port, '# Doc\n\noriginal-body\n', { docName, position: 'replace' });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes('original-body'));
+
+ await agentWriteMd(port, `${ACK_MARKER}\n`, { docName, position: 'append' });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes(ACK_MARKER));
+
+ await wait(STALE_WRITE_DELAY_MS);
+ const settled = readTestDoc(contentDir, docName);
+ writeFileSync(join(contentDir, `${docName}.md`), `${settled}\nEXTERNAL-EDIT-LINE\n`, 'utf-8');
+
+ await pollUntil(
+ () =>
+ getServerState(server as TestServer, docName)
+ ?.ytext.toString()
+ .includes('EXTERNAL-EDIT-LINE') === true,
+ 10_000,
+ 100,
+ 'unrelated external edit applied',
+ );
+
+ expect(lifecycleOf(server, docName).status).toBeUndefined();
+ });
+
+ test('a restart keeps the acknowledged content and stale-write conflict', async () => {
+ server = await createTestServer({
+ debounce: 50,
+ maxDebounce: 200,
+ keepContentDir: true,
+ });
+ const docName = `stale-restart-${randomUUID()}`;
+ const contentDir = server.contentDir;
+
+ await agentWriteMd(server.port, '# Doc\n\noriginal-body\n', {
+ docName,
+ position: 'replace',
+ });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes('original-body'));
+ const staleBytes = readTestDoc(contentDir, docName);
+ await agentWriteMd(server.port, `${ACK_MARKER}\n`, { docName, position: 'append' });
+ await pollUntil(() => readTestDoc(contentDir, docName).includes(ACK_MARKER));
+ await wait(STALE_WRITE_DELAY_MS);
+ writeFileSync(join(contentDir, `${docName}.md`), staleBytes, 'utf-8');
+ await pollUntil(
+ () => lifecycleOf(server as TestServer, docName).status === 'conflict',
+ 10_000,
+ 100,
+ 'pre-restart stale-write lifecycle conflict',
+ );
+
+ await server.cleanup();
+ server = undefined;
+ server = await createTestServer({ contentDir, debounce: 50, maxDebounce: 200 });
+ const client = await createTestClient(server.port, docName);
+ try {
+ expect(client.ytext.toString()).toContain(ACK_MARKER);
+ expect(lifecycleOf(server, docName)).toEqual({
+ status: 'conflict',
+ reason: 'stale-external-write',
+ });
+ } finally {
+ await client.cleanup();
+ }
+ });
+});
diff --git a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
index d17b43825..6488e105a 100644
--- a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
+++ b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
@@ -350,52 +350,55 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
});
describe('GET /api/sync/conflict-content?source=ytext', () => {
- test('returns Y.Text snapshot when source=ytext and snapshot is marker-free', async () => {
- const docName = `fr3-source-ytext-${crypto.randomUUID()}`;
- const server = await setupServerWithDoc(docName, BASE_CONTENT);
- const client = await createTestClient(server.port, docName);
- cleanups.push(() => client.cleanup());
-
- await pollUntil(() => client.ytext.toString().includes('Base paragraph'));
-
- const lifecycle = client.doc.getMap('lifecycle');
- const filePath = join(server.contentDir, `${docName}.md`);
-
- writeFileSync(filePath, CONFLICT_MARKERS, 'utf-8');
- await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
-
- const midConflictMarker = '## Mid-conflict authored content\n';
- client.doc.transact(() => {
- client.ytext.insert(client.ytext.toString().length, midConflictMarker);
- });
-
- await pollUntil(() => {
- const serverDoc = server.instance.hocuspocus.documents.get(docName);
- return serverDoc?.getText('source').toString().includes(midConflictMarker) ?? false;
- }, 5000);
-
- const ytextRes = await fetch(
- `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
- );
- expect(ytextRes.ok).toBe(true);
- const ytextBody = (await ytextRes.json()) as {
- file: string;
- base: string;
- ours: string;
- theirs: string;
- lifecycleStatus: string | null;
- };
- expect(ytextBody.file).toBe(`${docName}.md`);
- expect(ytextBody.ours).toContain(midConflictMarker);
- expect(ytextBody.lifecycleStatus).toBe('conflict');
-
- const defaultRes = await fetch(
- `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md`,
- );
- expect(defaultRes.ok).toBe(true);
- const defaultBody = (await defaultRes.json()) as { ours: string };
- expect(defaultBody.ours).not.toContain(midConflictMarker);
- }, 30_000);
+ test.each(['## Mid-conflict authored content\n', 'Mid-conflict authored content\n=======\n'])(
+ 'returns Y.Text snapshot when source=ytext and snapshot has no unresolved block: %j',
+ async (midConflictMarker) => {
+ const docName = `fr3-source-ytext-${crypto.randomUUID()}`;
+ const server = await setupServerWithDoc(docName, BASE_CONTENT);
+ const client = await createTestClient(server.port, docName);
+ cleanups.push(() => client.cleanup());
+
+ await pollUntil(() => client.ytext.toString().includes('Base paragraph'));
+
+ const lifecycle = client.doc.getMap('lifecycle');
+ const filePath = join(server.contentDir, `${docName}.md`);
+
+ writeFileSync(filePath, CONFLICT_MARKERS, 'utf-8');
+ await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
+
+ client.doc.transact(() => {
+ client.ytext.insert(client.ytext.toString().length, midConflictMarker);
+ });
+
+ await pollUntil(() => {
+ const serverDoc = server.instance.hocuspocus.documents.get(docName);
+ return serverDoc?.getText('source').toString().includes(midConflictMarker) ?? false;
+ }, 5000);
+
+ const ytextRes = await fetch(
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
+ );
+ expect(ytextRes.ok).toBe(true);
+ const ytextBody = (await ytextRes.json()) as {
+ file: string;
+ base: string;
+ ours: string;
+ theirs: string;
+ lifecycleStatus: string | null;
+ };
+ expect(ytextBody.file).toBe(`${docName}.md`);
+ expect(ytextBody.ours).toContain(midConflictMarker);
+ expect(ytextBody.lifecycleStatus).toBe('conflict');
+
+ const defaultRes = await fetch(
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md`,
+ );
+ expect(defaultRes.ok).toBe(true);
+ const defaultBody = (await defaultRes.json()) as { ours: string };
+ expect(defaultBody.ours).not.toContain(midConflictMarker);
+ },
+ 30_000,
+ );
test('falls back to git-index ours when Y.Text snapshot contains conflict markers', async () => {
const docName = `fr3-marker-fallback-${crypto.randomUUID()}`;
diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.ts
index b0264e013..5995e1966 100644
--- a/packages/cli/src/commands/start.test.ts
+++ b/packages/cli/src/commands/start.test.ts
@@ -16,7 +16,7 @@ import { basename, dirname, join, relative, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { idleShutdownToMs } from '@inkeep/open-knowledge-core';
import { type Config, ConfigSchema } from '@inkeep/open-knowledge-server';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
type BootedStartServer,
bootStartServer,
@@ -1177,6 +1177,40 @@ describe('startCommand — --mode flag wiring', () => {
return cmd;
}
+ test('reports a preserved corrupt recovery snapshot without an unhandled startup stack', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-start-corrupt-snapshot-'));
+ const snapshot = join(dir, '.ok', 'local', 'stale-external-writes.json');
+ mkdirSync(join(dir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(dir, '.ok', 'config.yml'), '');
+ writeFileSync(snapshot, '{protected edits, truncated');
+ const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(dir);
+ const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const exit = new Error('test process exit');
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
+ throw exit;
+ });
+ const originalTitle = process.title;
+ try {
+ await expect(
+ quietCommand().parseAsync(['--mode', 'browser', '--only', 'server', '--no-open-browser'], {
+ from: 'user',
+ }),
+ ).rejects.toBe(exit);
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ const output = stderrSpy.mock.calls.flat().join('\n');
+ expect(output).toContain(snapshot);
+ expect(output).toContain('ok bug-report');
+ expect(output).not.toContain(' at ');
+ expect(readFileSync(snapshot, 'utf-8')).toBe('{protected edits, truncated');
+ } finally {
+ cwdSpy.mockRestore();
+ stderrSpy.mockRestore();
+ exitSpy.mockRestore();
+ process.title = originalTitle;
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('--mode <value> rejects values outside the browser|app enum (FR13)', () => {
const cmd = quietCommand();
expect(() => cmd.parse(['--mode', 'desktop'], { from: 'user' })).toThrow(
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 774b93107..976971afb 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -736,7 +736,10 @@ export async function runStartCommand(configArg: Config, opts: StartCommandOptio
process.exit(1);
}
- if (err instanceof serverModule.MissingOkConfigError) {
+ if (
+ err instanceof serverModule.MissingOkConfigError ||
+ err instanceof serverModule.DocumentDurabilityStateError
+ ) {
console.error(error(err.message));
process.exit(1);
}
diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.ts
index 0603b7dc8..66191c1c5 100644
--- a/packages/core/src/handoff/urn-ipc-registry.ts
+++ b/packages/core/src/handoff/urn-ipc-registry.ts
@@ -54,6 +54,7 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>([
'urn:ok:error:no-active-session',
'urn:ok:error:too-many-agent-sessions',
'urn:ok:error:disk-divergence',
+ 'urn:ok:error:stale-external-write',
'urn:ok:error:doc-in-conflict',
'urn:ok:error:no-conflict-tracked',
'urn:ok:error:unresolved-conflict-markers',
diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.ts
index a15c4e5ff..104427d34 100644
--- a/packages/core/src/schemas/api/_envelope.ts
+++ b/packages/core/src/schemas/api/_envelope.ts
@@ -77,6 +77,7 @@ export const ProblemTypeSchema = z.enum([
'urn:ok:error:no-active-session',
'urn:ok:error:too-many-agent-sessions',
'urn:ok:error:disk-divergence',
+ 'urn:ok:error:stale-external-write',
'urn:ok:error:doc-not-found',
'urn:ok:error:doc-already-exists',
'urn:ok:error:doc-not-open',
diff --git a/packages/core/src/schemas/api/sync-seed.test.ts b/packages/core/src/schemas/api/sync-seed.test.ts
index 8cb7f9b15..b0b34bc50 100644
--- a/packages/core/src/schemas/api/sync-seed.test.ts
+++ b/packages/core/src/schemas/api/sync-seed.test.ts
@@ -342,6 +342,52 @@ describe('ConflictEntrySchema', () => {
}).success,
).toBe(true);
});
+ test('preserves both recognized conflict origins', () => {
+ for (const conflictKind of ['git', 'stale-external-write']) {
+ const entry = {
+ file: 'docs/foo.md',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ conflictKind,
+ };
+ expect(ConflictEntrySchema.parse(entry)).toEqual(entry);
+ }
+ });
+ test.each([
+ { conflictKind: 'unknown', variant: 'working-tree', degradedField: 'conflictKind' },
+ { conflictKind: 'git', variant: 'unknown', degradedField: 'variant' },
+ ])('drops unrecognized $degradedField while preserving the entry', (metadata) => {
+ const entry = {
+ file: 'docs/foo.md',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ conflictKind: metadata.conflictKind,
+ variant: metadata.variant,
+ oursSha: 'a'.repeat(40),
+ theirsSha: 'b'.repeat(40),
+ baseSha: 'c'.repeat(40),
+ };
+ expect(ConflictEntrySchema.parse(entry)).toEqual({
+ ...entry,
+ [metadata.degradedField]: undefined,
+ });
+ });
+ test('still rejects missing or empty required fields with unrecognized metadata', () => {
+ for (const invalidFields of [
+ { file: '' },
+ { file: undefined },
+ { detectedAt: '' },
+ { detectedAt: undefined },
+ ]) {
+ expect(
+ ConflictEntrySchema.safeParse({
+ file: 'docs/foo.md',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ conflictKind: 'unknown',
+ variant: 'unknown',
+ ...invalidFields,
+ }).success,
+ ).toBe(false);
+ }
+ });
test('rejects empty file', () => {
expect(
ConflictEntrySchema.safeParse({ file: '', detectedAt: '2026-04-30T10:00:00.000Z' }).success,
@@ -363,9 +409,36 @@ describe('SyncConflictsSuccessSchema', () => {
test('rejects missing conflicts field', () => {
expect(SyncConflictsSuccessSchema.safeParse({}).success).toBe(false);
});
+ test('keeps every conflict when one entry has unrecognized metadata', () => {
+ const known = {
+ file: 'known.md',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ conflictKind: 'git',
+ variant: 'working-tree',
+ theirsSha: 'a'.repeat(40),
+ };
+ const unknown = {
+ file: 'unknown.md',
+ detectedAt: '2026-04-30T10:01:00.000Z',
+ conflictKind: 'unknown',
+ variant: 'unknown',
+ };
+ expect(SyncConflictsSuccessSchema.parse({ conflicts: [unknown, known] })).toEqual({
+ conflicts: [{ ...unknown, conflictKind: undefined, variant: undefined }, known],
+ });
+ });
});
describe('SyncResolveConflictRequestSchema', () => {
+ test('accepts explicit empty content but rejects omitted content', () => {
+ expect(
+ SyncResolveConflictRequestSchema.safeParse({ file: 'a.md', strategy: 'content', content: '' })
+ .success,
+ ).toBe(true);
+ expect(
+ SyncResolveConflictRequestSchema.safeParse({ file: 'a.md', strategy: 'content' }).success,
+ ).toBe(false);
+ });
test('parses {file, strategy:mine}', () => {
expect(
SyncResolveConflictRequestSchema.safeParse({ file: 'a.md', strategy: 'mine' }).success,
@@ -452,6 +525,32 @@ describe('SyncConflictContentSuccessSchema', () => {
}).success,
).toBe(true);
});
+ test('parses both conflict origins and rejects an unrecognized origin on the content response', () => {
+ for (const conflictKind of ['git', 'stale-external-write']) {
+ expect(
+ SyncConflictContentSuccessSchema.safeParse({
+ file: 'a.md',
+ base: 'b',
+ ours: 'o',
+ theirs: 't',
+ kind: 'both-modified',
+ lifecycleStatus: 'conflict',
+ conflictKind,
+ }).success,
+ ).toBe(true);
+ }
+ expect(
+ SyncConflictContentSuccessSchema.safeParse({
+ file: 'a.md',
+ base: 'b',
+ ours: 'o',
+ theirs: 't',
+ kind: 'both-modified',
+ lifecycleStatus: 'conflict',
+ conflictKind: 'unknown',
+ }).success,
+ ).toBe(false);
+ });
test('rejects missing kind (always-required discriminator)', () => {
expect(
SyncConflictContentSuccessSchema.safeParse({
diff --git a/packages/core/src/schemas/api/sync-seed.ts b/packages/core/src/schemas/api/sync-seed.ts
index dee704252..ca7ebe723 100644
--- a/packages/core/src/schemas/api/sync-seed.ts
+++ b/packages/core/src/schemas/api/sync-seed.ts
@@ -142,6 +142,8 @@ export const ConflictEntrySchema = z
.object({
file: z.string().min(1),
detectedAt: z.string().min(1),
+ conflictKind: z.enum(['git', 'stale-external-write']).optional().catch(undefined),
+ variant: z.literal('working-tree').optional().catch(undefined),
oursSha: z.string().optional(),
theirsSha: z.string().optional(),
baseSha: z.string().optional(),
@@ -163,8 +165,9 @@ export const SyncResolveConflictRequestSchema = z
content: z.string().optional(),
})
.loose()
- .refine((d) => d.strategy !== 'content' || (d.content !== undefined && d.content !== ''), {
- message: "content must be a non-empty string when strategy is 'content'",
+ .refine((d) => d.strategy !== 'content' || d.content !== undefined, {
+ message:
+ "content must be provided when strategy is 'content' (an empty string keeps an empty file)",
path: ['content'],
}) satisfies StandardSchemaV1;
export type SyncResolveConflictRequest = z.infer<typeof SyncResolveConflictRequestSchema>;
@@ -180,6 +183,7 @@ export const SyncConflictContentSuccessSchema = z
theirs: z.string(),
kind: z.enum(['both-modified', 'delete-modify', 'modify-delete']),
lifecycleStatus: z.string().nullable(),
+ conflictKind: z.enum(['git', 'stale-external-write']).optional(),
})
.loose() satisfies StandardSchemaV1;
export type SyncConflictContentSuccess = z.infer<typeof SyncConflictContentSuccessSchema>;
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index 5e6fa8d1a..d789159b0 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -27,7 +27,7 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th
- **Reads** — `exec` (primary; `cat`/`ls`/`grep`/… on a read-only filesystem, plus frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (doc versions), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for one call), `skills` (search + read: `query` → skills.sh; omit `name` to LIST managed (Project + Global); `name` READs one — by `name`+`scope`, never path), `config` (resolved config), `palette` (authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (browser preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors without a GitHub remote), `lint` (markdown-lint violations: `document` for one doc, omit for the project; `fix: true` with `document` auto-fixes fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one read-only report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`; caveats in `references/linking.md`). **Read `ran` on successful `lint`/`audit` results to see which enabled source families were selected. A family absent from `ran` was not checked, and `[]` means no checks were selected at all.**
- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (pass EXACTLY ONE target, nested under its address key): `write` (create/overwrite; `write({ skill: {…} })` authors a skill as a REAL folder at the project's default skill home — live immediately for that folder's agent), `edit` (body find/replace/frontmatter merge-patch; no asset), `delete` (remove), `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` for Project↔Global — history resets, re-`install`). Output mirrors the input key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (WHERE a `skill` lives: `add`/`remove` locations additively — editor ids, `agents`, or custom roots; `mode` + `convert` re-form ONLY the locations named; `source` moves the real folder. The source folder IS the skill — no "uninstall everywhere"; a skill dies only via `delete`), `import` (acquire a skill-dir into `add`'s locations; scripts never run), `checkpoint` (named version), and `restore_version` (roll back). A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with.
-- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution + commit; destructive). See `references/conflict-resolution.md`.
+- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution; commits for Git-index conflicts only; destructive). See `references/conflict-resolution.md`.
**Self-correcting on misuse:** constraints JSON Schema can't express ("exactly one target", "`find` needs a `replace`", body-XOR-frontmatter) return `isError: true` with a one-line corrective shape. Read it and retry with that shape; don't guess.
@@ -91,7 +91,7 @@ Every `.md` / `.mdx` needs YAML frontmatter — `title` + `description` required
## Conflict-aware writes
-Projects with GitHub sync may carry docs in merge-conflict state; mutating calls against them return RFC 9457 `urn:ok:error:doc-in-conflict` (409). Detect proactively — `exec("cat <path>.md")` returns `lifecycle: {status, reason} | null`; on `status === 'conflict'` switch to the `conflicts` + `resolve_conflict` flow. Full flow: `references/conflict-resolution.md`.
+Git or local stale-save conflicts freeze writes (409 `doc-in-conflict`). A flush-time 409 `stale-external-write` retains the edit in Yjs/recovery, not disk: resolve and re-read; never blindly retry an append. For `exec` lifecycle `status: 'conflict'`, load `references/conflict-resolution.md`.
## Anti-patterns — the top offenders
diff --git a/packages/server/assets/skills/project/references/conflict-resolution.md b/packages/server/assets/skills/project/references/conflict-resolution.md
index 590ee9456..e24d495bb 100644
--- a/packages/server/assets/skills/project/references/conflict-resolution.md
+++ b/packages/server/assets/skills/project/references/conflict-resolution.md
@@ -1,28 +1,34 @@
# Conflict-aware writes
-Projects with GitHub sync enabled may carry docs in a merge-conflict state. The MCP server refuses every mutating call against such a doc with a structured RFC 9457 response:
+Documents can be frozen by either a Git merge conflict or a `stale-external-write` conflict, even with GitHub sync disabled. A stale external write means the file was restored to the exact older version that OpenKnowledge had replaced with a newer acknowledged edit. This may be a stale editor save or an intentional revert. The protected content remains in Yjs and a local recovery snapshot while the disk file is frozen for resolution. The MCP server refuses every mutating call against either kind of conflicted doc with a structured RFC 9457 response:
```json
{
"type": "urn:ok:error:doc-in-conflict",
"title": "Document is in conflict.",
"status": 409,
- "detail": "The document is in a merge-conflict state. Call conflicts({ kind: 'content' }) + resolve_conflict before retrying.",
+ "detail": "The document is frozen by a Git or stale external-write conflict. Call conflicts({ kind: \"list\" }) to identify the kind, then conflicts({ kind: \"content\" }) + resolve_conflict before retrying.",
"file": "notes/sso.md",
"resolutionOptions": ["mine", "theirs", "content", "delete"]
}
```
-The gate covers `write`, `edit`, `delete`, `move`, `restore_version`, and agent undo (the doc-CRDT write spine; template/folder ops are fs-direct). You cannot route around it by writing content that byte-matches one of the merge stages — the gate refuses on lifecycle state, not on body equality.
+The gate covers `write`, `edit`, `delete`, `move`, `restore_version`, and agent undo on the document write spine, including live template writes. You cannot route around it by writing content that byte-matches one of the merge stages — the gate refuses on lifecycle state, not on body equality.
+
+A write that first detects the stale file during its final disk flush instead returns `urn:ok:error:stale-external-write` (409). This is a partial outcome: the edit reached collaborative state and the local recovery snapshot, but the disk write was skipped. Inspect the conflict, resolve it, and re-read the document before deciding whether to repeat the original operation. Blindly retrying an append can duplicate content already retained in `ours`.
+
+While such a pending edit is retained, further external saves do not discard it or automatically clear the conflict. Re-read the conflict before resolving: `theirs` can reflect a subsequent disk save while `ours` still preserves the pending edit.
**Detect proactively.** `exec("cat <path>.md")` always returns `lifecycle: {status, reason} | null` alongside the body. When `status === 'conflict'`, switch to the resolution flow before attempting any mutation.
**Resolution flow.** Three tools compose:
-1. `conflicts({ kind: 'list' })` → enumerate every doc currently tracked in conflict.
-2. `conflicts({ kind: 'content', file })` → returns `{ content: { base, ours, theirs, shape, lifecycleStatus } }` (the result nests under the `content` kind key). `ours` reflects the live Y.Text (what the human user sees in the editor) when the doc is loaded server-side and is marker-free; falls back to `git show :2:<file>` otherwise (e.g. after an editor reopen seeded markers into Y.Text).
-3. `resolve_conflict({ file, strategy, content? })` → write the chosen bytes and commit. Strategies: `mine` runs `git checkout --ours` (your committed stage 2), `theirs` runs `git checkout --theirs` (their stage 3), `content` writes the bytes you supply, `delete` runs `git rm` (for delete-modify / modify-delete shapes where a stage is missing).
+1. `conflicts({ kind: 'list' })` → enumerate every doc currently tracked in conflict. Each entry includes `conflictKind: 'git' | 'stale-external-write'`, and Git working-tree overlays also carry `variant: 'working-tree'`. The content response's `conflictKind: "git"` covers both Git-index conflicts and working-tree overlays; inspect the list entry to distinguish them, because the resolution mechanics below differ.
+2. `conflicts({ kind: 'content', file })` → returns `{ content: { base, ours, theirs, shape, lifecycleStatus, conflictKind } }` (the result nests under the `content` kind key). For Git conflicts, `ours` reflects the live Y.Text when loaded and marker-free, falling back to `git show :2:<file>` otherwise. For stale external writes, `ours` is the protected content, recovered from the local snapshot when unloaded, and `theirs` is the rejected older save. An intentional exact revert can trigger the same protection; choose `theirs` to confirm that revert.
+3. `resolve_conflict({ file, strategy, content? })` → write the chosen bytes. For Git-index conflicts, `mine` runs `git checkout --ours`, `theirs` runs `git checkout --theirs`, `content` writes the bytes you supply, and `delete` runs `git rm`; each stages the result and commits after the final tracked conflict clears. For Git working-tree overlays, `mine` keeps the working-tree file, `theirs` restores the pinned incoming blob, `content` writes the bytes you supply, and `delete` removes the file; nothing is staged and no resolution commit is created. For stale external writes, `mine` keeps the acknowledged Yjs content, `theirs` accepts the rejected disk version, `content` writes the bytes you supply, and `delete` removes the document; these local resolutions do not create a Git commit. For every kind, `content` accepts an explicit empty string, which keeps an empty file; omitting `content` is invalid.
`file` is a `.md` / `.mdx` path relative to the project dir (extension included) — mirrors the on-disk shape, not the extension-less `document` path used by other tools.
-The resolve operation is best-effort and NOT atomic: `git checkout --ours/--theirs && git add` may succeed but the subsequent `git commit --no-edit` can fail (pre-commit hook rejection, locked index). On commit failure the staged files are re-`git add`-ed back into the unmerged index and the tracked entry remains in `conflicts.json` — re-call `resolve_conflict` after the user clears the blocker.
+The resolve operation is best-effort and NOT atomic across disk, collaborative state, and indexes. A failed local resolution retains its recovery record for retry; re-read the conflict before retrying. For Git-index conflicts, `git checkout --ours/--theirs && git add` may succeed but the subsequent `git commit --no-edit` can fail (pre-commit hook rejection, locked index). On commit failure the file stays staged in git's index — the resolution itself is not undone — but the tracked entry is re-added to `conflicts.json`, so the write gate keeps refusing mutations against it; re-call `resolve_conflict` after the user clears the blocker. A working-tree overlay resolution attempts no commit; if it fails, its entry is added back to `conflicts.json` and can be retried directly.
+
+Local recovery data lives in `.ok/local/stale-external-writes.json`, with owner-only file permissions. If the server reports that snapshot as corrupt, unreadable, or incompatible, do not delete it or restart with empty state: it may hold the only copy of protected edits. Preserve the file, restore a known-good backup, and run `ok bug-report` from the project directory to collect diagnostics without starting the server; seek support if its edits need recovery. An unresolved conflict does not expire with the 30-minute displaced-hash window.
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index a0ee47c68..364e6ad56 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -211,7 +211,12 @@ import { CommentIndex } from './comments/comment-index.ts';
import { CommentService } from './comments/comment-service.ts';
import { CommentThreadStore } from './comments/thread-store.ts';
import { CONFIG_VALIDATION_REVERT_ORIGIN } from './config-edit-origin.ts';
-import { DocInConflictError, isDocInConflict, respondDocInConflict } from './conflict-errors.ts';
+import {
+ DocInConflictError,
+ isDocInConflict,
+ RESOLUTION_OPTIONS,
+ respondDocInConflict,
+} from './conflict-errors.ts';
import {
applySkillBundleFileDelete,
applySkillBundleFileRename,
@@ -335,6 +340,7 @@ import {
import { composeAndWriteRawBody, type PrecomputedParse, replaceRawBody } from './bridge-intake.ts';
import type { BridgeDeriveLossReporter } from './bridge-loss-detector.ts';
import { isConfigDoc, isLinkIndexExcludedDoc, isSystemDoc } from './cc1-broadcast.ts';
+import type { ResolveStrategy } from './conflict-storage.ts';
import {
isReservedProjectStatePath,
listManagedDocNamesUnderFolder,
@@ -1484,9 +1490,15 @@ export interface ApiExtensionOptions {
contentFilter?: ContentFilter;
installedAgentsProbe?: (scheme: InstalledAgentScheme) => Promise<boolean>;
forceUnloadDocument?: (document: Document) => Promise<void>;
+ resetDocumentDurability?: (docName: string) => void;
ready?: Promise<void>;
recentlyRemovedDocs?: RecentlyRemovedDocs;
serializeDoc?: (docName: string) => string | null;
+ resolveStaleExternalWrite?: (
+ file: string,
+ strategy: ResolveStrategy,
+ content?: string,
+ ) => Promise<boolean>;
evictManagedArtifactLkg?: (docName: string) => void;
semanticSearch?: SemanticSearchService;
getSemanticSimilarityFloor?: () => number | undefined;
@@ -1595,9 +1607,11 @@ export function createApiExtension(
contentFilter,
installedAgentsProbe,
forceUnloadDocument,
+ resetDocumentDurability,
ready,
recentlyRemovedDocs,
serializeDoc,
+ resolveStaleExternalWrite,
evictManagedArtifactLkg,
semanticSearch,
getSemanticSimilarityFloor,
@@ -1910,7 +1924,11 @@ export function createApiExtension(
});
}
- type FlushOutcome = { kind: 'failure'; failure: StoreFailure } | { kind: 'divergence' } | null;
+ type FlushOutcome =
+ | { kind: 'failure'; failure: StoreFailure }
+ | { kind: 'divergence' }
+ | { kind: 'stale-external-write' }
+ | null;
async function flushDiskAndDetectOutcome(docName: string): Promise<FlushOutcome> {
const debounceId = `onStoreDocument-${docName}`;
@@ -1920,6 +1938,9 @@ export function createApiExtension(
}
const failure = durabilityState.takeStoreFailure(docName);
if (failure) return { kind: 'failure', failure };
+ if (durabilityState.takeStaleExternalWriteFreeze(docName)) {
+ return { kind: 'stale-external-write' };
+ }
if (durabilityState.takeStoreDivergence(docName)) return { kind: 'divergence' };
return null;
}
@@ -1949,6 +1970,27 @@ export function createApiExtension(
);
}
+ function staleExternalWriteProblem(docName: string) {
+ return {
+ type: 'urn:ok:error:stale-external-write' as const,
+ title: 'Edit retained; disk write blocked by a stale external-write conflict.',
+ detail:
+ 'An older version was restored on disk. Your edit was applied and is retained in memory and in the recovery snapshot, but its Markdown disk write was skipped. Do not repeat this edit: inspect conflicts({ kind: "content" }) for this file and resolve_conflict, then re-read the document before making further changes.',
+ file:
+ durabilityState.getStaleExternalWrite(docName)?.file ??
+ relative(projectDir ?? contentDir, safeContentPath(docName, contentDir)).replaceAll(
+ '\\',
+ '/',
+ ),
+ resolutionOptions: RESOLUTION_OPTIONS,
+ } satisfies BatchEntryError;
+ }
+
+ function respondStaleExternalWrite(res: ServerResponse, handler: string, docName: string): void {
+ const { type, title, detail, ...extensions } = staleExternalWriteProblem(docName);
+ errorResponse(res, 409, type, title, { handler, detail, extensions });
+ }
+
function buildReconcileWarning(
reconcile: ReconcileBeforeWriteResult,
): DiskEditReconciledWarning | undefined {
@@ -3533,6 +3575,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'agent-write');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'agent-write', docName);
+ return;
+ }
flushDocToDisk(docName, 'agent-write');
onAgentWrite?.();
@@ -3722,6 +3768,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'agent-write-md');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'agent-write-md', resolvedDocName);
+ return;
+ }
flushDocToDisk(resolvedDocName, 'agent-write-md');
@@ -3829,7 +3879,7 @@ export function createApiExtension(
interface BatchErrorResult {
status: 'error';
docName: string;
- error: { type: BatchEntryError['type']; title: string; detail?: string };
+ error: BatchEntryError;
}
interface BatchWrittenResult {
status: 'written';
@@ -4054,6 +4104,8 @@ export function createApiExtension(
title:
'The document changed on disk after your edit was prepared; your edit was NOT applied. Re-read the document and retry.',
});
+ } else if (flushOutcome?.kind === 'stale-external-write') {
+ flushErrors.set(p.docName, staleExternalWriteProblem(p.docName));
} else {
flushErrors.set(p.docName, undefined);
}
@@ -4327,6 +4379,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'frontmatter-patch');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'frontmatter-patch', resolvedDocName);
+ return;
+ }
}
flushDocToDisk(resolvedDocName, 'frontmatter-patch');
}
@@ -4644,6 +4700,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'agent-patch');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'agent-patch', docName);
+ return;
+ }
flushDocToDisk(docName, 'agent-patch');
@@ -4829,6 +4889,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'agent-undo');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'agent-undo', docName);
+ return;
+ }
flushDocToGit(docName, 'agent-undo');
}
@@ -5050,6 +5114,7 @@ export function createApiExtension(
const doc = hocuspocus.documents.get(docName);
if (doc) await (forceUnloadDocument ?? hocuspocus.unloadDocument.bind(hocuspocus))(doc);
+ resetDocumentDurability?.(docName);
writeFileSync(filePath, '', 'utf-8');
await derivedDocumentIndex?.testOnly?.resetDocumentForTest(docName);
@@ -5439,6 +5504,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'rollback');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'rollback', docName);
+ return;
+ }
flushDocToGit(docName, 'rollback');
@@ -6988,6 +7057,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'skill-put');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'skill-put', docName);
+ return;
+ }
if (body.scope === 'project') {
attributeOkArtifactWrite(
@@ -8127,6 +8200,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'skill-file-put');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'skill-file-put', refDocName);
+ return;
+ }
} else {
const fsResult = applySkillBundleFileWrite({
skillsRoot: dirname(skillDirAbs),
@@ -9268,7 +9345,11 @@ export function createApiExtension(
body.scope === 'project'
? `${relative(inPlaceScanBase, skillDir).split(sep).join('/')}/SKILL`
: skillLiveDocName(body.scope, body.name);
- await flushDiskAndDetectOutcome(liveSkillDoc);
+ const liveSkillFlush = await flushDiskAndDetectOutcome(liveSkillDoc);
+ if (liveSkillFlush?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'skill-install', liveSkillDoc);
+ return;
+ }
const validity = validateSkillForInstall(skillDir, body.name, {
allowReservedName: isInternalBundleSkillName(body.name),
@@ -10939,6 +11020,10 @@ export function createApiExtension(
respondDiskDivergence(res, 'lint-fix');
return;
}
+ if (flushOutcome?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'lint-fix', resolvedDocName);
+ return;
+ }
flushDocToDisk(resolvedDocName, 'lint-fix');
try {
@@ -11262,10 +11347,12 @@ export function createApiExtension(
contentDir,
getPrincipal,
hocuspocus,
+ durabilityState,
log,
checkLocalOpSecurity,
getSyncEngine,
serializeDoc,
+ resolveStaleExternalWrite,
});
const shareRoutes = createShareRoutes({
projectDir,
@@ -11361,6 +11448,7 @@ export function createApiExtension(
flushDiskAndDetectOutcome,
respondPersistenceFailure,
respondDiskDivergence,
+ respondStaleExternalWrite,
registerWrittenDocInFileIndex,
captureAndCloseDocuments,
renameTrackedPathInGit,
diff --git a/packages/server/src/conflict-errors.test.ts b/packages/server/src/conflict-errors.test.ts
index eb8905a34..a8f6f38d5 100644
--- a/packages/server/src/conflict-errors.test.ts
+++ b/packages/server/src/conflict-errors.test.ts
@@ -66,7 +66,7 @@ describe('respondDocInConflict — slim RFC 9457 envelope', () => {
expect(body.title).toBe('Document is in conflict.');
expect(body.status).toBe(409);
expect(body.detail).toBe(
- 'The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',
+ 'The document is frozen by a Git or stale external-write conflict. Call conflicts({ kind: "list" }) to identify the kind, then conflicts({ kind: "content" }) + resolve_conflict before retrying.',
);
expect(body.file).toBe('docs/notes.md');
diff --git a/packages/server/src/conflict-errors.ts b/packages/server/src/conflict-errors.ts
index ad1b81b2a..58e329864 100644
--- a/packages/server/src/conflict-errors.ts
+++ b/packages/server/src/conflict-errors.ts
@@ -62,7 +62,7 @@ export function respondDocInConflict(
errorResponse(res, 409, 'urn:ok:error:doc-in-conflict', 'Document is in conflict.', {
handler,
detail:
- 'The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',
+ 'The document is frozen by a Git or stale external-write conflict. Call conflicts({ kind: "list" }) to identify the kind, then conflicts({ kind: "content" }) + resolve_conflict before retrying.',
extensions: {
file: err.file,
resolutionOptions: RESOLUTION_OPTIONS,
diff --git a/packages/server/src/conflict-resolution-input.ts b/packages/server/src/conflict-resolution-input.ts
new file mode 100644
index 000000000..8e570d11a
--- /dev/null
+++ b/packages/server/src/conflict-resolution-input.ts
@@ -0,0 +1,15 @@
+import { ConflictMarkersInContentError } from './conflict-errors.ts';
+import { containsUnresolvedConflictBlock } from './reconciliation.ts';
+
+export function requireConflictResolutionContent(
+ file: string,
+ content: string | undefined,
+): string {
+ if (content === undefined) {
+ throw new Error(`[conflicts] strategy 'content' requires content parameter`);
+ }
+ if (containsUnresolvedConflictBlock(content)) {
+ throw new ConflictMarkersInContentError({ file });
+ }
+ return content;
+}
diff --git a/packages/server/src/conflict-storage.test.ts b/packages/server/src/conflict-storage.test.ts
index 738d039f1..0dd49d0ff 100644
--- a/packages/server/src/conflict-storage.test.ts
+++ b/packages/server/src/conflict-storage.test.ts
@@ -1,11 +1,21 @@
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { ConflictMarkersInContentError } from './conflict-errors.ts';
import { type ConflictEntry, ConflictStore } from './conflict-storage.ts';
+import { getLogger } from './logger.ts';
let tmpDir = '';
let projectDir = '';
@@ -35,6 +45,37 @@ function readStore(): { version: number; branch: string; conflicts: ConflictEntr
return JSON.parse(readFileSync(storePath, 'utf-8'));
}
+describe('ConflictStore variant discipline', () => {
+ test('an unrecognized variant is reported once per load, not once per read', () => {
+ writeFileSync(
+ storePath,
+ JSON.stringify({
+ version: 1,
+ branch: 'main',
+ conflicts: [
+ { file: 'weird.md', detectedAt: '2026-09-08T10:00:00.000Z', variant: 'index' },
+ { file: 'ok.md', detectedAt: '2026-09-08T10:01:00.000Z', variant: 'working-tree' },
+ ],
+ }),
+ );
+ const warn = vi.spyOn(getLogger('conflict-storage'), 'warn').mockImplementation(() => {});
+ try {
+ const store = new ConflictStore(projectDir, 'main');
+ store.list();
+ store.list();
+ expect(warn.mock.calls.map(([payload]) => payload)).toEqual([
+ expect.objectContaining({
+ event: 'conflict-discriminator-unrecognized',
+ file: 'weird.md',
+ receivedVariant: 'index',
+ }),
+ ]);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
describe('ConflictStore CRUD', () => {
test('starts empty when no conflicts.json exists', () => {
const store = new ConflictStore(projectDir, 'main');
@@ -328,6 +369,38 @@ describe('ConflictStore resolveConflict()', () => {
});
describe('ConflictStore resolveConflict() — working-tree variant', () => {
+ test('rejects a content target replaced by an escaping symlink after ledger removal', async () => {
+ const { blobSha } = await seedOverlay('a.md', 'remote', 'local');
+ const target = join(projectDir, 'a.md');
+ const outside = join(tmpDir, 'outside.md');
+ writeFileSync(target, 'local');
+ writeFileSync(outside, 'private');
+ const store = new ConflictStore(projectDir, 'main');
+ store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));
+ const removeConflict = store.removeConflict.bind(store);
+ store.removeConflict = (file) => {
+ const result = removeConflict(file);
+ unlinkSync(target);
+ symlinkSync(outside, target);
+ return result;
+ };
+ await expect(store.resolveConflict('a.md', 'content', 'replacement')).rejects.toThrow(
+ /outside/,
+ );
+ expect(readFileSync(outside, 'utf-8')).toBe('private');
+ expect(store.hasConflicts()).toBe(true);
+ });
+
+ test('deleting a tracked symlink preserves its in-project content target', async () => {
+ const { blobSha } = await seedOverlay('real.md', 'remote', 'keep target');
+ symlinkSync('real.md', join(projectDir, 'link.md'));
+ const store = new ConflictStore(projectDir, 'main');
+ store.addConflict(makeEntry('link.md', { variant: 'working-tree', theirsSha: blobSha }));
+ await store.resolveConflict('link.md', 'delete');
+ expect(existsSync(join(projectDir, 'link.md'))).toBe(false);
+ expect(readFileSync(join(projectDir, 'real.md'), 'utf-8')).toBe('keep target');
+ });
+
async function seedOverlay(
file: string,
remote: string,
@@ -406,6 +479,19 @@ describe('ConflictStore resolveConflict() — working-tree variant', () => {
expect(await headSha()).toBe(before);
});
+ test("'content' with an empty string keeps an empty file without committing", async () => {
+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');
+ const store = new ConflictStore(projectDir, 'main');
+ store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));
+
+ await store.resolveConflict('a.md', 'content', '');
+
+ expect(existsSync(join(projectDir, 'a.md'))).toBe(true);
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('');
+ expect(store.count()).toBe(0);
+ expect(await headSha()).toBe(before);
+ });
+
test("'delete' honors the local deletion without committing", async () => {
const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');
const store = new ConflictStore(projectDir, 'main');
diff --git a/packages/server/src/conflict-storage.ts b/packages/server/src/conflict-storage.ts
index 22d4a5e6e..ea9e2be53 100644
--- a/packages/server/src/conflict-storage.ts
+++ b/packages/server/src/conflict-storage.ts
@@ -1,13 +1,13 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { getLocalDir } from './config/paths.ts';
-import { ConflictMarkersInContentError, NoConflictTrackedError } from './conflict-errors.ts';
+import { NoConflictTrackedError } from './conflict-errors.ts';
+import { requireConflictResolutionContent } from './conflict-resolution-input.ts';
import { isShareableOkArtifact } from './content-filter.ts';
import { tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';
import { listNames } from './git-paths.ts';
import { getLogger } from './logger.ts';
import { isWithinDir } from './path-utils.ts';
-import { containsUnresolvedConflictBlock } from './reconciliation.ts';
import { assertRealpathWithinDir } from './symlink-guard.ts';
const log = getLogger('conflict-storage');
@@ -57,6 +57,18 @@ export class ConflictStore {
}
this.branch = data.branch ?? this.branch;
this.conflicts = data.conflicts ?? [];
+ for (const entry of this.conflicts) {
+ const receivedVariant: unknown = entry.variant;
+ if (receivedVariant === undefined || receivedVariant === 'working-tree') continue;
+ log.warn(
+ {
+ event: 'conflict-discriminator-unrecognized',
+ file: entry.file,
+ receivedVariant,
+ },
+ '[conflicts] unrecognized conflict variant — the field is dropped from the conflicts list',
+ );
+ }
} catch (e) {
log.warn({ err: e }, '[conflicts] failed to load conflicts.json — starting empty');
this.conflicts = [];
@@ -134,17 +146,7 @@ export class ConflictStore {
throw new NoConflictTrackedError({ file });
}
- if (
- strategy === 'content' &&
- content !== undefined &&
- containsUnresolvedConflictBlock(content)
- ) {
- throw new ConflictMarkersInContentError({ file });
- }
-
- if (strategy === 'content' && content === undefined) {
- throw new Error(`[conflicts] strategy 'content' requires content parameter`);
- }
+ if (strategy === 'content') requireConflictResolutionContent(file, content);
if (entry.variant === 'working-tree') {
await this.resolveWorkingTreeConflict(entry, strategy, content);
@@ -166,18 +168,16 @@ export class ConflictStore {
break;
case 'content': {
- if (content === undefined) {
- throw new Error(`[conflicts] strategy 'content' requires content parameter`);
- }
+ const resolved = requireConflictResolutionContent(file, content);
const projectRoot = resolve(this.projectDir);
const absPath = resolve(projectRoot, file);
if (!isWithinDir(absPath, projectRoot)) {
throw new Error(`[conflicts] file path escapes project directory: ${file}`);
}
- assertRealpathWithinDir(absPath, projectRoot, {
+ const target = assertRealpathWithinDir(absPath, projectRoot, {
allowShareableOkArtifact: isShareableOkArtifact,
});
- tracedWriteFileSync(absPath, content, 'utf-8');
+ tracedWriteFileSync(target, resolved, 'utf-8');
await handle.git.raw(['add', '--', file]);
break;
}
@@ -252,7 +252,7 @@ export class ConflictStore {
if (!isWithinDir(absPath, projectRoot)) {
throw new Error(`[conflicts] file path escapes project directory: ${entry.file}`);
}
- assertRealpathWithinDir(absPath, projectRoot, {
+ const target = assertRealpathWithinDir(absPath, projectRoot, {
allowShareableOkArtifact: isShareableOkArtifact,
});
@@ -265,7 +265,7 @@ export class ConflictStore {
}
try {
- await this.applyWorkingTreeStrategy(absPath, projectRoot, entry, strategy, content);
+ await this.applyWorkingTreeStrategy(absPath, target, projectRoot, entry, strategy, content);
} catch (err) {
if (!this.addConflict(restoreOnFailure)) {
log.error(
@@ -279,6 +279,7 @@ export class ConflictStore {
private async applyWorkingTreeStrategy(
absPath: string,
+ target: string,
projectRoot: string,
entry: ConflictEntry,
strategy: ResolveStrategy,
@@ -297,18 +298,22 @@ export class ConflictStore {
const { createGitInstance } = await import('./git-handle.ts');
const handle = createGitInstance(this.projectDir, { credentialConfig: [] });
const theirsBytes = await handle.git.raw(['cat-file', 'blob', entry.theirsSha]);
- assertRealpathWithinDir(absPath, projectRoot, {
+ const writeTarget = assertRealpathWithinDir(target, projectRoot, {
allowShareableOkArtifact: isShareableOkArtifact,
});
- tracedWriteFileSync(absPath, theirsBytes, 'utf-8');
+ tracedWriteFileSync(writeTarget, theirsBytes, 'utf-8');
break;
}
case 'content': {
- if (content === undefined) {
- throw new Error(`[conflicts] strategy 'content' requires content parameter`);
- }
- tracedWriteFileSync(absPath, content, 'utf-8');
+ const writeTarget = assertRealpathWithinDir(target, projectRoot, {
+ allowShareableOkArtifact: isShareableOkArtifact,
+ });
+ tracedWriteFileSync(
+ writeTarget,
+ requireConflictResolutionContent(entry.file, content),
+ 'utf-8',
+ );
break;
}
diff --git a/packages/server/src/disk-content-intake.ts b/packages/server/src/disk-content-intake.ts
index 2dff48a47..0fd185187 100644
--- a/packages/server/src/disk-content-intake.ts
+++ b/packages/server/src/disk-content-intake.ts
@@ -1,5 +1,5 @@
import type * as Y from 'yjs';
-import { composeAndWriteRawBody } from './bridge-intake.ts';
+import { composeAndWriteRawBody, type PrecomputedParse } from './bridge-intake.ts';
import type { DeriveLossDetectOptions } from './bridge-loss-detector.ts';
import type { PairedWriteOrigin } from './server-observers.ts';
@@ -16,8 +16,9 @@ export function applyDiskContentToDoc(
sourcePath?: string,
resolveSize?: (basename: string, sourcePath: string) => number | null,
detect?: DeriveLossDetectOptions,
+ precomputed?: PrecomputedParse,
): void {
const embedResolver =
resolveEmbed && sourcePath ? { resolveEmbed, resolveSize, sourcePath } : undefined;
- composeAndWriteRawBody(document, content, 'file-watcher', embedResolver, undefined, detect);
+ composeAndWriteRawBody(document, content, 'file-watcher', embedResolver, precomputed, detect);
}
diff --git a/packages/server/src/document-durability-cache.test.ts b/packages/server/src/document-durability-cache.test.ts
new file mode 100644
index 000000000..b3251d01b
--- /dev/null
+++ b/packages/server/src/document-durability-cache.test.ts
@@ -0,0 +1,298 @@
+import {
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ unlinkSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import {
+ DISPLACED_VERSION_LIMIT,
+ DISPLACED_VERSION_TTL_MS,
+ DocumentDurabilityState,
+} from './document-durability-state.ts';
+import * as tracedFs from './fs-traced.ts';
+import { contentHash } from './version-hash.ts';
+
+const fixtures: string[] = [];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ for (const fixture of fixtures.splice(0)) rmSync(fixture, { recursive: true, force: true });
+});
+
+function setup() {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-cache-'));
+ fixtures.push(dir);
+ const persistencePath = join(dir, 'state.json');
+ return { dir, persistencePath, state: new DocumentDurabilityState('main', { persistencePath }) };
+}
+
+describe('durable snapshot serialization cache', () => {
+ test.each(['__proto__', 'constructor', 'toString'])(
+ 'restores protected rows on the valid prototype-like branch %s',
+ (branch) => {
+ const { persistencePath, state } = setup();
+ state.switchReconciledBaseScope(branch);
+ state.recordSuccessfulStore('doc', 'acknowledged', 'old');
+
+ const restored = new DocumentDurabilityState(branch, { persistencePath });
+
+ expect(restored.getReconciledBase('doc')).toBe('acknowledged');
+ expect(restored.isDisplacedVersion('doc', 'old')).toBe(true);
+ },
+ );
+
+ test('records a successful agent store as one synchronous snapshot replacement', () => {
+ const { persistencePath, state } = setup();
+ state.setReconciledBase('doc', 'original');
+ state.recordDisplacedVersion('doc', 'previous');
+ const writes = vi.spyOn(tracedFs, 'tracedWriteFileSync');
+ const renames = vi.spyOn(tracedFs, 'tracedRenameSync');
+
+ state.recordSuccessfulStore('doc', 'acknowledged', 'original');
+
+ expect(writes).toHaveBeenCalledTimes(1);
+ expect(renames).toHaveBeenCalledTimes(1);
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getReconciledBase('doc')).toBe('acknowledged');
+ expect(restored.isDisplacedVersion('doc', 'original')).toBe(true);
+ expect(restored.isDisplacedVersion('doc', 'previous')).toBe(true);
+ });
+
+ test('unchanged protected bases avoid serialization and writes until expiry is due', () => {
+ const { persistencePath, state } = setup();
+ state.setReconciledBase('doc', 'acknowledged');
+ state.recordDisplacedVersion('doc', 'old');
+ utimesSync(persistencePath, 1, 1);
+ const before = statSync(persistencePath);
+ const serialize = vi.spyOn(JSON, 'stringify');
+ const writes = vi.spyOn(tracedFs, 'tracedWriteFileSync');
+
+ state.setReconciledBase('doc', 'acknowledged');
+
+ expect(serialize).not.toHaveBeenCalled();
+ expect(writes).not.toHaveBeenCalled();
+ expect(statSync(persistencePath).mtimeMs).toBe(before.mtimeMs);
+ });
+
+ test('an unchanged base still sweeps due history without dropping unresolved conflicts', () => {
+ vi.useFakeTimers();
+ const { persistencePath, state } = setup();
+ state.setReconciledBase('expired', 'old plaintext');
+ state.recordDisplacedVersion('expired', 'older');
+ state.setReconciledBase('conflict', 'protected');
+ state.recordStaleExternalWrite('conflict', 'disk', 'retained');
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1);
+
+ state.setReconciledBase('conflict', 'protected');
+
+ expect(readFileSync(persistencePath, 'utf8')).not.toContain('old plaintext');
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getReconciledBase('expired')).toBeUndefined();
+ expect(restored.getStaleExternalWrite('conflict')).toMatchObject({
+ diskContent: 'disk',
+ retainedContent: 'retained',
+ });
+ });
+
+ test('failed replacement restores base and history, and retry commits both', () => {
+ const { dir, persistencePath, state } = setup();
+ state.setReconciledBase('doc', 'original');
+ state.recordDisplacedVersion('doc', 'previous');
+ const before = readFileSync(persistencePath, 'utf8');
+ const backup = `${persistencePath}.backup`;
+ renameSync(persistencePath, backup);
+ mkdirSync(persistencePath);
+
+ expect(() => state.recordSuccessfulStore('doc', 'acknowledged', 'original')).toThrow(
+ expect.objectContaining({
+ code: expect.stringMatching(/^(EISDIR|EACCES|EPERM|ENOTEMPTY|EEXIST)$/),
+ }),
+ );
+
+ expect(state.getReconciledBase('doc')).toBe('original');
+ expect(state.isDisplacedVersion('doc', 'original')).toBe(false);
+ expect(state.isDisplacedVersion('doc', 'previous')).toBe(true);
+ expect(readFileSync(backup, 'utf8')).toBe(before);
+ expect(readdirSync(dir).filter((name) => name.includes('.tmp.'))).toEqual([]);
+ rmSync(persistencePath, { recursive: true });
+ renameSync(backup, persistencePath);
+ state.recordSuccessfulStore('doc', 'acknowledged', 'original');
+
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getReconciledBase('doc')).toBe('acknowledged');
+ expect(restored.isDisplacedVersion('doc', 'original')).toBe(true);
+ expect(restored.isDisplacedVersion('doc', 'previous')).toBe(true);
+ });
+
+ test('first-snapshot failure restores absent state and does not poison its retry', () => {
+ const { persistencePath, state } = setup();
+ mkdirSync(persistencePath);
+
+ expect(() => state.recordSuccessfulStore('doc', 'acknowledged', 'original')).toThrow(
+ expect.objectContaining({
+ code: expect.stringMatching(/^(EISDIR|EACCES|EPERM|ENOTEMPTY|EEXIST)$/),
+ }),
+ );
+ expect(state.getReconciledBase('doc')).toBeUndefined();
+ expect(state.isDisplacedVersion('doc', 'original')).toBe(false);
+ rmSync(persistencePath, { recursive: true });
+ state.recordSuccessfulStore('doc', 'acknowledged', 'original');
+
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getReconciledBase('doc')).toBe('acknowledged');
+ expect(restored.isDisplacedVersion('doc', 'original')).toBe(true);
+ });
+
+ test('a failed snapshot preparation preserves the committed cache through an unrelated save', () => {
+ const { dir, persistencePath, state } = setup();
+ state.recordSuccessfulStore('doc', 'original', 'previous');
+ const before = readFileSync(persistencePath, 'utf8');
+ const movedDir = `${dir}-moved`;
+ fixtures.push(movedDir);
+ renameSync(dir, movedDir);
+ writeFileSync(dir, 'file blocks the snapshot parent');
+
+ expect(() => state.recordSuccessfulStore('doc', 'acknowledged', 'original')).toThrow(
+ expect.objectContaining({ code: expect.stringMatching(/^(EEXIST|ENOTDIR|EACCES|EPERM)$/) }),
+ );
+ expect(state.getReconciledBase('doc')).toBe('original');
+ expect(state.isDisplacedVersion('doc', 'original')).toBe(false);
+ expect(readFileSync(join(movedDir, 'state.json'), 'utf8')).toBe(before);
+ unlinkSync(dir);
+ renameSync(movedDir, dir);
+ state.recordSuccessfulStore('other', 'other acknowledged', 'other old');
+ const afterOther = new DocumentDurabilityState('main', { persistencePath });
+ expect(afterOther.getReconciledBase('doc')).toBe('original');
+ expect(afterOther.isDisplacedVersion('doc', 'original')).toBe(false);
+ state.recordSuccessfulStore('doc', 'acknowledged', 'original');
+ const afterRetry = new DocumentDurabilityState('main', { persistencePath });
+ expect(afterRetry.getReconciledBase('doc')).toBe('acknowledged');
+ expect(afterRetry.getReconciledBase('other')).toBe('other acknowledged');
+ expect(afterRetry.isDisplacedVersion('doc', 'original')).toBe(true);
+ });
+
+ test('cached rows isolate branch identity and invalidate conflicts, clears, and deletion', () => {
+ const { persistencePath, state } = setup();
+ state.recordSuccessfulStore('doc', 'main acknowledged', 'main old');
+ state.recordStaleExternalWrite('doc', 'main old', 'main candidate');
+ state.switchReconciledBaseScope('feature/"quoted"');
+ state.recordSuccessfulStore('doc', 'feature acknowledged', 'feature old');
+ state.recordStaleExternalWrite('doc', 'feature old', 'feature candidate');
+ state.recordStaleExternalWrite('doc', 'different rejected bytes', '');
+ state.clearDisplacedVersions('doc');
+ state.switchReconciledBaseScope('main');
+ state.clearStaleExternalWrite('doc');
+ state.recordSuccessfulStore('other', 'other preserved', 'other old');
+ state.deleteReconciledBase('doc');
+
+ const main = new DocumentDurabilityState('main', { persistencePath });
+ expect(main.getReconciledBase('doc')).toBeUndefined();
+ expect(main.getReconciledBase('other')).toBe('other preserved');
+ const feature = new DocumentDurabilityState('feature/"quoted"', { persistencePath });
+ expect(feature.getReconciledBase('doc')).toBe('feature acknowledged');
+ expect(feature.isDisplacedVersion('doc', 'feature old')).toBe(false);
+ expect(feature.getStaleExternalWrite('doc')).toMatchObject({
+ diskContent: 'different rejected bytes',
+ retainedContent: '',
+ });
+ feature.clearStaleExternalWrite('doc');
+ expect(
+ new DocumentDurabilityState('feature/"quoted"', { persistencePath }).getReconciledBase('doc'),
+ ).toBeUndefined();
+ });
+
+ test('changing one document serializes only that row and retains untouched document bytes', () => {
+ const { persistencePath, state } = setup();
+ state.recordSuccessfulStore('doc', 'original', 'previous');
+ state.recordSuccessfulStore('untouched', 'large preserved text '.repeat(1000), 'old untouched');
+ const serialize = vi.spyOn(JSON, 'stringify');
+
+ state.recordSuccessfulStore('doc', 'acknowledged', 'original');
+
+ const objects = serialize.mock.calls
+ .map(([value]) => value)
+ .filter((value) => value !== null && typeof value === 'object');
+ expect(objects).toHaveLength(1);
+ expect(objects[0]).toMatchObject({ docName: 'doc', acknowledgedContent: 'acknowledged' });
+ serialize.mockRestore();
+ expect(
+ new DocumentDurabilityState('main', { persistencePath }).getReconciledBase('untouched'),
+ ).toBe('large preserved text '.repeat(1000));
+ });
+
+ test('a returned conflict changed in place invalidates its cached encoding on the next store', () => {
+ const { persistencePath, state } = setup();
+ state.recordSuccessfulStore('doc', 'acknowledged', 'old');
+ const conflict = state.recordStaleExternalWrite('doc', 'old', 'first candidate');
+ conflict.retainedContent = 'updated candidate';
+
+ state.recordSuccessfulStore('other', 'other acknowledged', 'other old');
+
+ expect(
+ new DocumentDurabilityState('main', { persistencePath }).getStaleExternalWrite('doc')
+ ?.retainedContent,
+ ).toBe('updated candidate');
+ });
+
+ test('combined updates deduplicate and bound history without a separate expiry write', () => {
+ vi.useFakeTimers();
+ const { persistencePath, state } = setup();
+ state.recordSuccessfulStore('doc', 'current', 'expired');
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1);
+ const writes = vi.spyOn(tracedFs, 'tracedWriteFileSync');
+ state.recordSuccessfulStore('doc', 'current 2', 'fresh');
+ expect(writes).toHaveBeenCalledTimes(1);
+ for (let index = 0; index <= DISPLACED_VERSION_LIMIT; index += 1) {
+ state.recordSuccessfulStore('doc', `current ${index}`, `old ${index}`);
+ }
+ state.recordSuccessfulStore('doc', 'final', `old ${DISPLACED_VERSION_LIMIT}`);
+
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.isDisplacedVersion('doc', 'expired')).toBe(false);
+ expect(restored.isDisplacedVersion('doc', 'fresh')).toBe(false);
+ expect(restored.isDisplacedVersion('doc', 'old 0')).toBe(false);
+ expect(restored.isDisplacedVersion('doc', 'old 1')).toBe(true);
+ expect(restored.isDisplacedVersion('doc', `old ${DISPLACED_VERSION_LIMIT}`)).toBe(true);
+ });
+
+ test('retains the v1 JSON byte shape including numeric branch ordering and escaped content', () => {
+ vi.useFakeTimers();
+ const { persistencePath, state } = setup();
+ const at = Date.now();
+ state.switchReconciledBaseScope('10');
+ state.recordSuccessfulStore('doc', 'line\n"quote" 🍊', 'old ten');
+ state.switchReconciledBaseScope('2');
+ state.recordSuccessfulStore('doc', 'two', 'old two');
+ expect(readFileSync(persistencePath, 'utf8')).toBe(
+ JSON.stringify({
+ version: 1,
+ branches: {
+ 2: [
+ {
+ docName: 'doc',
+ acknowledgedContent: 'two',
+ displacedVersions: [{ hash: contentHash('old two'), at }],
+ },
+ ],
+ 10: [
+ {
+ docName: 'doc',
+ acknowledgedContent: 'line\n"quote" 🍊',
+ displacedVersions: [{ hash: contentHash('old ten'), at }],
+ },
+ ],
+ },
+ }),
+ );
+ });
+});
diff --git a/packages/server/src/document-durability-state.test.ts b/packages/server/src/document-durability-state.test.ts
index 4af8ccced..219f432b1 100644
--- a/packages/server/src/document-durability-state.test.ts
+++ b/packages/server/src/document-durability-state.test.ts
@@ -1,5 +1,32 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { describe, expect, test, vi } from 'vitest';
-import { DocumentDurabilityState } from './document-durability-state.ts';
+import {
+ _resetDocExtensionsForTests,
+ docNameToRelativePath,
+ isRegisteredMarkdownDocName,
+ registerDocExtension,
+} from './doc-extensions.ts';
+import {
+ DISPLACED_VERSION_LIMIT,
+ DISPLACED_VERSION_TTL_MS,
+ DocumentDurabilityState,
+ DocumentDurabilityStateError,
+} from './document-durability-state.ts';
+import * as tracedFs from './fs-traced.ts';
+import { getLogger } from './logger.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
describe('DocumentDurabilityState', () => {
@@ -221,3 +248,589 @@ describe('in-flight flush queue semantics', () => {
}
});
});
+
+describe('displaced-version history', () => {
+ test('recognizes a version this server displaced and ignores one it never wrote', () => {
+ const state = new DocumentDurabilityState();
+ state.recordDisplacedVersion('doc', 'v1 bytes');
+
+ expect(state.isDisplacedVersion('doc', 'v1 bytes')).toBe(true);
+ expect(state.isDisplacedVersion('doc', 'never written')).toBe(false);
+ expect(state.isDisplacedVersion('other-doc', 'v1 bytes')).toBe(false);
+ });
+
+ test('retains only the newest DISPLACED_VERSION_LIMIT versions per document', () => {
+ const state = new DocumentDurabilityState();
+ for (let i = 0; i <= DISPLACED_VERSION_LIMIT; i++) {
+ state.recordDisplacedVersion('doc', `v${i}`);
+ }
+
+ expect(state.isDisplacedVersion('doc', 'v0')).toBe(false);
+ expect(state.isDisplacedVersion('doc', 'v1')).toBe(true);
+ expect(state.isDisplacedVersion('doc', `v${DISPLACED_VERSION_LIMIT}`)).toBe(true);
+ });
+
+ test('a re-displaced version refreshes in place instead of consuming another slot', () => {
+ const state = new DocumentDurabilityState();
+ for (let i = 0; i < DISPLACED_VERSION_LIMIT; i++) {
+ state.recordDisplacedVersion('doc', 'repeat');
+ }
+ state.recordDisplacedVersion('doc', 'distinct');
+
+ expect(state.isDisplacedVersion('doc', 'repeat')).toBe(true);
+ expect(state.isDisplacedVersion('doc', 'distinct')).toBe(true);
+ });
+
+ test('a displaced version expires on read once its TTL has passed', () => {
+ vi.useFakeTimers();
+ try {
+ const state = new DocumentDurabilityState();
+ state.recordDisplacedVersion('doc', 'v1 bytes');
+ expect(state.isDisplacedVersion('doc', 'v1 bytes')).toBe(true);
+
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1_000);
+
+ expect(state.isDisplacedVersion('doc', 'v1 bytes')).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('displaced versions are scoped to the branch that displaced them', () => {
+ const state = new DocumentDurabilityState();
+ state.recordDisplacedVersion('doc', 'main v1');
+ state.switchReconciledBaseScope('feature');
+
+ expect(state.isDisplacedVersion('doc', 'main v1')).toBe(false);
+ state.recordDisplacedVersion('doc', 'feature v1');
+ state.switchReconciledBaseScope('main');
+ expect(state.isDisplacedVersion('doc', 'feature v1')).toBe(false);
+ expect(state.isDisplacedVersion('doc', 'main v1')).toBe(true);
+ });
+
+ test('deleting a doc clears its displaced versions, leaving other documents intact', () => {
+ const state = new DocumentDurabilityState();
+ state.recordDisplacedVersion('doc', 'v1 bytes');
+ state.recordDisplacedVersion('other', 'v1 bytes');
+
+ state.deleteReconciledBase('doc');
+
+ expect(state.isDisplacedVersion('doc', 'v1 bytes')).toBe(false);
+ expect(state.isDisplacedVersion('other', 'v1 bytes')).toBe(true);
+ });
+
+ test('tracks stale external conflicts per branch and clears them with document state', () => {
+ const state = new DocumentDurabilityState();
+ const conflict = state.recordStaleExternalWrite('doc', 'stale bytes');
+
+ expect(state.staleExternalWriteMatches('doc', 'stale bytes')).toBe(true);
+ expect(state.listStaleExternalWrites()).toEqual([conflict]);
+ state.switchReconciledBaseScope('feature');
+ expect(state.listStaleExternalWrites()).toEqual([]);
+ state.switchReconciledBaseScope('main');
+ state.deleteReconciledBase('doc');
+ expect(state.listStaleExternalWrites()).toEqual([]);
+ });
+
+ test('restores displaced history, acknowledged content, and unresolved conflicts after restart', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-state-'));
+ const persistencePath = join(dir, 'stale-external-writes.json');
+ try {
+ const first = new DocumentDurabilityState('main', { persistencePath });
+ first.setReconciledBase('doc', 'old bytes');
+ first.recordDisplacedVersion('doc', 'old bytes');
+ first.setReconciledBase('doc', 'acknowledged bytes');
+ first.recordStaleExternalWrite('doc', 'old bytes');
+
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+
+ expect(restored.getReconciledBase('doc')).toBe('acknowledged bytes');
+ expect(restored.isDisplacedVersion('doc', 'old bytes')).toBe(true);
+ expect(restored.staleExternalWriteMatches('doc', 'old bytes')).toBe(true);
+
+ restored.deleteReconciledBase('doc');
+ const afterDelete = new DocumentDurabilityState('main', { persistencePath });
+ expect(afterDelete.getReconciledBase('doc')).toBeUndefined();
+ expect(afterDelete.isDisplacedVersion('doc', 'old bytes')).toBe(false);
+ expect(afterDelete.staleExternalWriteMatches('doc', 'old bytes')).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('keeps unresolved persisted conflicts after their displaced-history window expires', () => {
+ vi.useFakeTimers();
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-conflict-'));
+ const persistencePath = join(dir, 'stale-external-writes.json');
+ try {
+ const first = new DocumentDurabilityState('main', { persistencePath });
+ first.setReconciledBase('doc', 'acknowledged bytes');
+ first.recordDisplacedVersion('doc', 'old bytes');
+ first.recordStaleExternalWrite('doc', 'old bytes');
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1_000);
+
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+
+ expect(restored.getReconciledBase('doc')).toBe('acknowledged bytes');
+ expect(restored.isDisplacedVersion('doc', 'old bytes')).toBe(false);
+ expect(restored.staleExternalWriteMatches('doc', 'old bytes')).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('sweeps expired inactive history without expiring unresolved conflicts', () => {
+ vi.useFakeTimers();
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-expiry-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('expired-doc', 'acknowledged');
+ state.recordDisplacedVersion('expired-doc', 'old');
+ state.setReconciledBase('conflicted-doc', 'preserved');
+ state.recordDisplacedVersion('conflicted-doc', 'rejected');
+ state.recordStaleExternalWrite('conflicted-doc', 'rejected');
+ state.switchReconciledBaseScope('feature');
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1);
+ state.setReconciledBase('fresh-doc', 'new acknowledged');
+ state.recordDisplacedVersion('fresh-doc', 'new old');
+ const serialized = readFileSync(persistencePath, 'utf-8');
+ expect(serialized).not.toContain('expired-doc');
+ expect(serialized).toContain('conflicted-doc');
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getReconciledBase('conflicted-doc')).toBe('preserved');
+ expect(restored.staleExternalWriteMatches('conflicted-doc', 'rejected')).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a branch switch purges expired restored plaintext but retains unresolved recovery data', () => {
+ vi.useFakeTimers();
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-restored-expiry-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('expired', 'expired plaintext');
+ state.recordDisplacedVersion('expired', 'old');
+ state.setReconciledBase('pending', 'protected plaintext');
+ state.recordStaleExternalWrite('pending', 'rejected');
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1);
+ const beforeRestore = readFileSync(persistencePath, 'utf-8');
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getReconciledBase('expired')).toBeUndefined();
+ expect(readFileSync(persistencePath, 'utf-8')).toBe(beforeRestore);
+ restored.switchReconciledBaseScope('feature');
+ expect(readFileSync(persistencePath, 'utf-8')).not.toContain('expired plaintext');
+ expect(readFileSync(persistencePath, 'utf-8')).toContain('protected plaintext');
+ expect(readFileSync(persistencePath, 'utf-8')).toContain('rejected');
+ } finally {
+ vi.useRealTimers();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('failed durable clearing retains the conflict until a successful retry', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-clear-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('doc', 'acknowledged');
+ state.recordStaleExternalWrite('doc', 'rejected');
+ renameSync(persistencePath, `${persistencePath}.backup`);
+ mkdirSync(persistencePath);
+ expect(() => state.clearStaleExternalWrite('doc')).toThrow();
+ expect(state.getStaleExternalWrite('doc')?.diskContent).toBe('rejected');
+ expect(readdirSync(dir).filter((name) => name.includes('.tmp.'))).toEqual([]);
+ rmSync(persistencePath, { recursive: true });
+ renameSync(`${persistencePath}.backup`, persistencePath);
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getStaleExternalWrite('doc')?.diskContent).toBe('rejected');
+ state.clearStaleExternalWrite('doc');
+ expect(state.getStaleExternalWrite('doc')).toBeUndefined();
+ expect(
+ new DocumentDurabilityState('main', { persistencePath }).getStaleExternalWrite('doc'),
+ ).toBeUndefined();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test.each([
+ ['{invalid', 'corrupt'],
+ [JSON.stringify({ version: 2, branches: {} }), 'incompatible'],
+ [JSON.stringify({ version: 1, branches: { main: [{ docName: 'bad' }] } }), 'corrupt'],
+ ])('preserves invalid recovery state and fails with actionable %s diagnostics', (raw, kind) => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-invalid-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ writeFileSync(persistencePath, raw);
+ expect(() => new DocumentDurabilityState('main', { persistencePath })).toThrow(
+ DocumentDurabilityStateError,
+ );
+ try {
+ new DocumentDurabilityState('main', { persistencePath });
+ } catch (error) {
+ expect(error).toMatchObject({ kind, path: persistencePath });
+ expect(error instanceof Error ? error.message : '').toContain('Do not delete');
+ }
+ expect(readFileSync(persistencePath, 'utf-8')).toBe(raw);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('reports an unreadable snapshot without replacing it', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-unreadable-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ mkdirSync(persistencePath);
+ expect(() => new DocumentDurabilityState('main', { persistencePath })).toThrow(
+ expect.objectContaining({ kind: 'unreadable', path: persistencePath }),
+ );
+ expect(statSync(persistencePath).isDirectory()).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test.each([
+ ['EACCES', 'permissions'],
+ ['EPERM', 'permissions'],
+ ['EISDIR', 'regular file'],
+ ['EIO', 'filesystem'],
+ ])('unreadable %s diagnostics name the filesystem problem', (code, guidance) => {
+ const cause = Object.assign(new Error('read failed'), { code });
+ const error = new DocumentDurabilityStateError('/project/state.json', 'unreadable', cause);
+ expect(error.message).toContain(code);
+ expect(error.message).toContain(guidance);
+ expect(error.message).not.toContain('Restore this snapshot from a known-good backup');
+ expect(error.cause).toBe(cause);
+ });
+
+ test('incompatible diagnostics do not claim an unrecorded writer version is known', () => {
+ const error = new DocumentDurabilityStateError('/project/state.json', 'incompatible');
+ expect(error.message).not.toContain('version that wrote');
+ expect(error.message).toContain('schema');
+ });
+
+ test('a tracked target is re-derived from docName rather than trusted from the snapshot', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-target-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('protected', 'acknowledged');
+ state.recordStaleExternalWrite('protected', 'old');
+ const tampered = readFileSync(persistencePath, 'utf-8').replace(
+ '"file":"protected.md"',
+ '"file":"unrelated.md"',
+ );
+ writeFileSync(persistencePath, tampered);
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getStaleExternalWrite('protected')?.file).toBe('protected.md');
+ expect(restored.listStaleExternalWrites().map((entry) => entry.file)).toEqual([
+ 'protected.md',
+ ]);
+ expect(readFileSync(persistencePath, 'utf-8')).toBe(tampered);
+ const invalidPath = new Error('document path escapes content directory');
+ expect(
+ () =>
+ new DocumentDurabilityState('main', {
+ persistencePath,
+ fileForDocName: () => {
+ throw invalidPath;
+ },
+ }),
+ ).toThrow(expect.objectContaining({ kind: 'corrupt', cause: invalidPath }));
+ expect(readFileSync(persistencePath, 'utf-8')).toBe(tampered);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('re-recording the same disk hash with a new retained edit does not count a new conflict', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-recount-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('doc', 'acknowledged');
+ const beforeCount = getMetrics().staleExternalWriteRefused;
+ state.recordStaleExternalWrite('doc', 'old');
+ expect(getMetrics().staleExternalWriteRefused).toBe(beforeCount + 1);
+ const first = state.getStaleExternalWrite('doc');
+ state.recordStaleExternalWrite('doc', 'old', 'a pending edit');
+ expect(getMetrics().staleExternalWriteRefused).toBe(beforeCount + 1);
+ expect(state.getStaleExternalWrite('doc')?.retainedContent).toBe('a pending edit');
+ expect(state.getStaleExternalWrite('doc')?.detectedAt).toBe(first?.detectedAt);
+ state.recordStaleExternalWrite('doc', 'newer disk bytes');
+ expect(getMetrics().staleExternalWriteRefused).toBe(beforeCount + 2);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('an .mdx document restored before the watcher scan resolves to its .mdx file', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-mdx-'));
+ const persistencePath = join(dir, 'state.json');
+ const options = {
+ persistencePath,
+ fileForDocName: docNameToRelativePath,
+ hasResolvedExtension: isRegisteredMarkdownDocName,
+ };
+ try {
+ _resetDocExtensionsForTests();
+ registerDocExtension('notes/guide', '.mdx');
+ const state = new DocumentDurabilityState('main', options);
+ state.setReconciledBase('notes/guide', 'acknowledged');
+ state.recordStaleExternalWrite('notes/guide', 'old');
+ expect(state.getStaleExternalWrite('notes/guide')?.file).toBe('notes/guide.mdx');
+
+ _resetDocExtensionsForTests();
+ const booting = new DocumentDurabilityState('main', options);
+ expect(booting.getStaleExternalWrite('notes/guide')?.file).toBe('notes/guide.mdx');
+ expect(booting.listStaleExternalWrites().map((entry) => entry.file)).toEqual([
+ 'notes/guide.mdx',
+ ]);
+ } finally {
+ _resetDocExtensionsForTests();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a scan that observes .md displaces an .mdx snapshot instead of being outranked by it', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-mdx-renamed-'));
+ const persistencePath = join(dir, 'state.json');
+ const options = {
+ persistencePath,
+ fileForDocName: docNameToRelativePath,
+ hasResolvedExtension: isRegisteredMarkdownDocName,
+ };
+ try {
+ _resetDocExtensionsForTests();
+ registerDocExtension('notes/guide', '.mdx');
+ const state = new DocumentDurabilityState('main', options);
+ state.setReconciledBase('notes/guide', 'acknowledged');
+ state.recordStaleExternalWrite('notes/guide', 'old');
+ expect(state.getStaleExternalWrite('notes/guide')?.file).toBe('notes/guide.mdx');
+
+ _resetDocExtensionsForTests();
+ const booting = new DocumentDurabilityState('main', options);
+ expect(registerDocExtension('notes/guide', '.md')).toEqual({
+ effective: '.md',
+ changed: true,
+ shadowed: null,
+ });
+ expect(booting.getStaleExternalWrite('notes/guide')?.file).toBe('notes/guide.md');
+ } finally {
+ _resetDocExtensionsForTests();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a restored file naming an extension the registry rejects still opens the project', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-mmd-'));
+ const persistencePath = join(dir, 'state.json');
+ const options = {
+ persistencePath,
+ fileForDocName: docNameToRelativePath,
+ hasResolvedExtension: isRegisteredMarkdownDocName,
+ };
+ try {
+ _resetDocExtensionsForTests();
+ const state = new DocumentDurabilityState('main', options);
+ state.setReconciledBase('flow.mmd', 'acknowledged');
+ state.recordStaleExternalWrite('flow.mmd', 'old');
+ expect(state.getStaleExternalWrite('flow.mmd')?.file).toBe('flow.mmd');
+
+ _resetDocExtensionsForTests();
+ const booting = new DocumentDurabilityState('main', options);
+ expect(booting.getStaleExternalWrite('flow.mmd')?.file).toBe('flow.mmd');
+ } finally {
+ _resetDocExtensionsForTests();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a conflict file is re-derived from the resolver on every read, never replayed', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-moved-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', {
+ persistencePath,
+ fileForDocName: (docName) => `sub/${docName}.md`,
+ });
+ state.setReconciledBase('guide', 'acknowledged');
+ state.recordStaleExternalWrite('guide', 'old');
+ expect(state.getStaleExternalWrite('guide')?.file).toBe('sub/guide.md');
+
+ const moved = new DocumentDurabilityState('main', {
+ persistencePath,
+ fileForDocName: (docName) => `moved/${docName}.md`,
+ });
+ expect(moved.getStaleExternalWrite('guide')?.file).toBe('moved/guide.md');
+ expect(moved.listStaleExternalWrites().map((entry) => entry.file)).toEqual([
+ 'moved/guide.md',
+ ]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('an unrelated mutation on a document whose conflict file moved does not re-notify', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-renotify-'));
+ const persistencePath = join(dir, 'state.json');
+ const changed = vi.fn();
+ let prefix = 'sub';
+ try {
+ const state = new DocumentDurabilityState('main', {
+ persistencePath,
+ fileForDocName: (docName) => `${prefix}/${docName}.md`,
+ onStaleExternalWriteChange: changed,
+ });
+ state.setReconciledBase('guide', 'acknowledged');
+ state.recordStaleExternalWrite('guide', 'old');
+ expect(changed).toHaveBeenCalledTimes(1);
+
+ prefix = 'moved';
+ expect(state.getStaleExternalWrite('guide')?.file).toBe('moved/guide.md');
+ state.setReconciledBase('guide', 'a later acknowledgement');
+ expect(changed).toHaveBeenCalledTimes(1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('ordinary clears and branch switches create no snapshot, and restore does not rewrite one', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-noop-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('ordinary', 'content');
+ state.clearStaleExternalWrite('ordinary');
+ state.clearDisplacedVersions('ordinary');
+ state.deleteReconciledBase('ordinary');
+ state.switchReconciledBaseScope('feature');
+ expect(existsSync(persistencePath)).toBe(false);
+ state.setReconciledBase('protected', 'content');
+ state.recordDisplacedVersion('protected', 'old');
+ utimesSync(persistencePath, 1, 1);
+ const before = statSync(persistencePath);
+ new DocumentDurabilityState('feature', { persistencePath });
+ expect(statSync(persistencePath).mtimeMs).toBe(before.mtimeMs);
+ if (process.platform !== 'win32') expect(before.mode & 0o777).toBe(0o600);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('all persisted mutators retain their previous state when the atomic replacement fails', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-atomic-'));
+ const persistencePath = join(dir, 'state.json');
+ const changed = vi.fn();
+ try {
+ const state = new DocumentDurabilityState('main', {
+ persistencePath,
+ onStaleExternalWriteChange: changed,
+ });
+ state.setReconciledBase('doc', 'acknowledged');
+ state.recordDisplacedVersion('doc', 'old');
+ const beforeCount = getMetrics().staleExternalWriteRefused;
+ state.recordStaleExternalWrite('doc', 'old');
+ state.recordStaleExternalWrite('doc', 'old');
+ expect(getMetrics().staleExternalWriteRefused).toBe(beforeCount + 1);
+ expect(changed).toHaveBeenCalledTimes(1);
+ renameSync(persistencePath, `${persistencePath}.backup`);
+ mkdirSync(persistencePath);
+ for (const mutate of [
+ () => state.setReconciledBase('doc', 'changed'),
+ () => state.recordDisplacedVersion('doc', 'another'),
+ () => state.clearDisplacedVersions('doc'),
+ () => state.recordStaleExternalWrite('doc', 'another'),
+ () => state.clearStaleExternalWrite('doc'),
+ () => state.deleteReconciledBase('doc'),
+ ]) {
+ expect(mutate).toThrow();
+ expect(state.getReconciledBase('doc')).toBe('acknowledged');
+ expect(state.getStaleExternalWrite('doc')?.diskContent).toBe('old');
+ expect(state.isDisplacedVersion('doc', 'old')).toBe(true);
+ expect(state.isDisplacedVersion('doc', 'another')).toBe(false);
+ expect(changed).toHaveBeenCalledTimes(1);
+ expect(getMetrics().staleExternalWriteRefused).toBe(beforeCount + 1);
+ expect(readdirSync(dir).filter((name) => name.includes('.tmp.'))).toEqual([]);
+ }
+ rmSync(persistencePath, { recursive: true });
+ renameSync(`${persistencePath}.backup`, persistencePath);
+ const restored = new DocumentDurabilityState('main', {
+ persistencePath,
+ onStaleExternalWriteChange: changed,
+ });
+ expect(changed).toHaveBeenCalledTimes(1);
+ restored.clearStaleExternalWrite('doc');
+ expect(changed).toHaveBeenCalledTimes(2);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('keeps the original replacement failure when temporary-file cleanup also fails', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-cleanup-'));
+ const persistencePath = join(dir, 'state.json');
+ let originalError: unknown;
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('doc', 'acknowledged');
+ mkdirSync(persistencePath);
+ const renameSpy = vi.spyOn(tracedFs, 'tracedRenameSync').mockImplementation((from, to) => {
+ try {
+ renameSync(from, to);
+ } catch (cause) {
+ originalError = cause;
+ rmSync(from);
+ mkdirSync(from);
+ throw cause;
+ }
+ });
+ const warnSpy = vi.spyOn(getLogger('document-durability-state'), 'warn');
+ try {
+ let actualError: unknown;
+ try {
+ state.recordDisplacedVersion('doc', 'old');
+ } catch (cause) {
+ actualError = cause;
+ }
+ expect(originalError).toBeInstanceOf(Error);
+ expect(actualError).toBe(originalError);
+ expect(state.isDisplacedVersion('doc', 'old')).toBe(false);
+ const payload = (warnSpy.mock.calls[0]?.[0] ?? {}) as { writeError?: unknown };
+ expect(payload.writeError).toBe((originalError as Error).message);
+ expect(JSON.stringify(payload.writeError)).not.toBe('{}');
+ } finally {
+ warnSpy.mockRestore();
+ renameSpy.mockRestore();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a different rejected version preserves the retained candidate across restart', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-durability-retained-'));
+ const persistencePath = join(dir, 'state.json');
+ try {
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ state.setReconciledBase('doc', 'acknowledged');
+ state.recordDisplacedVersion('doc', 'old A');
+ state.recordDisplacedVersion('doc', 'old Z');
+ state.recordStaleExternalWrite('doc', 'old A', 'retained C');
+ state.recordStaleExternalWrite('doc', 'old Z');
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ expect(restored.getStaleExternalWrite('doc')).toMatchObject({
+ diskContent: 'old Z',
+ retainedContent: 'retained C',
+ });
+ restored.recordStaleExternalWrite('doc', 'old A', '');
+ expect(restored.getStaleExternalWrite('doc')?.retainedContent).toBe('');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/document-durability-state.ts b/packages/server/src/document-durability-state.ts
index 236e72faa..46e732b74 100644
--- a/packages/server/src/document-durability-state.ts
+++ b/packages/server/src/document-durability-state.ts
@@ -1,4 +1,15 @@
-import { incrementInFlightFlushExpired } from './metrics.ts';
+import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import {
+ tracedMkdirSync,
+ tracedRenameSync,
+ tracedUnlinkSync,
+ tracedWriteFileSync,
+} from './fs-traced.ts';
+import { getLogger } from './logger.ts';
+import { incrementInFlightFlushExpired, incrementStaleExternalWriteRefused } from './metrics.ts';
+import { contentHash } from './version-hash.ts';
export interface StoreFailure {
code?: string;
@@ -7,26 +18,220 @@ export interface StoreFailure {
const IN_FLIGHT_FLUSH_TTL_MS = 60_000;
+export const DISPLACED_VERSION_TTL_MS = 30 * 60_000;
+export const DISPLACED_VERSION_LIMIT = 8;
+
interface PendingFlush {
value: string;
at: number;
}
+interface DisplacedVersion {
+ hash: string;
+ at: number;
+}
+
+export interface StaleExternalWriteConflict {
+ docName: string;
+ file: string;
+ diskHash: string;
+ diskContent: string;
+ retainedContent?: string;
+ detectedAt: string;
+}
+
+interface PersistedDocumentDurability {
+ docName: string;
+ acknowledgedContent: string;
+ displacedVersions: DisplacedVersion[];
+ staleExternalWrite?: StaleExternalWriteConflict;
+}
+
+interface PersistedDocumentDurabilityState {
+ version: 1;
+ branches: Record<string, PersistedDocumentDurability[]>;
+}
+
+interface CachedDurabilityDocument {
+ acknowledgedContent: string;
+ displacedVersions: DisplacedVersion[] | undefined;
+ staleExternalWrite: StaleExternalWriteConflict | undefined;
+ expiresAt: number;
+ serialized: string;
+}
+
+function nextDisplacedExpiry(versions: readonly DisplacedVersion[]): number {
+ return versions.reduce(
+ (next, entry) => Math.min(next, entry.at + DISPLACED_VERSION_TTL_MS),
+ Number.POSITIVE_INFINITY,
+ );
+}
+
+function snapshotParts(branches: ReadonlyMap<string, string[]>): string[] {
+ const parts = ['{"version":1,"branches":{'];
+ for (const [branch, documents] of Object.entries(Object.fromEntries(branches))) {
+ if (parts.length > 1) parts.push(',');
+ parts.push(JSON.stringify(branch), ':[');
+ for (const [index, document] of documents.entries()) {
+ if (index > 0) parts.push(',');
+ parts.push(document);
+ }
+ parts.push(']');
+ }
+ parts.push('}}');
+ return parts;
+}
+
+function sameStaleConflict(
+ previous: StaleExternalWriteConflict | undefined,
+ current: StaleExternalWriteConflict | undefined,
+): boolean {
+ return (
+ previous?.docName === current?.docName &&
+ previous?.file === current?.file &&
+ previous?.diskHash === current?.diskHash &&
+ previous?.diskContent === current?.diskContent &&
+ previous?.retainedContent === current?.retainedContent &&
+ previous?.detectedAt === current?.detectedAt
+ );
+}
+
+export interface DocumentDurabilityStateOptions {
+ persistencePath?: string;
+ fileForDocName?: (docName: string) => string;
+ onStaleExternalWriteChange?: () => void;
+ hasResolvedExtension?: (docName: string) => boolean;
+}
+
+export class DocumentDurabilityStateError extends Error {
+ readonly kind: 'unreadable' | 'corrupt' | 'incompatible';
+ readonly path: string;
+
+ constructor(path: string, kind: 'unreadable' | 'corrupt' | 'incompatible', cause?: unknown) {
+ const code =
+ cause instanceof Error && 'code' in cause && typeof cause.code === 'string'
+ ? cause.code
+ : undefined;
+ const recovery =
+ kind === 'unreadable'
+ ? code === 'EACCES' || code === 'EPERM'
+ ? 'Check the snapshot and parent-directory permissions for the account running OpenKnowledge, then retry.'
+ : code === 'EISDIR'
+ ? 'The snapshot path must be a regular file, not a directory. Preserve that directory and restore the snapshot file to this path.'
+ : 'Check the filesystem or mount and restore read access to this path, then retry.'
+ : kind === 'incompatible'
+ ? 'This build does not support the snapshot schema. Preserve the file and restore a compatible backup or contact support to identify a compatible build.'
+ : 'Restore this snapshot from a known-good backup, or contact support to recover its protected edits.';
+ super(
+ `Cannot safely open this project: its stale-write recovery snapshot is ${kind}${code ? ` [${code}]` : ''} (${path}). The snapshot has been preserved because it may contain the only copy of protected edits. ${recovery} Run ok bug-report from the project directory to collect diagnostics without starting the server. Do not delete it to bypass recovery.`,
+ { cause },
+ );
+ this.name = 'DocumentDurabilityStateError';
+ this.kind = kind;
+ this.path = path;
+ }
+}
+
+function restoreEntry<T>(map: Map<string, T>, key: string, previous: T | undefined): void {
+ if (previous === undefined) map.delete(key);
+ else map.set(key, previous);
+}
+
+function isDisplacedVersion(value: unknown): value is DisplacedVersion {
+ if (!value || typeof value !== 'object') return false;
+ const entry = value as Record<string, unknown>;
+ return typeof entry.hash === 'string' && typeof entry.at === 'number';
+}
+
+function isStaleConflict(value: unknown): value is StaleExternalWriteConflict {
+ if (!value || typeof value !== 'object') return false;
+ const entry = value as Record<string, unknown>;
+ return (
+ typeof entry.docName === 'string' &&
+ typeof entry.file === 'string' &&
+ typeof entry.diskHash === 'string' &&
+ typeof entry.diskContent === 'string' &&
+ typeof entry.detectedAt === 'string' &&
+ (entry.retainedContent === undefined || typeof entry.retainedContent === 'string')
+ );
+}
+
+function parsePersistedState(value: unknown): PersistedDocumentDurabilityState | null {
+ if (!value || typeof value !== 'object') return null;
+ const root = value as Record<string, unknown>;
+ if (
+ root.version !== 1 ||
+ !root.branches ||
+ typeof root.branches !== 'object' ||
+ Array.isArray(root.branches)
+ )
+ return null;
+ const branches = new Map<string, PersistedDocumentDurability[]>();
+ for (const [branch, documents] of Object.entries(root.branches)) {
+ if (!Array.isArray(documents)) return null;
+ const parsed: PersistedDocumentDurability[] = [];
+ for (const value of documents) {
+ if (!value || typeof value !== 'object') return null;
+ const document = value as Record<string, unknown>;
+ if (
+ typeof document.docName !== 'string' ||
+ typeof document.acknowledgedContent !== 'string' ||
+ !Array.isArray(document.displacedVersions) ||
+ !document.displacedVersions.every(isDisplacedVersion) ||
+ (document.staleExternalWrite !== undefined &&
+ (!isStaleConflict(document.staleExternalWrite) ||
+ document.staleExternalWrite.docName !== document.docName ||
+ document.staleExternalWrite.diskHash !==
+ contentHash(document.staleExternalWrite.diskContent)))
+ ) {
+ return null;
+ }
+ parsed.push({
+ docName: document.docName,
+ acknowledgedContent: document.acknowledgedContent,
+ displacedVersions: document.displacedVersions,
+ ...(document.staleExternalWrite ? { staleExternalWrite: document.staleExternalWrite } : {}),
+ });
+ }
+ branches.set(branch, parsed);
+ }
+ return { version: 1, branches: Object.fromEntries(branches) };
+}
+
export class DocumentDurabilityState {
private readonly reconciledBaseByBranch = new Map<string, Map<string, string>>();
+ private readonly displacedVersionsByBranch = new Map<string, Map<string, DisplacedVersion[]>>();
+ private readonly staleExternalWritesByBranch = new Map<
+ string,
+ Map<string, StaleExternalWriteConflict>
+ >();
private readonly inFlightFlushByDoc = new Map<string, PendingFlush[]>();
private readonly agentWriteStores = new Set<string>();
private readonly storeFailures = new Map<string, StoreFailure>();
private readonly storeDivergences = new Set<string>();
+ private readonly staleExternalWriteFreezes = new Set<string>();
+ private readonly persistencePath: string | undefined;
+ private readonly fileForDocName: (docName: string) => string;
+ private readonly onStaleExternalWriteChange: (() => void) | undefined;
+ private readonly hasResolvedExtension: ((docName: string) => boolean) | undefined;
+ private cachedDocumentsByBranch = new Map<string, Map<string, CachedDurabilityDocument>>();
+ private lastPersistedParts = snapshotParts(new Map());
+ private nextDisplacedExpiryAt = Number.POSITIVE_INFINITY;
private activeBranch: string;
private batchInProgress = false;
- constructor(initialBranch = 'main') {
+ constructor(initialBranch = 'main', options: DocumentDurabilityStateOptions = {}) {
this.activeBranch = initialBranch;
+ this.persistencePath = options.persistencePath;
+ this.fileForDocName = options.fileForDocName ?? ((docName) => `${docName}.md`);
+ this.onStaleExternalWriteChange = options.onStaleExternalWriteChange;
+ this.hasResolvedExtension = options.hasResolvedExtension;
this.reconciledBaseByBranch.set(initialBranch, new Map());
+ this.restore();
}
switchReconciledBaseScope(branch: string): void {
+ this.persist();
this.activeBranch = branch;
if (!this.reconciledBaseByBranch.has(branch)) {
this.reconciledBaseByBranch.set(branch, new Map());
@@ -47,7 +252,40 @@ export class DocumentDurabilityState {
bases = new Map();
this.reconciledBaseByBranch.set(this.activeBranch, bases);
}
- bases.set(docName, content);
+ if (bases.get(docName) === content && Date.now() < this.nextDisplacedExpiryAt) return;
+ const persist = this.isPersistedDocument(docName);
+ if (!persist) {
+ bases.set(docName, content);
+ return;
+ }
+ this.mutateDocument(docName, () => bases.set(docName, content));
+ }
+
+ recordSuccessfulStore(docName: string, content: string, displacedContent?: string): void {
+ if (displacedContent === undefined) {
+ this.setReconciledBase(docName, content);
+ return;
+ }
+ const at = Date.now();
+ const hash = contentHash(displacedContent);
+ this.mutateDocument(docName, () => {
+ let bases = this.reconciledBaseByBranch.get(this.activeBranch);
+ if (!bases) {
+ bases = new Map();
+ this.reconciledBaseByBranch.set(this.activeBranch, bases);
+ }
+ let versions = this.displacedVersionsByBranch.get(this.activeBranch);
+ if (!versions) {
+ versions = new Map();
+ this.displacedVersionsByBranch.set(this.activeBranch, versions);
+ }
+ const retained = (versions.get(docName) ?? []).filter(
+ (entry) => entry.at > at - DISPLACED_VERSION_TTL_MS && entry.hash !== hash,
+ );
+ retained.push({ hash, at });
+ bases.set(docName, content);
+ versions.set(docName, retained.slice(-DISPLACED_VERSION_LIMIT));
+ });
}
/**
@@ -60,8 +298,353 @@ export class DocumentDurabilityState {
* reads that same base and returns early without it.
*/
deleteReconciledBase(docName: string): void {
- this.reconciledBaseByBranch.get(this.activeBranch)?.delete(docName);
- this.inFlightFlushByDoc.delete(docName);
+ const persist = this.isPersistedDocument(docName);
+ if (!persist) {
+ this.reconciledBaseByBranch.get(this.activeBranch)?.delete(docName);
+ this.inFlightFlushByDoc.delete(docName);
+ return;
+ }
+ this.mutateDocument(
+ docName,
+ () => {
+ this.reconciledBaseByBranch.get(this.activeBranch)?.delete(docName);
+ this.inFlightFlushByDoc.delete(docName);
+ this.displacedVersionsByBranch.get(this.activeBranch)?.delete(docName);
+ this.staleExternalWritesByBranch.get(this.activeBranch)?.delete(docName);
+ },
+ persist,
+ );
+ }
+
+ private freshDisplacedVersions(docName: string): DisplacedVersion[] {
+ const perDoc = this.displacedVersionsByBranch.get(this.activeBranch);
+ const entries = perDoc?.get(docName);
+ if (!perDoc || !entries) return [];
+ const cutoff = Date.now() - DISPLACED_VERSION_TTL_MS;
+ const fresh = entries.filter((entry) => entry.at > cutoff);
+ if (fresh.length === entries.length) return entries;
+ this.mutateDocument(docName, () => {
+ if (fresh.length === 0) perDoc.delete(docName);
+ else perDoc.set(docName, fresh);
+ });
+ return fresh;
+ }
+
+ recordDisplacedVersion(docName: string, content: string): void {
+ const hash = contentHash(content);
+ const retained = this.freshDisplacedVersions(docName).filter((entry) => entry.hash !== hash);
+ retained.push({ hash, at: Date.now() });
+ let perDoc = this.displacedVersionsByBranch.get(this.activeBranch);
+ if (!perDoc) {
+ perDoc = new Map();
+ this.displacedVersionsByBranch.set(this.activeBranch, perDoc);
+ }
+ this.mutateDocument(docName, () =>
+ perDoc.set(docName, retained.slice(-DISPLACED_VERSION_LIMIT)),
+ );
+ }
+
+ clearDisplacedVersions(docName: string): void {
+ if (!this.displacedVersionsByBranch.get(this.activeBranch)?.has(docName)) return;
+ this.mutateDocument(docName, () =>
+ this.displacedVersionsByBranch.get(this.activeBranch)?.delete(docName),
+ );
+ }
+
+ isDisplacedVersion(docName: string, content: string): boolean {
+ const entries = this.freshDisplacedVersions(docName);
+ if (entries.length === 0) return false;
+ const hash = contentHash(content);
+ return entries.some((entry) => entry.hash === hash);
+ }
+
+ recordStaleExternalWrite(
+ docName: string,
+ diskContent: string,
+ retainedContent?: string,
+ ): StaleExternalWriteConflict {
+ let conflicts = this.staleExternalWritesByBranch.get(this.activeBranch);
+ if (!conflicts) {
+ conflicts = new Map();
+ this.staleExternalWritesByBranch.set(this.activeBranch, conflicts);
+ }
+ const diskHash = contentHash(diskContent);
+ const existing = conflicts.get(docName);
+ if (
+ existing?.diskHash === diskHash &&
+ (retainedContent === undefined || retainedContent === existing.retainedContent)
+ )
+ return existing;
+ const isNewConflict = existing?.diskHash !== diskHash;
+ const candidateContent = retainedContent ?? existing?.retainedContent;
+ const conflict = {
+ docName,
+ file: this.fileForDocName(docName),
+ diskHash,
+ diskContent,
+ ...(candidateContent === undefined ? {} : { retainedContent: candidateContent }),
+ detectedAt: existing?.diskHash === diskHash ? existing.detectedAt : new Date().toISOString(),
+ };
+ this.mutateDocument(docName, () => conflicts.set(docName, conflict));
+ if (isNewConflict) incrementStaleExternalWriteRefused();
+ return conflict;
+ }
+
+ staleExternalWriteMatches(docName: string, diskContent: string): boolean {
+ const conflict = this.staleExternalWritesByBranch.get(this.activeBranch)?.get(docName);
+ return conflict !== undefined && conflict.diskHash === contentHash(diskContent);
+ }
+
+ listStaleExternalWrites(): StaleExternalWriteConflict[] {
+ return [...(this.staleExternalWritesByBranch.get(this.activeBranch)?.values() ?? [])].map(
+ (conflict) => this.withResolvedFile(conflict),
+ );
+ }
+
+ getStaleExternalWrite(docName: string): StaleExternalWriteConflict | undefined {
+ const conflict = this.staleExternalWritesByBranch.get(this.activeBranch)?.get(docName);
+ return conflict === undefined ? undefined : this.withResolvedFile(conflict);
+ }
+
+ private withResolvedFile(conflict: StaleExternalWriteConflict): StaleExternalWriteConflict {
+ if (this.hasResolvedExtension && !this.hasResolvedExtension(conflict.docName)) return conflict;
+ const resolved = this.fileForDocName(conflict.docName);
+ return resolved === conflict.file ? conflict : { ...conflict, file: resolved };
+ }
+
+ clearStaleExternalWrite(docName: string): void {
+ const conflicts = this.staleExternalWritesByBranch.get(this.activeBranch);
+ const previous = conflicts?.get(docName);
+ if (!previous) return;
+ this.mutateDocument(docName, () => conflicts?.delete(docName));
+ }
+
+ private mutateDocument<T>(docName: string, mutate: () => T, persist = true): T {
+ const bases = this.reconciledBaseByBranch.get(this.activeBranch) ?? new Map<string, string>();
+ const versions =
+ this.displacedVersionsByBranch.get(this.activeBranch) ??
+ new Map<string, DisplacedVersion[]>();
+ const conflicts =
+ this.staleExternalWritesByBranch.get(this.activeBranch) ??
+ new Map<string, StaleExternalWriteConflict>();
+ const base = bases.get(docName);
+ const displaced = versions.get(docName);
+ const conflict = conflicts.get(docName);
+ const inFlight = this.inFlightFlushByDoc.get(docName);
+ let result: T;
+ try {
+ result = mutate();
+ if (persist) this.persist();
+ } catch (cause) {
+ restoreEntry(bases, docName, base);
+ restoreEntry(versions, docName, displaced);
+ restoreEntry(conflicts, docName, conflict);
+ restoreEntry(this.inFlightFlushByDoc, docName, inFlight);
+ this.reconciledBaseByBranch.set(this.activeBranch, bases);
+ this.displacedVersionsByBranch.set(this.activeBranch, versions);
+ this.staleExternalWritesByBranch.set(this.activeBranch, conflicts);
+ throw cause;
+ }
+ if (conflict !== conflicts.get(docName)) this.onStaleExternalWriteChange?.();
+ return result;
+ }
+
+ private isPersistedDocument(docName: string): boolean {
+ return (
+ this.displacedVersionsByBranch.get(this.activeBranch)?.has(docName) === true ||
+ this.staleExternalWritesByBranch.get(this.activeBranch)?.has(docName) === true
+ );
+ }
+
+ private restore(): void {
+ if (!this.persistencePath) return;
+ let raw: string;
+ try {
+ raw = readFileSync(this.persistencePath, 'utf-8');
+ } catch (cause) {
+ if (cause instanceof Error && 'code' in cause && cause.code === 'ENOENT') return;
+ throw new DocumentDurabilityStateError(this.persistencePath, 'unreadable', cause);
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (cause) {
+ throw new DocumentDurabilityStateError(this.persistencePath, 'corrupt', cause);
+ }
+ if (parsed && typeof parsed === 'object' && 'version' in parsed && parsed.version !== 1) {
+ throw new DocumentDurabilityStateError(this.persistencePath, 'incompatible');
+ }
+ const persisted = parsePersistedState(parsed);
+ if (!persisted) {
+ throw new DocumentDurabilityStateError(this.persistencePath, 'corrupt');
+ }
+ const cutoff = Date.now() - DISPLACED_VERSION_TTL_MS;
+ const persistedBranches = new Map<string, string[]>();
+ for (const [branch, documents] of Object.entries(persisted.branches)) {
+ const bases = new Map<string, string>();
+ const displaced = new Map<string, DisplacedVersion[]>();
+ const conflicts = new Map<string, StaleExternalWriteConflict>();
+ const cached = new Map<string, CachedDurabilityDocument>();
+ const serializedDocuments: string[] = [];
+ for (const document of documents) {
+ if (document.staleExternalWrite) {
+ try {
+ this.fileForDocName(document.docName);
+ } catch (cause) {
+ throw new DocumentDurabilityStateError(this.persistencePath, 'corrupt', cause);
+ }
+ }
+ const serialized = JSON.stringify(document);
+ serializedDocuments.push(serialized);
+ const expiresAt = nextDisplacedExpiry(document.displacedVersions);
+ this.nextDisplacedExpiryAt = Math.min(this.nextDisplacedExpiryAt, expiresAt);
+ const freshDisplaced = document.displacedVersions.filter((entry) => entry.at > cutoff);
+ if (freshDisplaced.length === 0 && !document.staleExternalWrite) continue;
+ bases.set(document.docName, document.acknowledgedContent);
+ if (freshDisplaced.length > 0) {
+ displaced.set(document.docName, freshDisplaced);
+ }
+ if (document.staleExternalWrite) {
+ conflicts.set(document.docName, document.staleExternalWrite);
+ }
+ if (freshDisplaced.length === document.displacedVersions.length) {
+ cached.set(document.docName, {
+ acknowledgedContent: document.acknowledgedContent,
+ displacedVersions: displaced.get(document.docName),
+ staleExternalWrite: document.staleExternalWrite
+ ? { ...document.staleExternalWrite }
+ : undefined,
+ expiresAt,
+ serialized,
+ });
+ }
+ }
+ persistedBranches.set(branch, serializedDocuments);
+ this.reconciledBaseByBranch.set(branch, bases);
+ if (displaced.size > 0) this.displacedVersionsByBranch.set(branch, displaced);
+ if (conflicts.size > 0) this.staleExternalWritesByBranch.set(branch, conflicts);
+ if (cached.size > 0) this.cachedDocumentsByBranch.set(branch, cached);
+ }
+ if (!this.reconciledBaseByBranch.has(this.activeBranch)) {
+ this.reconciledBaseByBranch.set(this.activeBranch, new Map());
+ }
+ this.lastPersistedParts = snapshotParts(persistedBranches);
+ }
+
+ private pruneExpiredDisplacedVersions(cutoff: number): void {
+ this.nextDisplacedExpiryAt = Number.POSITIVE_INFINITY;
+ for (const [branch, documents] of this.displacedVersionsByBranch) {
+ for (const [docName, entries] of documents) {
+ const fresh = entries.filter((entry) => entry.at > cutoff);
+ if (fresh.length === 0) documents.delete(docName);
+ else if (fresh.length !== entries.length) documents.set(docName, fresh);
+ for (const entry of fresh) {
+ this.nextDisplacedExpiryAt = Math.min(
+ this.nextDisplacedExpiryAt,
+ entry.at + DISPLACED_VERSION_TTL_MS,
+ );
+ }
+ }
+ if (documents.size === 0) this.displacedVersionsByBranch.delete(branch);
+ }
+ }
+
+ private persist(): void {
+ const cutoff = Date.now() - DISPLACED_VERSION_TTL_MS;
+ if (!this.persistencePath) {
+ this.pruneExpiredDisplacedVersions(cutoff);
+ return;
+ }
+ const branches = new Map<string, string[]>();
+ const nextCache = new Map<string, Map<string, CachedDurabilityDocument>>();
+ const branchNames = new Set([
+ ...this.displacedVersionsByBranch.keys(),
+ ...this.staleExternalWritesByBranch.keys(),
+ ]);
+ for (const branch of branchNames) {
+ const docNames = new Set([
+ ...(this.displacedVersionsByBranch.get(branch)?.keys() ?? []),
+ ...(this.staleExternalWritesByBranch.get(branch)?.keys() ?? []),
+ ]);
+ const documents: string[] = [];
+ const cachedDocuments = new Map<string, CachedDurabilityDocument>();
+ for (const docName of docNames) {
+ const acknowledgedContent = this.reconciledBaseByBranch.get(branch)?.get(docName);
+ if (acknowledgedContent === undefined) continue;
+ const versions = this.displacedVersionsByBranch.get(branch)?.get(docName);
+ const staleExternalWrite = this.staleExternalWritesByBranch.get(branch)?.get(docName);
+ const cached = this.cachedDocumentsByBranch.get(branch)?.get(docName);
+ if (
+ cached &&
+ cached.acknowledgedContent === acknowledgedContent &&
+ cached.displacedVersions === versions &&
+ sameStaleConflict(cached.staleExternalWrite, staleExternalWrite) &&
+ cached.expiresAt > cutoff + DISPLACED_VERSION_TTL_MS
+ ) {
+ documents.push(cached.serialized);
+ cachedDocuments.set(docName, cached);
+ continue;
+ }
+ const displacedVersions = (versions ?? []).filter((entry) => entry.at > cutoff);
+ if (displacedVersions.length === 0 && !staleExternalWrite) continue;
+ const document: PersistedDocumentDurability = {
+ docName,
+ acknowledgedContent,
+ displacedVersions,
+ ...(staleExternalWrite ? { staleExternalWrite } : {}),
+ };
+ const serialized = JSON.stringify(document);
+ documents.push(serialized);
+ cachedDocuments.set(docName, {
+ acknowledgedContent,
+ displacedVersions: versions,
+ staleExternalWrite: staleExternalWrite ? { ...staleExternalWrite } : undefined,
+ expiresAt: nextDisplacedExpiry(displacedVersions),
+ serialized,
+ });
+ }
+ if (documents.length > 0) {
+ branches.set(branch, documents);
+ nextCache.set(branch, cachedDocuments);
+ }
+ }
+ const parts = snapshotParts(branches);
+ if (
+ parts.length === this.lastPersistedParts.length &&
+ parts.every((part, index) => part === this.lastPersistedParts[index])
+ ) {
+ this.cachedDocumentsByBranch = nextCache;
+ this.pruneExpiredDisplacedVersions(cutoff);
+ return;
+ }
+ const serialized = parts.join('');
+ tracedMkdirSync(dirname(this.persistencePath), { recursive: true });
+ const temporaryPath = `${this.persistencePath}.tmp.${randomUUID()}`;
+ try {
+ tracedWriteFileSync(temporaryPath, serialized, {
+ encoding: 'utf-8',
+ mode: 0o600,
+ flag: 'wx',
+ });
+ tracedRenameSync(temporaryPath, this.persistencePath);
+ this.lastPersistedParts = parts;
+ this.cachedDocumentsByBranch = nextCache;
+ } catch (cause) {
+ try {
+ if (existsSync(temporaryPath)) tracedUnlinkSync(temporaryPath);
+ } catch (cleanupError) {
+ getLogger('document-durability-state').warn(
+ {
+ err: cleanupError,
+ writeError: cause instanceof Error ? cause.message : String(cause),
+ temporaryPath,
+ },
+ 'Unable to remove failed recovery snapshot temporary file',
+ );
+ }
+ throw cause;
+ }
+ this.pruneExpiredDisplacedVersions(cutoff);
}
private freshInFlightFlushes(docName: string): PendingFlush[] {
@@ -142,4 +725,12 @@ export class DocumentDurabilityState {
takeStoreDivergence(docName: string): boolean {
return this.storeDivergences.delete(docName);
}
+
+ recordStaleExternalWriteFreeze(docName: string): void {
+ this.staleExternalWriteFreezes.add(docName);
+ }
+
+ takeStaleExternalWriteFreeze(docName: string): boolean {
+ return this.staleExternalWriteFreezes.delete(docName);
+ }
}
diff --git a/packages/server/src/external-change.test.ts b/packages/server/src/external-change.test.ts
index 98a971fa2..6b7b35a27 100644
--- a/packages/server/src/external-change.test.ts
+++ b/packages/server/src/external-change.test.ts
@@ -1,3 +1,6 @@
+import { mkdirSync, mkdtempSync, renameSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { Hocuspocus } from '@hocuspocus/server';
import {
BridgeInvariantViolationError,
@@ -18,6 +21,20 @@ function getDoc(conn: Conn): Y.Doc {
return doc;
}
+const SECRET_YTEXT = 'PRIVATE-NOTE-ytext-body';
+const SECRET_FRAGMENT = 'PRIVATE-NOTE-fragment-body';
+const SECRET_DIFF = 'PRIVATE-NOTE-unified-diff-body';
+
+function loggedReconcileErrorPayload(spy: {
+ mock: { calls: unknown[][] };
+}): Record<string, unknown> {
+ const call = spy.mock.calls.find(
+ (args) => typeof args[1] === 'string' && args[1].includes('reconciled base'),
+ );
+ if (!call) throw new Error('reconcile recovery failure was not logged');
+ return call[0] as Record<string, unknown>;
+}
+
describe('applyExternalChange — throwing helper', () => {
let hp: Hocuspocus;
let durabilityState: DocumentDurabilityState;
@@ -203,6 +220,112 @@ describe('applyExternalChange — throwing helper', () => {
doc.transact = originalTransact as typeof doc.transact;
await conn.disconnect();
});
+
+ test('preserves the original bridge violation when recovery snapshot persistence also fails', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-external-double-failure-'));
+ const persistencePath = join(dir, 'state.json');
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ const docName = 'double-failure';
+ const conn = await hp.openDirectConnection(docName);
+ const doc = getDoc(conn);
+ const originalTransact = doc.transact.bind(doc);
+ const originalError = new BridgeInvariantViolationError({
+ site: 'observer-b',
+ docName,
+ ytextSnapshot: SECRET_YTEXT,
+ fragmentMdSnapshot: SECRET_FRAGMENT,
+ unifiedDiff: SECRET_DIFF,
+ stack: undefined,
+ });
+ const errorSpy = vi.spyOn(getLogger('reconcile'), 'error');
+ try {
+ applyExternalChange(state, hp, docName, '# Original\n');
+ state.recordDisplacedVersion(docName, 'old');
+ renameSync(persistencePath, `${persistencePath}.backup`);
+ mkdirSync(persistencePath);
+ doc.transact = ((fn: () => void, origin: unknown) => {
+ originalTransact(() => {
+ fn();
+ throw originalError;
+ }, origin);
+ }) as typeof doc.transact;
+ let actualError: unknown;
+ try {
+ applyExternalChange(state, hp, docName, '# Next\n');
+ } catch (cause) {
+ actualError = cause;
+ }
+ expect(actualError).toBe(originalError);
+ expect(doc.getText('source').toString()).toBe('# Next\n');
+ expect(state.getReconciledBase(docName)).toBe('# Original\n');
+
+ const serialized = JSON.stringify(loggedReconcileErrorPayload(errorSpy));
+ for (const secret of [SECRET_YTEXT, SECRET_FRAGMENT, SECRET_DIFF]) {
+ expect(serialized).not.toContain(secret);
+ }
+ expect(serialized).toContain('bridge-invariant-violation');
+ expect(serialized).toContain('"redacted":true');
+ } finally {
+ errorSpy.mockRestore();
+ doc.transact = originalTransact as typeof doc.transact;
+ await conn.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('redacts merge content loss and keeps ordinary failures diagnosable in the same field', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-external-redaction-'));
+ const persistencePath = join(dir, 'state.json');
+ const state = new DocumentDurabilityState('main', { persistencePath });
+ const docName = 'redaction';
+ const conn = await hp.openDirectConnection(docName);
+ const doc = getDoc(conn);
+ const originalTransact = doc.transact.bind(doc);
+ const contentLoss = new BridgeMergeContentLossError({
+ which: 'substring',
+ side: 'user',
+ baseline: SECRET_YTEXT,
+ userText: SECRET_FRAGMENT,
+ agentText: SECRET_DIFF,
+ result: '',
+ lostSubstrings: [SECRET_YTEXT],
+ });
+ const ordinary = new Error('atomic rename failed with EACCES');
+ const errorSpy = vi.spyOn(getLogger('reconcile'), 'error');
+ try {
+ applyExternalChange(state, hp, docName, '# Original\n');
+ state.recordDisplacedVersion(docName, 'old');
+ renameSync(persistencePath, `${persistencePath}.backup`);
+ mkdirSync(persistencePath);
+ let thrown: unknown = contentLoss;
+ doc.transact = ((fn: () => void, origin: unknown) => {
+ originalTransact(() => {
+ fn();
+ throw thrown;
+ }, origin);
+ }) as typeof doc.transact;
+
+ expect(() => applyExternalChange(state, hp, docName, '# Loss\n')).toThrow(contentLoss);
+ const lossPayload = JSON.stringify(loggedReconcileErrorPayload(errorSpy));
+ for (const secret of [SECRET_YTEXT, SECRET_FRAGMENT, SECRET_DIFF]) {
+ expect(lossPayload).not.toContain(secret);
+ }
+ expect(lossPayload).toContain('bridge-merge-content-loss');
+ expect(lossPayload).toContain('"redacted":true');
+
+ errorSpy.mockClear();
+ thrown = ordinary;
+ expect(() => applyExternalChange(state, hp, docName, '# Ordinary\n')).toThrow(ordinary);
+ const payload = loggedReconcileErrorPayload(errorSpy);
+ expect(payload.originalError).toBe('atomic rename failed with EACCES');
+ expect(JSON.stringify(payload.originalError)).not.toBe('{}');
+ } finally {
+ errorSpy.mockRestore();
+ doc.transact = originalTransact as typeof doc.transact;
+ await conn.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});
describe('createExternalChangeHandler — error-swallowing factory', () => {
diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.ts
index 4f890b93b..7a1b82b5a 100644
--- a/packages/server/src/external-change.ts
+++ b/packages/server/src/external-change.ts
@@ -6,8 +6,11 @@ import {
normalizeBridge,
prependFrontmatter,
stripFrontmatter,
+ toBridgeInvariantLog,
} from '@inkeep/open-knowledge-core';
import { formatReconcileSubject } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import type * as Y from 'yjs';
+import type { PrecomputedParse } from './bridge-intake.ts';
import {
type BridgeDeriveLossReporter,
DERIVE_LOSS_SITE_FILE_WATCHER_INTAKE,
@@ -39,6 +42,15 @@ import { FILE_SYSTEM_WRITER } from './shadow-repo.ts';
export { FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
+export function redactedErrorSummary(err: unknown): unknown {
+ const verbose = process.env.OK_TELEMETRY_VERBOSE === '1';
+ if (err instanceof BridgeMergeContentLossError) return err.toLog({ verbose });
+ if (err instanceof BridgeInvariantViolationError) {
+ return toBridgeInvariantLog(err.violation, { verbose });
+ }
+ return err instanceof Error ? err.message : String(err);
+}
+
export function applyExternalChange(
durabilityState: DocumentDurabilityState,
hocuspocus: Hocuspocus,
@@ -47,6 +59,7 @@ export function applyExternalChange(
resolveEmbed?: (basename: string, sourcePath: string) => string | null,
resolveSize?: (basename: string, sourcePath: string) => number | null,
bridgeLossReporter?: BridgeDeriveLossReporter,
+ precomputed?: PrecomputedParse,
): void {
if (
isSystemDoc(docName) ||
@@ -81,10 +94,25 @@ export function applyExternalChange(
try {
document.transact(() => {
- applyDiskContentToDoc(document, content, resolveEmbed, docName, resolveSize, detect);
+ applyDiskContentToDoc(
+ document,
+ content,
+ resolveEmbed,
+ docName,
+ resolveSize,
+ detect,
+ precomputed,
+ );
}, FILE_WATCHER_ORIGIN);
} catch (err) {
- durabilityState.setReconciledBase(docName, document.getText('source').toString());
+ try {
+ durabilityState.setReconciledBase(docName, document.getText('source').toString());
+ } catch (recoveryError) {
+ getLogger('reconcile').error(
+ { err: recoveryError, originalError: redactedErrorSummary(err), docName },
+ 'Unable to persist the reconciled base after an external-change failure',
+ );
+ }
throw err;
}
@@ -146,6 +174,76 @@ export function createExternalChangeHandler(
};
}
+const STALE_EXTERNAL_WRITE_REASON = 'stale-external-write';
+
+function clearStaleExternalWriteConflict(
+ durabilityState: DocumentDurabilityState,
+ document: Y.Doc | undefined,
+ docName: string,
+): void {
+ const retained = durabilityState.getStaleExternalWrite(docName)?.retainedContent;
+ if (retained !== undefined && retained !== durabilityState.getReconciledBase(docName)) return;
+ durabilityState.clearStaleExternalWrite(docName);
+ const lifecycleMap = document?.getMap('lifecycle');
+ if (lifecycleMap?.get('reason') !== STALE_EXTERNAL_WRITE_REASON) return;
+ lifecycleMap.delete('status');
+ lifecycleMap.delete('reason');
+ lifecycleMap.delete('detectedAt');
+}
+
+export function refuseStaleExternalWrite(
+ durabilityState: DocumentDurabilityState,
+ document: Y.Doc | undefined,
+ docName: string,
+ diskContent: string,
+ retainedContent?: string,
+): boolean {
+ const currentBase = durabilityState.getReconciledBase(docName);
+ const lifecycleMap = document?.getMap('lifecycle');
+ const pending = durabilityState.getStaleExternalWrite(docName);
+ if (pending?.retainedContent !== undefined && pending.retainedContent !== currentBase) {
+ const conflict = durabilityState.recordStaleExternalWrite(
+ docName,
+ diskContent,
+ retainedContent ?? pending.retainedContent,
+ );
+ lifecycleMap?.set('status', 'conflict');
+ lifecycleMap?.set('reason', STALE_EXTERNAL_WRITE_REASON);
+ lifecycleMap?.set('detectedAt', conflict.detectedAt);
+ return true;
+ }
+ if (currentBase === diskContent) {
+ clearStaleExternalWriteConflict(durabilityState, document, docName);
+ return false;
+ }
+
+ if (durabilityState.staleExternalWriteMatches(docName, diskContent)) {
+ const conflict =
+ retainedContent === undefined
+ ? durabilityState.getStaleExternalWrite(docName)
+ : durabilityState.recordStaleExternalWrite(docName, diskContent, retainedContent);
+ lifecycleMap?.set('status', 'conflict');
+ lifecycleMap?.set('reason', STALE_EXTERNAL_WRITE_REASON);
+ if (conflict) lifecycleMap?.set('detectedAt', conflict.detectedAt);
+ return true;
+ }
+
+ if (!durabilityState.isDisplacedVersion(docName, diskContent)) {
+ clearStaleExternalWriteConflict(durabilityState, document, docName);
+ return false;
+ }
+
+ getLogger('reconcile').warn(
+ { docName, diskBytes: diskContent.length },
+ `[reconcile] refused stale external write for ${docName}; disk restores a version this server already displaced`,
+ );
+ const conflict = durabilityState.recordStaleExternalWrite(docName, diskContent, retainedContent);
+ lifecycleMap?.set('status', 'conflict');
+ lifecycleMap?.set('reason', STALE_EXTERNAL_WRITE_REASON);
+ lifecycleMap?.set('detectedAt', conflict.detectedAt);
+ return true;
+}
+
export interface ReconcileBeforeWriteResult {
reconciled: boolean;
baseBytes: number;
@@ -185,7 +283,13 @@ export function reconcileDiskBeforeAgentWrite(
return NOT_RECONCILED;
const document = hocuspocus.documents.get(docName);
- if (document && isDocInConflict(document)) return NOT_RECONCILED;
+ if (
+ document &&
+ isDocInConflict(document) &&
+ document.getMap('lifecycle').get('reason') !== STALE_EXTERNAL_WRITE_REASON
+ ) {
+ return NOT_RECONCILED;
+ }
const base = durabilityState.getReconciledBase(docName);
if (base === undefined) return NOT_RECONCILED;
@@ -222,7 +326,10 @@ export function reconcileDiskBeforeAgentWrite(
}
const normalizedDisk = normalizeBridge(diskContent);
- if (normalizedDisk === normalizeBridge(base)) return NOT_RECONCILED;
+ if (diskContent === base) {
+ clearStaleExternalWriteConflict(durabilityState, document, docName);
+ return NOT_RECONCILED;
+ }
const pendingFlushes = durabilityState.inFlightFlushCount(docName);
if (pendingFlushes > 0) {
@@ -243,6 +350,11 @@ export function reconcileDiskBeforeAgentWrite(
if (!document) return NOT_RECONCILED;
+ if (refuseStaleExternalWrite(durabilityState, document, docName, diskContent)) {
+ return NOT_RECONCILED;
+ }
+ if (normalizedDisk === normalizeBridge(base)) return NOT_RECONCILED;
+
const ours = serializeYDocSource(document);
const outcome = reconcile({ docName, base, ours, theirs: diskContent });
diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.ts
index 82f373f1e..d3a9c6999 100644
--- a/packages/server/src/file-watcher.ts
+++ b/packages/server/src/file-watcher.ts
@@ -1,4 +1,3 @@
-import { createHash } from 'node:crypto';
import {
type Dirent,
existsSync,
@@ -33,6 +32,9 @@ import {
import { toPosix } from './path-utils.ts';
import { containsConflictMarkers } from './reconciliation.ts';
import { getMeter, withSpan } from './telemetry.ts';
+import { contentHash } from './version-hash.ts';
+
+export { contentHash } from './version-hash.ts';
const log = getLogger('file-watcher');
@@ -182,10 +184,6 @@ export function evictStaleTrackerEntries(): void {
}
}
-export function contentHash(content: string): string {
- return createHash('sha256').update(content).digest('hex');
-}
-
type WatcherDropReason =
| 'symlink-escape'
| 'filter-excluded'
diff --git a/packages/server/src/http/folder-template-routes.ts b/packages/server/src/http/folder-template-routes.ts
index d809a0b12..98704a156 100644
--- a/packages/server/src/http/folder-template-routes.ts
+++ b/packages/server/src/http/folder-template-routes.ts
@@ -96,9 +96,15 @@ export interface FolderTemplateRouteDeps {
scheduleOkArtifactFlush: (context: string) => void;
flushDiskAndDetectOutcome: (
docName: string,
- ) => Promise<{ kind: 'failure'; failure: StoreFailure } | { kind: 'divergence' } | null>;
+ ) => Promise<
+ | { kind: 'failure'; failure: StoreFailure }
+ | { kind: 'divergence' }
+ | { kind: 'stale-external-write' }
+ | null
+ >;
respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;
respondDiskDivergence: (res: ServerResponse, handler: string) => void;
+ respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;
registerWrittenDocInFileIndex: (docName: string, content: string) => void;
captureAndCloseDocuments: (
docNames: string[],
@@ -138,6 +144,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo
flushDiskAndDetectOutcome,
respondPersistenceFailure,
respondDiskDivergence,
+ respondStaleExternalWrite,
registerWrittenDocInFileIndex,
captureAndCloseDocuments,
renameTrackedPathInGit,
@@ -509,6 +516,10 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo
respondDiskDivergence(res, 'template-put');
return;
}
+ if (templateFlush?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'template-put', templateDocName);
+ return;
+ }
registerWrittenDocInFileIndex(templateDocName, composed.content);
@@ -1021,6 +1032,10 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo
respondDiskDivergence(res, 'template-import');
return;
}
+ if (templateFlush?.kind === 'stale-external-write') {
+ respondStaleExternalWrite(res, 'template-import', templateDocName);
+ return;
+ }
registerWrittenDocInFileIndex(templateDocName, composed.content);
diff --git a/packages/server/src/http/sync-routes.test.ts b/packages/server/src/http/sync-routes.test.ts
index 94001f7ed..e41433f09 100644
--- a/packages/server/src/http/sync-routes.test.ts
+++ b/packages/server/src/http/sync-routes.test.ts
@@ -4,6 +4,8 @@ import { join } from 'node:path';
import { Hocuspocus } from '@hocuspocus/server';
import { describe, expect, test } from 'vitest';
import { makeCaptureRes, makeSyntheticReq } from '../composition-rig.test-helper.ts';
+import type { ConflictEntry } from '../conflict-storage.ts';
+import { DocumentDurabilityState } from '../document-durability-state.ts';
import { loggerFactory } from '../logger.ts';
import type { SyncEngine } from '../sync-engine.ts';
import { createSyncRoutes } from './sync-routes.ts';
@@ -14,6 +16,7 @@ function buildGroup() {
contentDir: '/tmp/ok-sync-routes-test',
getPrincipal: undefined,
hocuspocus: new Hocuspocus({ quiet: true }),
+ durabilityState: new DocumentDurabilityState(),
log: loggerFactory.getLogger('test'),
checkLocalOpSecurity: () => true,
getSyncEngine: undefined,
@@ -50,6 +53,93 @@ describe('createSyncRoutes table', () => {
});
});
+describe('conflict list origins', () => {
+ test('labels Git and stale external-write conflicts distinctly', async () => {
+ const durabilityState = new DocumentDurabilityState();
+ durabilityState.recordStaleExternalWrite('stale', 'old bytes');
+ const gitConflicts: ConflictEntry[] = [
+ { file: 'git.md', detectedAt: '2026-09-08T10:00:00.000Z' },
+ ];
+ const engine = { getConflicts: () => gitConflicts } as unknown as SyncEngine;
+ const group = createSyncRoutes({
+ projectDir: '/tmp/ok-sync-routes-test',
+ contentDir: '/tmp/ok-sync-routes-test',
+ getPrincipal: undefined,
+ hocuspocus: new Hocuspocus({ quiet: true }),
+ durabilityState,
+ log: loggerFactory.getLogger('test'),
+ checkLocalOpSecurity: () => true,
+ getSyncEngine: () => engine,
+ serializeDoc: undefined,
+ });
+ const resolved = group.table.resolve('/api/sync/conflicts');
+ if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/conflicts');
+ const req = makeSyntheticReq({ url: '/api/sync/conflicts' });
+ const { res, captured } = makeCaptureRes();
+
+ await resolved.dispatch(req, res);
+
+ expect(captured.status).toBe(200);
+ expect(JSON.parse(captured.body)).toEqual({
+ conflicts: [
+ { file: 'git.md', detectedAt: '2026-09-08T10:00:00.000Z', conflictKind: 'git' },
+ {
+ file: 'stale.md',
+ detectedAt: expect.any(String),
+ conflictKind: 'stale-external-write',
+ },
+ ],
+ });
+ });
+
+ test('an unrecognized variant degrades that field instead of failing the whole list', async () => {
+ const degradedConflicts: ConflictEntry[] = [
+ {
+ file: 'weird.md',
+ detectedAt: '2026-09-08T10:00:00.000Z',
+ variant: 'index' as unknown as ConflictEntry['variant'],
+ },
+ {
+ file: 'ok.md',
+ detectedAt: '2026-09-08T10:01:00.000Z',
+ variant: 'working-tree',
+ theirsSha: 'a'.repeat(40),
+ },
+ ];
+ const engine = { getConflicts: () => degradedConflicts } as unknown as SyncEngine;
+ const group = createSyncRoutes({
+ projectDir: '/tmp/ok-sync-routes-test',
+ contentDir: '/tmp/ok-sync-routes-test',
+ getPrincipal: undefined,
+ hocuspocus: new Hocuspocus({ quiet: true }),
+ durabilityState: new DocumentDurabilityState(),
+ log: loggerFactory.getLogger('test'),
+ checkLocalOpSecurity: () => true,
+ getSyncEngine: () => engine,
+ serializeDoc: undefined,
+ });
+ const resolved = group.table.resolve('/api/sync/conflicts');
+ if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/conflicts');
+ const { res, captured } = makeCaptureRes();
+
+ await resolved.dispatch(makeSyntheticReq({ url: '/api/sync/conflicts' }), res);
+
+ expect(captured.status).toBe(200);
+ expect(JSON.parse(captured.body)).toEqual({
+ conflicts: [
+ { file: 'weird.md', detectedAt: '2026-09-08T10:00:00.000Z', conflictKind: 'git' },
+ {
+ file: 'ok.md',
+ detectedAt: '2026-09-08T10:01:00.000Z',
+ variant: 'working-tree',
+ theirsSha: 'a'.repeat(40),
+ conflictKind: 'git',
+ },
+ ],
+ });
+ });
+});
+
describe('conflict-content working-tree ours-read errno discrimination', () => {
function buildConflictGroup(projectDir: string) {
const engine = {
@@ -62,6 +152,7 @@ describe('conflict-content working-tree ours-read errno discrimination', () => {
contentDir: '/tmp/ok-sync-routes-test',
getPrincipal: undefined,
hocuspocus: new Hocuspocus({ quiet: true }),
+ durabilityState: new DocumentDurabilityState(),
log: loggerFactory.getLogger('test'),
checkLocalOpSecurity: () => true,
getSyncEngine: () => engine,
diff --git a/packages/server/src/http/sync-routes.ts b/packages/server/src/http/sync-routes.ts
index 757855903..551c1853b 100644
--- a/packages/server/src/http/sync-routes.ts
+++ b/packages/server/src/http/sync-routes.ts
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { join, resolve } from 'node:path';
import type { Hocuspocus } from '@hocuspocus/server';
-import type { Principal } from '@inkeep/open-knowledge-core';
+import type { ConflictEntryWire, Principal } from '@inkeep/open-knowledge-core';
import {
SyncConflictContentSuccessSchema,
SyncConflictsSuccessSchema,
@@ -22,11 +22,13 @@ import {
} from '../conflict-errors.ts';
import type { ResolveStrategy } from '../conflict-storage.ts';
import { isShareableOkArtifact } from '../content-filter.ts';
-import { stripDocExtension } from '../doc-extensions.ts';
+import type { DocumentDurabilityState } from '../document-durability-state.ts';
import { claimExternalChange, releaseExternalChangeClaim } from '../external-change-attribution.ts';
import { extractActorIdentity } from '../extract-actor-identity.ts';
import { pathToDocName } from '../file-watcher.ts';
+import { SymlinkEscapeError } from '../fs-safety.ts';
import type { PinoLogger } from '../logger.ts';
+import { containsUnresolvedConflictBlock } from '../reconciliation.ts';
import { assertRealpathWithinDir } from '../symlink-guard.ts';
import type { SyncEngine } from '../sync-engine.ts';
import { type ApiRouteGroup, type ApiRouteRecord, createApiRouteGroup } from './api-pipeline.ts';
@@ -35,10 +37,6 @@ import { errnoCode } from './handler-utils.ts';
import { withValidation } from './request-validation.ts';
import { successResponse } from './success-response.ts';
-function ytextHasConflictMarkers(text: string): boolean {
- return /^<{7} /m.test(text) && /^={7}$/m.test(text) && /^>{7} /m.test(text);
-}
-
const RESOLVE_ATTRIBUTION_WINDOW_MS = 3_000;
export interface SyncRouteDeps {
@@ -47,6 +45,7 @@ export interface SyncRouteDeps {
/** Server-side principal resolver — the only trusted actor source (precedent #24). */
getPrincipal: (() => Principal | null) | undefined;
hocuspocus: Hocuspocus;
+ durabilityState: DocumentDurabilityState;
log: PinoLogger;
checkLocalOpSecurity: (
req: IncomingMessage,
@@ -55,6 +54,11 @@ export interface SyncRouteDeps {
) => boolean;
getSyncEngine: (() => SyncEngine | null) | undefined;
serializeDoc: ((docName: string) => string | null) | undefined;
+ resolveStaleExternalWrite?: (
+ file: string,
+ strategy: ResolveStrategy,
+ content?: string,
+ ) => Promise<boolean>;
}
export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
@@ -63,10 +67,12 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
contentDir,
getPrincipal,
hocuspocus,
+ durabilityState,
log,
checkLocalOpSecurity,
getSyncEngine,
serializeDoc,
+ resolveStaleExternalWrite,
} = deps;
async function handleSyncStatus(req: IncomingMessage, res: ServerResponse): Promise<void> {
@@ -209,7 +215,18 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
}
try {
const engine = getSyncEngine?.();
- const conflicts = engine ? engine.getConflicts() : [];
+ const conflicts: ConflictEntryWire[] = engine
+ ? engine.getConflicts().map((entry) => ({ ...entry, conflictKind: 'git' as const }))
+ : [];
+ const knownFiles = new Set(conflicts.map((entry) => entry.file));
+ for (const conflict of durabilityState.listStaleExternalWrites()) {
+ if (knownFiles.has(conflict.file)) continue;
+ conflicts.push({
+ file: conflict.file,
+ detectedAt: conflict.detectedAt,
+ conflictKind: 'stale-external-write',
+ });
+ }
successResponse(
res,
200,
@@ -230,13 +247,6 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
const handleSyncResolveConflict = withValidation(
SyncResolveConflictRequestSchema,
async (_req, res, body) => {
- const engine = getSyncEngine?.();
- if (!engine) {
- errorResponse(res, 503, 'urn:ok:error:sync-not-active', 'Sync engine not active.', {
- handler: 'sync-resolve-conflict',
- });
- return;
- }
const { file, strategy, content } = body;
/**
* `extractActorIdentity` is the mandated resolver for actor-attributed handlers
@@ -258,6 +268,31 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
);
}
try {
+ const engine = getSyncEngine?.();
+ const gitConflict = engine?.getConflicts().some((entry) => entry.file === file) === true;
+ if (
+ !gitConflict &&
+ (await resolveStaleExternalWrite?.(file, strategy as ResolveStrategy, content))
+ ) {
+ if (claimedDocName) releaseExternalChangeClaim(claimedDocName);
+ successResponse(
+ res,
+ 200,
+ SyncResolveConflictSuccessSchema,
+ {},
+ {
+ handler: 'sync-resolve-conflict',
+ },
+ );
+ return;
+ }
+ if (!engine) {
+ if (claimedDocName) releaseExternalChangeClaim(claimedDocName);
+ errorResponse(res, 503, 'urn:ok:error:sync-not-active', 'Sync engine not active.', {
+ handler: 'sync-resolve-conflict',
+ });
+ return;
+ }
await engine.resolveConflict(file, strategy as ResolveStrategy, content);
successResponse(
res,
@@ -270,6 +305,12 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
);
} catch (e) {
if (claimedDocName) releaseExternalChangeClaim(claimedDocName);
+ if (e instanceof SymlinkEscapeError) {
+ errorResponse(res, 400, 'urn:ok:error:path-escape', 'Path escape detected.', {
+ handler: 'sync-resolve-conflict',
+ });
+ return;
+ }
if (e instanceof NoConflictTrackedError) {
errorResponse(
res,
@@ -320,7 +361,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
preBodyGate: (req, res) => {
if (!checkLocalOpSecurity(req, res, { handler: 'sync-resolve-conflict' })) return false;
const engine = getSyncEngine?.();
- if (!engine) {
+ if (!engine && !resolveStaleExternalWrite) {
errorResponse(res, 503, 'urn:ok:error:sync-not-active', 'Sync engine not active.', {
handler: 'sync-resolve-conflict',
});
@@ -373,12 +414,14 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
});
return;
}
- const trackedDocName = stripDocExtension(file);
+ const absoluteFile = resolve(projectDir, file);
+ const trackedDocName = pathToDocName(absoluteFile, contentDir);
const loadedDoc = hocuspocus.documents.get(trackedDocName);
const isConflictedByLifecycle = loadedDoc?.getMap('lifecycle').get('status') === 'conflict';
+ const staleConflict = durabilityState.getStaleExternalWrite(trackedDocName);
const engine = getSyncEngine?.();
const isTrackedByStore = engine ? engine.getConflicts().some((c) => c.file === file) : false;
- if (!isConflictedByLifecycle && !isTrackedByStore) {
+ if (!isConflictedByLifecycle && !isTrackedByStore && staleConflict?.file !== file) {
errorResponse(
res,
404,
@@ -394,6 +437,44 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
const source = url.searchParams.get('source');
const pg = simpleGit({ baseDir: projectDir, timeout: { block: 15_000 } });
+ if (staleConflict?.file === file && !isTrackedByStore) {
+ try {
+ assertRealpathWithinDir(absoluteFile, contentDir, {
+ allowShareableOkArtifact: isShareableOkArtifact,
+ });
+ const theirs = staleConflict.diskContent;
+ const ours =
+ serializeDoc?.(trackedDocName) ??
+ staleConflict.retainedContent ??
+ durabilityState.getReconciledBase(trackedDocName) ??
+ '';
+ successResponse(
+ res,
+ 200,
+ SyncConflictContentSuccessSchema,
+ {
+ file,
+ base: theirs,
+ ours,
+ theirs,
+ kind: 'both-modified',
+ lifecycleStatus: 'conflict',
+ conflictKind: 'stale-external-write',
+ },
+ { handler: 'sync-conflict-content' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read conflict content.',
+ { handler: 'sync-conflict-content', cause: e },
+ );
+ }
+ return;
+ }
+
const wtEntry = engine
?.getConflicts()
.find((c) => c.file === file && c.variant === 'working-tree');
@@ -417,7 +498,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
};
const theirs = await readBlob(wtEntry.theirsSha);
const base = await readBlob(wtEntry.baseSha);
- const docName = stripDocExtension(file);
+ const docName = trackedDocName;
const loaded = hocuspocus.documents.get(docName);
let ours = '';
let oursPresent = false;
@@ -462,7 +543,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
res,
200,
SyncConflictContentSuccessSchema,
- { file, base, ours, theirs, kind, lifecycleStatus },
+ { file, base, ours, theirs, kind, lifecycleStatus, conflictKind: 'git' },
{ handler: 'sync-conflict-content' },
);
} catch (e) {
@@ -521,7 +602,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
let ours = oursResult.present ? oursResult.content : '';
let lifecycleStatus: string | null = null;
if (source === 'ytext') {
- const docName = stripDocExtension(file);
+ const docName = trackedDocName;
const loaded = hocuspocus.documents.get(docName);
if (loaded) {
const rawStatus = loaded.getMap('lifecycle').get('status');
@@ -529,7 +610,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
typeof rawStatus === 'string' && rawStatus.length > 0 ? rawStatus : null;
if (kind !== 'delete-modify') {
const ytextOurs = serializeDoc ? serializeDoc(docName) : null;
- if (ytextOurs !== null && !ytextHasConflictMarkers(ytextOurs)) {
+ if (ytextOurs !== null && !containsUnresolvedConflictBlock(ytextOurs)) {
ours = ytextOurs;
} else if (ytextOurs !== null) {
console.warn(
@@ -552,7 +633,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
res,
200,
SyncConflictContentSuccessSchema,
- { file, base, ours, theirs, kind, lifecycleStatus },
+ { file, base, ours, theirs, kind, lifecycleStatus, conflictKind: 'git' },
{ handler: 'sync-conflict-content' },
);
} catch (e) {
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index c905785ae..35a8284f6 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -135,7 +135,11 @@ export {
detectClaudeDesktopPresence,
} from './detect-claude-desktop.ts';
export { FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
-export { DocumentDurabilityState, type StoreFailure } from './document-durability-state.ts';
+export {
+ DocumentDurabilityState,
+ DocumentDurabilityStateError,
+ type StoreFailure,
+} from './document-durability-state.ts';
export {
canonicalProjectKey,
clearAllEmbeddingsKeys,
diff --git a/packages/server/src/mcp/tools/conflicts.test.ts b/packages/server/src/mcp/tools/conflicts.test.ts
index 015abe50d..758856269 100644
--- a/packages/server/src/mcp/tools/conflicts.test.ts
+++ b/packages/server/src/mcp/tools/conflicts.test.ts
@@ -1,6 +1,9 @@
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
+import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
+import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register } from './conflicts.ts';
@@ -24,8 +27,38 @@ type Handler = (args: {
function capture(serverUrl: string | undefined, cwd: string): Handler {
let handler: Handler | undefined;
const server = {
- registerTool(_n: string, _c: unknown, h: Handler) {
- handler = h;
+ registerTool(_n: string, config: { outputSchema: unknown }, h: Handler) {
+ const normalized = normalizeObjectSchema(config.outputSchema);
+ if (!normalized) throw new Error('missing output schema');
+ const schema = toJsonSchemaCompat(normalized, { strictUnions: true, pipeStrategy: 'output' });
+ expect(JSON.stringify(schema)).toContain('stale-external-write');
+ expect(JSON.stringify(schema)).toContain('working-tree');
+ const validateAgainstAdvertisedSchema = new AjvJsonSchemaValidator().getValidator(schema);
+ handler = async (args) => {
+ const result = await h(args);
+ if (result.structuredContent) {
+ expect(validateAgainstAdvertisedSchema(result.structuredContent).valid).toBe(true);
+ if (args.kind === 'content') {
+ expect(
+ validateAgainstAdvertisedSchema({
+ ...result.structuredContent,
+ content: {
+ ...(result.structuredContent.content as Record<string, unknown>),
+ conflictKind: 'unknown',
+ },
+ }).valid,
+ ).toBe(false);
+ } else {
+ expect(
+ validateAgainstAdvertisedSchema({
+ ...result.structuredContent,
+ list: [{ file: 'a.md', detectedAt: 'now', conflictKind: 'unknown' }],
+ }).valid,
+ ).toBe(false);
+ }
+ }
+ return result;
+ };
},
} as unknown as ServerInstance;
register(server, { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwd });
@@ -46,7 +79,10 @@ beforeAll(async () => {
if (url.pathname === '/api/sync/conflicts') {
return Response.json({
ok: true,
- conflicts: [{ file: 'notes/sso.md', detectedAt: 'now' }],
+ conflicts: [
+ { file: 'notes/sso.md', detectedAt: 'now', conflictKind: 'stale-external-write' },
+ { file: 'overlay.md', detectedAt: 'now', conflictKind: 'git', variant: 'working-tree' },
+ ],
});
}
if (url.pathname === '/api/sync/conflict-content') {
@@ -57,6 +93,7 @@ beforeAll(async () => {
ours: 'O',
theirs: 'T',
kind: 'both-modified',
+ conflictKind: 'stale-external-write',
lifecycleStatus: 'conflict',
});
}
@@ -72,6 +109,10 @@ describe('conflicts — kind discriminator', () => {
const result = await capture(baseUrl, cwd)({ kind: 'list' });
expect(result.isError).toBeFalsy();
expect(Array.isArray(result.structuredContent?.list)).toBe(true);
+ expect(result.structuredContent?.list).toMatchObject([
+ { conflictKind: 'stale-external-write' },
+ { conflictKind: 'git', variant: 'working-tree' },
+ ]);
expect(result.content[0]?.text).toContain('notes/sso.md');
});
@@ -80,6 +121,7 @@ describe('conflicts — kind discriminator', () => {
expect(result.isError).toBeFalsy();
const content = result.structuredContent?.content as { shape?: string } | undefined;
expect(content?.shape).toBe('both-modified');
+ expect(content).toHaveProperty('conflictKind', 'stale-external-write');
expect(content).not.toHaveProperty('kind');
expect(result.content[0]?.text).toContain('shape: both-modified');
});
diff --git a/packages/server/src/mcp/tools/conflicts.ts b/packages/server/src/mcp/tools/conflicts.ts
index c5457cefc..20c6d3177 100644
--- a/packages/server/src/mcp/tools/conflicts.ts
+++ b/packages/server/src/mcp/tools/conflicts.ts
@@ -1,9 +1,9 @@
+import { ConflictEntrySchema } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import {
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpGet,
- looseObjectArray,
outputSchemaWithText,
ROUTED_CWD_DESCRIPTION,
resolveProjectServerContext,
@@ -12,10 +12,12 @@ import {
} from './shared.ts';
const DESCRIPTION = [
- '[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:',
+ '[Requires: Hocuspocus server] Read Git merge conflicts and local stale external-write conflicts. Dispatches on `kind`:',
'',
- '- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.',
- '- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',
+ '- `kind: "list"` — enumerate every tracked conflict. Returns `{ list: [{ file, detectedAt, conflictKind, ... }] }` (empty when none). The entry point to the resolve flow.',
+ '- `kind: "content"` — fetch the versions for one `file`. Returns `{ content: { file, base, ours, theirs, shape, conflictKind, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',
+ '- `conflictKind: "git"` uses Git versions. `conflictKind: "stale-external-write"` means a known older disk version was refused: `base` is the last reconciled version, `ours` is the protected live or recovered version, and `theirs` is the rejected disk version. Resolving this local conflict does not create a Git commit.',
+ '- A Git list entry with `variant: "working-tree"` is a local overlay conflict: resolution changes the working tree without a resolution commit. Other Git entries use index stages and commit only when the last conflict clears. The content response does not distinguish these two Git variants; inspect the list entry.',
'',
'**Parameters:**',
'- `kind` — `list` | `content`.',
@@ -49,12 +51,16 @@ export function register(server: ServerInstance, deps: ConflictsDeps): void {
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
outputSchema: outputSchemaWithText({
- list: looseObjectArray
+ list: z
+ .array(ConflictEntrySchema)
.optional()
- .describe('`kind: "list"` — every tracked conflict (`{ file, detectedAt, ... }`).'),
+ .describe('`kind: "list"` — every tracked conflict, including its conflictKind.'),
content: z
.object({
file: z.string().describe('The conflicted file.'),
+ conflictKind: z
+ .enum(['git', 'stale-external-write'])
+ .describe('Git merge or local stale disk-write conflict.'),
base: z.string().describe('Merge-base stage content.'),
ours: z.string().describe('Our stage (live Y.Text when loaded server-side).'),
theirs: z.string().describe('Their stage content.'),
@@ -102,10 +108,12 @@ export function register(server: ServerInstance, deps: ConflictsDeps): void {
rec.kind === 'delete-modify' || rec.kind === 'modify-delete' ? rec.kind : 'both-modified';
const lifecycleStatus =
typeof rec.lifecycleStatus === 'string' ? rec.lifecycleStatus : null;
+ const conflictKind =
+ rec.conflictKind === 'stale-external-write' ? 'stale-external-write' : 'git';
const lifecycleSuffix = lifecycleStatus ? ` (lifecycle: ${lifecycleStatus})` : '';
const text = `Conflict stages for ${file} (shape: ${shape})${lifecycleSuffix}:\n--- base ---\n${base}\n--- ours ---\n${ours}\n--- theirs ---\n${theirs}`;
return textPlusStructured(text, {
- content: { file, base, ours, theirs, shape, lifecycleStatus },
+ content: { file, base, ours, theirs, shape, conflictKind, lifecycleStatus },
});
}
diff --git a/packages/server/src/mcp/tools/resolve-conflict.test.ts b/packages/server/src/mcp/tools/resolve-conflict.test.ts
index a96a096ea..9db9502d5 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.test.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.test.ts
@@ -137,7 +137,7 @@ describe('resolve_conflict MCP tool', () => {
expect(result.isError).toBeUndefined();
});
- test('strategy=content forwards the content arg verbatim', async () => {
+ test.each(['merged-by-hand', ''])('strategy=content forwards exact bytes %j', async (content) => {
const { server, registrations } = createCapturingServer();
const fetchCalls: Array<{ init?: RequestInit }> = [];
globalThis.fetch = (async (_input, init) => {
@@ -153,13 +153,13 @@ describe('resolve_conflict MCP tool', () => {
const result = await tool.handler({
file: 'a.md',
strategy: 'content',
- content: 'merged-by-hand',
+ content,
});
expect(JSON.parse(String(fetchCalls[0]?.init?.body))).toEqual({
file: 'a.md',
strategy: 'content',
- content: 'merged-by-hand',
+ content,
});
expect(result.isError).toBeUndefined();
});
diff --git a/packages/server/src/mcp/tools/resolve-conflict.ts b/packages/server/src/mcp/tools/resolve-conflict.ts
index a879c21d1..f96c6b327 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.ts
@@ -11,22 +11,22 @@ import {
} from './shared.ts';
const DESCRIPTION = [
- '[Requires: Hocuspocus server] Resolve a tracked merge conflict by writing the chosen content to disk and committing.',
+ '[Requires: Hocuspocus server] Resolve a tracked Git merge or local stale external-write conflict. Inspect `conflictKind` and any `variant` from conflicts({ kind: "list" }), then fetch conflicts({ kind: "content", file }) to choose exact versions.',
'',
'Strategy:',
- '- `mine` — runs `git checkout --ours -- <file>` then `git add` (your committed ours stage, stage 2). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.',
- '- `theirs` — runs `git checkout --theirs -- <file>` then `git add` (their committed stage 3). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.',
- '- `content` — writes the provided `content` argument (e.g. a per-hunk merged result, or the live Y.Text bytes the user sees in the DiffView). The provided string must be non-empty — use `delete` to remove the file entirely (an agent constructing a per-hunk merge that happens to land on `""` gets a 400 at the Zod boundary rather than a misleading 500).',
- '- `delete` — runs `git rm <file>` then commits the deletion. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `shape` field on `conflicts({ kind: "content" })` to pick the right strategy for the conflict shape.',
+ '- `mine` — for a stale external write, keeps the protected live or recovered version. For a Git index conflict, selects committed stage 2; for a working-tree conflict, keeps the current working-tree file. A missing Git stage requires `delete` instead.',
+ '- `theirs` — for a stale external write, accepts the rejected disk version. For a Git conflict, selects the incoming version (stage 3 for index conflicts). A missing Git stage requires `delete` instead.',
+ '- `content` — writes the exact provided string, including `""` to keep an empty file. Use this to preserve the live Y.Text bytes returned as `ours`, which can differ from the Git version selected by `mine`. Omitted content is rejected.',
+ '- `delete` — removes the file explicitly. For Git index conflicts, stages the deletion. For stale external writes and Git working-tree overlays, clears the conflict without a resolution commit.',
'',
- 'Returns 200 on success. 422 (`urn:ok:error:unresolved-conflict-markers`) means the `content` you sent still contains a `<<<<<<< … >>>>>>>` block — a permanent rejection of those bytes, so resolve every region before retrying rather than re-sending. 500 indicates commit failure (re-call `conflicts({ kind: "list" })` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',
+ 'Returns 200 on success. 422 (`urn:ok:error:unresolved-conflict-markers`) means the provided content still contains an unresolved conflict block. A 500 can indicate disk, bridge, recovery-snapshot, or Git commit failure. Re-call conflicts({ kind: "list" }) and inspect content before retrying: resolution is best-effort and non-atomic. Local stale-write protection remains until resolution succeeds.',
'',
- '**DESTRUCTIVE:** this modifies the working tree and creates a git commit.',
+ '**DESTRUCTIVE:** this modifies the working tree. Git index resolutions stage each file and commit when the last conflict clears. Local stale external-write and Git working-tree overlay resolutions do not create a resolution commit.',
'',
'**Parameters:**',
- '- `file` — Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`).',
+ '- `file` — Exact relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',
'- `strategy` — One of `mine` | `theirs` | `content` | `delete`.',
- '- `content` — Required (non-empty) when `strategy === "content"`; ignored otherwise.',
+ '- `content` — Required when `strategy === "content"`; an empty string keeps an empty file. Ignored otherwise.',
].join('\n');
interface ResolveConflictDeps {
@@ -49,17 +49,19 @@ export function register(server: ServerInstance, deps: ResolveConflictDeps): voi
file: z
.string()
.min(1)
- .describe('Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`).'),
+ .describe(
+ 'Exact relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',
+ ),
strategy: z
.enum(['mine', 'theirs', 'content', 'delete'])
.describe(
- 'Resolution strategy. `content` requires the `content` arg. `delete` runs `git rm` — use for delete-vs-modify (DU/UD) shapes where one stage is missing.',
+ 'Resolution strategy. `content` requires exact bytes, including an empty string. `delete` explicitly removes the file. Inspect list conflictKind and variant, then content: Git index, working-tree, and stale external-write sides differ.',
),
content: z
.string()
.optional()
.describe(
- 'Exact bytes to write. Required when `strategy === "content"`; ignored otherwise.',
+ 'Exact bytes to write, including an empty string to keep an empty file. Required when strategy is content; ignored otherwise.',
),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
diff --git a/packages/server/src/metrics.test.ts b/packages/server/src/metrics.test.ts
index 05021bf86..354f338e8 100644
--- a/packages/server/src/metrics.test.ts
+++ b/packages/server/src/metrics.test.ts
@@ -15,6 +15,7 @@ import {
incrementPark,
incrementReconcile,
incrementRescueBuffer,
+ incrementStaleExternalWriteRefused,
incrementUpstreamImport,
resetMetrics,
} from './metrics';
@@ -70,6 +71,18 @@ describe('reconciliation metrics', () => {
expect(m.parkCount).toBe(2);
});
+ test('stale-write refusal does not count as a merge conflict or content loss', () => {
+ resetMetrics();
+ incrementStaleExternalWriteRefused();
+ const metrics = getMetrics();
+ expect(metrics.staleExternalWriteRefused).toBe(1);
+ expect(metrics.conflictCount).toBe(0);
+ expect(metrics.persistenceDivergenceRealign).toBe(0);
+ expect(metrics.persistenceDivergenceRealignCheckpointCreated).toBe(0);
+ resetMetrics();
+ expect(getMetrics().staleExternalWriteRefused).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 c10fe5155..2c812b292 100644
--- a/packages/server/src/metrics.ts
+++ b/packages/server/src/metrics.ts
@@ -16,6 +16,7 @@ export type MapDrivenSpliceMemoSkipReason =
export interface ReconciliationMetrics {
reconcileCount: number;
conflictCount: number;
+ staleExternalWriteRefused: number;
batchCount: number;
upstreamImportCount: number;
persistenceStoreRemovedDocCount: number;
@@ -118,6 +119,7 @@ export interface ReconciliationMetrics {
const counters: ReconciliationMetrics = {
reconcileCount: 0,
conflictCount: 0,
+ staleExternalWriteRefused: 0,
batchCount: 0,
upstreamImportCount: 0,
persistenceStoreRemovedDocCount: 0,
@@ -215,6 +217,10 @@ export function incrementConflict(): void {
counters.conflictCount++;
}
+export function incrementStaleExternalWriteRefused(): void {
+ counters.staleExternalWriteRefused++;
+}
+
export function incrementBatch(): void {
counters.batchCount++;
}
@@ -580,6 +586,7 @@ export function getMetrics(): ReconciliationMetrics {
export function resetMetrics(): void {
counters.reconcileCount = 0;
counters.conflictCount = 0;
+ counters.staleExternalWriteRefused = 0;
counters.batchCount = 0;
counters.upstreamImportCount = 0;
counters.persistenceStoreRemovedDocCount = 0;
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index 78f061a21..e5a179aa5 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -54,6 +54,7 @@ import {
import type { DerivedDocumentIndexPersistencePort } from './derived-document-index.ts';
import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
import { DocumentDurabilityState, type StoreFailure } from './document-durability-state.ts';
+import { refuseStaleExternalWrite } from './external-change.ts';
import { contentHash, registerWrite } from './file-watcher.ts';
import { tracedMkdir, tracedRename, tracedUnlinkSync, tracedWriteFile } from './fs-traced.ts';
import { errnoCode } from './http/handler-utils.ts';
@@ -1447,19 +1448,37 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
await tracedWriteFile(canonicalPath, '# NATIVE\n\nnative-divergence-injected\n', 'utf-8');
}
+ let diskBeforeWrite: string | null = null;
if (agentTriggeredStore && currentBase !== undefined) {
- let diskNow: string | null = null;
try {
- if (existsSync(canonicalPath)) diskNow = readFileSync(canonicalPath, 'utf-8');
+ if (existsSync(canonicalPath)) {
+ diskBeforeWrite = readFileSync(canonicalPath, 'utf-8');
+ }
} catch (err) {
- diskNow = null;
+ diskBeforeWrite = null;
log.warn(
{ err, documentName },
'[persistence] L3 disk-read failed; divergence check skipped for this store',
);
}
- if (diskNow !== null && normalizeBridge(diskNow) !== normalizeBridge(currentBase)) {
- const diskContent = diskNow;
+ if (
+ diskBeforeWrite !== null &&
+ normalizeBridge(diskBeforeWrite) !== normalizeBridge(currentBase)
+ ) {
+ const diskContent = diskBeforeWrite;
+ if (
+ refuseStaleExternalWrite(
+ durabilityState,
+ document,
+ documentName,
+ diskContent,
+ markdown,
+ )
+ ) {
+ durabilityState.recordStaleExternalWriteFreeze(documentName);
+ persistenceDeferCounts.delete(documentName);
+ return;
+ }
console.warn(
JSON.stringify({
event: 'agent-write-content-divergence',
@@ -1557,7 +1576,13 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
`[persistence] Wrote ${canonicalPath} (${markdown.length} bytes)`,
);
- durabilityState.setReconciledBase(documentName, markdown);
+ durabilityState.recordSuccessfulStore(
+ documentName,
+ markdown,
+ agentTriggeredStore && currentBase !== undefined && currentBase !== markdown
+ ? (diskBeforeWrite ?? currentBase)
+ : undefined,
+ );
docsWithSettledWrite.add(documentName);
tripwireResetFailedDocs.delete(documentName);
persistenceDeferCounts.delete(documentName);
@@ -1746,6 +1771,24 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
}
const raw = readFileSync(filePath, 'utf-8');
+ const currentBase = durabilityState.getReconciledBase(documentName);
+ const staleExternalWrite = refuseStaleExternalWrite(
+ durabilityState,
+ document,
+ documentName,
+ raw,
+ );
+ let contentToLoad = raw;
+ if (staleExternalWrite) {
+ const retainedContent =
+ durabilityState.getStaleExternalWrite(documentName)?.retainedContent ?? currentBase;
+ if (retainedContent === undefined) {
+ throw new Error(
+ `Missing acknowledged content for stale external write: ${documentName}`,
+ );
+ }
+ contentToLoad = retainedContent;
+ }
const xmlFragment = document.getXmlFragment('default');
log.info(
@@ -1757,7 +1800,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
document.transact(() => {
applyDiskContentToDoc(
document,
- raw,
+ contentToLoad,
options?.resolveEmbed,
documentName,
options?.resolveSize,
@@ -1781,7 +1824,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
);
}
- durabilityState.setReconciledBase(documentName, raw);
+ if (!staleExternalWrite) durabilityState.setReconciledBase(documentName, raw);
},
).finally(() => {
loadDurationHist?.record((Date.now() - started) / 1000);
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index 01634f0ef..02099111d 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -30,6 +30,7 @@ import { BacklinkIndex } from './backlink-index.ts';
import { getBootTimings, resetBootTimingsForTest, startBootTimings } from './boot-timings.ts';
import { updateGeneratedIndexGitAttributes } from './content/generated-index-git-attributes.ts';
import { DerivedDocumentIndex } from './derived-document-index.ts';
+import { _resetDocExtensionsForTests } from './doc-extensions.ts';
import { classifyGitError } from './error-classification.ts';
import { applyExternalChange } from './external-change.ts';
import type {
@@ -52,6 +53,7 @@ import { createServer, type ServerInstance } from './server-factory.ts';
import { releaseServerLock } from './server-lock.ts';
import { initShadowRepo, shadowGit } from './shadow-repo.ts';
import { TagIndex } from './tag-index.ts';
+import { contentHash } from './version-hash.ts';
const watcherStartupFailures = vi.hoisted(() => ({ file: false, head: false }));
@@ -873,6 +875,48 @@ describe('createServer() degraded signal', () => {
}
});
+ test('an .mdx conflict restored before any scan resolves to its .mdx file', async () => {
+ watcherStartupFailures.file = true;
+ _resetDocExtensionsForTests();
+ const contentDir = mkdtempSync(resolve(testProjectDir, 'content-'));
+ const diskContent = 'bytes the editor tried to overwrite';
+ mkdirSync(join(testProjectDir, '.ok', LOCAL_DIR), { recursive: true });
+ writeFileSync(
+ join(testProjectDir, '.ok', LOCAL_DIR, 'stale-external-writes.json'),
+ JSON.stringify({
+ version: 1,
+ branches: {
+ main: [
+ {
+ docName: 'notes/guide',
+ acknowledgedContent: 'acknowledged',
+ displacedVersions: [],
+ staleExternalWrite: {
+ docName: 'notes/guide',
+ file: `${resolve(contentDir).slice(resolve(testProjectDir).length + 1)}/notes/guide.mdx`,
+ diskHash: contentHash(diskContent),
+ diskContent,
+ detectedAt: '2026-09-08T10:00:00.000Z',
+ },
+ },
+ ],
+ },
+ }),
+ );
+
+ const srv = createServer({ contentDir, projectDir: testProjectDir, quiet: true });
+ try {
+ await srv.ready;
+ expect(srv.degraded).toEqual(['file-watcher']);
+ expect(srv.durabilityState.getStaleExternalWrite('notes/guide')?.file).toMatch(
+ /notes\/guide\.mdx$/,
+ );
+ } finally {
+ await srv.destroy();
+ _resetDocExtensionsForTests();
+ }
+ });
+
test('degraded is readonly — push and reassignment are compile-time errors', async () => {
const contentDir = mkdtempSync(resolve(testProjectDir, 'content-'));
const srv: ServerInstance = createServer({
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index b4d87a5f0..20bba1fcc 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -40,6 +40,7 @@ import {
resolveLocalAutoSyncMode,
type SyncMode,
type SyncModeChangeSource,
+ stripFrontmatter,
toEffectiveBase,
} from '@inkeep/open-knowledge-core';
import {
@@ -71,6 +72,7 @@ import {
parseHocuspocusAuthToken,
} from './auth-token-schema.ts';
import { bootElapsedMs, recordBootPhase, setBootField } from './boot-timings.ts';
+import type { PrecomputedParse } from './bridge-intake.ts';
import {
type BridgeDeriveLossReporter,
createBridgeDeriveLossReporter,
@@ -95,6 +97,8 @@ import {
createConflictLifecycleSeedExtension,
entryMatchesDocName,
} from './conflict-lifecycle-seed.ts';
+import { requireConflictResolutionContent } from './conflict-resolution-input.ts';
+import type { ResolveStrategy } from './conflict-storage.ts';
import { type GeneratedArtifactEnv, writeGeneratedArtifact } from './content/generated-artifact.ts';
import {
type GeneratedIndexGitAttributesStatus,
@@ -112,7 +116,11 @@ import {
planDirectoryIndexRegenerations,
ROOT_INDEX_DOC_NAME,
} from './content/regenerate-index.ts';
-import { type ContentFilter, createContentFilter } from './content-filter.ts';
+import {
+ type ContentFilter,
+ createContentFilter,
+ isShareableOkArtifact,
+} from './content-filter.ts';
import { isWithinContentDir, safeContentPath } from './content-path.ts';
import { dropPendingDocs, recordContributor } from './contributor-tracker.ts';
import {
@@ -124,6 +132,7 @@ import {
canonicalDocName,
docNameToRelativePath,
getDocExtension,
+ isRegisteredMarkdownDocName,
stripDocExtension,
} from './doc-extensions.ts';
import { runDocLineageGuard } from './doc-lineage-guard.ts';
@@ -142,6 +151,8 @@ import {
import {
applyExternalChange,
FILE_WATCHER_ORIGIN,
+ redactedErrorSummary,
+ refuseStaleExternalWrite,
serializeYDocSource,
} from './external-change.ts';
import {
@@ -154,7 +165,7 @@ import {
startWatcher,
type WatcherHandle,
} from './file-watcher.ts';
-import { normalizeFsPath, tracedAtomicFs, tracedMkdirSync } from './fs-traced.ts';
+import { normalizeFsPath, tracedAtomicFs, tracedMkdirSync, tracedUnlinkSync } from './fs-traced.ts';
import { buildSyncCredentialConfig } from './git-handle.ts';
import type {
CheckPushPermissionOptions,
@@ -260,6 +271,7 @@ import {
import { readOriginGitHubRepo, shouldResetAmbientCredentials } from './share/git-context.ts';
import { resyncRecordedSkillCopies } from './skill-placements.ts';
import { assertCompatibleStateManifest } from './state-manifest.ts';
+import { assertRealpathWithinDir } from './symlink-guard.ts';
import { SyncEngine } from './sync-engine.ts';
import { createSyncHandshakeSpanExtension } from './sync-handshake-span-extension.ts';
import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';
@@ -475,7 +487,14 @@ export function createServer(options: ServerOptions): ServerInstance {
} = options;
const log = getLogger('server');
- const durabilityState = new DocumentDurabilityState();
+ const lockDir = getLocalDir(projectDir);
+ const durabilityState = new DocumentDurabilityState('main', {
+ persistencePath: join(lockDir, 'stale-external-writes.json'),
+ onStaleExternalWriteChange: () => signalChannel('sync-status'),
+ fileForDocName: (docName) =>
+ relative(projectDir, safeContentPath(docName, contentDir)).replaceAll('\\', '/'),
+ hasResolvedExtension: isRegisteredMarkdownDocName,
+ });
const getActiveBranch = () => durabilityState.getActiveBranch();
const getReconciledBase = (docName: string) => durabilityState.getReconciledBase(docName);
const setReconciledBase = (docName: string, content: string) =>
@@ -732,8 +751,6 @@ export function createServer(options: ServerOptions): ServerInstance {
const serverInstanceId = randomUUID();
- const lockDir = getLocalDir(projectDir);
-
const acpRegistry = new AcpRegistry({
localDir: lockDir,
log: getLogger('acp-registry'),
@@ -879,6 +896,7 @@ export function createServer(options: ServerOptions): ServerInstance {
| 'tags'
| 'comments'
| 'lint-config'
+ | 'sync-status'
| 'local-targets',
): void {
cc1Broadcaster?.signal(channel);
@@ -1966,9 +1984,84 @@ export function createServer(options: ServerOptions): ServerInstance {
loadAcpCustomAgents: () => loadCustomAgents(lockDir, getLogger('acp-registry')),
homeDirOverride: configHomedirOverride,
forceUnloadDocument,
+ resetDocumentDurability: deleteReconciledBase,
ready,
recentlyRemovedDocs,
serializeDoc,
+ resolveStaleExternalWrite: async (
+ file: string,
+ strategy: ResolveStrategy,
+ content?: string,
+ ) => {
+ const requestedFile = file.replaceAll('\\', '/');
+ const staleConflict = durabilityState
+ .listStaleExternalWrites()
+ .find((entry) => entry.file === requestedFile);
+ if (!staleConflict) return false;
+ const { docName } = staleConflict;
+ const absolute = resolve(projectDir, staleConflict.file);
+ if (!isWithinContentDir(absolute, contentDir)) return false;
+ const target = assertRealpathWithinDir(absolute, contentDir, {
+ allowShareableOkArtifact: isShareableOkArtifact,
+ });
+ const document = hocuspocus.documents.get(docName);
+ const lifecycle = document?.getMap('lifecycle');
+
+ if (strategy === 'delete') {
+ if (existsSync(target)) tracedUnlinkSync(target);
+ await derivedDocumentIndex.recordDiskDelete(docName);
+ scheduleIndexRegenerationAfterRemoval(docName);
+ deleteReconciledBase(docName);
+ lifecycle?.set('status', 'deleted-upstream');
+ } else {
+ let resolved: string | null | undefined;
+ switch (strategy) {
+ case 'mine':
+ resolved =
+ serializeDoc(docName) ??
+ staleConflict.retainedContent ??
+ getReconciledBase(docName);
+ break;
+ case 'theirs':
+ resolved = staleConflict.diskContent;
+ break;
+ case 'content':
+ resolved = requireConflictResolutionContent(file, content);
+ break;
+ default: {
+ const exhaustive: never = strategy;
+ throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);
+ }
+ }
+ if (resolved === null || resolved === undefined) {
+ throw new Error(`Unable to resolve stale external write for ${file}`);
+ }
+ const parsedJson = mdManager.parseWithFallback(stripFrontmatter(resolved).body, {
+ resolveEmbed,
+ resolveSize,
+ sourcePath: docName,
+ });
+ schema.nodeFromJSON(parsedJson);
+ const precomputed = { rawContent: resolved, parsedJson };
+ await atomicWriteFile(target, resolved, { fs: tracedAtomicFs });
+ registerWrite(target, contentHash(resolved));
+ if (document) applyToDoc(docName, resolved, precomputed);
+ else setReconciledBase(docName, resolved);
+ await derivedDocumentIndex.recordDiskUpsert(docName, resolved);
+ }
+ if (strategy === 'mine' || strategy === 'content') {
+ durabilityState.recordDisplacedVersion(docName, staleConflict.diskContent);
+ } else {
+ durabilityState.clearDisplacedVersions(docName);
+ }
+ durabilityState.clearStaleExternalWrite(docName);
+ if (strategy !== 'delete') lifecycle?.delete('status');
+ lifecycle?.delete('reason');
+ lifecycle?.delete('detectedAt');
+ signalChannel('sync-status');
+ signalChannel('files');
+ return true;
+ },
evictManagedArtifactLkg: (docName: string) => {
persistence.managedArtifactCtx.lkgCache.delete(docName);
},
@@ -2076,7 +2169,7 @@ export function createServer(options: ServerOptions): ServerInstance {
return serializeYDocSource(document);
}
- const applyToDoc = (docName: string, content: string): void =>
+ function applyToDoc(docName: string, content: string, precomputed?: PrecomputedParse): void {
applyExternalChange(
durabilityState,
hocuspocus,
@@ -2085,7 +2178,9 @@ export function createServer(options: ServerOptions): ServerInstance {
resolveEmbed,
resolveSize,
bridgeLossReporter,
+ precomputed,
);
+ }
function clearLifecycleConflict(document: Document): void {
if (!isDocInConflict(document)) return;
@@ -2116,7 +2211,7 @@ export function createServer(options: ServerOptions): ServerInstance {
}, FILE_WATCHER_ORIGIN);
} catch (err) {
log.error(
- { err, docName, assetBasename },
+ { originalError: redactedErrorSummary(err), docName, assetBasename },
`[asset-event] failed to re-render ${docName} for asset basename ${assetBasename}`,
);
}
@@ -2213,10 +2308,17 @@ export function createServer(options: ServerOptions): ServerInstance {
}
const document = hocuspocus.documents.get(docName);
if (!document) {
+ if (refuseStaleExternalWrite(durabilityState, undefined, docName, theirs)) {
+ return;
+ }
await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
return;
}
+ if (refuseStaleExternalWrite(durabilityState, document, docName, theirs)) {
+ break;
+ }
+
const base = getReconciledBase(docName) ?? '';
const ours = serializeDoc(docName) ?? base;
@@ -2323,6 +2425,7 @@ export function createServer(options: ServerOptions): ServerInstance {
const { docName } = event;
const document = hocuspocus.documents.get(docName);
if (!document) {
+ deleteReconciledBase(docName);
await derivedDocumentIndex.recordDiskDelete(docName);
signalChannel('files');
onUpstreamDelete(docName);
diff --git a/packages/server/src/stale-external-write-gate.test.ts b/packages/server/src/stale-external-write-gate.test.ts
new file mode 100644
index 000000000..033ad6cb1
--- /dev/null
+++ b/packages/server/src/stale-external-write-gate.test.ts
@@ -0,0 +1,414 @@
+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Hocuspocus } from '@hocuspocus/server';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import * as Y from 'yjs';
+import { isDocInConflict } from './conflict-errors.ts';
+import { DISPLACED_VERSION_TTL_MS, DocumentDurabilityState } from './document-durability-state.ts';
+import { reconcileDiskBeforeAgentWrite, refuseStaleExternalWrite } from './external-change.ts';
+import { getMetrics } from './metrics.ts';
+import { createPersistenceExtension } from './persistence.ts';
+
+const BROWSER_ORIGIN = {
+ source: 'connection',
+ connection: { context: { principalId: 'principal-test' } },
+};
+
+const STALE_CONTENT = 'alpha\n\nbeta\n';
+const ACKNOWLEDGED_CONTENT = 'alpha\n\nbeta gamma\n';
+
+function replaceDocParagraphs(document: Y.Doc, texts: string[]): void {
+ const fragment = document.getXmlFragment('default');
+ const ytext = document.getText('source');
+ if (fragment.length > 0) fragment.delete(0, fragment.length);
+ fragment.insert(
+ 0,
+ texts.map((text) => {
+ const paragraph = new Y.XmlElement('paragraph');
+ paragraph.insert(0, [new Y.XmlText(text)]);
+ return paragraph;
+ }),
+ );
+ if (ytext.length > 0) ytext.delete(0, ytext.length);
+ ytext.insert(0, `${texts.join('\n\n')}\n`);
+}
+
+function fakeHocuspocusWith(docName: string, document: Y.Doc): Hocuspocus {
+ return { documents: new Map([[docName, document]]) } as unknown as Hocuspocus;
+}
+
+describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
+ let tmpDir: string;
+ let docName: string;
+ let document: Y.Doc;
+ let durabilityState: DocumentDurabilityState;
+
+ async function settleWrite(agentTriggered = true): Promise<void> {
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: docName,
+ context: {},
+ } as never);
+ document.transact(
+ () => replaceDocParagraphs(document, ['alpha', 'beta gamma']),
+ BROWSER_ORIGIN,
+ );
+ if (agentTriggered) durabilityState.markAgentWriteStore(docName);
+ await persistence.extension.onStoreDocument?.({
+ document,
+ documentName: docName,
+ lastTransactionOrigin: BROWSER_ORIGIN,
+ lastContext: {},
+ } as never);
+ expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
+ }
+
+ beforeEach(() => {
+ tmpDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-stale-gate-')));
+ docName = 'gated-doc';
+ document = new Y.Doc();
+ durabilityState = new DocumentDurabilityState();
+ });
+
+ afterEach(() => {
+ document.destroy();
+ rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ test('refuses disk bytes the server itself displaced and conflicts the document', async () => {
+ await settleWrite();
+ const before = getMetrics();
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+
+ const result = reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+
+ expect(result.reconciled).toBe(false);
+ expect(isDocInConflict(document as never)).toBe(true);
+ expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
+ expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
+ refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT);
+ const after = getMetrics();
+ expect(after.staleExternalWriteRefused).toBe(before.staleExternalWriteRefused + 1);
+ expect(after.conflictCount).toBe(before.conflictCount);
+ expect(after.persistenceDivergenceRealign).toBe(before.persistenceDivergenceRealign);
+ expect(after.bridgeMergeContentLoss).toBe(before.bridgeMergeContentLoss);
+ });
+
+ test('refuses to load rejected bytes when the acknowledged base is missing', async () => {
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+ durabilityState.recordDisplacedVersion(docName, STALE_CONTENT);
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+ await expect(
+ persistence.extension.onLoadDocument?.({
+ document,
+ documentName: docName,
+ context: {},
+ } as never),
+ ).rejects.toThrow('Missing acknowledged content');
+ expect(document.getText('source').toString()).toBe('');
+ });
+
+ test('lets an external edit that matches no displaced version reconcile normally', async () => {
+ await settleWrite();
+ writeFileSync(join(tmpDir, `${docName}.md`), 'alpha\n\nbeta gamma\n\ndelta\n', 'utf-8');
+
+ const result = reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+
+ expect(result.reconciled).toBe(true);
+ expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getText('source').toString()).toContain('delta');
+ });
+
+ test('does not classify bytes displaced by a non-agent save as a stale agent rollback', async () => {
+ await settleWrite(false);
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+
+ const result = reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+
+ expect(result.reconciled).toBe(true);
+ expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getText('source').toString()).toBe(STALE_CONTENT);
+ });
+
+ test('keeps refusing a detected stale write after its history entry expires', async () => {
+ vi.useFakeTimers();
+ try {
+ await settleWrite();
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT)).toBe(
+ true,
+ );
+
+ vi.advanceTimersByTime(DISPLACED_VERSION_TTL_MS + 1_000);
+
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT)).toBe(
+ true,
+ );
+ expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('clears a stale conflict when disk catches up to the acknowledged version', async () => {
+ await settleWrite();
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT)).toBe(true);
+
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, ACKNOWLEDGED_CONTENT)).toBe(
+ false,
+ );
+ expect(isDocInConflict(document as never)).toBe(false);
+ expect(durabilityState.listStaleExternalWrites()).toEqual([]);
+ });
+
+ test('pre-write reconciliation can clear a stale conflict after disk catches up', async () => {
+ await settleWrite();
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT)).toBe(true);
+ writeFileSync(join(tmpDir, `${docName}.md`), ACKNOWLEDGED_CONTENT, 'utf-8');
+
+ reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+
+ expect(isDocInConflict(document as never)).toBe(false);
+ expect(durabilityState.listStaleExternalWrites()).toEqual([]);
+ });
+
+ test('lets a genuinely new external edit replace a stale conflict', async () => {
+ await settleWrite();
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT)).toBe(true);
+
+ const externalEdit = `${ACKNOWLEDGED_CONTENT}\ndelta\n`;
+ expect(refuseStaleExternalWrite(durabilityState, document, docName, externalEdit)).toBe(false);
+ expect(isDocInConflict(document as never)).toBe(false);
+ expect(durabilityState.listStaleExternalWrites()).toEqual([]);
+ });
+
+ test('restores the acknowledged base instead of stale disk bytes when a document reloads', async () => {
+ await settleWrite();
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+ expect(refuseStaleExternalWrite(durabilityState, undefined, docName, STALE_CONTENT)).toBe(true);
+
+ document.destroy();
+ document = new Y.Doc();
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: docName,
+ context: {},
+ } as never);
+
+ expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
+ expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
+ });
+
+ test('restores the acknowledged base instead of stale disk bytes after a server restart', async () => {
+ const persistencePath = join(tmpDir, 'stale-external-writes.json');
+ durabilityState = new DocumentDurabilityState('main', { persistencePath });
+ await settleWrite();
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+
+ document.destroy();
+ document = new Y.Doc();
+ durabilityState = new DocumentDurabilityState('main', { persistencePath });
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: docName,
+ context: {},
+ } as never);
+
+ expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
+ expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ });
+
+ test('the final persistence disk read refuses a stale version that arrives after preflight', async () => {
+ const persistencePath = join(tmpDir, 'state.json');
+ durabilityState = new DocumentDurabilityState('main', { persistencePath });
+ durabilityState.setReconciledBase(docName, ACKNOWLEDGED_CONTENT);
+ durabilityState.recordDisplacedVersion(docName, STALE_CONTENT);
+ replaceDocParagraphs(document, ['alpha', 'beta gamma', 'next agent edit']);
+ writeFileSync(join(tmpDir, `${docName}.md`), STALE_CONTENT, 'utf-8');
+ durabilityState.markAgentWriteStore(docName);
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+
+ await persistence.extension.onStoreDocument?.({
+ document,
+ documentName: docName,
+ lastTransactionOrigin: BROWSER_ORIGIN,
+ lastContext: {},
+ } as never);
+
+ expect(document.getText('source').toString()).toContain('next agent edit');
+ expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
+ expect(durabilityState.takeStaleExternalWriteFreeze(docName)).toBe(true);
+ expect(durabilityState.takeStoreDivergence(docName)).toBe(false);
+ const retained = document.getText('source').toString();
+ durabilityState.recordDisplacedVersion(docName, 'an older displaced version\n');
+ writeFileSync(join(tmpDir, `${docName}.md`), 'an older displaced version\n', 'utf-8');
+ expect(
+ refuseStaleExternalWrite(durabilityState, document, docName, 'an older displaced version\n'),
+ ).toBe(true);
+ document.destroy();
+ document = new Y.Doc();
+ const restoredState = new DocumentDurabilityState('main', { persistencePath });
+ const restarted = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState: restoredState,
+ });
+ await restarted.extension.onLoadDocument?.({
+ document,
+ documentName: docName,
+ context: {},
+ } as never);
+ expect(document.getText('source').toString()).toBe(retained);
+ expect(restoredState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
+ expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ });
+
+ test('normalized-equal displaced bytes remain a conflict until exact acknowledged bytes return', async () => {
+ const crlfStale = ACKNOWLEDGED_CONTENT.replaceAll('\n', '\r\n');
+ durabilityState.setReconciledBase(docName, ACKNOWLEDGED_CONTENT);
+ durabilityState.recordDisplacedVersion(docName, crlfStale);
+ replaceDocParagraphs(document, ['alpha', 'beta gamma']);
+ writeFileSync(join(tmpDir, `${docName}.md`), crlfStale, 'utf-8');
+ reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+ expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
+ writeFileSync(join(tmpDir, `${docName}.md`), ACKNOWLEDGED_CONTENT, 'utf-8');
+ reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+ expect(document.getMap('lifecycle').get('status')).toBeUndefined();
+ });
+
+ test.each([ACKNOWLEDGED_CONTENT, 'genuinely new external content\n'])(
+ 'a pending retained edit survives disk replacement with %s before restart',
+ async (diskContent) => {
+ const persistencePath = join(tmpDir, 'state.json');
+ durabilityState = new DocumentDurabilityState('main', { persistencePath });
+ const retained = `${ACKNOWLEDGED_CONTENT}\nnext retained edit\n`;
+ durabilityState.setReconciledBase(docName, ACKNOWLEDGED_CONTENT);
+ durabilityState.recordDisplacedVersion(docName, STALE_CONTENT);
+ durabilityState.recordStaleExternalWrite(docName, STALE_CONTENT, retained);
+ const beforeReplacement = getMetrics();
+ replaceDocParagraphs(document, ['alpha', 'beta gamma', 'next retained edit']);
+ document.getMap('lifecycle').set('status', 'conflict');
+ document.getMap('lifecycle').set('reason', 'stale-external-write');
+ writeFileSync(join(tmpDir, `${docName}.md`), diskContent, 'utf-8');
+ reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ fakeHocuspocusWith(docName, document),
+ docName,
+ tmpDir,
+ );
+ expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(refuseStaleExternalWrite(durabilityState, undefined, docName, diskContent)).toBe(true);
+ expect(getMetrics().staleExternalWriteRefused).toBe(
+ beforeReplacement.staleExternalWriteRefused + 1,
+ );
+ expect(getMetrics().conflictCount).toBe(beforeReplacement.conflictCount);
+ document.destroy();
+ document = new Y.Doc();
+ const restored = new DocumentDurabilityState('main', { persistencePath });
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState: restored,
+ });
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: docName,
+ context: {},
+ } as never);
+ expect(document.getText('source').toString()).toBe(retained);
+ expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(restored.getStaleExternalWrite(docName)?.diskContent).toBe(diskContent);
+ expect(getMetrics().staleExternalWriteRefused).toBe(
+ beforeReplacement.staleExternalWriteRefused + 1,
+ );
+ },
+ );
+
+ test('records the exact disk spelling displaced by an agent write', async () => {
+ const crlfStale = STALE_CONTENT.replaceAll('\n', '\r\n');
+ writeFileSync(join(tmpDir, `${docName}.md`), crlfStale, 'utf-8');
+ durabilityState.setReconciledBase(docName, STALE_CONTENT);
+ replaceDocParagraphs(document, ['alpha', 'beta gamma']);
+ durabilityState.markAgentWriteStore(docName);
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+
+ await persistence.extension.onStoreDocument?.({
+ document,
+ documentName: docName,
+ lastTransactionOrigin: BROWSER_ORIGIN,
+ lastContext: {},
+ } as never);
+
+ expect(durabilityState.isDisplacedVersion(docName, crlfStale)).toBe(true);
+ });
+});
diff --git a/packages/server/src/symlink-guard.ts b/packages/server/src/symlink-guard.ts
index 81eb04b78..8c40d0abc 100644
--- a/packages/server/src/symlink-guard.ts
+++ b/packages/server/src/symlink-guard.ts
@@ -11,7 +11,7 @@ export function assertRealpathWithinDir(
targetAbsPath: string,
rootDir: string,
opts: RealpathGuardOptions = {},
-): void {
+): string {
const resolvedRoot = resolve(rootDir);
let canonicalRoot: string;
try {
@@ -45,7 +45,7 @@ export function assertRealpathWithinDir(
throw new SymlinkEscapeError('path resolves into the .git/.ok state tree');
}
}
- return;
+ return resolve(canonical, ...pendingSuffix);
} catch (err) {
if (err instanceof SymlinkEscapeError) throw err;
const code = (err as NodeJS.ErrnoException).code;
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 54a9447a6..26d2ddb9e 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -1973,8 +1973,8 @@ export class SyncEngine {
const guardOpts = { allowShareableOkArtifact: isShareableOkArtifact };
for (const { path, bytes } of writes) {
const abs = join(this.projectDir, path);
- assertRealpathWithinDir(abs, this.projectDir, guardOpts);
- tracedWriteFileSync(abs, bytes);
+ const target = assertRealpathWithinDir(abs, this.projectDir, guardOpts);
+ tracedWriteFileSync(target, bytes);
}
for (const path of deletions) {
const abs = join(this.projectDir, path);
@@ -2544,17 +2544,17 @@ export class SyncEngine {
for (const item of reconciled) {
try {
const absolutePath = join(this.projectDir, item.path);
- assertRealpathWithinDir(absolutePath, this.projectDir);
+ const target = assertRealpathWithinDir(absolutePath, this.projectDir);
let existing: string | null = null;
try {
- existing = readFileSync(absolutePath, 'utf8');
+ existing = readFileSync(target, 'utf8');
} catch (err) {
log.warn(
{ err, path: item.path },
'[sync] could not read MCP config before restoring reconciled overlay',
);
}
- if (existing !== item.raw) tracedWriteFileSync(absolutePath, item.raw, 'utf8');
+ if (existing !== item.raw) tracedWriteFileSync(target, item.raw, 'utf8');
} catch (err) {
restored = false;
log.warn({ err, path: item.path }, '[sync] could not restore reconciled MCP overlay');
@@ -2688,9 +2688,9 @@ export class SyncEngine {
`${replay.mode},${replay.blobSha},${replay.path}`,
]);
const absolutePath = join(this.projectDir, replay.path);
- assertRealpathWithinDir(absolutePath, this.projectDir);
- if (readFileSync(absolutePath, 'utf8') !== replay.raw) {
- tracedWriteFileSync(absolutePath, replay.raw, 'utf8');
+ const target = assertRealpathWithinDir(absolutePath, this.projectDir);
+ if (readFileSync(target, 'utf8') !== replay.raw) {
+ tracedWriteFileSync(target, replay.raw, 'utf8');
}
}
} catch (err) {
diff --git a/packages/server/src/version-hash.ts b/packages/server/src/version-hash.ts
new file mode 100644
index 000000000..8cdd2b6a2
--- /dev/null
+++ b/packages/server/src/version-hash.ts
@@ -0,0 +1,5 @@
+import { createHash } from 'node:crypto';
+
+export function contentHash(content: string): string {
+ return createHash('sha256').update(content).digest('hex');
+}