Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): one authority for document conflicts (PRD-8318, PRD-7947) (#4102)

miles-kt-inkeep96504582c2ea
diff --git a/.changeset/conflict-single-authority.md b/.changeset/conflict-single-authority.md
new file mode 100644
index 000000000..f85680dbc
--- /dev/null
+++ b/.changeset/conflict-single-authority.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Conflicted documents become editable again after resolution in Git or OpenKnowledge. Locally detected conflicts can be inspected and resolved in the app or through MCP. Keeping your version preserves newer collaborative edits, and malformed conflict records no longer prevent startup.
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index d24336dd4..58ae2dd67 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -139,7 +139,11 @@ 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.
+### Conflicts that don't come from GitHub
+
+A conflict doesn't need a remote. When a file changes on disk while OpenKnowledge has it open, OpenKnowledge merges the two versions itself, and raises a conflict if it can't merge them cleanly.
+
+Another app can also save an exact older copy over an edit OpenKnowledge already acknowledged. In the diff view, **Current** is the protected OpenKnowledge version and **Incoming** is the rejected external save. Choose which to keep. An intentional exact revert can trigger the same confirmation. Both versions stay recoverable after a restart, and keeping current protects against repeated saves from the stale editor. That protection expires after 30 minutes, so update or close the other app rather than relying on that protection.
## Work on multiple branches
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index e6aa9cf12..13a5ef83b 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 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 |
+| `conflicts` | Read tracked conflicts. `kind: "list"` enumerates them (`{ file, detectedAt, conflict, reason?, conflictKind?, docName }`); `kind: "content"` returns one file's stages and metadata (`{ file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions }`). `conflictKind: "stale-external-write"` identifies a protected stale save; Git working-tree overlays use `conflict.kind: "working-tree"` |
+| `resolve_conflict` | Write a chosen resolution (`mine` / `theirs` / `content` / `delete`, narrowed by that conflict's `resolutionOptions`). Only `merge-native` creates a resolution commit |
## Output shape mirrors the input
@@ -66,24 +66,41 @@ 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 lifecycle status is `conflict`, returning `urn:ok:error:doc-in-conflict` (409). This includes local stale-external-write conflicts with GitHub sync disabled.
+A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OpenKnowledge's own reconciliation of the editor against disk. Reconciliation covers `stale-external-write`, which protects an acknowledged edit when another app restores the exact older file version, even with GitHub sync disabled. Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses a conflicted doc with an RFC 9457 problem response (409) that names the kind and the strategies that apply to it:
-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:
+```json
+{
+ "type": "urn:ok:error:doc-in-conflict",
+ "title": "Document is in conflict.",
+ "status": 409,
+ "detail": "The document is in a conflict state. Call conflicts({ kind: \"content\" }) + resolve_conflict before retrying.",
+ "file": "notes/sso.md",
+ "conflict": { "kind": "reconcile", "reason": "disk-markers" },
+ "resolutionOptions": ["mine", "content", "delete"]
+}
+```
-- `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).
+A write that first detects the stale file during its final disk flush returns a different 409, `urn:ok:error:stale-external-write`. The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Resolve and re-read before retrying, so you don't duplicate an append that already reached `ours`.
-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.
+`conflict.kind` says where the conflict came from, and the kind decides what a resolve does. `merge-native` is a git merge that left unmerged stages in the index. Resolving one stages your choice with git and commits the merge once no `merge-native` conflict is left. `working-tree` is a pull-only overlay collision, pinned to the origin blob it hit. `reconcile` is OpenKnowledge's own three-way merge of the editor against disk, including protected stale saves; no git object holds those stages, so OpenKnowledge snapshots them when it detects the conflict. Resolving a `working-tree` or `reconcile` conflict commits nothing.
-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.
+A `reconcile` conflict also carries a `reason`: `merged-with-markers`, `refused-conflict-markers`, `refused-too-large`, `disk-markers`, or `stale-external-write`. On that last reason the compatibility field `conflictKind` is `stale-external-write`. Every other row uses `conflictKind: "git"`.
A write to a document whose file has been deleted returns `urn:ok:error:doc-removed` (409): the edit reached collaborative state, but the disk write was refused rather than recreating the removed file. This is not retryable — the document is gone. Re-create it with `write` if you still want the content.
A write whose document path cannot be resolved inside the content directory returns `urn:ok:error:path-escape` (400): the edit reached collaborative state, but the disk write was refused. This covers a symlink cycle at the document's own path and a link resolving outside the content directory. It is not retryable — repair the path on disk before writing this content again.
-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.
+### Resolving a conflict
+
+1. `conflicts({ kind: "list" })` returns every tracked conflict as `{ file, detectedAt, conflict, reason?, conflictKind?, docName }`. Call it to detect conflicts without waiting for a 409.
+2. `conflicts({ kind: "content", file })` returns `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }`. `ours` is the live Y.Text when the doc is loaded and marker-free; otherwise it falls back to the stage pinned at detection. For a stale external write, `ours` is the protected content and `theirs` is the rejected older save.
+3. `resolve_conflict({ file, strategy, content? })` writes the chosen bytes. Send a strategy from that conflict's `resolutionOptions`, not the full set. A `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and sending it anyway returns a 422 with `refusal: "strategy-not-offered"`. The same 422 shape carries `refusal: "markers-in-content"` when the bytes you sent still contain markers, and that field is what tells the two apart. A 404 (`urn:ok:error:no-conflict-tracked`) means nothing is tracked for that path. Re-read the list; it does not mean your resolution was saved.
+
+What `mine` and `theirs` mean depends on the kind. On `merge-native` they are `git checkout --ours` and `git checkout --theirs` (the committed stages 2 and 3), and `delete` is `git rm`. On `working-tree`, `mine` keeps your overlay verbatim and `theirs` restores the pinned origin blob. On `reconcile`, `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk bytes captured at detection. `content` always writes the bytes you supply, and `delete` always removes the file.
+
+`file` is a `.md` or `.mdx` path relative to the project directory, extension included. It mirrors the on-disk shape, not the extension-less `document` path the other tools take.
+
+For how a conflict appears and resolves in the app, see [Resolving a conflict](../features/github-sync.mdx#resolving-a-conflict). The `conflicts` and `resolve_conflict` tool descriptions repeat the per-kind rules at the call site.
## Preview links
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index d6bb67ca8..154dce89a 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -113,8 +113,9 @@ 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/sync-state.json` | GitHub-sync engine state | In-project, gitignored |
+| `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |
+| `.ok/local/stale-external-writes.json` | Recovery snapshot for a rejected stale external save. It can hold the acknowledged, rejected, and retained document text. Protection expires after 30 minutes, but an unresolved snapshot stays until you resolve the conflict | 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 |
@@ -237,8 +238,9 @@ 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/sync-state.json` | GitHub-sync engine state | In-project, gitignored |
+| `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |
+| `.ok/local/stale-external-writes.json` | Recovery snapshot for a rejected stale external save. It can hold the acknowledged, rejected, and retained document text. Protection expires after 30 minutes, but an unresolved snapshot stays until you resolve the conflict | 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/App.tsx b/packages/app/src/App.tsx
index 82453aefc..ec351e320 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -41,6 +41,7 @@ import {
import { EditorLifecycleFlush } from '@/editor/EditorLifecycleFlush';
import { parseEditorTabId, tabIdForNavigationTarget } from '@/editor/editor-tabs';
import { previewOpenDisposition } from '@/editor/preview-open-disposition';
+import { ConflictsProvider } from '@/hooks/use-conflicts';
import { useFolderConfig } from '@/hooks/use-folder-config';
import { useInstalledClis } from '@/hooks/use-installed-clis';
import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';
@@ -539,11 +540,13 @@ export function App() {
<ProfilerBoundary name="app">
<DocumentProvider>
<ConfigProviderHost>
- <PreviewTabsSettingsBridge>
- <SingleFileModeProvider>
- <AppBody />
- </SingleFileModeProvider>
- </PreviewTabsSettingsBridge>
+ <ConflictsProvider>
+ <PreviewTabsSettingsBridge>
+ <SingleFileModeProvider>
+ <AppBody />
+ </SingleFileModeProvider>
+ </PreviewTabsSettingsBridge>
+ </ConflictsProvider>
</ConfigProviderHost>
</DocumentProvider>
</ProfilerBoundary>
diff --git a/packages/app/src/components/ConflictsSection.dom.test.tsx b/packages/app/src/components/ConflictsSection.dom.test.tsx
index 350253cee..cc46706b7 100644
--- a/packages/app/src/components/ConflictsSection.dom.test.tsx
+++ b/packages/app/src/components/ConflictsSection.dom.test.tsx
@@ -2,11 +2,7 @@ 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;
- conflictKind?: 'git' | 'stale-external-write';
- }>;
+ conflicts: Array<{ file: string; detectedAt: string; docName: string | null }>;
loading: boolean;
error: 'network' | 'server' | null;
}
@@ -33,16 +29,23 @@ describe('ConflictsSection', () => {
test('renders nothing when there are no conflicts (auto-hide at zero)', () => {
mockResult = { conflicts: [], loading: false, error: null };
- const { container } = render(<ConflictsSection />);
- expect(container.firstChild).toBeNull();
+ render(<ConflictsSection />);
expect(screen.queryByTestId('conflicts-section')).toBeNull();
});
test('renders the section with header + count + one row per conflict when count > 0', () => {
mockResult = {
conflicts: [
- { file: 'docs/notes.md', detectedAt: '2026-05-20T10:00:00.000Z' },
- { file: 'team/draft.md', detectedAt: '2026-05-20T10:01:00.000Z' },
+ {
+ file: 'docs/notes.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ docName: 'docs/notes',
+ },
+ {
+ file: 'team/draft.md',
+ detectedAt: '2026-05-20T10:01:00.000Z',
+ docName: 'team/draft',
+ },
],
loading: false,
error: null,
@@ -59,62 +62,90 @@ describe('ConflictsSection', () => {
expect(rows[1]?.getAttribute('data-file')).toBe('team/draft.md');
});
- test('clicking a row navigates by setting window.location.hash (strips .md)', () => {
+ test('a row whose entry has no docName is present but not navigable', () => {
mockResult = {
- conflicts: [{ file: 'docs/notes.md', detectedAt: '2026-05-20T10:00:00.000Z' }],
+ conflicts: [
+ {
+ file: 'outside/notes.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ docName: null,
+ },
+ ],
loading: false,
error: null,
};
render(<ConflictsSection />);
const row = screen.getByTestId('conflicts-section-row');
+ expect(row.getAttribute('data-navigable')).toBe('false');
+ expect((row as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(row);
- expect(window.location.hash).toBe('#/docs/notes');
+ expect(window.location.hash).toBe('');
});
- test('clicking a row also strips .mdx extension', () => {
+ test('a row navigates to the entry docName, not to a path-derived guess', () => {
mockResult = {
- conflicts: [{ file: 'docs/page.mdx', detectedAt: '2026-05-20T10:00:00.000Z' }],
+ conflicts: [
+ {
+ file: 'content/docs/notes.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ docName: 'docs/notes',
+ },
+ ],
loading: false,
error: null,
};
render(<ConflictsSection />);
+
fireEvent.click(screen.getByTestId('conflicts-section-row'));
- expect(window.location.hash).toBe('#/docs/page');
+ expect(window.location.hash).toBe('#/docs/notes');
});
- test('explains stale external writes without labeling Git conflicts as external edits', () => {
+ test('clicking a row navigates by setting window.location.hash (strips .md)', () => {
mockResult = {
conflicts: [
{
- file: 'docs/stale.md',
+ file: 'docs/notes.md',
detectedAt: '2026-05-20T10:00:00.000Z',
- conflictKind: 'stale-external-write',
+ docName: 'docs/notes',
},
+ ],
+ loading: false,
+ error: null,
+ };
+ render(<ConflictsSection />);
+
+ const row = screen.getByTestId('conflicts-section-row');
+ fireEvent.click(row);
+ expect(window.location.hash).toBe('#/docs/notes');
+ });
+
+ test('clicking a row also strips .mdx extension', () => {
+ mockResult = {
+ conflicts: [
{
- file: 'docs/git.md',
- detectedAt: '2026-05-20T10:01:00.000Z',
- conflictKind: 'git',
+ file: 'docs/page.mdx',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ docName: 'docs/page',
},
],
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');
+ fireEvent.click(screen.getByTestId('conflicts-section-row'));
+ expect(window.location.hash).toBe('#/docs/page');
});
test('section has NO quick-action buttons ([Keep mine] / [Keep theirs])', () => {
mockResult = {
- conflicts: [{ file: 'docs/notes.md', detectedAt: '2026-05-20T10:00:00.000Z' }],
+ conflicts: [
+ {
+ file: 'docs/notes.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ docName: 'docs/notes',
+ },
+ ],
loading: false,
error: null,
};
@@ -127,9 +158,21 @@ describe('ConflictsSection', () => {
test('row count matches the conflicts length (parity input)', () => {
mockResult = {
conflicts: [
- { file: 'a.md', detectedAt: 't' },
- { file: 'b.md', detectedAt: 't' },
- { file: 'c.md', detectedAt: 't' },
+ {
+ file: 'a.md',
+ detectedAt: 't',
+ docName: 'a',
+ },
+ {
+ file: 'b.md',
+ detectedAt: 't',
+ docName: 'b',
+ },
+ {
+ file: 'c.md',
+ detectedAt: 't',
+ docName: 'c',
+ },
],
loading: false,
error: null,
@@ -147,17 +190,34 @@ describe('ConflictsSection', () => {
expect(errorBand.textContent ?? '').toMatch(/Couldn't load conflicts/i);
});
- test('returns null on a network-level fetch error (FileTree owns the global signal)', () => {
+ test('renders nothing on a connectivity-level fetch error (FileTree carries that signal)', () => {
mockResult = { conflicts: [], loading: false, error: 'network' };
- const { container } = render(<ConflictsSection />);
- expect(container.firstChild).toBeNull();
+ render(<ConflictsSection />);
expect(screen.queryByTestId('conflicts-section')).toBeNull();
expect(screen.queryByTestId('conflicts-section-error')).toBeNull();
});
- test('returns null while the initial fetch is still loading', () => {
+ test('renders nothing while the initial fetch is still loading', () => {
mockResult = { conflicts: [], loading: true, error: null };
- const { container } = render(<ConflictsSection />);
- expect(container.firstChild).toBeNull();
+ render(<ConflictsSection />);
+ expect(screen.queryByTestId('conflicts-section')).toBeNull();
+ });
+
+ test('keeps the retained rows and shows no band on a network fetch error', () => {
+ mockResult = {
+ conflicts: [
+ {
+ file: 'docs/notes.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ docName: 'docs/notes',
+ },
+ ],
+ loading: false,
+ error: 'network',
+ };
+ render(<ConflictsSection />);
+
+ expect(screen.getAllByTestId('conflicts-section-row').length).toBe(1);
+ expect(screen.queryByTestId('conflicts-section-error')).toBeNull();
});
});
diff --git a/packages/app/src/components/ConflictsSection.tsx b/packages/app/src/components/ConflictsSection.tsx
index ab0478260..ed4fa176c 100644
--- a/packages/app/src/components/ConflictsSection.tsx
+++ b/packages/app/src/components/ConflictsSection.tsx
@@ -4,10 +4,9 @@ import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useConflicts } from '@/hooks/use-conflicts';
-import { filePathToDocName, hashFromDocName, isSameHash } from '@/lib/doc-hash';
+import { hashFromDocName, isSameHash } from '@/lib/doc-hash';
-function navigateToConflictedDoc(filePath: string) {
- const docName = filePathToDocName(filePath);
+function navigateToConflictedDoc(docName: string) {
const nextHash = hashFromDocName(docName);
if (typeof window === 'undefined') return;
if (!isSameHash(window.location.hash, nextHash)) {
@@ -60,33 +59,40 @@ export function ConflictsSection() {
</span>
</header>
<ul className="flex flex-col gap-px">
- {conflicts.map((entry) => (
- <li key={entry.file}>
- <Button
- variant="ghost"
- size="sm"
- data-testid="conflicts-section-row"
- data-file={entry.file}
- data-conflict-kind={entry.conflictKind}
- title={entry.file}
- 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="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>
- ))}
+ {conflicts.map((entry) => {
+ const docName = entry.docName;
+ return (
+ <li key={entry.file}>
+ <Button
+ variant="ghost"
+ size="sm"
+ data-testid="conflicts-section-row"
+ data-file={entry.file}
+ data-conflict-kind={entry.conflictKind}
+ data-navigable={docName === null ? 'false' : 'true'}
+ disabled={docName === null}
+ title={entry.file}
+ 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={() => {
+ if (docName !== null) navigateToConflictedDoc(docName);
+ }}
+ >
+ <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>
+ );
+ })}
</ul>
</section>
);
diff --git a/packages/app/src/components/DiffViewBoundary.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.dom.test.tsx
index 421385133..5017f0bcf 100644
--- a/packages/app/src/components/DiffViewBoundary.dom.test.tsx
+++ b/packages/app/src/components/DiffViewBoundary.dom.test.tsx
@@ -1,20 +1,15 @@
-import { SyncResolveConflictRequestSchema } from '@inkeep/open-knowledge-core';
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ConflictEntryWire } from '@inkeep/open-knowledge-core';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import * as Y from 'yjs';
vi.doMock('sonner', () => ({
- toast: { error: () => {}, success: () => {}, info: () => {} },
+ toast: { error: () => {}, success: () => {}, info: () => {}, warning: () => {} },
}));
vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-vi.doMock('@/lib/documents-events', () => ({
- subscribeToDocumentsChanged: () => () => {},
-}));
-
const { DiffViewBoundary } = await import('./DiffViewBoundary');
interface CapturedFetch {
@@ -24,54 +19,78 @@ interface CapturedFetch {
const fetchCalls: CapturedFetch[] = [];
-function makeProvider(initialBody: string) {
- const doc = new Y.Doc();
- doc.getText('source').insert(0, initialBody);
- return { document: doc } as unknown as Parameters<typeof DiffViewBoundary>[0]['provider'];
+function entry(file: string, overrides: Partial<ConflictEntryWire> = {}): ConflictEntryWire {
+ return {
+ file,
+ detectedAt: '2026-05-20T00:00:00.000Z',
+ conflict: 'merge-native',
+ docName: file.replace(/\.mdx?$/, ''),
+ ...overrides,
+ } as ConflictEntryWire;
}
-type ConflictKind = 'both-modified' | 'delete-modify' | 'modify-delete';
+type ConflictShape = 'both-modified' | 'delete-modify' | 'modify-delete';
+
+function contentResponse(
+ file: string,
+ shape: ConflictShape,
+ overrides: Record<string, unknown> = {},
+): Response {
+ return new Response(
+ JSON.stringify({
+ file,
+ base: 'base content\n',
+ ours: shape === 'delete-modify' ? '' : 'our modification\n',
+ theirs: shape === 'modify-delete' ? '' : 'their modification\n',
+ kind: shape,
+ conflict: 'merge-native',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ ...overrides,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+}
-function strategyFetch(kind: ConflictKind, resolvePending?: Promise<unknown>) {
- return (input: RequestInfo | URL, init?: RequestInit) => {
+function stubFetch(
+ handler: (url: string, init?: RequestInit) => Response | Promise<Response>,
+): void {
+ 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(
- new Response(
- JSON.stringify({
- conflicts: [{ file: 'foo.md', detectedAt: '2026-05-20T00:00:00.000Z' }],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
+ return Promise.resolve(handler(url, init));
+ }) as typeof fetch;
+}
+
+function strategyFetch(
+ file: string,
+ shape: ConflictShape,
+ options: { resolvePending?: Promise<unknown>; resolutionOptions?: string[] } = {},
+) {
+ stubFetch((url) => {
if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'foo.md',
- base: 'base content\n',
- ours: kind === 'delete-modify' ? '' : 'our modification\n',
- theirs: kind === 'modify-delete' ? '' : 'their modification\n',
- kind,
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
+ return contentResponse(
+ file,
+ shape,
+ options.resolutionOptions === undefined
+ ? {}
+ : { resolutionOptions: options.resolutionOptions },
);
}
if (url === '/api/sync/resolve-conflict') {
const ok = new Response('{}', { status: 200 });
- return resolvePending ? resolvePending.then(() => ok) : Promise.resolve(ok);
+ return options.resolvePending ? options.resolvePending.then(() => ok) : ok;
}
- return Promise.resolve(new Response('not found', { status: 404 }));
- };
+ return new Response('not found', { status: 404 });
+ });
}
function lastResolveBody(): { file?: string; strategy?: string } {
const call = fetchCalls.find((c) => c.url === '/api/sync/resolve-conflict');
- return SyncResolveConflictRequestSchema.parse(JSON.parse(String(call?.init?.body ?? '{}')));
+ return JSON.parse(String(call?.init?.body ?? '{}'));
+}
+
+function contentFetches(): CapturedFetch[] {
+ return fetchCalls.filter((c) => c.url.startsWith('/api/sync/conflict-content'));
}
describe('DiffViewBoundary (Tier-3 mount)', () => {
@@ -79,41 +98,24 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
beforeEach(() => {
fetchCalls.length = 0;
- 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(
- new Response(
- JSON.stringify({
- conflicts: [
- { file: 'docs/notes.md', detectedAt: '2026-05-20T00:00:00.000Z' },
- { file: 'logs/entry.md', detectedAt: '2026-05-20T00:00:00.000Z' },
- ],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
+ stubFetch((url) => {
if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'docs/notes.md',
- base: '# Base\nbase paragraph\n',
- ours: '# Server-ours\nfrom-git-index\n',
- theirs: '# Theirs\nteam paragraph\n',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
+ return new Response(
+ JSON.stringify({
+ file: 'docs/notes.md',
+ base: '# Base\nbase paragraph\n',
+ ours: '# Server-ours\nfrom-git-index\n',
+ theirs: '# Theirs\nteam paragraph\n',
+ kind: 'both-modified',
+ conflict: 'merge-native',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
);
}
- if (url === '/api/sync/resolve-conflict') {
- return Promise.resolve(new Response('{}', { status: 200 }));
- }
- return Promise.resolve(new Response('not found', { status: 404 }));
- };
+ if (url === '/api/sync/resolve-conflict') return new Response('{}', { status: 200 });
+ return new Response('not found', { status: 404 });
+ });
consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
@@ -122,278 +124,64 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
consoleWarnSpy.mockRestore();
});
- test('fetches conflict-content with ?source=ytext and renders the diff', async () => {
- const provider = makeProvider('# My Y.Text bytes\nclient-side\n');
- render(<DiffViewBoundary docName="docs/notes" provider={provider} />);
+ test('issues the stage fetch on the first effect when the entry is present at mount', async () => {
+ render(<DiffViewBoundary docName="docs/notes" conflict={entry('docs/notes.md')} />);
await waitFor(() => {
- const fetched = fetchCalls.find((c) => c.url.startsWith('/api/sync/conflict-content'));
- expect(fetched).toBeTruthy();
- expect(fetched?.url).toContain('source=ytext');
- expect(fetched?.url).toContain('file=docs%2Fnotes.md');
+ expect(contentFetches().length).toBe(1);
});
-
+ const fetched = contentFetches()[0];
+ expect(fetched?.url).toContain('source=ytext');
+ expect(fetched?.url).toContain('file=docs%2Fnotes.md');
+ expect(fetchCalls.some((c) => c.url === '/api/sync/conflicts')).toBe(false);
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')} />,
- );
+ test('bounds the conflict-content fetch with an abort signal', async () => {
+ const timeout = vi.spyOn(AbortSignal, 'timeout');
- 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();
+ render(<DiffViewBoundary docName="docs/notes" conflict={entry('docs/notes.md')} />);
+
+ await waitFor(() => {
+ expect(contentFetches().length).toBe(1);
+ });
+ const fetched = contentFetches()[0];
+ expect(fetched?.init?.signal).toBeInstanceOf(AbortSignal);
+ expect(fetched?.init?.signal?.aborted).toBe(false);
+ expect(timeout).toHaveBeenCalledWith(20_000);
});
- 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('refetches the stages when the file or its detection time changes', async () => {
+ const raised = entry('docs/notes.md');
+ const { rerender } = render(<DiffViewBoundary docName="docs/notes" conflict={raised} />);
+ await waitFor(() => {
+ expect(contentFetches().length).toBe(1);
+ });
- 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 }),
- });
- });
- },
- );
+ rerender(<DiffViewBoundary docName="docs/notes" conflict={raised} />);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(contentFetches().length).toBe(1);
- test.each(['current', 'incoming'] as const)(
- 'accepts identical stale-write %s when activated as soon as it becomes observable',
- async (choice) => {
- 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',
- conflictKind: 'stale-external-write',
- },
- ],
- }
- : {
- file: 'foo.md',
- base: 'Same content.\n',
- ours: 'Same content.\n',
- theirs: 'Same content.\n',
- kind: 'both-modified',
- conflictKind: 'stale-external-write',
- lifecycleStatus: 'conflict',
- },
- ),
- );
- };
+ rerender(
+ <DiffViewBoundary
+ docName="docs/notes"
+ conflict={entry('docs/notes.md', { detectedAt: '2026-05-20T00:05:00.000Z' })}
+ />,
+ );
+ await waitFor(() => {
+ expect(contentFetches().length).toBe(2);
+ });
- let activated = false;
- const observer = new MutationObserver(() => {
- if (activated) return;
- const choiceButton = screen.queryByRole('button', {
- name: new RegExp(`^Accept ${choice}`),
- });
- if (!choiceButton) return;
- activated = true;
- fireEvent.click(choiceButton);
- });
- observer.observe(document.body, { childList: true, subtree: true });
-
- try {
- render(<DiffViewBoundary docName="foo" provider={makeProvider('Same content.\n')} />);
- expect(await screen.findByRole('button', { name: 'Apply changes' })).toBeTruthy();
- expect(activated).toBe(true);
- } finally {
- observer.disconnect();
- }
- },
- );
+ rerender(<DiffViewBoundary docName="docs/other" conflict={entry('docs/other.md')} />);
+ await waitFor(() => {
+ expect(contentFetches().length).toBe(3);
+ });
+ });
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} />);
+ const { unmount } = render(
+ <DiffViewBoundary docName="logs/entry" conflict={entry('logs/entry.md')} />,
+ );
await waitFor(() => {
const events = consoleWarnSpy.mock.calls.map((c) => c[0]);
@@ -414,71 +202,19 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
).toBe(true);
});
- test('threads .mdx extension from useConflicts when the doc is .mdx', async () => {
- 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(
- new Response(
- JSON.stringify({
- conflicts: [{ file: 'docs/note.mdx', detectedAt: '2026-05-20T00:00:00.000Z' }],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'docs/note.mdx',
- base: '',
- ours: '',
- theirs: '',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url === '/api/sync/resolve-conflict') {
- return Promise.resolve(new Response('{}', { status: 200 }));
- }
- return Promise.resolve(new Response('not found', { status: 404 }));
- };
-
- const provider = makeProvider('mdx body\n');
- render(<DiffViewBoundary docName="docs/note" provider={provider} />);
+ test('uses the entry file path verbatim, including a .mdx extension', async () => {
+ strategyFetch('docs/note.mdx', 'both-modified');
+ render(<DiffViewBoundary docName="docs/note" conflict={entry('docs/note.mdx')} />);
await waitFor(() => {
- const fetched = fetchCalls.find((c) => c.url.startsWith('/api/sync/conflict-content'));
- expect(fetched?.url).toContain('file=docs%2Fnote.mdx');
+ expect(contentFetches()[0]?.url).toContain('file=docs%2Fnote.mdx');
});
});
test('renders error fallback and hides actions when conflict-content fetch fails', async () => {
- 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(
- new Response(
- JSON.stringify({
- conflicts: [{ file: 'docs/missing.md', detectedAt: '2026-05-20T00:00:00.000Z' }],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(new Response('not found', { status: 404 }));
- }
- return Promise.resolve(new Response('', { status: 404 }));
- };
+ stubFetch(() => new Response('not found', { status: 404 }));
- const provider = makeProvider('# Anything\n');
- render(<DiffViewBoundary docName="docs/missing" provider={provider} />);
+ render(<DiffViewBoundary docName="docs/missing" conflict={entry('docs/missing.md')} />);
await screen.findByText(/Couldn't load conflict content for docs\/missing\.md/i);
const failureLog = consoleWarnSpy.mock.calls
@@ -487,172 +223,41 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
expect(failureLog).toBeTruthy();
});
- test('defers conflict-content fetch when conflicts list is empty (race window)', async () => {
- 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(
- new Response(JSON.stringify({ conflicts: [] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- }),
- );
- }
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(JSON.stringify({ file: '', base: '', ours: '', theirs: '' }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- }),
- );
- }
- return Promise.resolve(new Response('', { status: 404 }));
- };
-
- const provider = makeProvider('# Anything\n');
- render(<DiffViewBoundary docName="docs/note" provider={provider} />);
-
- await waitFor(() => {
- const conflictsFetch = fetchCalls.find((c) => c.url === '/api/sync/conflicts');
- expect(conflictsFetch).toBeTruthy();
- });
- expect(screen.queryByText(/Loading conflict for/i)).not.toBeNull();
- const contentFetch = fetchCalls.find((c) => c.url.startsWith('/api/sync/conflict-content'));
- expect(contentFetch).toBeUndefined();
- });
-
test('delete-modify (DU) renders Keep deletion + Restore affordances, not unified DiffView', async () => {
- 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(
- new Response(
- JSON.stringify({
- conflicts: [{ file: 'foo.md', detectedAt: '2026-05-20T00:00:00.000Z' }],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'foo.md',
- base: 'base content\n',
- ours: '',
- theirs: 'their modification\n',
- lifecycleStatus: 'conflict',
- kind: 'delete-modify',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url === '/api/sync/resolve-conflict') {
- return Promise.resolve(new Response('{}', { status: 200 }));
- }
- return Promise.resolve(new Response('not found', { status: 404 }));
- };
+ strategyFetch('foo.md', 'delete-modify');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
- const provider = makeProvider('# Anything\n');
- render(<DiffViewBoundary docName="foo" provider={provider} />);
+ expect(await screen.findByRole('button', { name: /keep file deleted/i })).toBeTruthy();
+ expect(await screen.findByRole('button', { name: /restore/i })).toBeTruthy();
+ });
- const keepDeletion = await screen.findByRole('button', { name: /keep file deleted/i });
- expect(keepDeletion).toBeTruthy();
+ test('delete-modify withholds the theirs affordance when resolutionOptions omits it', async () => {
+ strategyFetch('foo.md', 'delete-modify', { resolutionOptions: ['mine', 'content', 'delete'] });
+ render(
+ <DiffViewBoundary
+ docName="foo"
+ conflict={entry('foo.md', { conflict: 'reconcile', reason: 'disk-markers' })}
+ />,
+ );
- const restore = await screen.findByRole('button', { name: /restore/i });
- expect(restore).toBeTruthy();
+ expect(await screen.findByRole('button', { name: /keep file deleted/i })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /restore with remote changes/i })).toBeNull();
});
test('modify-delete (UD) renders Keep my version + Accept their deletion affordances', async () => {
- 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(
- new Response(
- JSON.stringify({
- conflicts: [{ file: 'foo.md', detectedAt: '2026-05-20T00:00:00.000Z' }],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'foo.md',
- base: 'base content\n',
- ours: 'our modification\n',
- theirs: '',
- lifecycleStatus: 'conflict',
- kind: 'modify-delete',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url === '/api/sync/resolve-conflict') {
- return Promise.resolve(new Response('{}', { status: 200 }));
- }
- return Promise.resolve(new Response('not found', { status: 404 }));
- };
-
- const provider = makeProvider('# Our version\n');
- render(<DiffViewBoundary docName="foo" provider={provider} />);
+ strategyFetch('foo.md', 'modify-delete');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
- const keepMine = await screen.findByRole('button', { name: /keep my version/i });
- expect(keepMine).toBeTruthy();
-
- const acceptDeletion = await screen.findByRole('button', { name: /accept their deletion/i });
- expect(acceptDeletion).toBeTruthy();
+ expect(await screen.findByRole('button', { name: /keep my version/i })).toBeTruthy();
+ expect(await screen.findByRole('button', { name: /accept their deletion/i })).toBeTruthy();
});
test('both-modified (regression) still renders the unified DiffView, NOT delete-prompt affordances', async () => {
- 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(
- new Response(
- JSON.stringify({
- conflicts: [{ file: 'docs/notes.md', detectedAt: '2026-05-20T00:00:00.000Z' }],
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'docs/notes.md',
- base: 'base content\n',
- ours: 'our version\n',
- theirs: 'their version\n',
- lifecycleStatus: 'conflict',
- kind: 'both-modified',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- if (url === '/api/sync/resolve-conflict') {
- return Promise.resolve(new Response('{}', { status: 200 }));
- }
- return Promise.resolve(new Response('not found', { status: 404 }));
- };
-
- const provider = makeProvider('# Our version\n');
- render(<DiffViewBoundary docName="docs/notes" provider={provider} />);
+ strategyFetch('docs/notes.md', 'both-modified');
+ render(<DiffViewBoundary docName="docs/notes" conflict={entry('docs/notes.md')} />);
await waitFor(() => {
- const fetched = fetchCalls.find((c) => c.url.startsWith('/api/sync/conflict-content'));
- expect(fetched).toBeTruthy();
+ expect(contentFetches().length).toBe(1);
});
expect(screen.queryByRole('button', { name: /keep file deleted/i })).toBeNull();
@@ -660,8 +265,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('delete-modify publishes --conflict-footer-height while mounted, removes on unmount', async () => {
- globalThis.fetch = strategyFetch('delete-modify') as typeof fetch;
- const { unmount } = render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'delete-modify');
+ const { unmount } = render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
await screen.findByRole('button', { name: /keep file deleted/i });
await waitFor(() => {
@@ -675,8 +280,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('modify-delete publishes --conflict-footer-height while mounted, removes on unmount', async () => {
- globalThis.fetch = strategyFetch('modify-delete') as typeof fetch;
- const { unmount } = render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'modify-delete');
+ const { unmount } = render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
await screen.findByRole('button', { name: /accept their deletion/i });
await waitFor(() => {
@@ -690,8 +295,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('delete-modify: "Keep deletion" dispatches strategy: delete', async () => {
- globalThis.fetch = strategyFetch('delete-modify') as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'delete-modify');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
fireEvent.click(await screen.findByRole('button', { name: /keep file deleted/i }));
await waitFor(() =>
expect(fetchCalls.some((c) => c.url === '/api/sync/resolve-conflict')).toBe(true),
@@ -700,8 +305,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('delete-modify: "Restore with remote changes" dispatches strategy: theirs', async () => {
- globalThis.fetch = strategyFetch('delete-modify') as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'delete-modify');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
fireEvent.click(await screen.findByRole('button', { name: /restore with remote changes/i }));
await waitFor(() =>
expect(fetchCalls.some((c) => c.url === '/api/sync/resolve-conflict')).toBe(true),
@@ -710,8 +315,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('modify-delete: "Keep my version" dispatches strategy: mine (never delete)', async () => {
- globalThis.fetch = strategyFetch('modify-delete') as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'modify-delete');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
fireEvent.click(await screen.findByRole('button', { name: /keep my version/i }));
await waitFor(() =>
expect(fetchCalls.some((c) => c.url === '/api/sync/resolve-conflict')).toBe(true),
@@ -720,8 +325,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('modify-delete: "Accept their deletion" dispatches strategy: delete', async () => {
- globalThis.fetch = strategyFetch('modify-delete') as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'modify-delete');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
fireEvent.click(await screen.findByRole('button', { name: /accept their deletion/i }));
await waitFor(() =>
expect(fetchCalls.some((c) => c.url === '/api/sync/resolve-conflict')).toBe(true),
@@ -734,8 +339,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
const pending = new Promise<void>((resolve) => {
release = resolve;
});
- globalThis.fetch = strategyFetch('delete-modify', pending) as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'delete-modify', { resolvePending: pending });
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
const keep = (await screen.findByRole('button', {
name: /keep file deleted/i,
@@ -754,8 +359,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('delete-modify (DU) renders header / content / footer with no collapsible-preview chrome', async () => {
- globalThis.fetch = strategyFetch('delete-modify') as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'delete-modify');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
expect(await screen.findByText(/you deleted/i, { exact: false, selector: 'p' })).toBeTruthy();
expect(screen.getByRole('button', { name: /keep file deleted/i })).toBeTruthy();
expect(screen.getByRole('button', { name: /restore with remote changes/i })).toBeTruthy();
@@ -764,8 +369,8 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
});
test('modify-delete (UD) renders header / content / footer with no collapsible-preview chrome', async () => {
- globalThis.fetch = strategyFetch('modify-delete') as typeof fetch;
- render(<DiffViewBoundary docName="foo" provider={makeProvider('x\n')} />);
+ strategyFetch('foo.md', 'modify-delete');
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
expect(await screen.findByText(/you modified/i, { exact: false, selector: 'p' })).toBeTruthy();
expect(screen.getByRole('button', { name: /keep my version/i })).toBeTruthy();
expect(screen.getByRole('button', { name: /accept their deletion/i })).toBeTruthy();
@@ -773,45 +378,161 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
expect(screen.queryByTestId('conflict-preview-trigger')).toBeNull();
});
- test('defers conflict-content fetch when other conflicts loaded but this docs entry missing', async () => {
- globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
+ test('a both-modified conflict that withholds content offers the wholesale choice instead', async () => {
+ strategyFetch('big.md', 'both-modified', { resolutionOptions: ['mine', 'theirs', 'delete'] });
+ render(
+ <DiffViewBoundary
+ docName="big"
+ conflict={entry('big.md', { conflict: 'reconcile', reason: 'refused-too-large' })}
+ />,
+ );
+
+ expect(await screen.findByRole('button', { name: /keep my version/i })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /use their version/i })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /delete the file/i })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /^Accept current/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Apply changes' })).toBeNull();
+ });
+
+ test('the wholesale choice dispatches the strategy the server offered', async () => {
+ strategyFetch('big.md', 'both-modified', { resolutionOptions: ['mine', 'theirs', 'delete'] });
+ render(
+ <DiffViewBoundary
+ docName="big"
+ conflict={entry('big.md', { conflict: 'reconcile', reason: 'refused-too-large' })}
+ />,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: /use their version/i }));
+ await waitFor(() =>
+ expect(fetchCalls.some((c) => c.url === '/api/sync/resolve-conflict')).toBe(true),
+ );
+ expect(lastResolveBody()).toMatchObject({ file: 'big.md', strategy: 'theirs' });
+ });
+
+ test('a stage body with no resolutionOptions offers nothing rather than guessing', async () => {
+ stubFetch((url) => {
+ if (url.startsWith('/api/sync/conflict-content')) {
+ return new Response(
+ JSON.stringify({
+ file: 'docs/skew.md',
+ base: 'base\n',
+ ours: 'ours\n',
+ theirs: 'theirs\n',
+ kind: 'delete-modify',
+ conflict: 'reconcile',
+ reason: 'disk-markers',
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+ return new Response('{}', { status: 200 });
+ });
+
+ render(<DiffViewBoundary docName="docs/skew" conflict={entry('docs/skew.md')} />);
+
+ await screen.findByText(/Couldn't load conflict content for docs\/skew\.md/i);
+ expect(screen.queryByRole('button', { name: /restore with remote changes/i })).toBeNull();
+ expect(screen.queryByRole('button', { name: /keep file deleted/i })).toBeNull();
+ expect(fetchCalls.some((c) => c.url === '/api/sync/resolve-conflict')).toBe(false);
+ });
+
+ test('a stage body whose resolutionOptions are malformed offers nothing', async () => {
+ stubFetch((url) => {
+ if (url.startsWith('/api/sync/conflict-content')) {
+ return new Response(
+ JSON.stringify({
+ file: 'docs/skew.md',
+ base: 'base\n',
+ ours: 'ours\n',
+ theirs: 'theirs\n',
+ kind: 'delete-modify',
+ conflict: 'reconcile',
+ reason: 'disk-markers',
+ resolutionOptions: 'mine',
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+ return new Response('{}', { status: 200 });
+ });
+
+ render(<DiffViewBoundary docName="docs/skew" conflict={entry('docs/skew.md')} />);
+
+ await screen.findByText(/Couldn't load conflict content for docs\/skew\.md/i);
+ expect(screen.queryByRole('button', { name: /restore with remote changes/i })).toBeNull();
+ });
+
+ test('resolve buttons come back after a dispatch that succeeds without unmounting', async () => {
+ let release: (() => void) | undefined;
+ const pending = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ strategyFetch('foo.md', 'delete-modify', { resolvePending: pending });
+ render(<DiffViewBoundary docName="foo" conflict={entry('foo.md')} />);
+
+ const keep = (await screen.findByRole('button', {
+ name: /keep file deleted/i,
+ })) as HTMLButtonElement;
+ const restore = screen.getByRole('button', {
+ name: /restore with remote changes/i,
+ }) as HTMLButtonElement;
+
+ fireEvent.click(keep);
+ await waitFor(() => expect(keep.disabled).toBe(true));
+
+ release?.();
+
+ await waitFor(() => expect(keep.disabled).toBe(false));
+ expect(restore.disabled).toBe(false);
+ });
+
+ test('Apply reaches the endpoint once, through the real boundary wiring', async () => {
+ const resolvePosts: string[] = [];
+ let releaseResolve: (() => void) | null = null;
+ globalThis.fetch = ((input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input.toString();
- fetchCalls.push({ url, init });
- if (url === '/api/sync/conflicts') {
+ if (url.startsWith('/api/sync/resolve-conflict')) {
+ resolvePosts.push(url);
+ return new Promise<Response>((resolveFetch) => {
+ releaseResolve = () => resolveFetch(new Response('{}', { status: 200 }));
+ });
+ }
+ if (url.startsWith('/api/sync/conflict-content')) {
return Promise.resolve(
new Response(
JSON.stringify({
- conflicts: [
- {
- file: 'other/doc.md',
- detectedAt: '2026-05-19T00:00:00Z',
- },
- ],
+ file: 'notes/roadmap.md',
+ kind: 'both-modified',
+ conflict: 'merge-native',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ base: '# Roadmap\n\n- Ship date: October 14\n',
+ ours: '# Roadmap\n\n- Ship date: October 21\n',
+ theirs: '# Roadmap\n\n- Ship date: Q4\n',
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
),
);
}
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(JSON.stringify({ file: '', base: '', ours: '', theirs: '' }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- }),
- );
- }
- return Promise.resolve(new Response('', { status: 404 }));
- };
+ return Promise.resolve(new Response('{}', { status: 200 }));
+ }) as typeof fetch;
- const provider = makeProvider('# Anything\n');
- render(<DiffViewBoundary docName="docs/mdx-note" provider={provider} />);
+ render(<DiffViewBoundary docName="notes/roadmap" conflict={entry('notes/roadmap.md')} />);
await waitFor(() => {
- const conflictsFetch = fetchCalls.find((c) => c.url === '/api/sync/conflicts');
- expect(conflictsFetch).toBeTruthy();
+ expect(screen.getAllByRole('button', { name: /^Accept current/ }).length).toBeGreaterThan(0);
});
- expect(screen.queryByText(/Loading conflict for/i)).not.toBeNull();
- const contentFetch = fetchCalls.find((c) => c.url.startsWith('/api/sync/conflict-content'));
- expect(contentFetch).toBeUndefined();
+ screen.getAllByRole('button', { name: /^Accept current/ })[0].click();
+
+ const apply = await screen.findByRole('button', { name: 'Apply changes' });
+ apply.click();
+ await act(async () => {});
+ apply.click();
+ await act(async () => {});
+
+ expect(resolvePosts).toHaveLength(1);
+
+ releaseResolve?.();
+ await act(async () => {});
});
});
diff --git a/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsx
new file mode 100644
index 000000000..4516e6029
--- /dev/null
+++ b/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsx
@@ -0,0 +1,211 @@
+import type { ConflictEntryWire } from '@inkeep/open-knowledge-core';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, expect, test, vi } from 'vitest';
+import * as Y from 'yjs';
+
+interface PoolEntry {
+ docName: string;
+ provider: { document: Y.Doc; configuration: { name: string }; synced: boolean };
+ poolEventId: string;
+ lastAccessedAt: number;
+}
+
+const poolEntries: PoolEntry[] = [];
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ poolEntries, serverRestartRecovery: { kind: 'idle' } }),
+}));
+vi.doMock('./PageListContext', () => ({
+ usePageList: () => ({ pages: new Map(), loading: false }),
+}));
+vi.doMock('@/editor/TiptapEditor', () => ({
+ TiptapEditor: () => <div data-testid="live-editor" />,
+}));
+vi.doMock('@/editor/SourceEditor', () => ({
+ SourceEditor: () => <div data-testid="source-editor" />,
+}));
+vi.doMock('./DocumentErrorBoundary', () => ({
+ DocumentErrorBoundary: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.doMock('./PageHeader', () => ({ PageHeader: () => <div /> }));
+vi.doMock('./PropertyPanel', () => ({ PropertyPanel: () => <div /> }));
+vi.doMock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
+
+const { EditorActivityPool } = await import('./EditorActivityPool');
+const { ConflictsProvider, useConflicts } = await import('@/hooks/use-conflicts');
+const { __resetRenameSnapshotStore } = await import('@/editor/editor-cache');
+const { __resetSyncPromiseCache } = await import('@/editor/sync-promise');
+const { Toaster, toast } = await import('sonner');
+
+const FILE = 'notes/roadmap.md';
+const DOC = 'notes/roadmap';
+const MISSING_TYPE = 'urn:ok:error:no-conflict-tracked';
+const MISSING_DETAIL =
+ 'This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Re-read conflicts({ kind: "list" }) before retrying.';
+const FIRST_CONFLICT: ConflictEntryWire = {
+ file: FILE,
+ docName: DOC,
+ detectedAt: '2026-05-20T00:00:00.000Z',
+ conflict: 'merge-native',
+};
+const KEEP_MINE = { strategy: 'mine', label: 'Keep my version' } as const;
+const APPLY_CONTENT = { strategy: 'content', label: 'Apply changes' } as const;
+type Action = typeof KEEP_MINE | typeof APPLY_CONTENT;
+
+let snapshot: ConflictEntryWire[];
+let contentMode: boolean;
+let requests: Array<{ file: string; strategy: string; content?: string }>;
+let resolveResponse: () => Response | Promise<Response>;
+
+function missingProblem(status = 404, type = MISSING_TYPE) {
+ return new Response(
+ JSON.stringify({
+ file: FILE,
+ type,
+ title: 'No conflict is tracked for this path.',
+ status: 404,
+ detail: MISSING_DETAIL,
+ }),
+ { status, headers: { 'Content-Type': 'application/problem+json' } },
+ );
+}
+
+function Snapshot() {
+ const { conflicts } = useConflicts();
+ return <output data-testid="conflict-snapshot">{JSON.stringify(conflicts)}</output>;
+}
+
+beforeEach(() => {
+ snapshot = [FIRST_CONFLICT];
+ contentMode = false;
+ requests = [];
+ resolveResponse = missingProblem;
+ const ydoc = new Y.Doc();
+ ydoc.getText('source').insert(0, '# Roadmap\n');
+ poolEntries.push({
+ docName: DOC,
+ provider: { document: ydoc, configuration: { name: DOC }, synced: true },
+ poolEventId: 'missing-conflict',
+ lastAccessedAt: 1,
+ });
+ vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === '/api/sync/conflicts') {
+ return new Response(JSON.stringify({ conflicts: snapshot }), { status: 200 });
+ }
+ if (url.startsWith('/api/sync/conflict-content')) {
+ return new Response(
+ JSON.stringify({
+ file: FILE,
+ kind: 'both-modified',
+ conflict: 'merge-native',
+ resolutionOptions: contentMode
+ ? ['mine', 'theirs', 'content', 'delete']
+ : ['mine', 'theirs', 'delete'],
+ base: '# Roadmap\n\n- Ship date: October 14\n',
+ ours: '# Roadmap\n\n- Ship date: October 21\n',
+ theirs: '# Roadmap\n\n- Ship date: Q4\n',
+ }),
+ { status: 200 },
+ );
+ }
+ if (url === '/api/sync/resolve-conflict') {
+ requests.push(JSON.parse(String(init?.body)));
+ snapshot = [];
+ return resolveResponse();
+ }
+ return new Response('not found', { status: 404 });
+ });
+});
+
+afterEach(async () => {
+ await act(async () => {
+ toast.dismiss();
+ });
+ cleanup();
+ __resetSyncPromiseCache();
+ __resetRenameSnapshotStore();
+ for (const entry of poolEntries) entry.provider.document.destroy();
+ poolEntries.length = 0;
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+async function mount(action: Action) {
+ contentMode = action.strategy === 'content';
+ await act(async () => {
+ render(
+ <ConflictsProvider>
+ <Snapshot />
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ <Toaster />
+ </ConflictsProvider>,
+ );
+ });
+ if (contentMode) {
+ const accept = await screen.findAllByRole('button', { name: /^Accept current/ });
+ fireEvent.click(accept[0]);
+ }
+ return screen.findByRole<HTMLButtonElement>('button', { name: action.label });
+}
+
+async function submit(button: HTMLButtonElement) {
+ await act(async () => {
+ fireEvent.click(button);
+ });
+}
+
+function expectInformationalFeedback(expectedType: 'info' | 'warning') {
+ const otherType = expectedType === 'info' ? 'warning' : 'info';
+ const notice = document.querySelector(`[data-sonner-toast][data-type="${expectedType}"]`);
+ expect(notice).not.toBeNull();
+ expect(notice?.textContent).toMatch(/no.*conflict|conflict.*(absent|no longer)/i);
+ expect(notice?.textContent).not.toMatch(
+ /(successfully (saved|applied)|your (resolution|changes) (were|have been) (saved|applied)|another session (has |already )?resolved|was resolved by another session)/i,
+ );
+ expect(document.querySelector(`[data-sonner-toast][data-type="${otherType}"]`)).toBeNull();
+ expect(document.querySelector('[data-sonner-toast][data-type="error"]')).toBeNull();
+ expect(document.querySelector('[data-sonner-toast][data-type="success"]')).toBeNull();
+}
+
+test('a typed 404 refreshes the authoritative list and reports the absence', async () => {
+ const button = await mount(KEEP_MINE);
+ await submit(button);
+
+ expect(requests).toHaveLength(1);
+ expect(requests[0]).toMatchObject({ file: FILE, strategy: 'mine' });
+ await waitFor(() => expect(screen.queryByTestId('live-editor')).not.toBeNull());
+ expect(screen.getByTestId('conflict-snapshot').textContent).toBe('[]');
+ await waitFor(() => expectInformationalFeedback('info'));
+});
+
+test('a generic 500 reports a failure without claiming the conflict was resolved', async () => {
+ resolveResponse = () =>
+ new Response(JSON.stringify({ detail: 'Server exploded' }), {
+ status: 500,
+ });
+ const button = await mount(KEEP_MINE);
+ await submit(button);
+
+ await screen.findByText(`Couldn't resolve the conflict for ${FILE}.`);
+ const failure = document.querySelector('[data-sonner-toast][data-type="error"]');
+ expect(failure?.textContent).toContain('Server exploded');
+ expect(document.querySelector('[data-sonner-toast][data-type="info"]')).toBeNull();
+ expect(document.querySelector('[data-sonner-toast][data-type="warning"]')).toBeNull();
+ expect(document.querySelector('[data-sonner-toast][data-type="success"]')).toBeNull();
+ expect(screen.queryByTestId('live-editor')).toBeNull();
+ expect(button.disabled).toBe(false);
+});
+
+test('the content path warns about the hand-merge risk instead of a plain notice', async () => {
+ const button = await mount(APPLY_CONTENT);
+ await submit(button);
+
+ expect(requests[0]?.content).toContain('October 21');
+ await waitFor(() => expectInformationalFeedback('warning'));
+ const notice = document.querySelector('[data-sonner-toast][data-type="warning"]');
+ expect(notice?.textContent).toContain(FILE);
+ expect(notice?.textContent).toContain(
+ "check the document's current content before redoing your edit",
+ );
+});
diff --git a/packages/app/src/components/DiffViewBoundary.resolved.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.resolved.dom.test.tsx
deleted file mode 100644
index dba6b7fd9..000000000
--- a/packages/app/src/components/DiffViewBoundary.resolved.dom.test.tsx
+++ /dev/null
@@ -1,191 +0,0 @@
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import * as Y from 'yjs';
-
-vi.doMock('sonner', () => ({
- toast: { error: () => {}, success: () => {}, info: () => {} },
-}));
-vi.doMock('next-themes', () => ({
- useTheme: () => ({ resolvedTheme: 'light' }),
-}));
-vi.doMock('@/lib/documents-events', () => ({
- subscribeToDocumentsChanged: () => () => {},
-}));
-
-let conflictsState: {
- conflicts: { file: string; detectedAt: string }[];
- loading: boolean;
- error: null;
-} = { conflicts: [], loading: true, error: null };
-
-vi.doMock('@/hooks/use-conflicts', () => ({
- useConflicts: () => conflictsState,
-}));
-
-const { DiffViewBoundary } = await import('./DiffViewBoundary');
-
-const CONFLICT_GRACE_OVERSHOOT_MS = 5_000;
-
-const ENTRY = { file: 'notes/roadmap.md', detectedAt: '2026-08-25T00:00:00.000Z' };
-
-function makeProvider(body: string) {
- const doc = new Y.Doc();
- doc.getText('source').insert(0, body);
- return { document: doc } as unknown as Parameters<typeof DiffViewBoundary>[0]['provider'];
-}
-
-const contentFetches: string[] = [];
-const resolvePosts: string[] = [];
-let releaseResolve: (() => void) | null = null;
-
-beforeEach(() => {
- contentFetches.length = 0;
- resolvePosts.length = 0;
- releaseResolve = null;
- conflictsState = { conflicts: [], loading: true, error: null };
- globalThis.fetch = ((input: RequestInfo | URL) => {
- const url = typeof input === 'string' ? input : input.toString();
- if (url.startsWith('/api/sync/resolve-conflict')) {
- resolvePosts.push(url);
- return new Promise<Response>((resolveFetch) => {
- releaseResolve = () =>
- resolveFetch(
- new Response(JSON.stringify({}), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- }),
- );
- });
- }
- if (url.startsWith('/api/sync/conflict-content')) contentFetches.push(url);
- if (url.startsWith('/api/sync/conflict-content')) {
- return Promise.resolve(
- new Response(
- JSON.stringify({
- file: 'notes/roadmap.md',
- kind: 'both-modified',
- base: '# Roadmap\n\n- Ship date: October 14\n',
- ours: '# Roadmap\n\n- Ship date: October 21\n',
- theirs: '# Roadmap\n\n- Ship date: Q4\n',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- ),
- );
- }
- return Promise.resolve(new Response('{}', { status: 200 }));
- }) as typeof fetch;
-});
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-describe('DiffViewBoundary — conflict resolved while open', () => {
- test('keeps waiting inside the CC1 catch-up window', async () => {
- vi.useFakeTimers();
- conflictsState = { conflicts: [], loading: false, error: null };
- render(<DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />);
-
- await act(async () => {
- vi.advanceTimersByTime(500);
- });
-
- expect(screen.queryByText('This conflict is resolved.')).toBeNull();
- vi.useRealTimers();
- });
-
- test('reports resolution on a FRESH mount once the entry never arrives', async () => {
- vi.useFakeTimers();
- conflictsState = { conflicts: [], loading: false, error: null };
- render(<DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />);
-
- await act(async () => {
- vi.advanceTimersByTime(2500);
- });
-
- expect(screen.getByText('This conflict is resolved.')).toBeTruthy();
- expect(screen.queryByText(/Loading conflict/)).toBeNull();
- vi.useRealTimers();
- });
-
- test('reports resolution when a conflict it was showing stops being tracked', async () => {
- conflictsState = { conflicts: [ENTRY], loading: false, error: null };
- const { rerender } = render(
- <DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />,
- );
- await waitFor(() => {
- expect(screen.queryByText(/Loading conflict/)).toBeNull();
- });
-
- conflictsState = { conflicts: [], loading: false, error: null };
- rerender(<DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />);
-
- await waitFor(
- () => {
- expect(screen.getByText('This conflict is resolved.')).toBeTruthy();
- },
- { timeout: 4000 },
- );
- });
-
- test('re-fetches when the same file gets a NEW conflict', async () => {
- conflictsState = { conflicts: [ENTRY], loading: false, error: null };
- const { rerender } = render(
- <DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />,
- );
- await waitFor(() => {
- expect(contentFetches.length).toBe(1);
- });
-
- conflictsState = {
- conflicts: [{ ...ENTRY, detectedAt: '2026-08-25T09:00:00.000Z' }],
- loading: false,
- error: null,
- };
- rerender(<DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />);
-
- await waitFor(() => {
- expect(contentFetches.length).toBe(2);
- });
- });
-
- test('a failed conflicts fetch is not reported as a resolution', async () => {
- vi.useFakeTimers();
- conflictsState = {
- conflicts: [],
- loading: false,
- error: 'network' as unknown as null,
- };
- render(<DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />);
-
- await act(async () => {
- vi.advanceTimersByTime(CONFLICT_GRACE_OVERSHOOT_MS);
- });
-
- expect(screen.queryByText('This conflict is resolved.')).toBeNull();
- expect(screen.getByText(/Couldn't check whether/)).toBeTruthy();
- vi.useRealTimers();
- });
-
- test('Apply reaches the endpoint once, through the real boundary wiring', async () => {
- conflictsState = { conflicts: [ENTRY], loading: false, error: null };
- render(<DiffViewBoundary docName="notes/roadmap" provider={makeProvider('# Roadmap\n')} />);
-
- await waitFor(() => {
- expect(screen.getAllByRole('button', { name: /^Accept current/ }).length).toBeGreaterThan(0);
- });
- screen.getAllByRole('button', { name: /^Accept current/ })[0].click();
-
- const apply = await screen.findByRole('button', { name: 'Apply changes' });
- apply.click();
- await act(async () => {});
- apply.click();
- await act(async () => {});
-
- expect(resolvePosts).toHaveLength(1);
-
- releaseResolve?.();
- await act(async () => {});
- });
-});
diff --git a/packages/app/src/components/DiffViewBoundary.tsx b/packages/app/src/components/DiffViewBoundary.tsx
index 665930ca0..0c283d475 100644
--- a/packages/app/src/components/DiffViewBoundary.tsx
+++ b/packages/app/src/components/DiffViewBoundary.tsx
@@ -1,47 +1,49 @@
-/**
- * Sibling to (NOT a replacement of) the editor `DocumentBoundary` mount; the hybrid render tree per
- * precedent #18(b) stays intact.
- */
-import type { HocuspocusProvider } from '@hocuspocus/provider';
-import type { SyncConflictContentSuccess } from '@inkeep/open-knowledge-core';
+import {
+ type ConflictEntryWire,
+ type ResolveStrategyWire,
+ type SyncConflictContentSuccess,
+ SyncConflictContentSuccessSchema,
+} 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';
import { useConflictFooterHeightVar } from '@/hooks/use-conflict-footer-height';
import { useConflicts } from '@/hooks/use-conflicts';
-import { filePathToDocName } from '@/lib/doc-hash';
import { ConflictFilePreview } from './ConflictFilePreview';
import { ConflictView } from './ConflictView';
import {
+ type ResolveConflictResult,
resolveConflictContent,
resolveConflictDelete,
resolveConflictMine,
resolveConflictTheirs,
} from './resolve-conflict-dispatch';
-const CONFLICT_ENTRY_GRACE_MS = 2_000;
-
interface DiffViewBoundaryProps {
docName: string;
- provider: HocuspocusProvider;
+ conflict: ConflictEntryWire;
}
-type ConflictKind = SyncConflictContentSuccess['kind'];
+type ConflictShape = 'both-modified' | 'delete-modify' | 'modify-delete';
interface ConflictSides {
+ file: string;
base: string;
ours: string;
theirs: string;
- kind: ConflictKind;
+ kind: ConflictShape;
+ resolutionOptions: readonly ResolveStrategyWire[];
conflictKind: SyncConflictContentSuccess['conflictKind'];
}
+const CONFLICT_CONTENT_REQUEST_TIMEOUT_MS = 20_000;
+
async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
try {
const res = await fetch(
`/api/sync/conflict-content?file=${encodeURIComponent(file)}&source=ytext`,
+ { signal: AbortSignal.timeout(CONFLICT_CONTENT_REQUEST_TIMEOUT_MS) },
);
if (!res.ok) {
let detail: string | undefined;
@@ -60,43 +62,27 @@ async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
);
return null;
}
- const data = (await res.json()) as Partial<Omit<ConflictSides, 'conflictKind'>> & {
- conflictKind?: unknown;
- };
- const kind: ConflictKind =
- data.kind === 'delete-modify' ||
- data.kind === 'modify-delete' ||
- data.kind === 'both-modified'
- ? data.kind
- : 'both-modified';
- if (data.kind !== kind) {
- console.warn(
- JSON.stringify({
- event: 'conflict-kind-missing-fallback',
- file,
- receivedKind: data.kind ?? null,
- }),
- );
- }
- if (
- data.conflictKind !== undefined &&
- data.conflictKind !== 'git' &&
- data.conflictKind !== 'stale-external-write'
- ) {
+ const body = await res.json().catch(() => null);
+ const parsed = SyncConflictContentSuccessSchema.safeParse(body);
+ if (!parsed.success) {
console.warn(
JSON.stringify({
- event: 'conflict-discriminator-unrecognized',
+ event: 'conflict-content-fetch-failed',
file,
- receivedConflictKind: data.conflictKind,
+ status: res.status,
+ detail: 'schema-drift',
}),
);
+ return null;
}
return {
- base: data.base ?? '',
- ours: data.ours ?? '',
- theirs: data.theirs ?? '',
- kind,
- conflictKind: data.conflictKind === 'stale-external-write' ? 'stale-external-write' : 'git',
+ file: parsed.data.file,
+ base: parsed.data.base,
+ ours: parsed.data.ours,
+ theirs: parsed.data.theirs,
+ kind: parsed.data.kind,
+ resolutionOptions: parsed.data.resolutionOptions,
+ conflictKind: parsed.data.conflictKind,
};
} catch (err) {
console.warn(
@@ -104,6 +90,7 @@ async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
event: 'conflict-content-fetch-failed',
file,
status: null,
+ errorName: err instanceof Error ? err.name : 'non-error-throw',
detail: err instanceof Error ? err.message : String(err),
}),
);
@@ -111,26 +98,24 @@ async function fetchConflictSides(file: string): Promise<ConflictSides | null> {
}
}
-export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
+export function DiffViewBoundary({ docName, conflict }: DiffViewBoundaryProps) {
const { t } = useLingui();
- const { conflicts, loading: conflictsLoading, error: conflictsError } = useConflicts();
- const conflictEntry = conflicts.find((entry) => filePathToDocName(entry.file) === docName);
- const filePath = conflictEntry?.file ?? `${docName}.md`;
- const [sides, setSides] = useState<ConflictSides | null>(null);
+ const { refresh } = useConflicts();
+ const filePath = conflict.file;
+ const detectedAt = conflict.detectedAt;
+ const [loadedSides, setLoadedSides] = useState<(ConflictSides & { detectedAt: string }) | null>(
+ null,
+ );
+ const sides =
+ loadedSides?.file === filePath && loadedSides.detectedAt === detectedAt ? loadedSides : null;
const [fetchFailed, setFetchFailed] = useState(false);
- const [waitedForEntry, setWaitedForEntry] = useState(false);
- useEffect(() => {
- if (conflictEntry !== undefined || conflictsLoading || conflictsError !== null) {
- setWaitedForEntry(false);
- return;
- }
- const timer = setTimeout(() => setWaitedForEntry(true), CONFLICT_ENTRY_GRACE_MS);
- return () => clearTimeout(timer);
- }, [conflictEntry, conflictsLoading, conflictsError]);
const [isResolving, setIsResolving] = useState(false);
- const duUdFooterRef = useConflictFooterHeightVar(
- sides?.kind === 'delete-modify' || sides?.kind === 'modify-delete',
- );
+ const hasStrategyFooter =
+ sides !== null &&
+ (sides.kind === 'delete-modify' ||
+ sides.kind === 'modify-delete' ||
+ !sides.resolutionOptions.includes('content'));
+ const strategyFooterRef = useConflictFooterHeightVar(hasStrategyFooter);
useEffect(() => {
console.warn(JSON.stringify({ event: 'editor-area-swap-to-diffview', 'doc.name': docName }));
@@ -141,88 +126,64 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
};
}, [docName]);
- const conflictSignature =
- conflictEntry === undefined
- ? null
- : [
- conflictEntry.detectedAt,
- conflictEntry.conflictKind ?? 'git',
- conflictEntry.baseSha ?? '',
- conflictEntry.oursSha ?? '',
- conflictEntry.theirsSha ?? '',
- ].join('|');
-
- const deferFetch = conflictsLoading || conflictEntry === undefined;
useEffect(() => {
- if (deferFetch || conflictSignature === null) return;
let cancelled = false;
- setSides(null);
+ setLoadedSides(null);
setFetchFailed(false);
void fetchConflictSides(filePath).then((result) => {
if (cancelled) return;
- if (result === null) {
+ if (result === null || result.file !== filePath) {
setFetchFailed(true);
} else {
- setSides(result);
+ setLoadedSides({ ...result, detectedAt });
}
});
return () => {
cancelled = true;
};
- }, [filePath, deferFetch, conflictSignature]);
-
- 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 });
- }
- }
+ }, [filePath, detectedAt]);
- async function handleResolveStrategy(
- dispatch: (file: string) => Promise<{ ok: boolean; detail?: string }>,
+ function handleResolveResult(
+ result: ResolveConflictResult,
+ failureMessage: string,
+ missingConflictDescription: string = filePath,
+ missingConflictSeverity: 'info' | 'warning' = 'info',
) {
- setIsResolving(true);
- const result = await dispatch(filePath);
- if (!result.ok) {
- setIsResolving(false);
- toast.error(t`Couldn't resolve the conflict for ${filePath}.`, {
- description: result.detail,
+ if (result.ok) return;
+ if (result.reason === 'no-conflict-tracked') {
+ refresh();
+ const notify = missingConflictSeverity === 'warning' ? toast.warning : toast.info;
+ notify(t`No conflict is tracked for this path.`, {
+ description: missingConflictDescription,
});
+ return;
}
+ toast.error(failureMessage, { description: result.detail });
}
- if (fetchFailed) {
- return (
- <div className="flex h-full items-center justify-center p-6 text-sm text-muted-foreground">
- <Trans>Couldn't load conflict content for {filePath}. Try reloading the page.</Trans>
- </div>
+ async function handleResolve(content: string) {
+ if (sides === null) return;
+ const result = await resolveConflictContent(sides.file, content);
+ handleResolveResult(
+ result,
+ t`Couldn't save the resolution for ${filePath}.`,
+ t`Someone may have already resolved ${filePath} — check the document's current content before redoing your edit.`,
+ 'warning',
);
}
- if (conflictsError !== null && conflictEntry === undefined) {
- return (
- <div className="flex h-full items-center justify-center p-6 text-sm text-muted-foreground">
- <Trans>Couldn't check whether {filePath} is still conflicted — retrying.</Trans>
- </div>
- );
+ async function handleResolveStrategy(dispatch: (file: string) => Promise<ResolveConflictResult>) {
+ if (sides === null) return;
+ setIsResolving(true);
+ const result = await dispatch(sides.file);
+ setIsResolving(false);
+ handleResolveResult(result, t`Couldn't resolve the conflict for ${filePath}.`);
}
- if (
- waitedForEntry &&
- !conflictsLoading &&
- conflictsError === null &&
- conflictEntry === undefined
- ) {
+ if (fetchFailed) {
return (
- <div className="flex h-full flex-col items-center justify-center gap-1 p-6 text-sm text-muted-foreground">
- <p>
- <Trans>This conflict is resolved.</Trans>
- </p>
- <p className="text-xs">
- <Trans>Reopen {filePath} to keep editing.</Trans>
- </p>
+ <div className="flex h-full items-center justify-center p-6 text-sm text-muted-foreground">
+ <Trans>Couldn't load conflict content for {filePath}. Try reloading the page.</Trans>
</div>
);
}
@@ -235,6 +196,8 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
);
}
+ const offersTheirs = sides.resolutionOptions.includes('theirs');
+
if (sides.kind === 'delete-modify') {
return (
<div className="flex h-full flex-col bg-background">
@@ -242,7 +205,7 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
<ConflictFilePreview filename={filePath} content={sides.theirs} />
</div>
<div
- ref={duUdFooterRef}
+ ref={strategyFooterRef}
className="flex flex-shrink-0 flex-wrap items-center justify-between gap-x-6 gap-y-3 border-t px-6 py-4"
>
<p className="text-sm text-muted-foreground">
@@ -261,14 +224,16 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
{}
<Trans>Keep file deleted</Trans>
</Button>
- <Button
- type="button"
- variant="default"
- disabled={isResolving}
- onClick={() => void handleResolveStrategy(resolveConflictTheirs)}
- >
- <Trans>Restore with remote changes</Trans>
- </Button>
+ {offersTheirs && (
+ <Button
+ type="button"
+ variant="default"
+ disabled={isResolving}
+ onClick={() => void handleResolveStrategy(resolveConflictTheirs)}
+ >
+ <Trans>Restore with remote changes</Trans>
+ </Button>
+ )}
</div>
</div>
</div>
@@ -282,7 +247,7 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
<ConflictFilePreview filename={filePath} content={sides.ours} />
</div>
<div
- ref={duUdFooterRef}
+ ref={strategyFooterRef}
className="flex flex-shrink-0 flex-wrap items-center justify-between gap-x-6 gap-y-3 border-t px-6 py-4"
>
<p className="text-sm text-muted-foreground">
@@ -314,6 +279,59 @@ export function DiffViewBoundary({ docName }: DiffViewBoundaryProps) {
);
}
+ if (!sides.resolutionOptions.includes('content')) {
+ return (
+ <div className="flex h-full flex-col bg-background">
+ <div className="min-h-0 flex-1">
+ <ConflictFilePreview filename={filePath} content={sides.ours} />
+ </div>
+ <div
+ ref={strategyFooterRef}
+ className="flex flex-shrink-0 flex-wrap items-center justify-between gap-x-6 gap-y-3 border-t px-6 py-4"
+ >
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ <span className="font-medium text-foreground">{filePath}</span> can't be merged here.
+ Pick the version to keep.
+ </Trans>
+ </p>
+ <div className="flex shrink-0 gap-3">
+ {sides.resolutionOptions.includes('mine') && (
+ <Button
+ type="button"
+ variant="default"
+ disabled={isResolving}
+ onClick={() => void handleResolveStrategy(resolveConflictMine)}
+ >
+ <Trans>Keep my version</Trans>
+ </Button>
+ )}
+ {offersTheirs && (
+ <Button
+ type="button"
+ variant="default"
+ disabled={isResolving}
+ onClick={() => void handleResolveStrategy(resolveConflictTheirs)}
+ >
+ <Trans>Use their version</Trans>
+ </Button>
+ )}
+ {sides.resolutionOptions.includes('delete') && (
+ <Button
+ type="button"
+ variant="destructive"
+ disabled={isResolving}
+ onClick={() => void handleResolveStrategy(resolveConflictDelete)}
+ >
+ <Trans>Delete the file</Trans>
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
return (
<ConflictView
fileName={filePath}
diff --git a/packages/app/src/components/EditorActivityPool.conflict-swap.dom.test.tsx b/packages/app/src/components/EditorActivityPool.conflict-swap.dom.test.tsx
new file mode 100644
index 000000000..dfcb81437
--- /dev/null
+++ b/packages/app/src/components/EditorActivityPool.conflict-swap.dom.test.tsx
@@ -0,0 +1,272 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { type ReactNode, useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import * as Y from 'yjs';
+
+interface FakePoolEntry {
+ docName: string;
+ provider: { document: Y.Doc; configuration: { name: string } };
+ poolEventId: string;
+ lastAccessedAt: number;
+}
+
+const poolEntries: FakePoolEntry[] = [];
+
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ poolEntries, serverRestartRecovery: { kind: 'idle' } }),
+}));
+vi.doMock('./PageListContext', () => ({
+ usePageList: () => ({ pages: new Map(), loading: false }),
+}));
+let tiptapMounts = 0;
+
+vi.doMock('@/editor/TiptapEditor', () => ({
+ TiptapEditor: () => {
+ useEffect(() => {
+ tiptapMounts += 1;
+ }, []);
+ return <div data-testid="tiptap-editor" />;
+ },
+}));
+vi.doMock('@/editor/SourceEditor', () => ({
+ SourceEditor: () => <div data-testid="source-editor" />,
+}));
+vi.doMock('./DocumentBoundary', () => ({
+ DocumentBoundary: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.doMock('./DocumentErrorBoundary', () => ({
+ DocumentErrorBoundary: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.doMock('./DiffViewBoundary', () => ({
+ DiffViewBoundary: ({ conflict }: { conflict: { file: string } }) => (
+ <div data-testid="diff-view">{conflict.file}</div>
+ ),
+}));
+vi.doMock('./EditorSkeleton', () => ({ EditorSkeleton: () => <div data-testid="skeleton" /> }));
+vi.doMock('./PageHeader', () => ({ PageHeader: () => <div /> }));
+vi.doMock('./PropertyPanel', () => ({ PropertyPanel: () => <div /> }));
+
+const { EditorActivityPool } = await import('./EditorActivityPool');
+const { ConflictsProvider } = await import('@/hooks/use-conflicts');
+const { __resetRenameSnapshotStore } = await import('@/editor/editor-cache');
+
+const DOC = 'docs/notes';
+
+let conflictsPayload: { conflicts: Array<Record<string, unknown>> } = { conflicts: [] };
+let conflictsResponder: () => Response = () =>
+ new Response(JSON.stringify(conflictsPayload), { status: 200 });
+let conflictsFetches = 0;
+
+function installFetchStub() {
+ globalThis.fetch = ((input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input.toString();
+ if (url === '/api/sync/conflicts') {
+ conflictsFetches += 1;
+ return Promise.resolve(conflictsResponder());
+ }
+ return Promise.resolve(new Response('{}', { status: 200 }));
+ }) as typeof fetch;
+}
+
+function makeEntry(docName: string): FakePoolEntry {
+ const document = new Y.Doc();
+ document.getText('source').insert(0, '# Notes\n\nbody\n');
+ return {
+ docName,
+ provider: { document, configuration: { name: docName } },
+ poolEventId: `pool-${docName}`,
+ lastAccessedAt: 1,
+ };
+}
+
+function signalSyncStatus() {
+ act(() => {
+ window.dispatchEvent(
+ new CustomEvent('open-knowledge:documents-changed', {
+ detail: { channels: ['sync-status'] },
+ }),
+ );
+ });
+}
+
+function lifecycleStatusOf(entry: FakePoolEntry): unknown {
+ return entry.provider.document.getMap('lifecycle').get('status');
+}
+
+describe('ActivityEntry — the conflict swap reads the conflicts provider', () => {
+ beforeEach(() => {
+ tiptapMounts = 0;
+ conflictsPayload = { conflicts: [] };
+ conflictsFetches = 0;
+ conflictsResponder = () => new Response(JSON.stringify(conflictsPayload), { status: 200 });
+ installFetchStub();
+ __resetRenameSnapshotStore();
+ poolEntries.length = 0;
+ poolEntries.push(makeEntry(DOC));
+ });
+
+ afterEach(() => {
+ cleanup();
+ __resetRenameSnapshotStore();
+ for (const entry of poolEntries) entry.provider.document.destroy();
+ poolEntries.length = 0;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ test('swaps to the DiffView from a provider entry, with no lifecycle map write anywhere', async () => {
+ conflictsPayload = {
+ conflicts: [
+ {
+ file: `${DOC}.md`,
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: DOC,
+ },
+ ],
+ };
+
+ render(
+ <ConflictsProvider>
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ </ConflictsProvider>,
+ );
+
+ const diff = await screen.findByTestId('diff-view');
+ expect(diff.textContent).toBe(`${DOC}.md`);
+ expect(screen.queryByTestId('tiptap-editor')).toBeNull();
+ expect(lifecycleStatusOf(poolEntries[0])).toBeUndefined();
+ });
+
+ test('mounts the editor while the conflicts lookup is still in flight', async () => {
+ conflictsPayload = {
+ conflicts: [
+ {
+ file: `${DOC}.md`,
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: DOC,
+ },
+ ],
+ };
+
+ render(
+ <ConflictsProvider>
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ </ConflictsProvider>,
+ );
+
+ expect(screen.getByTestId('tiptap-editor')).toBeTruthy();
+ expect(screen.queryByTestId('diff-view')).toBeNull();
+
+ const diff = await screen.findByTestId('diff-view');
+ expect(diff.textContent).toBe(`${DOC}.md`);
+ });
+
+ test('remounts the editor on the SAME provider instance when the entry vanishes after a signal', async () => {
+ conflictsPayload = {
+ conflicts: [
+ {
+ file: `${DOC}.md`,
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: DOC,
+ },
+ ],
+ };
+
+ render(
+ <ConflictsProvider>
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ </ConflictsProvider>,
+ );
+ await screen.findByTestId('diff-view');
+
+ conflictsPayload = { conflicts: [] };
+ signalSyncStatus();
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('diff-view')).toBeNull();
+ });
+ await screen.findByTestId('tiptap-editor');
+ expect(lifecycleStatusOf(poolEntries[0])).toBeUndefined();
+ });
+
+ test('a failed conflicts fetch leaves the editor open rather than blocking it', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ conflictsResponder = () => new Response('internal', { status: 500 });
+
+ render(
+ <ConflictsProvider>
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(conflictsFetches).toBeGreaterThan(0);
+ });
+ await act(async () => {});
+
+ expect(screen.getByTestId('tiptap-editor')).toBeTruthy();
+ expect(screen.queryByTestId('diff-view')).toBeNull();
+ expect(tiptapMounts).toBe(1);
+ warn.mockRestore();
+ });
+
+ test('a sync-status refetch after a failed lookup swaps to the DiffView', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ conflictsPayload = {
+ conflicts: [
+ {
+ file: `${DOC}.md`,
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: DOC,
+ },
+ ],
+ };
+ conflictsResponder = () => new Response('internal', { status: 500 });
+
+ render(
+ <ConflictsProvider>
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ </ConflictsProvider>,
+ );
+
+ await act(async () => {});
+ expect(conflictsFetches).toBe(1);
+ expect(screen.getByTestId('tiptap-editor')).toBeTruthy();
+
+ conflictsResponder = () => new Response(JSON.stringify(conflictsPayload), { status: 200 });
+ signalSyncStatus();
+
+ const diff = await screen.findByTestId('diff-view');
+ expect(diff.textContent).toBe(`${DOC}.md`);
+ expect(lifecycleStatusOf(poolEntries[0])).toBeUndefined();
+ warn.mockRestore();
+ });
+
+ test('a conflict on another doc leaves this entry on the editor branch', async () => {
+ conflictsPayload = {
+ conflicts: [
+ {
+ file: 'other/doc.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'other/doc',
+ },
+ ],
+ };
+
+ render(
+ <ConflictsProvider>
+ <EditorActivityPool activeDocName={DOC} isSourceMode={false} onRecycle={() => {}} />
+ </ConflictsProvider>,
+ );
+
+ await screen.findByTestId('tiptap-editor');
+ expect(screen.queryByTestId('diff-view')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx b/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx
index 52de00f1d..a04d3206f 100644
--- a/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx
+++ b/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx
@@ -23,7 +23,15 @@ vi.doMock('@/editor/DocumentContext', () => ({
vi.doMock('./PageListContext', () => ({
usePageList: () => ({ pages: new Map(), loading: false }),
}));
-vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
+vi.doMock('@/hooks/use-conflicts', () => ({
+ useDocConflict: () => null,
+ useConflicts: () => ({
+ conflicts: [],
+ loading: false,
+ error: null,
+ refresh: () => {},
+ }),
+}));
vi.doMock('@/editor/TiptapEditor', () => ({
TiptapEditor: () => <div data-testid="tiptap-editor" />,
}));
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index ed19f6fbe..525cd6bf7 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -37,7 +37,7 @@ import {
} from '@/editor/scroll-restore-coordination';
import { TiptapEditor } from '@/editor/TiptapEditor';
import type { EditorModeValue } from '@/editor/use-editor-mode';
-import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
+import { useDocConflict } from '@/hooks/use-conflicts';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
import { isNoteWindow } from '@/lib/note-window-mode';
import { mark, ProfilerBoundary } from '@/lib/perf';
@@ -741,16 +741,11 @@ function ActivityEntry({
}: ActivityEntryProps) {
const recoveryView = getServerRestartRecoveryView(entry.docName, serverRestartRecovery);
- /**
- * A conflicted doc swaps the editor children for the diff view inside the same
- * DocumentBoundary, preserving precedent #18(b)'s hybrid render tree.
- */
- const lifecycleStatus = useLifecycleStatus(entry.docName);
- const isConflict = lifecycleStatus === 'conflict';
+ const conflict = useDocConflict(entry.docName);
const isMermaid = isMermaidDocFile(entry.docName);
const isExcalidraw = isExcalidrawDocFile(entry.docName);
const isTextDoc = !isMermaid && !isExcalidraw && isEditableTextDocFile(entry.docName);
- const isDualEditor = !isConflict && isMarkdownDocFile(entry.docName);
+ const isDualEditor = conflict === null && isMarkdownDocFile(entry.docName);
const [portalTarget] = useState<HTMLDivElement>(() => {
const target = document.createElement('div');
target.setAttribute('data-ok-editor-portal', entry.docName);
@@ -857,7 +852,7 @@ function ActivityEntry({
mode={effectiveIsSourceMode ? 'source' : 'wysiwyg'}
initialScrollTop={warmSnapshot?.scrollTop}
bodyAnchorRef={bodyAnchorRef}
- hasToolbar={!isConflict}
+ hasToolbar={conflict === null}
>
{recoveryView ? (
<ServerRestartRecoveryPanel view={recoveryView} />
@@ -881,14 +876,9 @@ function ActivityEntry({
}
>
<DocumentBoundary docName={entry.docName} provider={entry.provider}>
- {isConflict ? (
- /*
- * The outer DocumentBoundary's syncPromise gate + the Suspense/error scopes
- * above stay intact (precedent #18(b) hybrid render tree preserved — we swap
- * children, not boundaries).
- */
+ {conflict !== null ? (
<Suspense fallback={<EditorSkeleton />}>
- <LazyDiffViewBoundary docName={entry.docName} provider={entry.provider} />
+ <LazyDiffViewBoundary docName={entry.docName} conflict={conflict} />
</Suspense>
) : isMermaid ? (
/*
diff --git a/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
index fd4f15082..2ca81386c 100644
--- a/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
@@ -42,7 +42,10 @@ vi.doMock('@/hooks/use-selection-stats', () => ({
return null;
},
}));
-vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
+vi.doMock('@/hooks/use-conflicts', () => ({
+ useDocConflict: () => null,
+ useConflicts: () => ({ conflicts: [], loading: false, error: null, refresh: () => {} }),
+}));
vi.doMock('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));
vi.doMock('@/lib/use-settings-route', () => ({
useSettingsRoute: () => ({ open: false, close: () => {} }),
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index e99eba573..1fd6be65a 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -255,8 +255,14 @@ vi.doMock('@/hooks/use-document-stats', () => ({
useDocumentStats: () => null,
}));
-vi.doMock('@/hooks/use-lifecycle-status', () => ({
- useLifecycleStatus: () => 'ready',
+vi.doMock('@/hooks/use-conflicts', () => ({
+ useDocConflict: () => null,
+ useConflicts: () => ({
+ conflicts: [],
+ loading: false,
+ error: null,
+ refresh: () => {},
+ }),
}));
vi.doMock('@/presence/use-sync-status', () => ({
diff --git a/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx b/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx
index 9eb45a300..969caaa91 100644
--- a/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx
@@ -35,7 +35,7 @@ vi.doMock('@/editor/DocumentContext', () => ({
}));
vi.doMock('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));
vi.doMock('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));
-vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
+vi.doMock('@/hooks/use-conflicts', () => ({ useDocConflict: () => null }));
vi.doMock('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));
vi.doMock('@/lib/use-settings-route', () => ({
useSettingsRoute: () => ({ open: false, close: () => {} }),
diff --git a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
index c620d5dab..bb7684e0a 100644
--- a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
@@ -30,7 +30,7 @@ vi.doMock('@/editor/DocumentContext', () => ({
}));
vi.doMock('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));
vi.doMock('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));
-vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
+vi.doMock('@/hooks/use-conflicts', () => ({ useDocConflict: () => null }));
vi.doMock('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));
vi.doMock('@/lib/use-settings-route', () => ({
useSettingsRoute: () => ({ open: false, close: () => {} }),
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 21e6c7a45..2f8909bc0 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -57,8 +57,8 @@ import {
partitionFrontmatterProblems,
useFrontmatterDiagnostics,
} from '@/editor/useFrontmatterDiagnostics';
+import { useDocConflict } from '@/hooks/use-conflicts';
import { useDocumentStats } from '@/hooks/use-document-stats';
-import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
import { useSelectionStats } from '@/hooks/use-selection-stats';
import { closeAgentDiff, useAgentDiffView } from '@/lib/agent-diff-store';
import {
@@ -182,8 +182,8 @@ function PaneDocumentToolbar({
frontmatterLintConfig?.effective ?? null,
),
);
- const lifecycleStatus = useLifecycleStatus(docName);
- if (lifecycleStatus === 'conflict') return null;
+ const conflict = useDocConflict(docName);
+ if (conflict !== null) return null;
return (
<EditorToolbar
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
index 60c70db88..eaaf5ee02 100644
--- a/packages/app/src/components/EditorTabs.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -21,7 +21,7 @@ let newTabIds: string[] = [];
let pinnedTabIds: string[] = [];
let previewTabId: string | null = null;
let pageMeta: Map<string, { docExt?: string }> = new Map();
-let lifecycleStatuses: Map<string, string> = new Map();
+let conflictedDocs: Set<string> = new Set();
let focusedPaneId = 'pane-a';
let skillsState: unknown = { status: 'idle' };
let renderRealTabTargetMenuItems = false;
@@ -371,8 +371,17 @@ vi.doMock('@/components/PageListContext', () => ({
}),
}));
-vi.doMock('@/hooks/use-lifecycle-status', () => ({
- useLifecycleStatus: (docName: string) => lifecycleStatuses.get(docName) ?? null,
+vi.doMock('@/hooks/use-conflicts', () => ({
+ useDocConflict: (docName: string | null) => {
+ return docName !== null && conflictedDocs.has(docName)
+ ? {
+ file: `${docName}.md`,
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName,
+ }
+ : null;
+ },
}));
vi.doMock('@/hooks/use-skills', () => ({
@@ -409,7 +418,7 @@ function resetState() {
['docs/team/spec', { docExt: '.mdx' }],
['docs/team/readme', { docExt: '.txt' }],
]);
- lifecycleStatuses = new Map();
+ conflictedDocs = new Set();
focusedPaneId = 'pane-a';
skillsState = { status: 'idle' };
renderRealTabTargetMenuItems = false;
@@ -1478,7 +1487,7 @@ describe('EditorTabs runtime behavior', () => {
});
test('tab context menus and active tab styling are visible behavior, not source-shape details', async () => {
- lifecycleStatuses.set('docs/team/notes', 'conflict');
+ conflictedDocs.add('docs/team/notes');
await renderEditorTabs();
const conflictedTabButton = screen.getByRole('button', {
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 772135ac9..edab307ec 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -56,7 +56,7 @@ import {
tabIdForNavigationTarget,
tabParts,
} from '@/editor/editor-tabs';
-import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
+import { useDocConflict } from '@/hooks/use-conflicts';
import { skillFileForDocName } from '@/hooks/use-reconcile-skill-tabs';
import { useSkills } from '@/hooks/use-skills';
import { emitFileTreeMenuActionRename } from '@/lib/file-tree-menu-action-events';
@@ -537,8 +537,8 @@ function DocumentTabButton({
tabId: string;
}) {
const { t } = useLingui();
- const lifecycleStatus = useLifecycleStatus(docName);
- const hasConflict = lifecycleStatus === 'conflict';
+ const docConflict = useDocConflict(docName);
+ const hasConflict = docConflict !== null;
const buttonAccessibleLabel = hasConflict ? t`${accessibleLabel} (conflict)` : accessibleLabel;
return (
diff --git a/packages/app/src/components/FileTree.duplicate.dom.test.tsx b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
index 49cd47a6c..642b0ac40 100644
--- a/packages/app/src/components/FileTree.duplicate.dom.test.tsx
+++ b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
@@ -252,6 +252,8 @@ function expectMenuOrder(labels: readonly RegExp[]) {
}
}
+let conflictsPayload: Array<Record<string, unknown>> = [];
+
function makeFetchMock() {
return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
@@ -268,6 +270,9 @@ function makeFetchMock() {
if (url === '/api/delete-path') {
return jsonResponse({ deletedDocNames: [] });
}
+ if (url === '/api/sync/conflicts') {
+ return jsonResponse({ conflicts: conflictsPayload });
+ }
if (url === '/api/duplicate-path') {
if (duplicateGate) await duplicateGate;
if (duplicateFetchError) throw duplicateFetchError;
@@ -438,6 +443,7 @@ vi.doMock('@pierre/trees/react', () => ({
}));
const { FileTree } = await import('./FileTree');
+const { ConflictsProvider } = await import('@/hooks/use-conflicts');
const { emitFileTreeMenuActionDelete, emitFileTreeMenuActionDuplicate } = await import(
'@/lib/file-tree-menu-action-events'
);
@@ -446,6 +452,14 @@ function renderFileTree() {
return render(<FileTree />);
}
+function renderFileTreeWithConflicts() {
+ return render(
+ <ConflictsProvider>
+ <FileTree />
+ </ConflictsProvider>,
+ );
+}
+
describe('FileTree duplicate action runtime behavior', () => {
let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
@@ -467,6 +481,7 @@ describe('FileTree duplicate action runtime behavior', () => {
projectLocalBindingMock = null;
mergedConfigMock = null;
deleteConfirmationProps = null;
+ conflictsPayload = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
toastSuccessMock.mockClear();
toastErrorMock.mockClear();
@@ -1145,6 +1160,64 @@ describe('FileTree duplicate action runtime behavior', () => {
});
});
+ test('a conflicted doc is refused by the delete guard before any delete-path call', async () => {
+ conflictsPayload = [
+ {
+ file: 'notes/source.mdx',
+ detectedAt: '2026-05-20T00:00:00.000Z',
+ conflict: 'merge-native',
+ docName: 'notes/source',
+ },
+ ];
+ renderFileTreeWithConflicts();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ await waitFor(() =>
+ expect(fetchCalls.some((call) => call.url === '/api/sync/conflicts')).toBe(true),
+ );
+ fetchCalls = [];
+ toastErrorMock.mockClear();
+
+ act(() => {
+ emitFileTreeMenuActionDelete({
+ kind: 'doc',
+ target: 'notes/source',
+ docName: 'notes/source',
+ } satisfies ResolvedNavigationTarget);
+ });
+
+ await screen.findByTestId('delete-confirmation-dialog');
+ await act(async () => {
+ await deleteConfirmationProps?.onDelete?.();
+ });
+
+ expect(deletePathCalls()).toHaveLength(0);
+ expect(toastErrorMock).toHaveBeenCalled();
+ });
+
+ test('an unconflicted doc still reaches delete-path with the provider mounted', async () => {
+ renderFileTreeWithConflicts();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ await waitFor(() =>
+ expect(fetchCalls.some((call) => call.url === '/api/sync/conflicts')).toBe(true),
+ );
+ fetchCalls = [];
+
+ act(() => {
+ emitFileTreeMenuActionDelete({
+ kind: 'doc',
+ target: 'notes/source',
+ docName: 'notes/source',
+ } satisfies ResolvedNavigationTarget);
+ });
+
+ await screen.findByTestId('delete-confirmation-dialog');
+ await act(async () => {
+ await deleteConfirmationProps?.onDelete?.();
+ });
+
+ await waitFor(() => expect(deletePathCalls()).toHaveLength(1));
+ });
+
test('delete event bus drops .ok targets before opening confirmation', async () => {
renderFileTree();
await screen.findByRole('menuitem', { name: /duplicate/i });
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 68e2cc44d..99a6e7368 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -2768,11 +2768,9 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
const blockingConflicts = activeConflicts.filter((c) =>
deleteTargets.some((t) => {
- if (t.kind === 'file') {
- const fileWithExt = `${t.path}${t.docExt ?? '.md'}`;
- return c.file === fileWithExt;
- }
- if (t.kind === 'folder') return c.file.startsWith(`${t.path}/`);
+ if (c.docName === null) return false;
+ if (t.kind === 'file') return c.docName === t.path;
+ if (t.kind === 'folder') return c.docName.startsWith(`${t.path}/`);
return false;
}),
);
diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
index c9ef34cfc..3c574b089 100644
--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx
+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
@@ -53,7 +53,12 @@ vi.doMock('@/hooks/use-git-sync-status', () => ({
}));
vi.doMock('@/hooks/use-conflicts', () => ({
- useConflicts: () => ({ conflicts: [{ file: 'docs/conflicted.md' }] }),
+ useConflicts: () => ({
+ conflicts: [{ file: 'docs/conflicted.md', docName: 'docs/conflicted' }],
+ loading: false,
+ error: null,
+ refresh: () => {},
+ }),
}));
type WorktreeTestEntry = {
diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsx
index 993ad2c5a..19909b820 100644
--- a/packages/app/src/components/SyncStatusBadge.tsx
+++ b/packages/app/src/components/SyncStatusBadge.tsx
@@ -36,7 +36,7 @@ import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';
import type { GitWorktreeStatus } from '@/hooks/use-git-worktree-status';
import { useGitWorktreeStatus } from '@/hooks/use-git-worktree-status';
import { useConfigContext } from '@/lib/config-provider';
-import { filePathToDocName, hashFromAssetPath, hashFromDocName, isSameHash } from '@/lib/doc-hash';
+import { hashFromAssetPath, hashFromDocName, isSameHash } from '@/lib/doc-hash';
import { triggerSync } from '@/lib/trigger-sync';
import { openSyncSettings } from '@/lib/use-settings-route';
import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';
@@ -1027,8 +1027,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
const blockingPaths = status.blockingPaths ?? [];
const { conflicts } = useConflicts();
- const firstConflict = conflicts[0] ?? null;
- const showConflictButton = state === 'conflict' && firstConflict !== null;
+ const firstConflictDocName = conflicts.find((entry) => entry.docName !== null)?.docName ?? null;
return (
<div className="flex flex-col gap-3.5">
@@ -1250,12 +1249,12 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
{}
<Trans>A document has a conflict — resolve it to keep it up to date.</Trans>
</p>
- {showConflictButton && firstConflict && (
+ {firstConflictDocName !== null && (
<Button
variant="outline"
size="xs"
className="self-start"
- onClick={() => navigateToHash(hashFromDocName(filePathToDocName(firstConflict.file)))}
+ onClick={() => navigateToHash(hashFromDocName(firstConflictDocName))}
>
<Trans>Review</Trans>
</Button>
diff --git a/packages/app/src/components/SystemDocSubscriber.dom.test.tsx b/packages/app/src/components/SystemDocSubscriber.dom.test.tsx
index c47a7798e..18d086aa2 100644
--- a/packages/app/src/components/SystemDocSubscriber.dom.test.tsx
+++ b/packages/app/src/components/SystemDocSubscriber.dom.test.tsx
@@ -80,5 +80,11 @@ test('first system sync recovers local-target invalidations emitted during conne
act(() => provider?.emitSynced());
- expect(emittedChannels).toContainEqual(['files', 'backlinks', 'graph', 'local-targets']);
+ expect(emittedChannels).toContainEqual([
+ 'files',
+ 'backlinks',
+ 'graph',
+ 'local-targets',
+ 'sync-status',
+ ]);
});
diff --git a/packages/app/src/components/SystemDocSubscriber.tsx b/packages/app/src/components/SystemDocSubscriber.tsx
index a693b6e3c..7664f3109 100644
--- a/packages/app/src/components/SystemDocSubscriber.tsx
+++ b/packages/app/src/components/SystemDocSubscriber.tsx
@@ -119,7 +119,7 @@ export function SystemDocSubscriber() {
void handlersRef.current.refreshServerInfo();
});
provider.on('synced', () => {
- emitDocumentsChanged(['files', 'backlinks', 'graph', 'local-targets']);
+ emitDocumentsChanged(['files', 'backlinks', 'graph', 'local-targets', 'sync-status']);
onReconnectSynced();
});
diff --git a/packages/app/src/components/file-tree-refresh.dom.test.tsx b/packages/app/src/components/file-tree-refresh.dom.test.tsx
index a3ea77776..3b750c20f 100644
--- a/packages/app/src/components/file-tree-refresh.dom.test.tsx
+++ b/packages/app/src/components/file-tree-refresh.dom.test.tsx
@@ -140,7 +140,12 @@ vi.doMock('@/lib/config-provider', () => ({
}));
vi.doMock('@/hooks/use-conflicts', () => ({
- useConflicts: () => ({ conflicts: [], loading: false, error: null }),
+ useConflicts: () => ({
+ conflicts: [],
+ loading: false,
+ error: null,
+ refresh: () => {},
+ }),
}));
vi.doMock('./handoff/useInstalledAgents', () => ({
diff --git a/packages/app/src/components/resolve-conflict-dispatch.ts b/packages/app/src/components/resolve-conflict-dispatch.ts
index f1acd20f0..9155ae6de 100644
--- a/packages/app/src/components/resolve-conflict-dispatch.ts
+++ b/packages/app/src/components/resolve-conflict-dispatch.ts
@@ -1,15 +1,18 @@
+import { ProblemDetailsSchema, type ProblemType } from '@inkeep/open-knowledge-core';
+
type ResolveStrategy = 'mine' | 'theirs' | 'content' | 'delete';
-interface DispatchResult {
- ok: boolean;
- detail?: string;
-}
+const NO_CONFLICT_TRACKED = 'urn:ok:error:no-conflict-tracked' satisfies ProblemType;
+
+export type ResolveConflictResult =
+ | { ok: true }
+ | { ok: false; reason: 'no-conflict-tracked' | 'failed'; detail?: string };
async function dispatchResolve(
file: string,
strategy: ResolveStrategy,
content?: string,
-): Promise<DispatchResult> {
+): Promise<ResolveConflictResult> {
try {
const body: { file: string; strategy: ResolveStrategy; content?: string } = {
file,
@@ -22,42 +25,46 @@ async function dispatchResolve(
body: JSON.stringify(body),
});
if (res.ok) return { ok: true };
+ const payload: unknown = await res.json().catch(() => null);
+ const problem = ProblemDetailsSchema.safeParse(payload);
let detail: string | undefined;
- try {
- const payload = (await res.json()) as { detail?: unknown; title?: unknown };
- if (typeof payload.detail === 'string') detail = payload.detail;
- else if (typeof payload.title === 'string') detail = payload.title;
- } catch {}
- return { ok: false, detail };
+ if (typeof payload === 'object' && payload !== null) {
+ if ('detail' in payload && typeof payload.detail === 'string') detail = payload.detail;
+ else if ('title' in payload && typeof payload.title === 'string') detail = payload.title;
+ }
+ if (problem.success && res.status === 404 && problem.data.type === NO_CONFLICT_TRACKED) {
+ return { ok: false, reason: 'no-conflict-tracked', detail };
+ }
+ return { ok: false, reason: 'failed', detail };
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
console.warn(
JSON.stringify({
- event: 'conflict-resolve-dispatch-failed',
+ event: 'resolve-conflict-dispatch-failed',
file,
strategy,
detail,
}),
);
- return { ok: false, detail };
+ return { ok: false, reason: 'failed', detail };
}
}
export async function resolveConflictContent(
file: string,
content: string,
-): Promise<DispatchResult> {
+): Promise<ResolveConflictResult> {
return dispatchResolve(file, 'content', content);
}
-export async function resolveConflictMine(file: string): Promise<DispatchResult> {
+export async function resolveConflictMine(file: string): Promise<ResolveConflictResult> {
return dispatchResolve(file, 'mine');
}
-export async function resolveConflictTheirs(file: string): Promise<DispatchResult> {
+export async function resolveConflictTheirs(file: string): Promise<ResolveConflictResult> {
return dispatchResolve(file, 'theirs');
}
-export async function resolveConflictDelete(file: string): Promise<DispatchResult> {
+export async function resolveConflictDelete(file: string): Promise<ResolveConflictResult> {
return dispatchResolve(file, 'delete');
}
diff --git a/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx b/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx
index 8be57fa36..0d20e0b13 100644
--- a/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx
+++ b/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx
@@ -1,13 +1,25 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-let conflictsState: { conflicts: { file: string; detectedAt: string }[] } = { conflicts: [] };
+let conflictsState: {
+ conflicts: { file: string; detectedAt: string; docName: string }[];
+} = {
+ conflicts: [],
+};
vi.doMock('@/hooks/use-conflicts', () => ({ useConflicts: () => conflictsState }));
const { useConflictComposerPrefill } = await import('./use-conflict-composer-prefill');
-const ENTRY = { file: 'notes/roadmap.md', detectedAt: '2026-08-25T00:00:00.000Z' };
-const DOC2 = { file: 'notes/doc2.md', detectedAt: '2026-08-25T00:00:00.000Z' };
+const ENTRY = {
+ file: 'notes/roadmap.md',
+ detectedAt: '2026-08-25T00:00:00.000Z',
+ docName: 'notes/roadmap',
+};
+const DOC2 = {
+ file: 'notes/doc2.md',
+ detectedAt: '2026-08-25T00:00:00.000Z',
+ docName: 'notes/doc2',
+};
function makeInput(initial = '') {
let text = initial;
diff --git a/packages/app/src/hooks/use-conflict-composer-prefill.ts b/packages/app/src/hooks/use-conflict-composer-prefill.ts
index ff10ff9aa..6031990a1 100644
--- a/packages/app/src/hooks/use-conflict-composer-prefill.ts
+++ b/packages/app/src/hooks/use-conflict-composer-prefill.ts
@@ -1,7 +1,6 @@
import { type RefObject, useEffect, useRef, useState } from 'react';
import { useConflicts } from '@/hooks/use-conflicts';
import { buildResolveDraft } from '@/lib/conflict-resolve-draft';
-import { filePathToDocName } from '@/lib/doc-hash';
interface PrefillTarget {
getContent: () => { instruction: string; mentions: string[] };
@@ -26,9 +25,7 @@ export function useConflictComposerPrefill(
): PrefillState {
const { conflicts } = useConflicts();
const conflictFile =
- docName === null
- ? undefined
- : conflicts.find((entry) => filePathToDocName(entry.file) === docName)?.file;
+ docName === null ? undefined : conflicts.find((entry) => entry.docName === docName)?.file;
const conflictFilesKey = conflicts
.map((entry) => entry.file)
diff --git a/packages/app/src/hooks/use-conflicts.dom.test.tsx b/packages/app/src/hooks/use-conflicts.dom.test.tsx
index 22a64ef6a..f2a8ab2c9 100644
--- a/packages/app/src/hooks/use-conflicts.dom.test.tsx
+++ b/packages/app/src/hooks/use-conflicts.dom.test.tsx
@@ -1,24 +1,35 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { useConflicts } from './use-conflicts';
+import { useEffect, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import {
+ ConflictsProvider,
+ ConflictsProviderMissingError,
+ useConflicts,
+ useDocConflict,
+} from './use-conflicts';
interface CapturedFetch {
url: string;
+ init?: RequestInit;
}
let fetchCalls: CapturedFetch[] = [];
-let fetchResponse: () => Response = () =>
+let fetchResponse: () => Response | Promise<Response> = () =>
new Response(JSON.stringify({ conflicts: [] }), { status: 200 });
function installFetchStub() {
fetchCalls = [];
- globalThis.fetch = (input: RequestInfo | URL) => {
+ globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input.toString();
- fetchCalls.push({ url });
+ fetchCalls.push({ url, init });
return Promise.resolve(fetchResponse());
};
}
+function conflictsFetchCount(): number {
+ return fetchCalls.filter((call) => call.url === '/api/sync/conflicts').length;
+}
+
function Probe() {
const { conflicts, loading, error } = useConflicts();
return (
@@ -31,13 +42,49 @@ function Probe() {
);
}
-describe('useConflicts', () => {
+let consumerRenders = 0;
+
+function RenderCountProbe() {
+ const { conflicts } = useConflicts();
+ consumerRenders += 1;
+ return <span data-testid="render-count-files">{conflicts.length}</span>;
+}
+
+function DocProbe({ docName, testId }: { docName: string | null; testId: string }) {
+ const entry = useDocConflict(docName);
+ return <span data-testid={testId}>{entry === null ? 'none' : entry.file}</span>;
+}
+
+function EntryEffectProbe({ docName, testId }: { docName: string; testId: string }) {
+ const entry = useDocConflict(docName);
+ const [effectRuns, setEffectRuns] = useState(0);
+ useEffect(() => {
+ if (entry === null) return;
+ setEffectRuns((runs) => runs + 1);
+ }, [entry]);
+ return <span data-testid={testId}>{effectRuns}</span>;
+}
+
+function signalSyncStatus() {
+ act(() => {
+ window.dispatchEvent(
+ new CustomEvent('open-knowledge:documents-changed', {
+ detail: { channels: ['sync-status'] },
+ }),
+ );
+ });
+}
+
+describe('ConflictsProvider', () => {
beforeEach(() => {
+ consumerRenders = 0;
installFetchStub();
});
afterEach(() => {
cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
});
test('fetches /api/sync/conflicts on mount and exposes results', async () => {
@@ -45,60 +92,146 @@ describe('useConflicts', () => {
new Response(
JSON.stringify({
conflicts: [
- { file: 'docs/a.md', detectedAt: '2026-05-20T10:00:00.000Z' },
- { file: 'docs/b.md', detectedAt: '2026-05-20T10:01:00.000Z' },
+ {
+ file: 'docs/a.md',
+ detectedAt: '2026-05-20T10:00:00.000Z',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ {
+ file: 'docs/b.md',
+ detectedAt: '2026-05-20T10:01:00.000Z',
+ conflict: 'merge-native',
+ docName: 'docs/b',
+ },
],
}),
{ status: 200 },
);
- render(<Probe />);
+ render(
+ <ConflictsProvider>
+ <Probe />
+ </ConflictsProvider>,
+ );
await waitFor(() => {
expect(screen.getByTestId('loading').textContent).toBe('no');
});
- expect(fetchCalls.some((c) => c.url === '/api/sync/conflicts')).toBe(true);
+ expect(conflictsFetchCount()).toBe(1);
expect(screen.getByTestId('count').textContent).toBe('2');
expect(screen.getByTestId('files').textContent).toBe('docs/a.md,docs/b.md');
expect(screen.getByTestId('error').textContent).toBe('none');
});
- test('re-fetches when a CC1 sync-status signal fires', async () => {
- let payload = { conflicts: [{ file: 'docs/a.md', detectedAt: 't0' }] };
+ test('bounds the conflicts request with an abort signal', async () => {
+ fetchResponse = () => new Response(JSON.stringify({ conflicts: [] }), { status: 200 });
+ const timeout = vi.spyOn(AbortSignal, 'timeout');
+
+ render(
+ <ConflictsProvider>
+ <Probe />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('loading').textContent).toBe('no');
+ });
+
+ const call = fetchCalls.find((entry) => entry.url === '/api/sync/conflicts');
+ expect(call).toBeDefined();
+ expect(call?.init?.signal).toBeInstanceOf(AbortSignal);
+ expect(call?.init?.signal?.aborted).toBe(false);
+ expect(timeout).toHaveBeenCalledWith(5_000);
+ });
+
+ test('many consumers share ONE fetch', async () => {
+ fetchResponse = () =>
+ new Response(
+ JSON.stringify({
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ }),
+ { status: 200 },
+ );
+
+ render(
+ <ConflictsProvider>
+ <Probe />
+ <DocProbe docName="docs/a" testId="one" />
+ <DocProbe docName="docs/a" testId="two" />
+ <DocProbe docName="docs/b" testId="three" />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('one').textContent).toBe('docs/a.md');
+ });
+ expect(conflictsFetchCount()).toBe(1);
+ expect(screen.getByTestId('two').textContent).toBe('docs/a.md');
+ expect(screen.getByTestId('three').textContent).toBe('none');
+ });
+
+ test('a sync-status signal causes exactly ONE refetch and flips useDocConflict', async () => {
+ let payload: { conflicts: Array<Record<string, unknown>> } = { conflicts: [] };
fetchResponse = () => new Response(JSON.stringify(payload), { status: 200 });
- render(<Probe />);
+ render(
+ <ConflictsProvider>
+ <DocProbe docName="docs/a" testId="a" />
+ <DocProbe docName="docs/b" testId="b" />
+ </ConflictsProvider>,
+ );
+
await waitFor(() => {
- expect(screen.getByTestId('count').textContent).toBe('1');
+ expect(conflictsFetchCount()).toBe(1);
});
+ expect(screen.getByTestId('a').textContent).toBe('none');
payload = {
conflicts: [
- { file: 'docs/a.md', detectedAt: 't0' },
- { file: 'docs/c.md', detectedAt: 't1' },
+ {
+ file: 'docs/a.md',
+ detectedAt: 't1',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
],
};
+ signalSyncStatus();
- act(() => {
- window.dispatchEvent(
- new CustomEvent('open-knowledge:documents-changed', {
- detail: { channels: ['sync-status'] },
- }),
- );
+ await waitFor(() => {
+ expect(screen.getByTestId('a').textContent).toBe('docs/a.md');
});
+ expect(conflictsFetchCount()).toBe(2);
+ expect(screen.getByTestId('b').textContent).toBe('none');
+
+ payload = { conflicts: [] };
+ signalSyncStatus();
await waitFor(() => {
- expect(screen.getByTestId('count').textContent).toBe('2');
+ expect(screen.getByTestId('a').textContent).toBe('none');
});
+ expect(conflictsFetchCount()).toBe(3);
});
test('does NOT re-fetch on non-sync-status channels', async () => {
fetchResponse = () => new Response(JSON.stringify({ conflicts: [] }), { status: 200 });
- render(<Probe />);
+ render(
+ <ConflictsProvider>
+ <Probe />
+ </ConflictsProvider>,
+ );
await waitFor(() => {
expect(screen.getByTestId('loading').textContent).toBe('no');
});
- const initialFetchCount = fetchCalls.length;
+ const initialFetchCount = conflictsFetchCount();
act(() => {
window.dispatchEvent(
@@ -109,23 +242,381 @@ describe('useConflicts', () => {
});
await new Promise((resolve) => setTimeout(resolve, 10));
- expect(fetchCalls.length).toBe(initialFetchCount);
+ expect(conflictsFetchCount()).toBe(initialFetchCount);
});
- test('classifies a server (HTTP non-2xx) failure as error: "server"', async () => {
+ test('two signals carrying an identical payload leave consumers un-re-rendered', async () => {
+ fetchResponse = () =>
+ new Response(
+ JSON.stringify({
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ }),
+ { status: 200 },
+ );
+
+ render(
+ <ConflictsProvider>
+ <RenderCountProbe />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('render-count-files').textContent).toBe('1');
+ });
+ const rendersAtFirstSnapshot = consumerRenders;
+
+ signalSyncStatus();
+ await waitFor(() => {
+ expect(conflictsFetchCount()).toBe(2);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ signalSyncStatus();
+ await waitFor(() => {
+ expect(conflictsFetchCount()).toBe(3);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ expect(consumerRenders).toBe(rendersAtFirstSnapshot);
+ expect(screen.getByTestId('render-count-files').textContent).toBe('1');
+ });
+
+ test('a changed payload does re-render consumers', async () => {
+ let payload: { conflicts: Array<Record<string, unknown>> } = {
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ };
+ fetchResponse = () => new Response(JSON.stringify(payload), { status: 200 });
+
+ render(
+ <ConflictsProvider>
+ <RenderCountProbe />
+ </ConflictsProvider>,
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId('render-count-files').textContent).toBe('1');
+ });
+ const rendersAtFirstSnapshot = consumerRenders;
+
+ payload = {
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't1',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ };
+ signalSyncStatus();
+
+ await waitFor(() => {
+ expect(consumerRenders).toBeGreaterThan(rendersAtFirstSnapshot);
+ });
+ });
+
+ test('an entry whose only change is an unlisted wire field is not reused', async () => {
+ let payload: { conflicts: Array<Record<string, unknown>> } = {
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ },
+ ],
+ };
+ fetchResponse = () => new Response(JSON.stringify(payload), { status: 200 });
+
+ render(
+ <ConflictsProvider>
+ <EntryEffectProbe docName="docs/a" testId="a-effects" />
+ </ConflictsProvider>,
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId('a-effects').textContent).toBe('1');
+ });
+
+ payload = {
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ resolutionOptions: ['mine', 'delete'],
+ },
+ ],
+ };
+ signalSyncStatus();
+
+ await waitFor(() => {
+ expect(screen.getByTestId('a-effects').textContent).toBe('2');
+ });
+ });
+
+ test('an unrelated conflict appearing leaves this entry identical to entry-keyed effects', async () => {
+ const docsA = {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ };
+ let payload: { conflicts: Array<Record<string, unknown>> } = { conflicts: [docsA] };
+ fetchResponse = () => new Response(JSON.stringify(payload), { status: 200 });
+
+ render(
+ <ConflictsProvider>
+ <EntryEffectProbe docName="docs/a" testId="a-effects" />
+ <DocProbe docName="docs/b" testId="b" />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('a-effects').textContent).toBe('1');
+ });
+
+ payload = {
+ conflicts: [
+ docsA,
+ {
+ file: 'docs/b.md',
+ detectedAt: 't1',
+ conflict: 'reconcile',
+ docName: 'docs/b',
+ },
+ ],
+ };
+ signalSyncStatus();
+
+ await waitFor(() => {
+ expect(screen.getByTestId('b').textContent).toBe('docs/b.md');
+ });
+ expect(screen.getByTestId('a-effects').textContent).toBe('1');
+ });
+
+ test('useDocConflict reads as no conflict until the first snapshot lands', async () => {
+ fetchResponse = () =>
+ new Response(
+ JSON.stringify({
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ }),
+ { status: 200 },
+ );
+
+ render(
+ <ConflictsProvider>
+ <DocProbe docName="docs/a" testId="a" />
+ <DocProbe docName="docs/b" testId="b" />
+ <DocProbe docName={null} testId="nothing-open" />
+ </ConflictsProvider>,
+ );
+
+ expect(screen.getByTestId('a').textContent).toBe('none');
+ expect(screen.getByTestId('b').textContent).toBe('none');
+ expect(screen.getByTestId('nothing-open').textContent).toBe('none');
+
+ await waitFor(() => {
+ expect(screen.getByTestId('a').textContent).toBe('docs/a.md');
+ });
+ expect(screen.getByTestId('b').textContent).toBe('none');
+ });
+
+ test('a failed first fetch reports the failure and still reads as no conflict', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ fetchResponse = () => new Response('internal', { status: 500 });
+
+ render(
+ <ConflictsProvider>
+ <Probe />
+ <DocProbe docName="docs/a" testId="a" />
+ </ConflictsProvider>,
+ );
+
+ expect(screen.getByTestId('a').textContent).toBe('none');
+ await waitFor(() => {
+ expect(screen.getByTestId('error').textContent).toBe('server');
+ });
+ expect(screen.getByTestId('loading').textContent).toBe('no');
+ expect(screen.getByTestId('a').textContent).toBe('none');
+ warn.mockRestore();
+ });
+
+ test('a failure after a good snapshot keeps the doc answers it already had', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ fetchResponse = () =>
+ new Response(
+ JSON.stringify({
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ }),
+ { status: 200 },
+ );
+
+ render(
+ <ConflictsProvider>
+ <Probe />
+ <DocProbe docName="docs/a" testId="a" />
+ <DocProbe docName="docs/b" testId="b" />
+ </ConflictsProvider>,
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId('a').textContent).toBe('docs/a.md');
+ });
+
fetchResponse = () => new Response('internal', { status: 500 });
- render(<Probe />);
+ signalSyncStatus();
+
+ await waitFor(() => {
+ expect(screen.getByTestId('error').textContent).toBe('server');
+ });
+ expect(screen.getByTestId('count').textContent).toBe('1');
+ expect(screen.getByTestId('a').textContent).toBe('docs/a.md');
+ expect(screen.getByTestId('b').textContent).toBe('none');
+ warn.mockRestore();
+ });
+
+ test('a 200 whose body fails the wire schema is treated as a server error, not as clear', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ fetchResponse = () =>
+ new Response(JSON.stringify({ conflicts: [{ nonsense: true }] }), { status: 200 });
+
+ render(
+ <ConflictsProvider>
+ <Probe />
+ <DocProbe docName="docs/a" testId="a" />
+ </ConflictsProvider>,
+ );
+
await waitFor(() => {
expect(screen.getByTestId('error').textContent).toBe('server');
});
- expect(screen.getByTestId('count').textContent).toBe('0');
+ expect(screen.getByTestId('a').textContent).toBe('none');
+ warn.mockRestore();
});
- test('classifies a thrown fetch (network) as error: "network"', async () => {
+ test('an unknown docName and a null docName both read as no conflict', async () => {
+ fetchResponse = () =>
+ new Response(
+ JSON.stringify({
+ conflicts: [
+ {
+ file: 'docs/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: 'docs/a',
+ },
+ ],
+ }),
+ { status: 200 },
+ );
+
+ render(
+ <ConflictsProvider>
+ <DocProbe docName="docs/a" testId="known" />
+ <DocProbe docName="docs/never-heard-of-it" testId="unknown" />
+ <DocProbe docName={null} testId="nullish" />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('known').textContent).toBe('docs/a.md');
+ });
+ expect(screen.getByTestId('unknown').textContent).toBe('none');
+ expect(screen.getByTestId('nullish').textContent).toBe('none');
+ });
+
+ test('an entry with a null docName is not indexed by doc name', async () => {
+ fetchResponse = () =>
+ new Response(
+ JSON.stringify({
+ conflicts: [
+ {
+ file: 'outside/a.md',
+ detectedAt: 't0',
+ conflict: 'merge-native',
+ docName: null,
+ },
+ ],
+ }),
+ { status: 200 },
+ );
+
+ render(
+ <ConflictsProvider>
+ <Probe />
+ <DocProbe docName="outside/a" testId="orphan" />
+ </ConflictsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('count').textContent).toBe('1');
+ });
+ expect(screen.getByTestId('orphan').textContent).toBe('none');
+ });
+
+ test('classifies a thrown fetch as error: "network"', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
globalThis.fetch = () => Promise.reject(new Error('boom'));
- render(<Probe />);
+ render(
+ <ConflictsProvider>
+ <Probe />
+ </ConflictsProvider>,
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId('error').textContent).toBe('network');
+ });
+ warn.mockRestore();
+ });
+
+ test('classifies a timed-out fetch as error: "network"', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const timedOut = new Error('The operation timed out.');
+ timedOut.name = 'TimeoutError';
+ globalThis.fetch = () => Promise.reject(timedOut);
+ render(
+ <ConflictsProvider>
+ <Probe />
+ </ConflictsProvider>,
+ );
await waitFor(() => {
expect(screen.getByTestId('error').textContent).toBe('network');
});
+ warn.mockRestore();
+ });
+
+ test('useDocConflict throws when rendered outside the provider', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(() => render(<DocProbe docName="docs/a" testId="loose" />)).toThrow(
+ ConflictsProviderMissingError,
+ );
+ error.mockRestore();
});
});
diff --git a/packages/app/src/hooks/use-conflicts.ts b/packages/app/src/hooks/use-conflicts.ts
deleted file mode 100644
index a2c33be6b..000000000
--- a/packages/app/src/hooks/use-conflicts.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import type { ConflictEntryWire } from '@inkeep/open-knowledge-core';
-import { useEffect, useRef, useState } from 'react';
-import { subscribeToDocumentsChanged } from '@/lib/documents-events';
-
-type ConflictsFetchError = 'network' | 'server';
-
-interface ConflictsFetchResult {
- conflicts: ConflictEntryWire[];
- error?: ConflictsFetchError;
-}
-
-async function fetchConflicts(): Promise<ConflictsFetchResult> {
- try {
- const res = await fetch('/api/sync/conflicts');
- if (!res.ok) {
- console.warn(
- JSON.stringify({
- event: 'conflicts-fetch-failed',
- status: res.status,
- }),
- );
- return { conflicts: [], error: 'server' };
- }
- const data = (await res.json()) as { conflicts?: ConflictEntryWire[] };
- return { conflicts: data.conflicts ?? [] };
- } catch (err) {
- console.warn(
- JSON.stringify({
- event: 'conflicts-fetch-failed',
- status: null,
- detail: err instanceof Error ? err.message : String(err),
- }),
- );
- return { conflicts: [], error: 'network' };
- }
-}
-
-export function useConflicts(): {
- conflicts: ConflictEntryWire[];
- loading: boolean;
- error: ConflictsFetchError | null;
-} {
- const [conflicts, setConflicts] = useState<ConflictEntryWire[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<ConflictsFetchError | null>(null);
- const latestRequestId = useRef(0);
-
- function refresh() {
- const requestId = ++latestRequestId.current;
- void fetchConflicts().then(({ conflicts: list, error: err }) => {
- if (requestId !== latestRequestId.current) return;
- if (err === undefined) setConflicts(list);
- setError(err ?? null);
- setLoading(false);
- });
- }
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is intentionally stable (defined in hook scope)
- useEffect(() => {
- refresh();
- }, []);
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is intentionally stable (defined in hook scope)
- useEffect(() => {
- return subscribeToDocumentsChanged((channels) => {
- if (channels.includes('sync-status')) {
- refresh();
- }
- });
- }, []);
-
- return { conflicts, loading, error };
-}
diff --git a/packages/app/src/hooks/use-conflicts.tsx b/packages/app/src/hooks/use-conflicts.tsx
new file mode 100644
index 000000000..cd0a5f027
--- /dev/null
+++ b/packages/app/src/hooks/use-conflicts.tsx
@@ -0,0 +1,191 @@
+import { type ConflictEntryWire, SyncConflictsSuccessSchema } from '@inkeep/open-knowledge-core';
+import { createContext, type ReactNode, use, useEffect, useRef, useState } from 'react';
+import { subscribeToDocumentsChanged } from '@/lib/documents-events';
+
+type ConflictsFetchError = 'network' | 'server';
+
+interface ConflictsFetchResult {
+ conflicts: ConflictEntryWire[];
+ error?: ConflictsFetchError;
+}
+
+interface ConflictsSnapshot {
+ conflicts: ConflictEntryWire[];
+ loading: boolean;
+ error: ConflictsFetchError | null;
+}
+
+interface ConflictsState extends ConflictsSnapshot {
+ byDocName: ReadonlyMap<string, ConflictEntryWire>;
+}
+
+interface ConflictsActions {
+ refresh: () => void;
+}
+
+type ConflictsContextValue = ConflictsState & ConflictsActions;
+type ConflictsResult = ConflictsSnapshot & ConflictsActions;
+
+export class ConflictsProviderMissingError extends Error {
+ constructor(hookName: string) {
+ super(`${hookName} must be rendered inside <ConflictsProvider />`);
+ this.name = 'ConflictsProviderMissingError';
+ }
+}
+
+const ConflictsContext = createContext<ConflictsContextValue | null>(null);
+
+const UNPROVIDED_CONFLICTS: ConflictsResult = {
+ conflicts: [],
+ loading: false,
+ error: null,
+ refresh: () => {},
+};
+
+const CONFLICTS_REQUEST_TIMEOUT_MS = 5_000;
+
+async function fetchConflicts(): Promise<ConflictsFetchResult> {
+ try {
+ const res = await fetch('/api/sync/conflicts', {
+ signal: AbortSignal.timeout(CONFLICTS_REQUEST_TIMEOUT_MS),
+ });
+ if (!res.ok) {
+ console.warn(
+ JSON.stringify({
+ event: 'conflicts-fetch-failed',
+ status: res.status,
+ }),
+ );
+ return { conflicts: [], error: 'server' };
+ }
+ const body = await res.json().catch(() => null);
+ const parsed = SyncConflictsSuccessSchema.safeParse(body);
+ if (!parsed.success) {
+ console.warn(
+ JSON.stringify({
+ event: 'conflicts-fetch-failed',
+ status: res.status,
+ detail: 'schema-drift',
+ }),
+ );
+ return { conflicts: [], error: 'server' };
+ }
+ return { conflicts: parsed.data.conflicts };
+ } catch (err) {
+ console.warn(
+ JSON.stringify({
+ event: 'conflicts-fetch-failed',
+ status: null,
+ errorName: err instanceof Error ? err.name : 'non-error-throw',
+ detail: err instanceof Error ? err.message : String(err),
+ }),
+ );
+ return { conflicts: [], error: 'network' };
+ }
+}
+
+function indexByDocName(
+ conflicts: readonly ConflictEntryWire[],
+): ReadonlyMap<string, ConflictEntryWire> {
+ const index = new Map<string, ConflictEntryWire>();
+ for (const entry of conflicts) {
+ if (typeof entry.docName === 'string' && entry.docName.length > 0) {
+ index.set(entry.docName, entry);
+ }
+ }
+ return index;
+}
+
+function entrySignature(entry: ConflictEntryWire): string {
+ const fields = entry as Record<string, unknown>;
+ return JSON.stringify(
+ Object.keys(fields)
+ .sort()
+ .map((key) => [key, fields[key]]),
+ );
+}
+
+function reuseUnchangedEntries(
+ previous: readonly ConflictEntryWire[],
+ next: readonly ConflictEntryWire[],
+): { entries: ConflictEntryWire[]; changed: boolean } {
+ const priorByFile = new Map<string, ConflictEntryWire>();
+ for (const entry of previous) priorByFile.set(entry.file, entry);
+
+ let changed = previous.length !== next.length;
+ const entries = next.map((entry, index) => {
+ const prior = priorByFile.get(entry.file);
+ const reused =
+ prior !== undefined && entrySignature(prior) === entrySignature(entry) ? prior : entry;
+ if (reused !== previous[index]) changed = true;
+ return reused;
+ });
+ return { entries, changed };
+}
+
+const INITIAL_VALUE: ConflictsState = {
+ conflicts: [],
+ loading: true,
+ error: null,
+ byDocName: new Map(),
+};
+
+function nextValue(
+ previous: ConflictsState,
+ conflicts: ConflictEntryWire[],
+ error: ConflictsFetchError | undefined,
+): ConflictsState {
+ if (error !== undefined) {
+ if (previous.error === error && !previous.loading) return previous;
+ return { ...previous, loading: false, error };
+ }
+ const { entries, changed } = reuseUnchangedEntries(previous.conflicts, conflicts);
+ if (!changed && !previous.loading && previous.error === null) return previous;
+ return {
+ conflicts: entries,
+ loading: false,
+ error: null,
+ byDocName: indexByDocName(entries),
+ };
+}
+
+export function ConflictsProvider({ children }: { children: ReactNode }) {
+ const [value, setValue] = useState<ConflictsState>(INITIAL_VALUE);
+ const latestRequestId = useRef(0);
+
+ function refresh() {
+ const requestId = ++latestRequestId.current;
+ void fetchConflicts().then(({ conflicts: list, error: err }) => {
+ if (requestId !== latestRequestId.current) return;
+ setValue((previous) => nextValue(previous, list, err));
+ });
+ }
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is intentionally stable (defined in hook scope)
+ useEffect(() => {
+ refresh();
+ return subscribeToDocumentsChanged((channels) => {
+ if (channels.includes('sync-status')) refresh();
+ });
+ }, []);
+
+ return <ConflictsContext value={{ ...value, refresh }}>{children}</ConflictsContext>;
+}
+
+export function useConflicts(): ConflictsResult {
+ const value = use(ConflictsContext);
+ if (value === null) return UNPROVIDED_CONFLICTS;
+ return {
+ conflicts: value.conflicts,
+ loading: value.loading,
+ error: value.error,
+ refresh: value.refresh,
+ };
+}
+
+export function useDocConflict(docName: string | null): ConflictEntryWire | null {
+ const value = use(ConflictsContext);
+ if (value === null) throw new ConflictsProviderMissingError('useDocConflict');
+ if (docName === null) return null;
+ return value.byDocName.get(docName) ?? null;
+}
diff --git a/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx b/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx
deleted file mode 100644
index 4ad18f131..000000000
--- a/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { act, cleanup, render, screen } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import * as Y from 'yjs';
-
-let mockPoolEntries: Array<{ docName: string; provider: { document: Y.Doc } }> = [];
-
-vi.doMock('@/editor/DocumentContext', () => ({
- useDocumentContext: () => ({
- poolEntries: mockPoolEntries,
- }),
-}));
-
-const { useLifecycleStatus } = await import('./use-lifecycle-status');
-
-function Probe({ docName }: { docName: string | null }) {
- const status = useLifecycleStatus(docName);
- return <span data-testid="status">{status === null ? 'null' : status}</span>;
-}
-
-describe('useLifecycleStatus', () => {
- beforeEach(() => {
- mockPoolEntries = [];
- });
-
- afterEach(() => {
- cleanup();
- });
-
- test('returns null when no pool entry exists for the docName', () => {
- render(<Probe docName="missing" />);
- expect(screen.getByTestId('status').textContent).toBe('null');
- });
-
- test("returns 'conflict' when the doc's lifecycle Y.Map carries status='conflict'", () => {
- const doc = new Y.Doc();
- doc.getMap('lifecycle').set('status', 'conflict');
- mockPoolEntries = [{ docName: 'doc-a', provider: { document: doc } }];
-
- render(<Probe docName="doc-a" />);
- expect(screen.getByTestId('status').textContent).toBe('conflict');
- });
-
- test('re-renders to null when status is deleted from the lifecycle Y.Map', () => {
- const doc = new Y.Doc();
- const lifecycle = doc.getMap('lifecycle');
- lifecycle.set('status', 'conflict');
- mockPoolEntries = [{ docName: 'doc-b', provider: { document: doc } }];
-
- render(<Probe docName="doc-b" />);
- expect(screen.getByTestId('status').textContent).toBe('conflict');
-
- act(() => {
- lifecycle.delete('status');
- });
-
- expect(screen.getByTestId('status').textContent).toBe('null');
- });
-
- test("re-renders to 'conflict' when status flips from unset → conflict", () => {
- const doc = new Y.Doc();
- const lifecycle = doc.getMap('lifecycle');
- mockPoolEntries = [{ docName: 'doc-c', provider: { document: doc } }];
-
- render(<Probe docName="doc-c" />);
- expect(screen.getByTestId('status').textContent).toBe('null');
-
- act(() => {
- lifecycle.set('status', 'conflict');
- });
-
- expect(screen.getByTestId('status').textContent).toBe('conflict');
- });
-});
diff --git a/packages/app/src/hooks/use-lifecycle-status.ts b/packages/app/src/hooks/use-lifecycle-status.ts
deleted file mode 100644
index 2d23ec9f9..000000000
--- a/packages/app/src/hooks/use-lifecycle-status.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { HocuspocusProvider } from '@hocuspocus/provider';
-import { useEffect, useState } from 'react';
-import { useDocumentContext } from '@/editor/DocumentContext';
-
-type LifecycleStatus = 'conflict' | null;
-
-function readStatus(provider: HocuspocusProvider | null): LifecycleStatus {
- if (!provider) return null;
- const raw = provider.document.getMap('lifecycle').get('status');
- return raw === 'conflict' ? 'conflict' : null;
-}
-
-export function useLifecycleStatus(docName: string | null): LifecycleStatus {
- const { poolEntries } = useDocumentContext();
- const entry = docName ? (poolEntries.find((e) => e.docName === docName) ?? null) : null;
- const provider = entry?.provider ?? null;
- const [status, setStatus] = useState<LifecycleStatus>(() => readStatus(provider));
-
- useEffect(() => {
- if (!provider) {
- setStatus(null);
- return;
- }
- const lifecycleMap = provider.document.getMap('lifecycle');
- setStatus(readStatus(provider));
- const onChange = () => setStatus(readStatus(provider));
- lifecycleMap.observe(onChange);
- return () => {
- lifecycleMap.unobserve(onChange);
- };
- }, [provider]);
-
- return status;
-}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index feeea42f9..ff976399d 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -121,6 +121,11 @@
") في ",
["targetLabel"]
],
+ "0bV3uj": [
+ "ربما يكون شخص ما قد حلّ التعارض في ",
+ ["filePath"],
+ " بالفعل — تحقّق من المحتوى الحالي للمستند قبل إعادة تنفيذ تعديلك."
+ ],
"0cGsQh": ["ما الذي يتم تضمينه"],
"0cspe_": ["حذف الصف"],
"0dslv8": [
@@ -412,6 +417,7 @@
"3aeN7X": ["كل الملفات"],
"3cOo2C": ["أنشئ مجلدًا من سياق المستند أو المجلد الحالي."],
"3ePd3I": ["ما الجديد"],
+ "3fOsvq": ["استخدام نسختهم"],
"3h5zMp": ["حدث خطأ ما أثناء تحميل لوحة الإعدادات."],
"3iyGWF": ["فتح مشروع حديث"],
"3jod3l": ["ربط GitHub"],
@@ -2642,6 +2648,7 @@
"RB_g_C": [
"في الفهرس الجذري، تتم كتابة okf_version كسلسلة مقتبسة مثل \"0.2\". بدون اقتباس، يقرأه YAML كرقم ويصبح 0.10 بصمت 0.1."
],
+ "RCMt3v": ["لا يتم تتبّع أي تعارض لهذا المسار."],
"RD6H9q": [
"يقوم Open Knowledge بإعادة كتابة ملفات index.md هذه مع تغير المستندات، لذلك يتم استبدال التعديلات اليدوية عليها."
],
@@ -2697,6 +2704,7 @@
"Rah7yq": ["ما الذي ينبغي أن يفعله الذكاء الاصطناعي؟ (اختياري)"],
"Rb1zMa": ["لا يوجد مقتطف"],
"RcrskJ": ["بدا التنسيق خاطئًا"],
+ "RduDYw": ["تعذّر دمج <0>", ["filePath"], "</0> هنا. اختر النسخة التي تريد الاحتفاظ بها."],
"RfHNf8": ["فتح لوحة النشاط لـ ", ["tooltipName"]],
"RfaEio": ["تبديل تعليق المصدر"],
"RfilGt": ["لا توجد قواعد تطابق مرشحاتك."],
@@ -2780,6 +2788,7 @@
"SXCSQd": ["تم نسخ المسار"],
"SXEdCq": ["هل تنقله إلى ", ["0"], "؟"],
"SYfHmN": ["إلغاء تثبيت التبويب"],
+ "S_RRZB": ["حذف الملف"],
"Sad2tK": ["جارٍ الإرسال…"],
"Sbb90e": [
[
@@ -3321,7 +3330,6 @@
"XwZiq2": [
"تمت استعادة الملف إلى إصدار أقدم. الحالي هو الإصدار الذي حماه OpenKnowledge. الوارد هو الإصدار المستعاد. اختر الإصدار الذي تريد الاحتفاظ به، ثم طبّق تغييراتك."
],
- "XzL7x7": ["أعد فتح ", ["filePath"], " لمواصلة التحرير."],
"Xzy0s0": ["إزالة ", ["fullLabel"], " من السياق"],
"Y-Urt2": ["معادلة رياضية بكتلة مستقلة تُعرض بواسطة KaTeX من نص مصدري بصيغة LaTeX."],
"Y1QMlM": ["ابدأ الإعداد"],
@@ -4386,7 +4394,6 @@
"احتفظ بسجل مكتوب لكيفية بناء منتجك. موطن لاقتراح الأفكار وتدوين القرارات وكتابة المواصفات وتسجيل ما تعلمته بعد أي عطل."
],
"hCattk": ["استورد OpenKnowledge ", ["source"]],
- "hCghAK": ["تم حل هذا التعارض."],
"hDEaQu": ["اربط OpenKnowledge بالأدوات الأخرى التي تستخدمها."],
"hDKtoF": ["قبل ", ["diffHrs"], " ساعة"],
"hDoLrm": ["إزالة ", ["projectName"], " من المشاريع الحديثة"],
@@ -4602,7 +4609,6 @@
"jSg1tA": ["مزيد من الإجراءات (", ["syncAttentionLabel"], ")"],
"jTLWxh": ["ضمّن صفحة خارجية في إطار مضمَّن (مستندات، عروض، Figma، CodeSandbox)."],
"jTUxaN": ["تفعيل تلقائي (سحب فقط)"],
- "jTdrn1": ["تعذر التحقق مما إذا كان ", ["filePath"], " لا يزال متعارضًا — تجري إعادة المحاولة."],
"jWwQo6": ["دفعة"],
"jWzDfC": ["جارٍ التحقق من أدوات الذكاء الاصطناعي المتوفّرة لديك"],
"jZ_E5M": ["فشل الجلب — راجع سجلات الخادم للتفاصيل."],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index d7c9f89db..a1ba9a055 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> ليس مكوّنًا معروفًا. انسخ الم
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "تعذّر عرض <{descriptorLabel}> (على الأرجح خاصية غير صالحة). انسخ المصدر لمعرفة الخطأ، أو احذف الكتلة."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "تعذّر دمج <0>{filePath}</0> هنا. اختر النسخة التي تريد الاحتفاظ بها."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>مرآة — اختر مصدرًا.</0> اضبط <1>src</1> + <2>anchor</2> من لوحة الخصائص للإشارة إلى <3><MirrorSource></3> في مكان آخر."
@@ -3908,10 +3912,6 @@ msgstr "تعذّر تغيير التدقيق الإملائي. حاول مرة
msgid "Couldn't change the spelling languages. Try again."
msgstr "تعذّر تغيير لغات التدقيق الإملائي. حاول مرة أخرى."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "تعذر التحقق مما إذا كان {filePath} لا يزال متعارضًا — تجري إعادة المحاولة."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "حذف الجدول المحدد"
msgid "Delete table"
msgstr "حذف الجدول"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "حذف الملف"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "هل تريد حذف هذه المحادثة؟"
@@ -9021,6 +9025,10 @@ msgstr "لا توجد تعليقات بعد. حدد نصًا في المستند
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "لا يوجد سلف مشترك — أضاف كلا الفرعين هذا الملف (تعارض إضافة/إضافة)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "لا يتم تتبّع أي تعارض لهذا المسار."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "لا تغييرات في المحتوى في هذه النسخة."
@@ -11475,10 +11483,6 @@ msgstr "معروض"
msgid "Reopen"
msgstr "إعادة فتح"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "أعد فتح {filePath} لمواصلة التحرير."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "إعادة فتح محادثة سابقة"
@@ -13109,6 +13113,10 @@ msgstr "لا تظهر بعض السمات المحفوظة لأن مجلد ال
msgid "Some skills were deleted with a warning"
msgstr "تم حذف بعض المهارات مع تحذير"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "ربما يكون شخص ما قد حلّ التعارض في {filePath} بالفعل — تحقّق من المحتوى الحالي للمستند قبل إعادة تنفيذ تعديلك."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "حدث عطل"
@@ -14389,10 +14397,6 @@ msgstr "هذا التعليق على الخاصية بأكملها"
msgid "This composer doesn't accept attachments."
msgstr "لا يمكن إرفاق الملفات هنا."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "تم حل هذا التعارض."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "تعذّر إعداد هذا لأن إدخال خادم MCP الذي يحتاجه لم تتم كتابته."
@@ -15492,6 +15496,10 @@ msgstr "استخدم الحروف الصغيرة والأرقام و<0>-</0> ف
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "استخدم الحروف الصغيرة والأرقام والشرطات فقط"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "استخدام نسختهم"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "استخدم حزمة البداية هذه"
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index ba9ae8bdb..d21fecc33 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -97,6 +97,11 @@
["fileName"],
") থেকে নতুন ফাইল"
],
+ "0bV3uj": [
+ "হয়তো কেউ ইতিমধ্যেই ",
+ ["filePath"],
+ "-এর দ্বন্দ্ব সমাধান করে ফেলেছেন — আপনার সম্পাদনা আবার করার আগে নথির বর্তমান বিষয়বস্তু দেখে নিন।"
+ ],
"0cGsQh": ["যা অন্তর্ভুক্ত থাকে"],
"0cspe_": ["সারি মুছুন"],
"0dslv8": [
@@ -339,6 +344,7 @@
"3aeN7X": ["সব ফাইল"],
"3cOo2C": ["বর্তমান নথি বা ফোল্ডারের প্রসঙ্গ থেকে একটি ফোল্ডার তৈরি করুন।"],
"3ePd3I": ["নতুন কী আছে"],
+ "3fOsvq": ["তাদের সংস্করণ ব্যবহার করুন"],
"3h5zMp": ["সেটিং প্যানেল লোড করার সময় কিছু একটা ভুল হয়েছে।"],
"3iyGWF": ["সাম্প্রতিক প্রকল্প খুলুন"],
"3jod3l": ["GitHub যুক্ত করুন"],
@@ -2240,6 +2246,7 @@
"RB_g_C": [
"রুট ইনডেক্সে, okf_version একটি উদ্ধৃত স্ট্রিং হিসাবে লেখা হয় যেমন \"0.2\"। উদ্ধৃতিহীন, YAML এটিকে একটি সংখ্যা হিসাবে পড়ে এবং 0.10 নিঃশব্দে 0.1 হয়ে যায়।"
],
+ "RCMt3v": ["এই পাথের জন্য কোনো দ্বন্দ্ব ট্র্যাক করা হচ্ছে না।"],
"RD6H9q": [
"Open Knowledge এই index.md ফাইলগুলিকে দস্তাবেজগুলি পরিবর্তন করার সাথে সাথে পুনঃলিখন করে, তাই তাদের ম্যানুয়াল সম্পাদনাগুলি প্রতিস্থাপিত হয়৷"
],
@@ -2293,6 +2300,7 @@
"Rah7yq": ["AI-এর কী করা উচিত? (ঐচ্ছিক)"],
"Rb1zMa": ["কোনো উদ্ধৃতাংশ নেই"],
"RcrskJ": ["বিন্যাস ভুল মনে হয়েছে"],
+ "RduDYw": ["<0>", ["filePath"], "</0> এখানে মার্জ করা যাবে না। কোন সংস্করণটি রাখবেন বেছে নিন।"],
"RfHNf8": [["tooltipName"], "-এর জন্য কার্যকলাপ প্যানেল খুলুন"],
"RfaEio": ["সোর্স মন্তব্য চালু বা বন্ধ করুন"],
"RfilGt": ["আপনার ছাঁকনির সঙ্গে কোনো নিয়ম মেলে না।"],
@@ -2369,6 +2377,7 @@
"SXCSQd": ["পথ কপি হয়েছে"],
"SXEdCq": [["0"], "-এ সরাবেন?"],
"SYfHmN": ["ট্যাব আনপিন করুন"],
+ "S_RRZB": ["ফাইলটি মুছে ফেলুন"],
"Sad2tK": ["পাঠানো হচ্ছে…"],
"Sbb90e": [
[
@@ -2788,7 +2797,6 @@
"XwZiq2": [
"ফাইলটি একটি পুরোনো সংস্করণে ফিরিয়ে আনা হয়েছে। বর্তমানটি হলো OpenKnowledge যে সংস্করণটি সুরক্ষিত রেখেছে। আগতটি হলো ফিরিয়ে আনা সংস্করণ। কোন সংস্করণটি রাখবেন তা বেছে নিন, তারপর আপনার পরিবর্তনগুলি প্রয়োগ করুন।"
],
- "XzL7x7": ["সম্পাদনা চালিয়ে যেতে ", ["filePath"], " আবার খুলুন।"],
"Xzy0s0": [["fullLabel"], " প্রসঙ্গ থেকে সরান"],
"Y-Urt2": ["একটি LaTeX সোর্স স্ট্রিং থেকে KaTeX দিয়ে রেন্ডার করা ব্লক গাণিতিক সমীকরণ।"],
"Y1QMlM": ["সেট আপ করুন"],
@@ -3684,7 +3692,6 @@
"আপনার পণ্য কীভাবে তৈরি হয় তার লিখিত হিসাব রাখুন। ধারণা প্রস্তাব করা, সিদ্ধান্ত নথিভুক্ত করা, স্পেক লেখা এবং কিছু ভেঙে যাওয়ার পর যা শিখলেন তা ধরে রাখার একটি ঘর।"
],
"hCattk": ["OpenKnowledge ", ["source"], " আমদানি করেছে"],
- "hCghAK": ["এই দ্বন্দ্বটি সমাধান হয়েছে।"],
"hDEaQu": ["OpenKnowledge-কে আপনার ব্যবহৃত অন্য টুলের সঙ্গে যুক্ত করুন।"],
"hDKtoF": [["diffHrs"], " ঘণ্টা আগে"],
"hDoLrm": [["projectName"], " সাম্প্রতিক প্রকল্প থেকে সরান"],
@@ -3899,7 +3906,6 @@
"jSg1tA": ["আরও ক্রিয়া (", ["syncAttentionLabel"], ")"],
"jTLWxh": ["একটি বাইরের পাতা ইনলাইন iframe-এ এমবেড করুন (নথি, ডেমো, Figma, CodeSandbox)।"],
"jTUxaN": ["স্বয়ংক্রিয় (শুধু টানুন) চালু করুন"],
- "jTdrn1": [["filePath"], "-এ এখনও কনফ্লিক্ট আছে কি না যাচাই করা যায়নি — আবার চেষ্টা করা হচ্ছে।"],
"jWwQo6": ["ব্যাচ"],
"jWzDfC": ["আপনার কোন AI টুল আছে তা যাচাই করা হচ্ছে"],
"jZ_E5M": ["আনা ব্যর্থ — বিস্তারিত জানতে সার্ভার লগ দেখুন।"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index 056efb99e..32c1f8247 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -1215,6 +1215,10 @@ msgstr "<{componentName}> একটি পরিচিত কম্পোনে
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> রেন্ডার করা যায়নি (সম্ভবত একটি ভুল প্রপ)। কী ভুল হয়েছে দেখতে সোর্স কপি করুন, নয়তো ব্লকটি মুছে দিন।"
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> এখানে মার্জ করা যাবে না। কোন সংস্করণটি রাখবেন বেছে নিন।"
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>মিরর — একটি উৎস বাছুন।</0> অন্য কোথাও থাকা কোনো <3><MirrorSource></3>-এর দিকে নির্দেশ করতে প্রপার্টি প্যানেল থেকে <1>src</1> + <2>anchor</2> নির্ধারণ করুন।"
@@ -3904,10 +3908,6 @@ msgstr "বানান পরীক্ষা পরিবর্তন করা
msgid "Couldn't change the spelling languages. Try again."
msgstr "বানান পরীক্ষার ভাষা পরিবর্তন করা যায়নি। আবার চেষ্টা করুন।"
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "{filePath}-এ এখনও কনফ্লিক্ট আছে কি না যাচাই করা যায়নি — আবার চেষ্টা করা হচ্ছে।"
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4785,6 +4785,10 @@ msgstr "নির্বাচিত টেবিল মুছুন"
msgid "Delete table"
msgstr "টেবিল মুছুন"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "ফাইলটি মুছে ফেলুন"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "এই চ্যাট মুছবেন?"
@@ -9017,6 +9021,10 @@ msgstr "এখনও কোনো মন্তব্য নেই। একট
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "কোনও সাধারণ পূর্বসূরি নেই — উভয় ব্রাঞ্চ এই ফাইলটি যোগ করেছে (add/add দ্বন্দ্ব)।"
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "এই পাথের জন্য কোনো দ্বন্দ্ব ট্র্যাক করা হচ্ছে না।"
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "এই সংস্করণে বিষয়বস্তুর কোনো পরিবর্তন নেই।"
@@ -11471,10 +11479,6 @@ msgstr "রেন্ডার করা"
msgid "Reopen"
msgstr "আবার খুলুন"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "সম্পাদনা চালিয়ে যেতে {filePath} আবার খুলুন।"
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "আগের চ্যাট আবার খুলুন"
@@ -13105,6 +13109,10 @@ msgstr "থিম ফোল্ডারটি স্ক্যানের সী
msgid "Some skills were deleted with a warning"
msgstr "কিছু স্কিল সতর্কবার্তাসহ মুছে ফেলা হয়েছে"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "হয়তো কেউ ইতিমধ্যেই {filePath}-এর দ্বন্দ্ব সমাধান করে ফেলেছেন — আপনার সম্পাদনা আবার করার আগে নথির বর্তমান বিষয়বস্তু দেখে নিন।"
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "কিছু ভেঙে গেছে"
@@ -14385,10 +14393,6 @@ msgstr "এই মন্তব্যটি পুরো প্রপার্ট
msgid "This composer doesn't accept attachments."
msgstr "এখানে ফাইল যুক্ত করা যায় না।"
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "এই দ্বন্দ্বটি সমাধান হয়েছে।"
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "এটি সেট আপ করা যায়নি কারণ এর প্রয়োজনীয় MCP সার্ভার এন্ট্রি লেখা হয়নি।"
@@ -15488,6 +15492,10 @@ msgstr "কেবল ছোট হাতের অক্ষর, অঙ্ক ও
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "কেবল ছোট হাতের অক্ষর, সংখ্যা ও হাইফেন ব্যবহার করুন"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "তাদের সংস্করণ ব্যবহার করুন"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "এই স্টার্টার প্যাক ব্যবহার করুন"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index d52309c28..932167b3a 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -101,6 +101,11 @@
") in ",
["targetLabel"]
],
+ "0bV3uj": [
+ "Someone may have already resolved ",
+ ["filePath"],
+ " — check the document's current content before redoing your edit."
+ ],
"0cGsQh": ["What's included"],
"0cspe_": ["Delete row"],
"0dslv8": [
@@ -345,6 +350,7 @@
"3aeN7X": ["All files"],
"3cOo2C": ["Create a folder from the current document or folder context."],
"3ePd3I": ["What's new"],
+ "3fOsvq": ["Use their version"],
"3h5zMp": ["Something went wrong loading the settings panel."],
"3iyGWF": ["Open recent project"],
"3jod3l": ["Connect GitHub"],
@@ -2309,6 +2315,7 @@
"RB_g_C": [
"On the root index, okf_version is written as a quoted string like \"0.2\". Unquoted, YAML reads it as a number and 0.10 silently becomes 0.1."
],
+ "RCMt3v": ["No conflict is tracked for this path."],
"RD6H9q": [
"Open Knowledge rewrites these index.md files as documents change, so manual edits to them are replaced."
],
@@ -2364,6 +2371,7 @@
"Rah7yq": ["What should the AI do? (optional)"],
"Rb1zMa": ["No excerpt"],
"RcrskJ": ["Formatting looked wrong"],
+ "RduDYw": ["<0>", ["filePath"], "</0> can't be merged here. Pick the version to keep."],
"RfHNf8": ["Open activity panel for ", ["tooltipName"]],
"RfaEio": ["Toggle source comment"],
"RfilGt": ["No rules match your filters."],
@@ -2437,6 +2445,7 @@
"SXCSQd": ["Copied path"],
"SXEdCq": ["Move to ", ["0"], "?"],
"SYfHmN": ["Unpin tab"],
+ "S_RRZB": ["Delete the file"],
"Sad2tK": ["Sending…"],
"Sbb90e": [
[
@@ -2862,7 +2871,6 @@
"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."],
"Y1QMlM": ["Get set up"],
@@ -3806,7 +3814,6 @@
"Keep a written record of how your product gets built. A home for proposing ideas, recording decisions, writing specs, and capturing what you learned after something broke."
],
"hCattk": ["OpenKnowledge imported ", ["source"]],
- "hCghAK": ["This conflict is resolved."],
"hDEaQu": ["Connect OpenKnowledge to other tools you use."],
"hDKtoF": [["diffHrs"], "h ago"],
"hDoLrm": ["Remove ", ["projectName"], " from recent projects"],
@@ -4023,7 +4030,6 @@
"jSg1tA": ["More actions (", ["syncAttentionLabel"], ")"],
"jTLWxh": ["Embed an external page in an inline iframe (docs, demos, Figma, CodeSandbox)."],
"jTUxaN": ["Enable Auto (Pull only)"],
- "jTdrn1": ["Couldn't check whether ", ["filePath"], " is still conflicted — retrying."],
"jWwQo6": ["batch"],
"jWzDfC": ["Checking which AI tools you have"],
"jZ_E5M": ["Fetch failed — check the server logs for details."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 669ca163c..912f3144f 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> isn't a known component. Copy the source to use it els
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
@@ -3908,10 +3912,6 @@ msgstr "Couldn't change spell checking. Try again."
msgid "Couldn't change the spelling languages. Try again."
msgstr "Couldn't change the spelling languages. Try again."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "Couldn't check whether {filePath} is still conflicted — retrying."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "Delete selected table"
msgid "Delete table"
msgstr "Delete table"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "Delete the file"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "Delete this chat?"
@@ -9021,6 +9025,10 @@ msgstr "No comments yet. Select text in the document to add one."
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "No common ancestor — both branches added this file (add/add conflict)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "No conflict is tracked for this path."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "No content changes at this version."
@@ -11475,10 +11483,6 @@ msgstr "Rendered"
msgid "Reopen"
msgstr "Reopen"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "Reopen {filePath} to keep editing."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "Reopen a past chat"
@@ -13109,6 +13113,10 @@ msgstr "Some saved themes aren’t shown because the theme folder exceeds the sc
msgid "Some skills were deleted with a warning"
msgstr "Some skills were deleted with a warning"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "Something broke"
@@ -14389,10 +14397,6 @@ msgstr "This comment is on the whole property"
msgid "This composer doesn't accept attachments."
msgstr "This composer doesn't accept attachments."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "This conflict is resolved."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "This could not be set up because the MCP server entry it needs was not written."
@@ -15492,6 +15496,10 @@ msgstr "Use lowercase letters, digits, and <0>-</0> only."
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "Use lowercase letters, numbers, and hyphens only"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "Use their version"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "Use this starter pack"
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index 0c1e1326e..ffeae3658 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -117,6 +117,11 @@
") en ",
["targetLabel"]
],
+ "0bV3uj": [
+ "Puede que alguien ya haya resuelto ",
+ ["filePath"],
+ " — revisa el contenido actual del documento antes de rehacer tu edición."
+ ],
"0cGsQh": ["Qué se incluye"],
"0cspe_": ["Eliminar fila"],
"0dslv8": [
@@ -398,6 +403,7 @@
"3aeN7X": ["Todos los archivos"],
"3cOo2C": ["Crea una carpeta a partir del documento o la carpeta actuales."],
"3ePd3I": ["Novedades"],
+ "3fOsvq": ["Usar su versión"],
"3h5zMp": ["Algo salió mal al cargar el panel de ajustes."],
"3iyGWF": ["Abrir un proyecto reciente"],
"3jod3l": ["Conectar GitHub"],
@@ -2661,6 +2667,7 @@
"RB_g_C": [
"En el índice raíz, okf_version se escribe como una cadena entrecomillada como \"0.2\". Sin comillas, YAML lo lee como un número y 0.10 silenciosamente se convierte en 0.1."
],
+ "RCMt3v": ["No se está siguiendo ningún conflicto para esta ruta."],
"RD6H9q": [
"Open Knowledge reescribe estos archivos index.md a medida que cambian los documentos, por lo que se reemplazan las ediciones manuales."
],
@@ -2716,6 +2723,11 @@
"Rah7yq": ["¿Qué debería hacer la IA? (opcional)"],
"Rb1zMa": ["Sin extracto"],
"RcrskJ": ["El formato se veía mal"],
+ "RduDYw": [
+ "<0>",
+ ["filePath"],
+ "</0> no se puede combinar aquí. Elige la versión que quieres conservar."
+ ],
"RfHNf8": ["Abrir el panel de actividad de ", ["tooltipName"]],
"RfaEio": ["Comentar o descomentar en el código"],
"RfilGt": ["Ninguna regla coincide con tus filtros."],
@@ -2796,6 +2808,7 @@
"SXCSQd": ["Ruta copiada"],
"SXEdCq": ["¿Mover a ", ["0"], "?"],
"SYfHmN": ["Dejar de fijar la pestaña"],
+ "S_RRZB": ["Eliminar el archivo"],
"Sad2tK": ["Enviando…"],
"Sbb90e": [
[
@@ -3337,7 +3350,6 @@
"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."],
"Y1QMlM": ["Ponte en marcha"],
@@ -4439,7 +4451,6 @@
"Deja constancia escrita de cómo se construye tu producto. Un sitio para proponer ideas, registrar decisiones, escribir especificaciones y anotar lo aprendido cuando algo falla."
],
"hCattk": ["OpenKnowledge importó ", ["source"]],
- "hCghAK": ["Este conflicto está resuelto."],
"hDEaQu": ["Conecta OpenKnowledge con las demás herramientas que usas."],
"hDKtoF": ["hace ", ["diffHrs"], " h"],
"hDoLrm": ["Quitar ", ["projectName"], " de los proyectos recientes"],
@@ -4676,7 +4687,6 @@
"Incrusta una página externa en un iframe en línea (documentación, demos, Figma, CodeSandbox)."
],
"jTUxaN": ["Activar Automático (solo Pull)"],
- "jTdrn1": ["No se pudo comprobar si ", ["filePath"], " sigue en conflicto: reintentando."],
"jWwQo6": ["lote"],
"jWzDfC": ["Comprobando qué herramientas de IA tienes"],
"jZ_E5M": ["Falló el fetch: consulta los registros del servidor para ver los detalles."],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 2a53007c1..12c3e2467 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> no es un componente conocido. Copia el código para us
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "No se pudo renderizar <{descriptorLabel}> (probablemente por una propiedad incorrecta). Copia el código para ver qué falló o elimina el bloque."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> no se puede combinar aquí. Elige la versión que quieres conservar."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>Espejo: elige una fuente.</0> Define <1>src</1> + <2>anchor</2> desde el panel de propiedades para apuntar a un <3><MirrorSource></3> de otro sitio."
@@ -3908,10 +3912,6 @@ msgstr "No se pudo cambiar la corrección ortográfica. Inténtalo de nuevo."
msgid "Couldn't change the spelling languages. Try again."
msgstr "No se pudieron cambiar los idiomas de la corrección ortográfica. Inténtalo de nuevo."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "No se pudo comprobar si {filePath} sigue en conflicto: reintentando."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "Eliminar la tabla seleccionada"
msgid "Delete table"
msgstr "Eliminar tabla"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "Eliminar el archivo"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "¿Eliminar este chat?"
@@ -9021,6 +9025,10 @@ msgstr "Todavía no hay comentarios. Selecciona texto en el documento para añad
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "Sin ancestro común: ambas ramas añadieron este archivo (conflicto add/add)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "No se está siguiendo ningún conflicto para esta ruta."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "No hay cambios de contenido en esta versión."
@@ -11475,10 +11483,6 @@ msgstr "Renderizado"
msgid "Reopen"
msgstr "Reabrir"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "Vuelve a abrir {filePath} para seguir editando."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "Reabrir un chat anterior"
@@ -13109,6 +13113,10 @@ msgstr "Algunos temas guardados no se muestran porque la carpeta de temas supera
msgid "Some skills were deleted with a warning"
msgstr "Algunas habilidades se eliminaron con una advertencia"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "Puede que alguien ya haya resuelto {filePath} — revisa el contenido actual del documento antes de rehacer tu edición."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "Algo se rompió"
@@ -14389,10 +14397,6 @@ msgstr "Este comentario es sobre toda la propiedad"
msgid "This composer doesn't accept attachments."
msgstr "Aquí no se pueden adjuntar archivos."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "Este conflicto está resuelto."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "No se pudo configurar porque la entrada del servidor MCP que necesita no se escribió."
@@ -15492,6 +15496,10 @@ msgstr "Usa solo letras minúsculas, dígitos y <0>-</0>."
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "Usa solo letras minúsculas, números y guiones"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "Usar su versión"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "Usar este paquete inicial"
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index c01182b84..bef47cf1d 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -119,6 +119,11 @@
") dans ",
["targetLabel"]
],
+ "0bV3uj": [
+ "Quelqu'un a peut-être déjà résolu ",
+ ["filePath"],
+ " — vérifiez le contenu actuel du document avant de refaire votre modification."
+ ],
"0cGsQh": ["Éléments inclus"],
"0cspe_": ["Supprimer la ligne"],
"0dslv8": [
@@ -410,6 +415,7 @@
"3aeN7X": ["Tous les fichiers"],
"3cOo2C": ["Crée un dossier à partir du document ou du dossier courant."],
"3ePd3I": ["Nouveautés"],
+ "3fOsvq": ["Utiliser leur version"],
"3h5zMp": ["Une erreur s'est produite lors du chargement du panneau des paramètres."],
"3iyGWF": ["Ouvrir un projet récent"],
"3jod3l": ["Connecter GitHub"],
@@ -2704,6 +2710,7 @@
"RB_g_C": [
"Sur l'index racine, okf_version est écrit sous forme de chaîne entre guillemets comme \"0.2\". Non cité, YAML le lit comme un nombre et 0.10 devient silencieusement 0.1."
],
+ "RCMt3v": ["Aucun conflit n’est suivi pour ce chemin."],
"RD6H9q": [
"Open Knowledge réécrit ces fichiers index.md à mesure que les documents changent, de sorte que les modifications manuelles apportées à ceux-ci sont remplacées."
],
@@ -2759,6 +2766,11 @@
"Rah7yq": ["Que doit faire l'IA ? (facultatif)"],
"Rb1zMa": ["Pas d'extrait"],
"RcrskJ": ["La mise en forme semblait incorrecte"],
+ "RduDYw": [
+ "<0>",
+ ["filePath"],
+ "</0> ne peut pas être fusionné ici. Choisissez la version à garder."
+ ],
"RfHNf8": ["Ouvrir le panneau d'activité de ", ["tooltipName"]],
"RfaEio": ["Basculer le commentaire de source"],
"RfilGt": ["Aucune règle ne correspond à vos filtres."],
@@ -2839,6 +2851,7 @@
"SXCSQd": ["Chemin copié"],
"SXEdCq": ["Déplacer vers ", ["0"], " ?"],
"SYfHmN": ["Détacher l'onglet"],
+ "S_RRZB": ["Supprimer le fichier"],
"Sad2tK": ["Envoi…"],
"Sbb90e": [
[
@@ -3378,7 +3391,6 @@
"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."],
"Y1QMlM": ["Configurer"],
@@ -4474,7 +4486,6 @@
"Gardez une trace écrite de la façon dont votre produit se construit. Un espace pour proposer des idées, consigner des décisions, rédiger des spécifications et noter ce que vous avez appris après un incident."
],
"hCattk": ["OpenKnowledge a importé ", ["source"]],
- "hCghAK": ["Ce conflit est résolu."],
"hDEaQu": ["Connectez OpenKnowledge aux autres outils que vous utilisez."],
"hDKtoF": ["il y a ", ["diffHrs"], " h"],
"hDoLrm": ["Retirer ", ["projectName"], " des projets récents"],
@@ -4713,11 +4724,6 @@
"Intègre une page externe dans une iframe en ligne (docs, démos, Figma, CodeSandbox)."
],
"jTUxaN": ["Activer Auto (Tirer seulement)"],
- "jTdrn1": [
- "Impossible de vérifier si ",
- ["filePath"],
- " est toujours en conflit — nouvelle tentative."
- ],
"jWwQo6": ["lot"],
"jWzDfC": ["Vérification des outils IA dont vous disposez"],
"jZ_E5M": ["Échec de la récupération — consultez les journaux du serveur pour les détails."],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 2a1a9d050..687e3826c 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> n'est pas un composant connu. Copiez la source pour l'
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "Le rendu de <{descriptorLabel}> a échoué (probablement une propriété incorrecte). Copiez la source pour voir ce qui ne va pas, ou supprimez le bloc."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> ne peut pas être fusionné ici. Choisissez la version à garder."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>Miroir — choisissez une source.</0> Définissez <1>src</1> + <2>anchor</2> dans le panneau des propriétés pour pointer vers un <3><MirrorSource></3> ailleurs."
@@ -3908,10 +3912,6 @@ msgstr "Impossible de modifier la vérification orthographique. Réessayez."
msgid "Couldn't change the spelling languages. Try again."
msgstr "Impossible de modifier les langues de la correction orthographique. Réessayez."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "Impossible de vérifier si {filePath} est toujours en conflit — nouvelle tentative."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "Supprimer le tableau sélectionné"
msgid "Delete table"
msgstr "Supprimer le tableau"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "Supprimer le fichier"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "Supprimer ce chat ?"
@@ -9021,6 +9025,10 @@ msgstr "Pas encore de commentaires. Sélectionnez du texte dans le document pour
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "Aucun ancêtre commun : les deux branches ont ajouté ce fichier (conflit add/add)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "Aucun conflit n’est suivi pour ce chemin."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "Aucune modification de contenu dans cette version."
@@ -11475,10 +11483,6 @@ msgstr "Rendu"
msgid "Reopen"
msgstr "Rouvrir"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "Rouvrez {filePath} pour continuer à modifier."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "Rouvrir un chat précédent"
@@ -13109,6 +13113,10 @@ msgstr "Certains thèmes enregistrés ne sont pas affichés car le dossier des t
msgid "Some skills were deleted with a warning"
msgstr "Certaines compétences ont été supprimées avec un avertissement"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "Quelqu'un a peut-être déjà résolu {filePath} — vérifiez le contenu actuel du document avant de refaire votre modification."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "Quelque chose s'est cassé"
@@ -14389,10 +14397,6 @@ msgstr "Ce commentaire porte sur toute la propriété"
msgid "This composer doesn't accept attachments."
msgstr "Impossible de joindre des fichiers ici."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "Ce conflit est résolu."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "La configuration a échoué, car l'entrée de serveur MCP nécessaire n'a pas été écrite."
@@ -15492,6 +15496,10 @@ msgstr "Utilisez uniquement des lettres minuscules, des chiffres et <0>-</0>."
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "Utilisez uniquement des lettres minuscules, des chiffres et des traits d'union"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "Utiliser leur version"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "Utiliser ce pack de démarrage"
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 4a26ad580..ad05b1493 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -101,6 +101,11 @@
["fileName"],
") से नई फ़ाइल"
],
+ "0bV3uj": [
+ "हो सकता है किसी ने ",
+ ["filePath"],
+ " का टकराव पहले ही सुलझा दिया हो — अपना संपादन दोबारा करने से पहले दस्तावेज़ की मौजूदा सामग्री देख लें।"
+ ],
"0cGsQh": ["क्या शामिल है"],
"0cspe_": ["पंक्ति हटाएँ"],
"0dslv8": [
@@ -339,6 +344,7 @@
"3aeN7X": ["सभी फ़ाइलें"],
"3cOo2C": ["मौजूदा दस्तावेज़ या फ़ोल्डर संदर्भ से एक फ़ोल्डर बनाएँ।"],
"3ePd3I": ["नया क्या है"],
+ "3fOsvq": ["उनका संस्करण लें"],
"3h5zMp": ["सेटिंग पैनल लोड करते समय कुछ ग़लत हो गया।"],
"3iyGWF": ["हाल का प्रोजेक्ट खोलें"],
"3jod3l": ["GitHub जोड़ें"],
@@ -2243,6 +2249,7 @@
"RB_g_C": [
"रूट इंडेक्स पर, okf_version को \"0.2\" जैसी उद्धृत स्ट्रिंग के रूप में लिखा जाता है। अउद्धृत, YAML इसे एक संख्या के रूप में पढ़ता है और 0.10 चुपचाप 0.1 बन जाता है।"
],
+ "RCMt3v": ["इस पथ के लिए कोई टकराव ट्रैक नहीं किया जा रहा है।"],
"RD6H9q": [
"दस्तावेज़ बदलने पर Open Knowledge इन index.md फ़ाइलों को फिर से लिखता है, इसलिए उनमें मैन्युअल संपादन बदल दिए जाते हैं।"
],
@@ -2293,6 +2300,7 @@
"Rah7yq": ["AI को क्या करना चाहिए? (वैकल्पिक)"],
"Rb1zMa": ["कोई अंश नहीं"],
"RcrskJ": ["फ़ॉर्मैटिंग ग़लत लगी"],
+ "RduDYw": ["<0>", ["filePath"], "</0> को यहाँ मर्ज नहीं किया जा सकता। रखने के लिए संस्करण चुनें।"],
"RfHNf8": [["tooltipName"], " के लिए गतिविधि पैनल खोलें"],
"RfaEio": ["स्रोत टिप्पणी चालू या बंद करें"],
"RfilGt": ["आपके फ़िल्टर से कोई नियम मेल नहीं खाता।"],
@@ -2365,6 +2373,7 @@
"SXCSQd": ["पथ कॉपी किया गया"],
"SXEdCq": [["0"], " में ले जाएँ?"],
"SYfHmN": ["टैब अनपिन करें"],
+ "S_RRZB": ["फ़ाइल हटाएँ"],
"Sad2tK": ["भेजा जा रहा है…"],
"Sbb90e": [
[
@@ -2783,7 +2792,6 @@
"XwZiq2": [
"फ़ाइल को पुराने संस्करण में बहाल किया गया है। वर्तमान वह संस्करण है जिसे OpenKnowledge ने सुरक्षित रखा है। आने वाला बहाल किया गया संस्करण है। कौन सा संस्करण रखना है, यह चुनें, फिर अपने बदलाव लागू करें।"
],
- "XzL7x7": ["संपादन जारी रखने के लिए ", ["filePath"], " फिर से खोलें।"],
"Xzy0s0": [["fullLabel"], " को संदर्भ से हटाएँ"],
"Y-Urt2": ["एक LaTeX स्रोत स्ट्रिंग से KaTeX द्वारा रेंडर किया गया ब्लॉक गणित समीकरण।"],
"Y1QMlM": ["सेट अप करें"],
@@ -3677,7 +3685,6 @@
"अपना उत्पाद कैसे बनता है इसका लिखित लेखा रखें। विचार प्रस्तावित करने, निर्णय दर्ज करने, स्पेक लिखने और किसी गड़बड़ी के बाद सीखी बातों को सहेजने का एक घर।"
],
"hCattk": ["OpenKnowledge ने ", ["source"], " आयात किया"],
- "hCghAK": ["यह विरोध हल हो गया है।"],
"hDEaQu": ["OpenKnowledge को अपने उपयोग के अन्य टूल से जोड़ें।"],
"hDKtoF": [["diffHrs"], " घंटे पहले"],
"hDoLrm": [["projectName"], " को हाल के प्रोजेक्ट से हटाएँ"],
@@ -3894,7 +3901,6 @@
"jSg1tA": ["और क्रियाएँ (", ["syncAttentionLabel"], ")"],
"jTLWxh": ["एक बाहरी पेज को इनलाइन iframe में एम्बेड करें (दस्तावेज़, डेमो, Figma, CodeSandbox)।"],
"jTUxaN": ["स्वचालित (केवल खींचें) चालू करें"],
- "jTdrn1": [["filePath"], " में अब भी कॉन्फ़्लिक्ट है या नहीं, जाँचा नहीं जा सका — पुनः प्रयास जारी।"],
"jWwQo6": ["बैच"],
"jWzDfC": ["जाँच रहे हैं कि आपके पास कौन-से AI टूल हैं"],
"jZ_E5M": ["फ़ेच विफल — विवरण के लिए सर्वर लॉग देखें।"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 71dbc43e6..34a2b7215 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -1215,6 +1215,10 @@ msgstr "<{componentName}> एक ज्ञात कंपोनेंट नह
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> रेंडर नहीं हो सका (शायद कोई ग़लत प्रॉप)। क्या ग़लत हुआ यह देखने के लिए स्रोत कॉपी करें, या ब्लॉक हटा दें।"
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> को यहाँ मर्ज नहीं किया जा सकता। रखने के लिए संस्करण चुनें।"
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>मिरर — एक स्रोत चुनें।</0> कहीं और मौजूद किसी <3><MirrorSource></3> की ओर इंगित करने के लिए प्रॉपर्टी पैनल से <1>src</1> + <2>anchor</2> सेट करें।"
@@ -3904,10 +3908,6 @@ msgstr "वर्तनी जाँच बदली नहीं जा सक
msgid "Couldn't change the spelling languages. Try again."
msgstr "वर्तनी जाँच की भाषाएँ नहीं बदली जा सकीं। फिर से कोशिश करें।"
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "{filePath} में अब भी कॉन्फ़्लिक्ट है या नहीं, जाँचा नहीं जा सका — पुनः प्रयास जारी।"
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4785,6 +4785,10 @@ msgstr "चयनित तालिका हटाएँ"
msgid "Delete table"
msgstr "तालिका हटाएँ"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "फ़ाइल हटाएँ"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "यह चैट हटाएं?"
@@ -9017,6 +9021,10 @@ msgstr "अभी कोई टिप्पणी नहीं। कोई ज
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "कोई साझा पूर्वज नहीं — दोनों ब्रांच ने यह फ़ाइल जोड़ी (add/add विरोध)।"
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "इस पथ के लिए कोई टकराव ट्रैक नहीं किया जा रहा है।"
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "इस संस्करण में सामग्री का कोई बदलाव नहीं।"
@@ -11471,10 +11479,6 @@ msgstr "रेंडर किया गया"
msgid "Reopen"
msgstr "फिर से खोलें"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "संपादन जारी रखने के लिए {filePath} फिर से खोलें।"
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "पिछली चैट फिर से खोलें"
@@ -13105,6 +13109,10 @@ msgstr "कुछ सहेजी गई थीम नहीं दिखाई
msgid "Some skills were deleted with a warning"
msgstr "कुछ स्किलें चेतावनी के साथ हटाई गईं"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "हो सकता है किसी ने {filePath} का टकराव पहले ही सुलझा दिया हो — अपना संपादन दोबारा करने से पहले दस्तावेज़ की मौजूदा सामग्री देख लें।"
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "कुछ टूट गया"
@@ -14385,10 +14393,6 @@ msgstr "यह टिप्पणी पूरी प्रॉपर्टी
msgid "This composer doesn't accept attachments."
msgstr "यहाँ फ़ाइलें अटैच नहीं की जा सकतीं।"
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "यह विरोध हल हो गया है।"
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "इसे सेट अप नहीं किया जा सका क्योंकि इसके लिए ज़रूरी MCP सर्वर एंट्री नहीं लिखी गई।"
@@ -15488,6 +15492,10 @@ msgstr "केवल छोटे अक्षर, अंक और <0>-</0> उ
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "केवल छोटे अक्षर, अंक और हाइफ़न उपयोग करें"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "उनका संस्करण लें"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "यह स्टार्टर पैक उपयोग करें"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 059d57eb1..499348778 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -101,6 +101,11 @@
") di ",
["targetLabel"]
],
+ "0bV3uj": [
+ "Mungkin seseorang sudah menyelesaikan ",
+ ["filePath"],
+ " — periksa isi dokumen saat ini sebelum mengulangi suntingan Anda."
+ ],
"0cGsQh": ["Yang disertakan"],
"0cspe_": ["Hapus baris"],
"0dslv8": [
@@ -342,6 +347,7 @@
"3aeN7X": ["Semua berkas"],
"3cOo2C": ["Membuat folder dari konteks dokumen atau folder saat ini."],
"3ePd3I": ["Yang baru"],
+ "3fOsvq": ["Pakai versi mereka"],
"3h5zMp": ["Ada yang tidak beres saat memuat panel pengaturan."],
"3iyGWF": ["Buka proyek terbaru"],
"3jod3l": ["Hubungkan GitHub"],
@@ -2320,6 +2326,7 @@
"RB_g_C": [
"Pada indeks root, okf_version ditulis sebagai string yang dikutip seperti \"0.2\". Tanpa tanda kutip, YAML membacanya sebagai angka dan 0.10 diam-diam menjadi 0.1."
],
+ "RCMt3v": ["Tidak ada konflik yang dilacak untuk jalur ini."],
"RD6H9q": [
"Open Knowledge menulis ulang file index.md ini seiring perubahan dokumen, sehingga pengeditan manual pada file tersebut diganti."
],
@@ -2375,6 +2382,11 @@
"Rah7yq": ["Apa yang harus dilakukan AI? (opsional)"],
"Rb1zMa": ["Tanpa cuplikan"],
"RcrskJ": ["Format terlihat salah"],
+ "RduDYw": [
+ "<0>",
+ ["filePath"],
+ "</0> tidak bisa digabungkan di sini. Pilih versi yang ingin disimpan."
+ ],
"RfHNf8": ["Buka panel aktivitas untuk ", ["tooltipName"]],
"RfaEio": ["Komentari atau batalkan komentar di sumber"],
"RfilGt": ["Tidak ada aturan yang cocok dengan filter Anda."],
@@ -2443,6 +2455,7 @@
"SXCSQd": ["Jalur disalin"],
"SXEdCq": ["Pindahkan ke ", ["0"], "?"],
"SYfHmN": ["Lepas sematan tab"],
+ "S_RRZB": ["Hapus berkas"],
"Sad2tK": ["Mengirim…"],
"Sbb90e": [
[
@@ -2888,7 +2901,6 @@
"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."],
"Y1QMlM": ["Mulai siapkan"],
@@ -3827,7 +3839,6 @@
"Simpan catatan tertulis tentang bagaimana produk Anda dibangun. Rumah untuk mengusulkan ide, mencatat keputusan, menulis spesifikasi, dan merekam apa yang Anda pelajari setelah sesuatu rusak."
],
"hCattk": ["OpenKnowledge mengimpor ", ["source"]],
- "hCghAK": ["Konflik ini sudah diselesaikan."],
"hDEaQu": ["Hubungkan OpenKnowledge dengan alat lain yang Anda pakai."],
"hDKtoF": [["diffHrs"], " j lalu"],
"hDoLrm": ["Hapus ", ["projectName"], " dari proyek terbaru"],
@@ -4059,7 +4070,6 @@
"Menyematkan halaman eksternal dalam iframe sebaris (dokumentasi, demo, Figma, CodeSandbox)."
],
"jTUxaN": ["Aktifkan Otomatis (hanya Pull)"],
- "jTdrn1": ["Tidak dapat memeriksa apakah ", ["filePath"], " masih berkonflik — mencoba lagi."],
"jWwQo6": ["batch"],
"jWzDfC": ["Memeriksa alat AI yang Anda miliki"],
"jZ_E5M": ["Fetch gagal — periksa log server untuk detailnya."],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index a3279f8be..d288c5ac1 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -1215,6 +1215,10 @@ msgstr "<{componentName}> bukan komponen yang dikenal. Salin sumbernya untuk dip
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> gagal dirender (kemungkinan prop yang salah). Salin sumbernya untuk melihat apa yang salah, atau hapus bloknya."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> tidak bisa digabungkan di sini. Pilih versi yang ingin disimpan."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>Cermin — pilih sebuah sumber.</0> Atur <1>src</1> + <2>anchor</2> lewat panel properti agar mengarah ke <3><MirrorSource></3> di tempat lain."
@@ -3904,10 +3908,6 @@ msgstr "Tidak dapat mengubah pemeriksaan ejaan. Coba lagi."
msgid "Couldn't change the spelling languages. Try again."
msgstr "Tidak dapat mengubah bahasa pemeriksaan ejaan. Coba lagi."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "Tidak dapat memeriksa apakah {filePath} masih berkonflik — mencoba lagi."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4785,6 +4785,10 @@ msgstr "Hapus tabel terpilih"
msgid "Delete table"
msgstr "Hapus tabel"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "Hapus berkas"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "Hapus obrolan ini?"
@@ -9017,6 +9021,10 @@ msgstr "Belum ada komentar. Pilih teks di dokumen untuk menambahkan satu."
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "Tidak ada leluhur bersama — kedua cabang menambahkan berkas ini (konflik add/add)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "Tidak ada konflik yang dilacak untuk jalur ini."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "Tidak ada perubahan isi pada versi ini."
@@ -11471,10 +11479,6 @@ msgstr "Dirender"
msgid "Reopen"
msgstr "Buka lagi"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "Buka kembali {filePath} untuk melanjutkan penyuntingan."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "Buka kembali obrolan sebelumnya"
@@ -13105,6 +13109,10 @@ msgstr "Beberapa tema tersimpan tidak ditampilkan karena folder tema melewati ba
msgid "Some skills were deleted with a warning"
msgstr "Beberapa keterampilan dihapus dengan peringatan"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "Mungkin seseorang sudah menyelesaikan {filePath} — periksa isi dokumen saat ini sebelum mengulangi suntingan Anda."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "Ada yang rusak"
@@ -14385,10 +14393,6 @@ msgstr "Komentar ini berlaku untuk seluruh properti"
msgid "This composer doesn't accept attachments."
msgstr "Berkas tidak bisa dilampirkan di sini."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "Konflik ini sudah diselesaikan."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "Ini tidak dapat disiapkan karena entri server MCP yang diperlukan tidak ditulis."
@@ -15488,6 +15492,10 @@ msgstr "Pakai hanya huruf kecil, angka, dan <0>-</0>."
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "Pakai hanya huruf kecil, angka, dan tanda hubung"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "Pakai versi mereka"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "Pakai paket awal ini"
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 154d7da98..3a4524d76 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -96,6 +96,11 @@
["targetLabel"],
"에 새 파일"
],
+ "0bV3uj": [
+ "누군가 이미 ",
+ ["filePath"],
+ "의 충돌을 해결했을 수 있습니다 — 편집을 다시 하기 전에 문서의 현재 내용을 확인하세요."
+ ],
"0cGsQh": ["포함되는 항목"],
"0cspe_": ["행 삭제"],
"0dslv8": [
@@ -329,6 +334,7 @@
"3aeN7X": ["모든 파일"],
"3cOo2C": ["현재 문서 또는 폴더를 기준으로 폴더를 만듭니다."],
"3ePd3I": ["새로운 기능"],
+ "3fOsvq": ["상대 버전 사용"],
"3h5zMp": ["설정 패널을 불러오는 중 문제가 발생했습니다."],
"3iyGWF": ["최근 프로젝트 열기"],
"3jod3l": ["GitHub 연결"],
@@ -2217,6 +2223,7 @@
"RB_g_C": [
"루트 인덱스에서 okf_version은 \"0.2\"와 같은 따옴표 문자열로 작성됩니다. 따옴표가 없으면 YAML이 숫자로 읽어 0.10이 조용히 0.1로 바뀝니다."
],
+ "RCMt3v": ["이 경로에 대해 추적 중인 충돌이 없습니다."],
"RD6H9q": [
"문서가 변경되면 Open Knowledge가 index.md 파일을 다시 작성하므로 직접 편집한 내용은 대체됩니다."
],
@@ -2270,6 +2277,7 @@
"Rah7yq": ["AI 작업 내용? (선택 사항)"],
"Rb1zMa": ["발췌문 없음"],
"RcrskJ": ["서식이 잘못 표시됨"],
+ "RduDYw": ["<0>", ["filePath"], "</0>은 여기에서 병합할 수 없습니다. 유지할 버전을 고르세요."],
"RfHNf8": [["tooltipName"], " 활동 패널 열기"],
"RfaEio": ["소스 댓글 전환"],
"RfilGt": ["필터와 일치하는 규칙 없음."],
@@ -2338,6 +2346,7 @@
"SXCSQd": ["복사된 경로"],
"SXEdCq": [["0"], "으로 이동할까요?"],
"SYfHmN": ["탭 고정 해제"],
+ "S_RRZB": ["파일 삭제"],
"Sad2tK": ["보내는 중…"],
"Sbb90e": [
[
@@ -2764,7 +2773,6 @@
"XwZiq2": [
"파일이 이전 버전으로 복원되었습니다. 현재 항목은 OpenKnowledge가 보호한 버전입니다. 수신 항목은 복원된 버전입니다. 유지할 버전을 선택한 다음 변경 사항을 적용하세요."
],
- "XzL7x7": ["계속 편집하려면 ", ["filePath"], "을(를) 다시 여세요."],
"Xzy0s0": ["현재 내용에서 ", ["fullLabel"], " 제거"],
"Y-Urt2": ["LaTeX 소스 문자열에서 KaTeX로 렌더링되는 블록 수식입니다."],
"Y1QMlM": ["설정 시작"],
@@ -3663,7 +3671,6 @@
"제품이 만들어지는 과정을 기록합니다. 아이디어 제안, 결정 기록, 사양 작성, 문제가 생긴 뒤 배운 점을 담는 공간입니다."
],
"hCattk": ["OpenKnowledge에서 ", ["source"], " 가져오기"],
- "hCghAK": ["이 충돌은 해결되었습니다."],
"hDEaQu": ["OpenKnowledge를 사용하는 다른 도구에 연결합니다."],
"hDKtoF": [["diffHrs"], "시간 전"],
"hDoLrm": ["프로젝트 \"", ["projectName"], "\"을 최근 프로젝트에서 제거"],
@@ -3880,7 +3887,6 @@
"외부 페이지를 인라인 iframe에 삽입합니다. 문서, 데모, Figma, CodeSandbox를 지원합니다."
],
"jTUxaN": ["자동(풀만) 활성화"],
- "jTdrn1": [["filePath"], "에 아직 충돌이 있는지 확인하지 못했습니다 — 다시 시도합니다."],
"jWwQo6": ["배치"],
"jWzDfC": ["보유한 AI 도구를 확인하는 중"],
"jZ_E5M": ["가져오기 실패. 자세한 내용은 서버 로그를 확인하세요."],
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 8a02e9c68..d64db1c20 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}>는 알려진 컴포넌트가 아닙니다. 다른 곳
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> 컴포넌트를 렌더링하지 못했습니다. 잘못된 속성 때문일 수 있습니다. 문제를 확인하려면 소스를 복사하거나 블록을 삭제하세요."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0>은 여기에서 병합할 수 없습니다. 유지할 버전을 고르세요."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>미러, 소스를 선택하세요.</0> 속성 패널에서 <1>src</1>와 <2>anchor</2>를 설정해 다른 곳의 <3><MirrorSource></3>를 가리키세요."
@@ -3908,10 +3912,6 @@ msgstr "맞춤법 검사를 변경할 수 없습니다. 다시 시도하세요."
msgid "Couldn't change the spelling languages. Try again."
msgstr "맞춤법 검사 언어를 변경하지 못했습니다. 다시 시도하세요."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "{filePath}에 아직 충돌이 있는지 확인하지 못했습니다 — 다시 시도합니다."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "선택한 표 삭제"
msgid "Delete table"
msgstr "표 삭제"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "파일 삭제"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "채팅 삭제?"
@@ -9021,6 +9025,10 @@ msgstr "아직 댓글 없음. 문서에서 텍스트 선택 후 댓글 추가"
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "공통 조상이 없습니다 — 두 브랜치가 이 파일을 각각 추가했습니다 (add/add 충돌)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "이 경로에 대해 추적 중인 충돌이 없습니다."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "이 버전에서 내용 변경 없음."
@@ -11475,10 +11483,6 @@ msgstr "렌더링됨"
msgid "Reopen"
msgstr "다시 열기"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "계속 편집하려면 {filePath}을(를) 다시 여세요."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "이전 채팅 다시 열기"
@@ -13109,6 +13113,10 @@ msgstr "테마 폴더가 스캔 한도를 초과해 일부 저장된 테마가
msgid "Some skills were deleted with a warning"
msgstr "일부 스킬이 경고와 함께 삭제되었습니다"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "누군가 이미 {filePath}의 충돌을 해결했을 수 있습니다 — 편집을 다시 하기 전에 문서의 현재 내용을 확인하세요."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "문제가 발생했습니다"
@@ -14389,10 +14397,6 @@ msgstr "이 댓글, 속성 전체에 적용됨"
msgid "This composer doesn't accept attachments."
msgstr "여기에는 파일을 첨부할 수 없습니다."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "이 충돌은 해결되었습니다."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "필요한 MCP 서버 항목이 기록되지 않아 설정할 수 없었습니다."
@@ -15492,6 +15496,10 @@ msgstr "소문자, 숫자, <0>-</0>만 사용하세요."
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "소문자, 숫자, 하이픈만 사용하세요"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "상대 버전 사용"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "이 스타터 팩 사용"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 888c87553..3d0d47e46 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -101,6 +101,11 @@
") ĩń ",
["targetLabel"]
],
+ "0bV3uj": [
+ "Śōḿēōńē ḿàŷ ĥàvē àĺŕēàďŷ ŕēśōĺvēď ",
+ ["filePath"],
+ " — ćĥēćķ ţĥē ďōćũḿēńţ'ś ćũŕŕēńţ ćōńţēńţ ƀēƒōŕē ŕēďōĩńĝ ŷōũŕ ēďĩţ."
+ ],
"0cGsQh": ["Ŵĥàţ'ś ĩńćĺũďēď"],
"0cspe_": ["Ďēĺēţē ŕōŵ"],
"0dslv8": [
@@ -345,6 +350,7 @@
"3aeN7X": ["Àĺĺ ƒĩĺēś"],
"3cOo2C": ["Ćŕēàţē à ƒōĺďēŕ ƒŕōḿ ţĥē ćũŕŕēńţ ďōćũḿēńţ ōŕ ƒōĺďēŕ ćōńţēxţ."],
"3ePd3I": ["Ŵĥàţ'ś ńēŵ"],
+ "3fOsvq": ["Ũśē ţĥēĩŕ vēŕśĩōń"],
"3h5zMp": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ĺōàďĩńĝ ţĥē śēţţĩńĝś ƥàńēĺ."],
"3iyGWF": ["Ōƥēń ŕēćēńţ ƥŕōĴēćţ"],
"3jod3l": ["Ćōńńēćţ ĜĩţĤũƀ"],
@@ -2309,6 +2315,7 @@
"RB_g_C": [
"Ōń ţĥē ŕōōţ ĩńďēx, ōķƒ_vēŕśĩōń ĩś ŵŕĩţţēń àś à ǫũōţēď śţŕĩńĝ ĺĩķē \"0.2\". Ũńǫũōţēď, ŶÀḾĹ ŕēàďś ĩţ àś à ńũḿƀēŕ àńď 0.10 śĩĺēńţĺŷ ƀēćōḿēś 0.1."
],
+ "RCMt3v": ["Ńō ćōńƒĺĩćţ ĩś ţŕàćķēď ƒōŕ ţĥĩś ƥàţĥ."],
"RD6H9q": [
"Ōƥēń Ķńōŵĺēďĝē ŕēŵŕĩţēś ţĥēśē ĩńďēx.ḿď ƒĩĺēś àś ďōćũḿēńţś ćĥàńĝē, śō ḿàńũàĺ ēďĩţś ţō ţĥēḿ àŕē ŕēƥĺàćēď."
],
@@ -2364,6 +2371,7 @@
"Rah7yq": ["Ŵĥàţ śĥōũĺď ţĥē ÀĨ ďō? (ōƥţĩōńàĺ)"],
"Rb1zMa": ["Ńō ēxćēŕƥţ"],
"RcrskJ": ["Ƒōŕḿàţţĩńĝ ĺōōķēď ŵŕōńĝ"],
+ "RduDYw": ["<0>", ["filePath"], "</0> ćàń'ţ ƀē ḿēŕĝēď ĥēŕē. Ƥĩćķ ţĥē vēŕśĩōń ţō ķēēƥ."],
"RfHNf8": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"]],
"RfaEio": ["Ţōĝĝĺē śōũŕćē ćōḿḿēńţ"],
"RfilGt": ["Ńō ŕũĺēś ḿàţćĥ ŷōũŕ ƒĩĺţēŕś."],
@@ -2437,6 +2445,7 @@
"SXCSQd": ["Ćōƥĩēď ƥàţĥ"],
"SXEdCq": ["Ḿōvē ţō ", ["0"], "?"],
"SYfHmN": ["Ũńƥĩń ţàƀ"],
+ "S_RRZB": ["Ďēĺēţē ţĥē ƒĩĺē"],
"Sad2tK": ["Śēńďĩńĝ…"],
"Sbb90e": [
[
@@ -2862,7 +2871,6 @@
"XwZiq2": [
"Ţĥē ƒĩĺē ŵàś ŕēśţōŕēď ţō àń ōĺďēŕ vēŕśĩōń. Ćũŕŕēńţ ĩś ţĥē vēŕśĩōń ŌƥēńĶńōŵĺēďĝē ƥŕōţēćţēď. Ĩńćōḿĩńĝ ĩś ţĥē ŕēśţōŕēď vēŕśĩōń. Ćĥōōśē ŵĥĩćĥ vēŕśĩōń ţō ķēēƥ, ţĥēń àƥƥĺŷ ŷōũŕ ćĥàńĝēś."
],
- "XzL7x7": ["Ŕēōƥēń ", ["filePath"], " ţō ķēēƥ ēďĩţĩńĝ."],
"Xzy0s0": ["Ŕēḿōvē ", ["fullLabel"], " ƒŕōḿ ćōńţēxţ"],
"Y-Urt2": ["ßĺōćķ ḿàţĥ ēǫũàţĩōń ŕēńďēŕēď ŵĩţĥ ĶàŢēX ƒŕōḿ à ĹàŢēX śōũŕćē śţŕĩńĝ."],
"Y1QMlM": ["Ĝēţ śēţ ũƥ"],
@@ -3806,7 +3814,6 @@
"Ķēēƥ à ŵŕĩţţēń ŕēćōŕď ōƒ ĥōŵ ŷōũŕ ƥŕōďũćţ ĝēţś ƀũĩĺţ. À ĥōḿē ƒōŕ ƥŕōƥōśĩńĝ ĩďēàś, ŕēćōŕďĩńĝ ďēćĩśĩōńś, ŵŕĩţĩńĝ śƥēćś, àńď ćàƥţũŕĩńĝ ŵĥàţ ŷōũ ĺēàŕńēď àƒţēŕ śōḿēţĥĩńĝ ƀŕōķē."
],
"hCattk": ["ŌƥēńĶńōŵĺēďĝē ĩḿƥōŕţēď ", ["source"]],
- "hCghAK": ["Ţĥĩś ćōńƒĺĩćţ ĩś ŕēśōĺvēď."],
"hDEaQu": ["Ćōńńēćţ ŌƥēńĶńōŵĺēďĝē ţō ōţĥēŕ ţōōĺś ŷōũ ũśē."],
"hDKtoF": [["diffHrs"], "ĥ àĝō"],
"hDoLrm": ["Ŕēḿōvē ", ["projectName"], " ƒŕōḿ ŕēćēńţ ƥŕōĴēćţś"],
@@ -4023,7 +4030,6 @@
"jSg1tA": ["Ḿōŕē àćţĩōńś (", ["syncAttentionLabel"], ")"],
"jTLWxh": ["Ēḿƀēď àń ēxţēŕńàĺ ƥàĝē ĩń àń ĩńĺĩńē ĩƒŕàḿē (ďōćś, ďēḿōś, Ƒĩĝḿà, ĆōďēŚàńďƀōx)."],
"jTUxaN": ["Ēńàƀĺē Àũţō (Ƥũĺĺ ōńĺŷ)"],
- "jTdrn1": ["Ćōũĺďń'ţ ćĥēćķ ŵĥēţĥēŕ ", ["filePath"], " ĩś śţĩĺĺ ćōńƒĺĩćţēď — ŕēţŕŷĩńĝ."],
"jWwQo6": ["ƀàţćĥ"],
"jWzDfC": ["Ćĥēćķĩńĝ ŵĥĩćĥ ÀĨ ţōōĺś ŷōũ ĥàvē"],
"jZ_E5M": ["Ƒēţćĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index b6511f0dd..e39a3d089 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1215,6 +1215,10 @@ msgstr ""
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr ""
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr ""
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr ""
@@ -3904,10 +3908,6 @@ msgstr ""
msgid "Couldn't change the spelling languages. Try again."
msgstr ""
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr ""
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4785,6 +4785,10 @@ msgstr ""
msgid "Delete table"
msgstr ""
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr ""
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr ""
@@ -9017,6 +9021,10 @@ msgstr ""
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr ""
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr ""
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr ""
@@ -11471,10 +11479,6 @@ msgstr ""
msgid "Reopen"
msgstr ""
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr ""
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr ""
@@ -13105,6 +13109,10 @@ msgstr ""
msgid "Some skills were deleted with a warning"
msgstr ""
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr ""
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr ""
@@ -14385,10 +14393,6 @@ msgstr ""
msgid "This composer doesn't accept attachments."
msgstr ""
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr ""
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr ""
@@ -15488,6 +15492,10 @@ msgstr ""
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr ""
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 9789a5ae4..0f97d7e16 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -115,6 +115,11 @@
") em ",
["targetLabel"]
],
+ "0bV3uj": [
+ "Talvez alguém já tenha resolvido ",
+ ["filePath"],
+ " — confira o conteúdo atual do documento antes de refazer sua edição."
+ ],
"0cGsQh": ["O que está incluído"],
"0cspe_": ["Excluir linha"],
"0dslv8": [
@@ -398,6 +403,7 @@
"3aeN7X": ["Todos os arquivos"],
"3cOo2C": ["Cria uma pasta a partir do documento ou da pasta atual."],
"3ePd3I": ["Novidades"],
+ "3fOsvq": ["Usar a versão deles"],
"3h5zMp": ["Algo deu errado ao carregar o painel de configurações."],
"3iyGWF": ["Abrir um projeto recente"],
"3jod3l": ["Conectar GitHub"],
@@ -2630,6 +2636,7 @@
"RB_g_C": [
"No índice raiz, okf_version é escrito como uma string entre aspas, como \"0.2\". Sem aspas, YAML lê-o como um número e 0.10 silenciosamente se torna 0.1."
],
+ "RCMt3v": ["Nenhum conflito está sendo rastreado para este caminho."],
"RD6H9q": [
"Open Knowledge reescreve esses arquivos index.md conforme os documentos são alterados, portanto, as edições manuais neles são substituídas."
],
@@ -2685,6 +2692,11 @@
"Rah7yq": ["O que a IA deve fazer? (opcional)"],
"Rb1zMa": ["Sem trecho"],
"RcrskJ": ["A formatação parecia errada"],
+ "RduDYw": [
+ "<0>",
+ ["filePath"],
+ "</0> não pode ser mesclado aqui. Escolha a versão que quer manter."
+ ],
"RfHNf8": ["Abrir o painel de atividade de ", ["tooltipName"]],
"RfaEio": ["Comentar ou descomentar no código"],
"RfilGt": ["Nenhuma regra corresponde aos seus filtros."],
@@ -2765,6 +2777,7 @@
"SXCSQd": ["Caminho copiado"],
"SXEdCq": ["Mover para ", ["0"], "?"],
"SYfHmN": ["Desafixar a aba"],
+ "S_RRZB": ["Excluir o arquivo"],
"Sad2tK": ["Enviando…"],
"Sbb90e": [
[
@@ -3286,7 +3299,6 @@
"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."],
"Y1QMlM": ["Comece agora"],
@@ -4349,7 +4361,6 @@
"Mantenha um registro escrito de como seu produto é construído. Um lugar para propor ideias, registrar decisões, escrever especificações e anotar o que você aprendeu depois que algo quebrou."
],
"hCattk": ["OpenKnowledge importou ", ["source"]],
- "hCghAK": ["Este conflito foi resolvido."],
"hDEaQu": ["Conecte o OpenKnowledge às outras ferramentas que você usa."],
"hDKtoF": ["há ", ["diffHrs"], " h"],
"hDoLrm": ["Remover ", ["projectName"], " dos projetos recentes"],
@@ -4584,11 +4595,6 @@
"Incorpora uma página externa em um iframe embutido (documentação, demos, Figma, CodeSandbox)."
],
"jTUxaN": ["Ativar Automático (somente Pull)"],
- "jTdrn1": [
- "Não foi possível verificar se ",
- ["filePath"],
- " ainda está em conflito — tentando novamente."
- ],
"jWwQo6": ["lote"],
"jWzDfC": ["Verificando quais ferramentas de IA você tem"],
"jZ_E5M": ["Falha ao buscar — veja os logs do servidor para os detalhes."],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 099a45903..7efbf9199 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -1215,6 +1215,10 @@ msgstr "<{componentName}> não é um componente conhecido. Copie o código para
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "Não foi possível renderizar <{descriptorLabel}> (provavelmente uma prop inválida). Copie o código para ver o que deu errado ou exclua o bloco."
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> não pode ser mesclado aqui. Escolha a versão que quer manter."
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>Espelho — escolha uma fonte.</0> Defina <1>src</1> + <2>anchor</2> no painel de propriedades para apontar para um <3><MirrorSource></3> em outro lugar."
@@ -3904,10 +3908,6 @@ msgstr "Não foi possível alterar a verificação ortográfica. Tente novamente
msgid "Couldn't change the spelling languages. Try again."
msgstr "Não foi possível alterar os idiomas da verificação ortográfica. Tente novamente."
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "Não foi possível verificar se {filePath} ainda está em conflito — tentando novamente."
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4785,6 +4785,10 @@ msgstr "Excluir a tabela selecionada"
msgid "Delete table"
msgstr "Excluir tabela"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "Excluir o arquivo"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "Excluir este chat?"
@@ -9017,6 +9021,10 @@ msgstr "Ainda não há comentários. Selecione um texto no documento para adicio
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "Sem ancestral comum: os dois ramos adicionaram este arquivo (conflito add/add)."
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "Nenhum conflito está sendo rastreado para este caminho."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "Nenhuma alteração de conteúdo nesta versão."
@@ -11471,10 +11479,6 @@ msgstr "Renderizado"
msgid "Reopen"
msgstr "Reabrir"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "Reabra {filePath} para continuar editando."
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "Reabrir um chat anterior"
@@ -13105,6 +13109,10 @@ msgstr "Alguns temas salvos não são exibidos porque a pasta de temas excede o
msgid "Some skills were deleted with a warning"
msgstr "Algumas habilidades foram excluídas com um aviso"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "Talvez alguém já tenha resolvido {filePath} — confira o conteúdo atual do documento antes de refazer sua edição."
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "Algo quebrou"
@@ -14385,10 +14393,6 @@ msgstr "Este comentário é sobre a propriedade inteira"
msgid "This composer doesn't accept attachments."
msgstr "Não é possível anexar arquivos aqui."
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "Este conflito foi resolvido."
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "Não foi possível configurar porque a entrada do servidor MCP necessária não foi gravada."
@@ -15488,6 +15492,10 @@ msgstr "Use apenas letras minúsculas, dígitos e <0>-</0>."
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "Use apenas letras minúsculas, números e hifens"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "Usar a versão deles"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "Usar este pacote inicial"
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 4647ef30b..2412a2f70 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -99,6 +99,11 @@
["fileName"],
") سے نئی فائل"
],
+ "0bV3uj": [
+ "ہو سکتا ہے کسی نے ",
+ ["filePath"],
+ " کا تنازع پہلے ہی حل کر دیا ہو — اپنی ترمیم دوبارہ کرنے سے پہلے دستاویز کا موجودہ مواد دیکھ لیں۔"
+ ],
"0cGsQh": ["کیا شامل ہے"],
"0cspe_": ["قطار حذف کریں"],
"0dslv8": [
@@ -343,6 +348,7 @@
"3aeN7X": ["تمام فائلیں"],
"3cOo2C": ["موجودہ دستاویز یا فولڈر کے سیاق سے فولڈر بنائیں۔"],
"3ePd3I": ["نیا کیا ہے"],
+ "3fOsvq": ["ان کا ورژن لیں"],
"3h5zMp": ["ترتیبات کا پینل لوڈ کرتے ہوئے کچھ غلط ہو گیا۔"],
"3iyGWF": ["حالیہ پروجیکٹ کھولیں"],
"3jod3l": ["GitHub منسلک کریں"],
@@ -2351,6 +2357,7 @@
"RB_g_C": [
"روٹ انڈیکس پر، okf_version کو \"0.2\" کی طرح کوٹڈ سٹرنگ کے طور پر لکھا جاتا ہے۔ بغیر حوالہ، YAML اسے ایک نمبر کے طور پر پڑھتا ہے اور 0.10 خاموشی سے 0.1 بن جاتا ہے۔"
],
+ "RCMt3v": ["اس پاتھ کے لیے کوئی تنازع ٹریک نہیں کیا جا رہا ہے۔"],
"RD6H9q": [
"Open Knowledge ان index.md فائلوں کو دوبارہ لکھتا ہے جیسے ہی دستاویزات میں تبدیلی آتی ہے، لہذا ان میں دستی ترامیم تبدیل کردی جاتی ہیں۔"
],
@@ -2404,6 +2411,7 @@
"Rah7yq": ["AI کو کیا کرنا چاہیے؟ (اختیاری)"],
"Rb1zMa": ["کوئی اقتباس نہیں"],
"RcrskJ": ["فارمیٹنگ غلط لگی"],
+ "RduDYw": ["<0>", ["filePath"], "</0> کو یہاں مرج نہیں کیا جا سکتا۔ رکھنے کے لیے ورژن چنیں۔"],
"RfHNf8": [["tooltipName"], " کے لیے سرگرمی کا پینل کھولیں"],
"RfaEio": ["سورس کا تبصرہ بدلیں"],
"RfilGt": ["آپ کے فلٹرز سے کوئی قاعدہ مماثل نہیں۔"],
@@ -2480,6 +2488,7 @@
"SXCSQd": ["راستہ نقل ہو گیا"],
"SXEdCq": [["0"], " پر منتقل کریں؟"],
"SYfHmN": ["ٹیب کی پن ہٹائیں"],
+ "S_RRZB": ["فائل حذف کریں"],
"Sad2tK": ["بھیجا جا رہا ہے…"],
"Sbb90e": [
[
@@ -2923,7 +2932,6 @@
"XwZiq2": [
"فائل کو ایک پرانے ورژن پر بحال کیا گیا ہے۔ موجودہ وہ ورژن ہے جسے OpenKnowledge نے محفوظ رکھا۔ آنے والا بحال کیا گیا ورژن ہے۔ منتخب کریں کہ کون سا ورژن رکھنا ہے، پھر اپنی تبدیلیاں لاگو کریں۔"
],
- "XzL7x7": ["ترمیم جاری رکھنے کے لیے ", ["filePath"], " دوبارہ کھولیں۔"],
"Xzy0s0": [["fullLabel"], " کو سیاق سے ہٹائیں"],
"Y-Urt2": ["LaTeX سورس سٹرنگ سے KaTeX کے ذریعے رینڈر کی گئی بلاک ریاضی مساوات۔"],
"Y1QMlM": ["ترتیب دیں"],
@@ -3882,7 +3890,6 @@
"اس کا تحریری ریکارڈ رکھیں کہ آپ کی مصنوع کیسے بنتی ہے۔ خیالات پیش کرنے، فیصلے درج کرنے، اسپیکس لکھنے، اور کچھ ٹوٹنے کے بعد سیکھے گئے اسباق محفوظ کرنے کا ٹھکانہ۔"
],
"hCattk": ["OpenKnowledge نے ", ["source"], " درآمد کیا"],
- "hCghAK": ["یہ تنازع حل ہو گیا ہے۔"],
"hDEaQu": ["OpenKnowledge کو اپنے استعمال کے دیگر ٹولز سے منسلک کریں۔"],
"hDKtoF": [["diffHrs"], " گھنٹے پہلے"],
"hDoLrm": [["projectName"], " کو حالیہ پروجیکٹس سے ہٹائیں"],
@@ -4106,7 +4113,6 @@
"کوئی بیرونی صفحہ اِن لائن iframe میں شامل کریں (دستاویزات، ڈیمو، Figma، CodeSandbox)۔"
],
"jTUxaN": ["خودکار (صرف کھینچیں) فعال کریں"],
- "jTdrn1": [["filePath"], " میں اب بھی کنفلکٹ ہے یا نہیں، جانچا نہ جا سکا — دوبارہ کوشش جاری۔"],
"jWwQo6": ["بیچ"],
"jWzDfC": ["دیکھا جا رہا ہے کہ آپ کے پاس کون سے AI ٹولز ہیں"],
"jZ_E5M": ["لانا ناکام رہا — تفصیلات کے لیے سرور کے لاگز دیکھیں۔"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 13afda2e9..9236d63ca 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> کوئی معلوم جزو نہیں ہے۔ اسے کہ
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> رینڈر نہیں ہو سکا (غالباً کوئی غلط پراپ)۔ خرابی دیکھنے کے لیے سورس کاپی کریں، یا بلاک حذف کر دیں۔"
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> کو یہاں مرج نہیں کیا جا سکتا۔ رکھنے کے لیے ورژن چنیں۔"
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>مرر — ایک ماخذ منتخب کریں۔</0> خصوصیات کے پینل سے <1>src</1> + <2>anchor</2> مقرر کریں تاکہ کہیں اور موجود <3><MirrorSource></3> کی طرف اشارہ ہو۔"
@@ -3908,10 +3912,6 @@ msgstr "املا کی جانچ تبدیل نہیں کی جا سکی۔ دوبار
msgid "Couldn't change the spelling languages. Try again."
msgstr "املا کی جانچ کی زبانیں تبدیل نہیں ہو سکیں۔ دوبارہ کوشش کریں۔"
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "{filePath} میں اب بھی کنفلکٹ ہے یا نہیں، جانچا نہ جا سکا — دوبارہ کوشش جاری۔"
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "منتخب ٹیبل حذف کریں"
msgid "Delete table"
msgstr "ٹیبل حذف کریں"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "فائل حذف کریں"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "یہ چیٹ حذف کریں؟"
@@ -9021,6 +9025,10 @@ msgstr "ابھی کوئی تبصرہ نہیں۔ ایک شامل کرنے کے ل
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "کوئی مشترکہ سلف نہیں — دونوں برانچوں نے یہ فائل شامل کی (add/add تنازع)۔"
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "اس پاتھ کے لیے کوئی تنازع ٹریک نہیں کیا جا رہا ہے۔"
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "اس ورژن میں مواد کی کوئی تبدیلی نہیں۔"
@@ -11475,10 +11483,6 @@ msgstr "رینڈر شدہ"
msgid "Reopen"
msgstr "دوبارہ کھولیں"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "ترمیم جاری رکھنے کے لیے {filePath} دوبارہ کھولیں۔"
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "پچھلی چیٹ دوبارہ کھولیں"
@@ -13109,6 +13113,10 @@ msgstr "تھیم فولڈر اسکین کی حد سے بڑا ہونے کی وج
msgid "Some skills were deleted with a warning"
msgstr "کچھ مہارتیں انتباہ کے ساتھ حذف ہوئیں"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "ہو سکتا ہے کسی نے {filePath} کا تنازع پہلے ہی حل کر دیا ہو — اپنی ترمیم دوبارہ کرنے سے پہلے دستاویز کا موجودہ مواد دیکھ لیں۔"
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "کچھ ٹوٹ گیا"
@@ -14389,10 +14397,6 @@ msgstr "یہ تبصرہ پوری خصوصیت پر ہے"
msgid "This composer doesn't accept attachments."
msgstr "یہاں فائلیں منسلک نہیں کی جا سکتیں۔"
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "یہ تنازع حل ہو گیا ہے۔"
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "اسے سیٹ اپ نہیں کیا جا سکا کیونکہ اس کے لیے درکار MCP سرور اندراج نہیں لکھا گیا۔"
@@ -15492,6 +15496,10 @@ msgstr "صرف چھوٹے حروف، ہندسے اور <0>-</0> استعمال
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "صرف چھوٹے حروف، اعداد اور ڈیش استعمال کریں"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "ان کا ورژن لیں"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "یہ ابتدائی پیک استعمال کریں"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 96e80e1db..c72d73933 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -90,6 +90,11 @@
["fileName"],
")"
],
+ "0bV3uj": [
+ "可能已有人解决了 ",
+ ["filePath"],
+ " 的冲突 — 请先查看文档的当前内容,再重做你的编辑。"
+ ],
"0cGsQh": ["包含的内容"],
"0cspe_": ["删除行"],
"0dslv8": [
@@ -307,6 +312,7 @@
"3aeN7X": ["所有文件"],
"3cOo2C": ["基于当前文档或文件夹创建一个文件夹。"],
"3ePd3I": ["新功能"],
+ "3fOsvq": ["使用对方的版本"],
"3h5zMp": ["加载设置面板时出了点问题。"],
"3iyGWF": ["打开最近的项目"],
"3jod3l": ["连接 GitHub"],
@@ -2015,6 +2021,7 @@
"RB_g_C": [
"在根索引上,okf_version 被写为带引号的字符串,如 \"0.2\"。不加引号,YAML 将其读取为数字,0.10 默默地变成 0.1。"
],
+ "RCMt3v": ["此路径没有正在跟踪的冲突。"],
"RD6H9q": [
"当文档更改时,Open Knowledge 会重写这些 index.md 文件,因此对它们的手动编辑将被替换。"
],
@@ -2064,6 +2071,7 @@
"Rah7yq": ["希望 AI 做什么?(可选)"],
"Rb1zMa": ["没有摘要"],
"RcrskJ": ["排版看起来不对"],
+ "RduDYw": ["<0>", ["filePath"], "</0> 无法在这里合并。请选择要保留的版本。"],
"RfHNf8": ["打开 ", ["tooltipName"], " 的活动面板"],
"RfaEio": ["切换源码注释"],
"RfilGt": ["没有规则匹配你的筛选条件。"],
@@ -2127,6 +2135,7 @@
"SXCSQd": ["已复制路径"],
"SXEdCq": ["要移动到 ", ["0"], " 吗?"],
"SYfHmN": ["取消固定标签页"],
+ "S_RRZB": ["删除文件"],
"Sad2tK": ["正在发送…"],
"Sbb90e": [
[
@@ -2512,7 +2521,6 @@
"XwZiq2": [
"文件已恢复为较旧的版本。当前版本是 OpenKnowledge 保护的版本。传入版本是恢复的版本。请选择要保留的版本,然后应用更改。"
],
- "XzL7x7": ["重新打开 ", ["filePath"], " 以继续编辑。"],
"Xzy0s0": ["把 ", ["fullLabel"], " 从上下文中移除"],
"Y-Urt2": ["由 LaTeX 源码经 KaTeX 渲染的独立数学公式。"],
"Y1QMlM": ["开始设置"],
@@ -3325,7 +3333,6 @@
"为你的产品是怎么做出来的留下书面记录。一个提出想法、记录决策、撰写规格,以及在出问题后总结经验的地方。"
],
"hCattk": ["OpenKnowledge 导入了 ", ["source"]],
- "hCghAK": ["此冲突已解决。"],
"hDEaQu": ["把 OpenKnowledge 与你使用的其他工具连接起来。"],
"hDKtoF": [["diffHrs"], " 小时前"],
"hDoLrm": ["把 ", ["projectName"], " 从最近的项目中移除"],
@@ -3522,7 +3529,6 @@
"jSg1tA": ["更多操作(", ["syncAttentionLabel"], ")"],
"jTLWxh": ["用内联 iframe 嵌入外部页面(文档、演示、Figma、CodeSandbox)。"],
"jTUxaN": ["启用自动(仅拉取)"],
- "jTdrn1": ["无法确认 ", ["filePath"], " 是否仍有冲突 — 正在重试。"],
"jWwQo6": ["批次"],
"jWzDfC": ["正在检查你安装了哪些 AI 工具"],
"jZ_E5M": ["获取失败——详情请查看服务器日志。"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 5ccce8164..356cbb2f5 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> 不是已知的组件。复制源码以便在别处使
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> 渲染失败(很可能是属性有误)。复制源码看看哪里出了问题,或删除这个块。"
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> 无法在这里合并。请选择要保留的版本。"
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>镜像——请选择一个来源。</0>在属性面板中设置 <1>src</1> + <2>anchor</2>,指向别处的 <3><MirrorSource></3>。"
@@ -3908,10 +3912,6 @@ msgstr "无法更改拼写检查。请重试。"
msgid "Couldn't change the spelling languages. Try again."
msgstr "无法更改拼写检查语言。请重试。"
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "无法确认 {filePath} 是否仍有冲突 — 正在重试。"
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "删除选中的表格"
msgid "Delete table"
msgstr "删除表格"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "删除文件"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "删除此对话?"
@@ -9021,6 +9025,10 @@ msgstr "还没有评论。在文档中选中文本即可添加。"
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "没有共同祖先 — 两个分支都新增了此文件(add/add 冲突)。"
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "此路径没有正在跟踪的冲突。"
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "这个版本没有内容改动。"
@@ -11475,10 +11483,6 @@ msgstr "已渲染"
msgid "Reopen"
msgstr "重新打开"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "重新打开 {filePath} 以继续编辑。"
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "重新打开之前的对话"
@@ -13109,6 +13113,10 @@ msgstr "因为主题文件夹超出扫描限制,部分已保存的主题未显
msgid "Some skills were deleted with a warning"
msgstr "部分技能删除时带有警告"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "可能已有人解决了 {filePath} 的冲突 — 请先查看文档的当前内容,再重做你的编辑。"
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "有东西坏了"
@@ -14389,10 +14397,6 @@ msgstr "这条评论针对的是整个属性"
msgid "This composer doesn't accept attachments."
msgstr "此处无法添加附件。"
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "此冲突已解决。"
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "无法完成设置,因为它所需的 MCP 服务器条目未写入。"
@@ -15492,6 +15496,10 @@ msgstr "只能使用小写字母、数字和 <0>-</0>。"
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "只能使用小写字母、数字和连字符"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "使用对方的版本"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "使用此入门包"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 52bf49766..13c7a353c 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -90,6 +90,11 @@
["fileName"],
")"
],
+ "0bV3uj": [
+ "可能已有人解決了 ",
+ ["filePath"],
+ " 的衝突 — 請先查看文件的目前內容,再重做你的編輯。"
+ ],
"0cGsQh": ["包含哪些內容"],
"0cspe_": ["刪除列"],
"0dslv8": [
@@ -309,6 +314,7 @@
"3aeN7X": ["所有檔案"],
"3cOo2C": ["依目前的文件或資料夾情境建立一個資料夾。"],
"3ePd3I": ["新功能"],
+ "3fOsvq": ["使用對方的版本"],
"3h5zMp": ["載入設定面板時出了點問題。"],
"3iyGWF": ["開啟最近的專案"],
"3jod3l": ["連接 GitHub"],
@@ -2033,6 +2039,7 @@
"RB_g_C": [
"在根索引上,okf_version 被寫為引號的字串,如 \"0.2\"。不加引號,YAML 將其讀為數字,0.10 默默地變成 0.1。"
],
+ "RCMt3v": ["此路徑沒有正在追蹤的衝突。"],
"RD6H9q": [
"當文件變更時,Open Knowledge 會重寫這些 index.md 文件,因此對它們的手動編輯將會被取代。"
],
@@ -2082,6 +2089,7 @@
"Rah7yq": ["希望 AI 做什麼?(選填)"],
"Rb1zMa": ["沒有摘錄"],
"RcrskJ": ["排版看起來不對"],
+ "RduDYw": ["<0>", ["filePath"], "</0> 無法在這裡合併。請選擇要保留的版本。"],
"RfHNf8": ["開啟 ", ["tooltipName"], " 的活動面板"],
"RfaEio": ["切換原始碼註解"],
"RfilGt": ["沒有規則符合你的篩選條件。"],
@@ -2145,6 +2153,7 @@
"SXCSQd": ["已複製路徑"],
"SXEdCq": ["要移動到 ", ["0"], " 嗎?"],
"SYfHmN": ["取消釘選分頁"],
+ "S_RRZB": ["刪除檔案"],
"Sad2tK": ["正在傳送…"],
"Sbb90e": [
[
@@ -2532,7 +2541,6 @@
"XwZiq2": [
"檔案已還原為較舊的版本。目前版本是 OpenKnowledge 保護的版本。傳入版本是還原的版本。請選擇要保留的版本,然後套用變更。"
],
- "XzL7x7": ["重新開啟 ", ["filePath"], " 以繼續編輯。"],
"Xzy0s0": ["把 ", ["fullLabel"], " 從脈絡中移除"],
"Y-Urt2": ["由 LaTeX 原始碼經 KaTeX 顯示的獨立數學公式。"],
"Y1QMlM": ["開始設定"],
@@ -3347,7 +3355,6 @@
"為你的產品是怎麼做出來的留下書面記錄。一個提出想法、記錄決策、撰寫規格,以及在出事之後總結心得的地方。"
],
"hCattk": ["OpenKnowledge 匯入了 ", ["source"]],
- "hCghAK": ["此衝突已解決。"],
"hDEaQu": ["把 OpenKnowledge 和你用的其他工具連接起來。"],
"hDKtoF": [["diffHrs"], " 小時前"],
"hDoLrm": ["把 ", ["projectName"], " 從最近的專案中移除"],
@@ -3540,7 +3547,6 @@
"jSg1tA": ["更多動作(", ["syncAttentionLabel"], ")"],
"jTLWxh": ["用行內 iframe 嵌入外部頁面(說明文件、示範、Figma、CodeSandbox)。"],
"jTUxaN": ["啟用自動(僅拉取)"],
- "jTdrn1": ["無法確認 ", ["filePath"], " 是否仍有衝突 — 正在重試。"],
"jWwQo6": ["批次"],
"jWzDfC": ["正在檢查你安裝了哪些 AI 工具"],
"jZ_E5M": ["取得失敗——詳情請看伺服器記錄。"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index b678444d1..0a2fa7aa2 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -1219,6 +1219,10 @@ msgstr "<{componentName}> 不是已知的元件。複製原始碼以便在別處
msgid "<{descriptorLabel}> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
msgstr "<{descriptorLabel}> 顯示失敗(很可能是屬性有誤)。複製原始碼看看哪裡出了問題,或刪除這個區塊。"
+#: src/components/DiffViewBoundary.tsx
+msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."
+msgstr "<0>{filePath}</0> 無法在這裡合併。請選擇要保留的版本。"
+
#: src/editor/components/Mirror.tsx
msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."
msgstr "<0>鏡像——請挑一個來源。</0>在屬性面板中設定 <1>src</1> + <2>anchor</2>,指向別處的 <3><MirrorSource></3>。"
@@ -3908,10 +3912,6 @@ msgstr "無法變更拼字檢查。請重試。"
msgid "Couldn't change the spelling languages. Try again."
msgstr "無法變更拼字檢查語言。請重試。"
-#: src/components/DiffViewBoundary.tsx
-msgid "Couldn't check whether {filePath} is still conflicted — retrying."
-msgstr "無法確認 {filePath} 是否仍有衝突 — 正在重試。"
-
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/TerminalAgentConnectionBanner.tsx
msgid "Couldn't check which tools are connected."
@@ -4789,6 +4789,10 @@ msgstr "刪除選取的表格"
msgid "Delete table"
msgstr "刪除表格"
+#: src/components/DiffViewBoundary.tsx
+msgid "Delete the file"
+msgstr "刪除檔案"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this chat?"
msgstr "刪除此對話?"
@@ -9021,6 +9025,10 @@ msgstr "還沒有註解。在文件中選取文字就能加上一則。"
msgid "No common ancestor — both branches added this file (add/add conflict)."
msgstr "沒有共同祖先 — 兩個分支都新增了此檔案(add/add 衝突)。"
+#: src/components/DiffViewBoundary.tsx
+msgid "No conflict is tracked for this path."
+msgstr "此路徑沒有正在追蹤的衝突。"
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "這個版本沒有內容變更。"
@@ -11475,10 +11483,6 @@ msgstr "已顯示"
msgid "Reopen"
msgstr "重新開啟"
-#: src/components/DiffViewBoundary.tsx
-msgid "Reopen {filePath} to keep editing."
-msgstr "重新開啟 {filePath} 以繼續編輯。"
-
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Reopen a past chat"
msgstr "重新開啟先前的對話"
@@ -13109,6 +13113,10 @@ msgstr "因為主題資料夾超出掃描限制,部分已儲存的主題未顯
msgid "Some skills were deleted with a warning"
msgstr "部分技能刪除時帶有警告"
+#: src/components/DiffViewBoundary.tsx
+msgid "Someone may have already resolved {filePath} — check the document's current content before redoing your edit."
+msgstr "可能已有人解決了 {filePath} 的衝突 — 請先查看文件的目前內容,再重做你的編輯。"
+
#: src/components/FeedbackForm.tsx
msgid "Something broke"
msgstr "有東西壞了"
@@ -14389,10 +14397,6 @@ msgstr "這則註解是針對整個屬性的"
msgid "This composer doesn't accept attachments."
msgstr "此處無法附加檔案。"
-#: src/components/DiffViewBoundary.tsx
-msgid "This conflict is resolved."
-msgstr "此衝突已解決。"
-
#: src/components/settings/AgentConnectionDialogs.tsx
msgid "This could not be set up because the MCP server entry it needs was not written."
msgstr "無法完成設定,因為它所需的 MCP 伺服器項目未寫入。"
@@ -15492,6 +15496,10 @@ msgstr "只能用小寫字母、數字和 <0>-</0>。"
msgid "Use lowercase letters, numbers, and hyphens only"
msgstr "只能用小寫字母、數字和連字號"
+#: src/components/DiffViewBoundary.tsx
+msgid "Use their version"
+msgstr "使用對方的版本"
+
#: src/components/CreateProjectDialog.tsx
msgid "Use this starter pack"
msgstr "使用此入門套件"
diff --git a/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts b/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts
index 1874627fd..98f08c8b0 100644
--- a/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts
@@ -60,11 +60,7 @@ describe('sync-resolve-conflict envelope (RFC 9457)', () => {
});
function trackConflict(file: string): void {
- const engine = server.instance.syncEngine;
- if (!engine) throw new Error('expected a SyncEngine on the test harness');
- const store = (engine as unknown as { conflictStore: { addConflict: (e: unknown) => boolean } })
- .conflictStore;
- store.addConflict({ file, detectedAt: new Date().toISOString() });
+ server.instance.conflicts.raise({ kind: 'merge-native', file });
}
test('content still carrying a conflict block is a typed 422, not a 500', async () => {
diff --git a/packages/app/tests/integration/api-error-envelope/test-reset.test.ts b/packages/app/tests/integration/api-error-envelope/test-reset.test.ts
index 95fd4e1bf..8d9a9e88b 100644
--- a/packages/app/tests/integration/api-error-envelope/test-reset.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/test-reset.test.ts
@@ -27,6 +27,27 @@ describe('test-reset envelope (RFC 9457)', () => {
expect((body as Record<string, unknown>).ok).toBeUndefined();
});
+ test('clears stale-write durability and its reconcile conflict', async () => {
+ const docName = `test-reset-stale-${crypto.randomUUID().slice(0, 8)}`;
+ const state = server.instance.durabilityState;
+ state.setReconciledBase(docName, 'current\n');
+ state.recordDisplacedVersion(docName, 'seed\n');
+ state.recordStaleExternalWrite(docName, 'seed\n', 'current\n');
+
+ expect(server.instance.conflicts.findByDocName(docName)?.reason).toBe('stale-external-write');
+
+ const res = await fetch(
+ `http://127.0.0.1:${server.port}/api/test-reset?docName=${encodeURIComponent(docName)}`,
+ { method: 'POST' },
+ );
+
+ expect(res.status).toBe(200);
+ expect(state.getReconciledBase(docName)).toBeUndefined();
+ expect(state.isDisplacedVersion(docName, 'seed\n')).toBe(false);
+ expect(state.getStaleExternalWrite(docName)).toBeUndefined();
+ expect(server.instance.conflicts.findByDocName(docName)).toBeUndefined();
+ });
+
test('path-traversal docName emits 400 urn:ok:error:invalid-request', async () => {
const res = await fetch(
`http://127.0.0.1:${server.port}/api/test-reset?docName=${encodeURIComponent('../escape')}`,
diff --git a/packages/app/tests/integration/conflict-authority-reconcile.test.ts b/packages/app/tests/integration/conflict-authority-reconcile.test.ts
new file mode 100644
index 000000000..86dfb4348
--- /dev/null
+++ b/packages/app/tests/integration/conflict-authority-reconcile.test.ts
@@ -0,0 +1,344 @@
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ createSyncWiredTestServer,
+ createTestClient,
+ createTestServer,
+ pollUntil,
+ type TestServer,
+} from './test-harness';
+
+const BASE_CONTENT = '# Doc\n\nalpha\n\nbeta\n';
+const DISK_CONTENT = '# Doc\n\nalpha-disk\n\nbeta\n';
+const MARKER_CONTENT =
+ '# Doc\n\n<<<<<<< ours\nalpha-ours\n=======\nalpha-theirs\n>>>>>>> theirs\n\nbeta\n';
+
+const STORE_DEBOUNCE_MS = 30_000;
+const STORE_MAX_DEBOUNCE_MS = 60_000;
+
+const cleanups: Array<() => Promise<void> | void> = [];
+
+afterEach(async () => {
+ while (cleanups.length > 0) {
+ await cleanups.pop()?.();
+ }
+}, 60_000);
+
+interface ConflictRow {
+ file: string;
+ conflict?: string;
+ reason?: string;
+ docName?: string | null;
+}
+
+async function listConflicts(port: number): Promise<ConflictRow[]> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`).catch(() => null);
+ if (!res?.ok) return [];
+ const data = (await res.json()) as { conflicts?: ConflictRow[] };
+ return data.conflicts ?? [];
+}
+
+async function conflictContent(
+ port: number,
+ file: string,
+): Promise<{ status: number; body: Record<string, unknown> }> {
+ const res = await fetch(
+ `http://127.0.0.1:${port}/api/sync/conflict-content?file=${encodeURIComponent(file)}&source=ytext`,
+ );
+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
+ return { status: res.status, body };
+}
+
+async function writeProbe(port: number, docName: string, markdown: string): Promise<number> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, markdown, position: 'replace', agentId: 'probe' }),
+ });
+ return res.status;
+}
+
+async function resolveConflict(
+ port: number,
+ file: string,
+ strategy: string,
+ content?: string,
+): Promise<number> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ file,
+ strategy,
+ ...(content === undefined ? {} : { content }),
+ }),
+ });
+ return res.status;
+}
+
+async function assertStaysAbsent(filePath: string, windowMs: number): Promise<void> {
+ const start = Date.now();
+ while (Date.now() - start < windowMs) {
+ if (existsSync(filePath)) {
+ throw new Error(
+ `file resurrected ${Date.now() - start}ms after a delete resolution: ${filePath}\n` +
+ `content: ${JSON.stringify(readFileSync(filePath, 'utf-8').slice(0, 160))}`,
+ );
+ }
+ await wait(100);
+ }
+}
+
+async function seedDoc(server: TestServer, docName: string): Promise<void> {
+ writeFileSync(join(server.contentDir, `${docName}.md`), BASE_CONTENT, 'utf-8');
+ await pollUntil(
+ async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
+ if (!res?.ok) return false;
+ const data = (await res.json()) as { documents?: Array<{ docName: string }> };
+ return data.documents?.some((d) => d.docName === docName) ?? false;
+ },
+ 30_000,
+ 100,
+ `${docName} to be indexed`,
+ );
+}
+
+async function driveReconcileConflict(
+ server: TestServer,
+ docName: string,
+): Promise<Awaited<ReturnType<typeof createTestClient>>> {
+ const client = await createTestClient(server.port, docName);
+ cleanups.push(() => client.cleanup());
+ await pollUntil(() => client.ytext.toString().includes('alpha'), 15_000);
+
+ const current = client.ytext.toString();
+ const at = current.indexOf('alpha');
+ client.doc.transact(() => {
+ client.ytext.delete(at, 'alpha'.length);
+ client.ytext.insert(at, 'alpha-editor');
+ });
+ await pollUntil(() => client.ytext.toString().includes('alpha-editor'), 5_000);
+ writeFileSync(join(server.contentDir, `${docName}.md`), DISK_CONTENT, 'utf-8');
+ return client;
+}
+
+async function assertReconcileConflictIsResolvable(
+ server: TestServer,
+ docName: string,
+ expectedReason: string,
+): Promise<void> {
+ const file = `${docName}.md`;
+
+ await pollUntil(
+ async () => (await listConflicts(server.port)).some((c) => c.file === file),
+ 30_000,
+ 250,
+ `a tracked conflict entry for ${file}`,
+ );
+
+ const entry = (await listConflicts(server.port)).find((c) => c.file === file);
+ expect(entry).toBeDefined();
+ expect(entry?.conflict).toBe('reconcile');
+ expect(entry?.reason).toBe(expectedReason);
+ expect(entry?.docName).toBe(docName);
+
+ const content = await conflictContent(server.port, file);
+ expect(content.status).toBe(200);
+ expect(content.body.conflict).toBe('reconcile');
+ expect(String(content.body.base ?? '').length).toBeGreaterThan(0);
+ expect(String(content.body.ours ?? '').length).toBeGreaterThan(0);
+ expect(String(content.body.theirs ?? '').length).toBeGreaterThan(0);
+
+ expect(await writeProbe(server.port, docName, '# blocked\n')).toBe(409);
+
+ expect(await resolveConflict(server.port, file, 'content', '# Doc\n\nalpha-resolved\n')).toBe(
+ 200,
+ );
+
+ await pollUntil(
+ async () => !(await listConflicts(server.port)).some((c) => c.file === file),
+ 15_000,
+ 100,
+ `the conflict entry for ${file} to clear`,
+ );
+
+ expect(await writeProbe(server.port, docName, '# after\n')).toBe(200);
+}
+
+describe('PRD-7947: a reconcile-born conflict is tracked, inspectable and resolvable', () => {
+ test('shape 1 — a three-way reconcile that conflicts registers a reconcile entry', async () => {
+ const server = await createTestServer({
+ debounce: STORE_DEBOUNCE_MS,
+ maxDebounce: STORE_MAX_DEBOUNCE_MS,
+ });
+ cleanups.push(() => server.cleanup());
+ const docName = `reconcile-conflicts-${crypto.randomUUID()}`;
+ await seedDoc(server, docName);
+ await driveReconcileConflict(server, docName);
+ await assertReconcileConflictIsResolvable(server, docName, 'merged-with-markers');
+ }, 120_000);
+
+ test('shape 2 — conflict markers landing on disk register a disk-markers entry', async () => {
+ const server = await createTestServer({
+ debounce: STORE_DEBOUNCE_MS,
+ maxDebounce: STORE_MAX_DEBOUNCE_MS,
+ });
+ cleanups.push(() => server.cleanup());
+ const docName = `reconcile-markers-${crypto.randomUUID()}`;
+ await seedDoc(server, docName);
+
+ const client = await createTestClient(server.port, docName);
+ cleanups.push(() => client.cleanup());
+ await pollUntil(() => client.ytext.toString().includes('alpha'), 15_000);
+
+ writeFileSync(join(server.contentDir, `${docName}.md`), MARKER_CONTENT, 'utf-8');
+
+ await assertReconcileConflictIsResolvable(server, docName, 'disk-markers');
+ }, 120_000);
+
+ test('shape 3 — the same reconcile conflict is tracked with sync wired to a remote', async () => {
+ const docName = `reconcile-sync-${crypto.randomUUID()}`;
+ const server = await createSyncWiredTestServer({
+ originSeed: { [`${docName}.md`]: BASE_CONTENT },
+ serverOptions: { debounce: STORE_DEBOUNCE_MS, maxDebounce: STORE_MAX_DEBOUNCE_MS },
+ });
+ cleanups.push(() => server.cleanup());
+
+ await pollUntil(
+ async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
+ if (!res?.ok) return false;
+ const data = (await res.json()) as { documents?: Array<{ docName: string }> };
+ return data.documents?.some((d) => d.docName === docName) ?? false;
+ },
+ 30_000,
+ 100,
+ `${docName} to be indexed`,
+ );
+
+ await driveReconcileConflict(server, docName);
+ await assertReconcileConflictIsResolvable(server, docName, 'merged-with-markers');
+ }, 180_000);
+});
+
+describe('PRD-7947: the editor-side edit survives into the conflict stages', () => {
+ test('the reconcile entry carries the pre-conflict editor text as `ours`', async () => {
+ const server = await createTestServer({
+ debounce: STORE_DEBOUNCE_MS,
+ maxDebounce: STORE_MAX_DEBOUNCE_MS,
+ });
+ cleanups.push(() => server.cleanup());
+ const docName = `reconcile-stages-${crypto.randomUUID()}`;
+ await seedDoc(server, docName);
+ await driveReconcileConflict(server, docName);
+
+ const file = `${docName}.md`;
+ await pollUntil(
+ async () => (await listConflicts(server.port)).some((c) => c.file === file),
+ 30_000,
+ 250,
+ `a tracked conflict entry for ${file}`,
+ );
+
+ const content = await conflictContent(server.port, file);
+ expect(content.status).toBe(200);
+ expect(String(content.body.theirs ?? '')).toContain('alpha-disk');
+ expect(String(content.body.ours ?? '')).toContain('alpha-editor');
+ expect(content.body.resolutionOptions).toEqual(
+ expect.arrayContaining(['mine', 'content', 'delete']),
+ );
+ }, 120_000);
+
+ test('mine lands marker-free editor text added after the conflict was raised', async () => {
+ const server = await createTestServer({
+ debounce: STORE_DEBOUNCE_MS,
+ maxDebounce: STORE_MAX_DEBOUNCE_MS,
+ });
+ cleanups.push(() => server.cleanup());
+ const docName = `reconcile-live-ours-${crypto.randomUUID()}`;
+ const file = `${docName}.md`;
+ await seedDoc(server, docName);
+ const client = await driveReconcileConflict(server, docName);
+
+ await pollUntil(
+ async () => (await listConflicts(server.port)).some((c) => c.file === file),
+ 30_000,
+ 250,
+ `a tracked conflict entry for ${file}`,
+ );
+
+ client.ytext.insert(client.ytext.length, '\npost-conflict editor text\n');
+ let preview = '';
+ await pollUntil(
+ async () => {
+ const content = await conflictContent(server.port, file);
+ preview = String(content.body.ours ?? '');
+ return preview.includes('post-conflict editor text');
+ },
+ 15_000,
+ 100,
+ 'the live editor text to reach the conflict preview',
+ );
+
+ expect(await resolveConflict(server.port, file, 'mine')).toBe(200);
+ expect(readFileSync(join(server.contentDir, file), 'utf-8')).toBe(preview);
+ await pollUntil(
+ () => client.ytext.toString() === preview,
+ 15_000,
+ 100,
+ 'the client to retain previewed text',
+ );
+ }, 120_000);
+});
+
+describe('PRD-7947: resolving a reconcile conflict with `delete` keeps the file gone', () => {
+ test('a keystroke from the still-open editor does not restore the deleted file', async () => {
+ const server = await createTestServer({
+ debounce: STORE_DEBOUNCE_MS,
+ maxDebounce: STORE_MAX_DEBOUNCE_MS,
+ });
+ cleanups.push(() => server.cleanup());
+ const docName = `reconcile-delete-${crypto.randomUUID()}`;
+ const file = `${docName}.md`;
+ const absPath = join(server.contentDir, file);
+
+ await seedDoc(server, docName);
+ const client = await createTestClient(server.port, docName);
+ cleanups.push(() => client.cleanup());
+ await pollUntil(() => client.ytext.toString().includes('alpha'), 15_000);
+
+ const at = client.ytext.toString().indexOf('alpha');
+ client.doc.transact(() => {
+ client.ytext.delete(at, 'alpha'.length);
+ client.ytext.insert(at, 'alpha-editor');
+ });
+ await pollUntil(() => client.ytext.toString().includes('alpha-editor'), 5_000);
+ writeFileSync(absPath, DISK_CONTENT, 'utf-8');
+
+ await pollUntil(
+ async () => (await listConflicts(server.port)).some((c) => c.file === file),
+ 30_000,
+ 250,
+ `a tracked conflict entry for ${file}`,
+ );
+
+ const content = await conflictContent(server.port, file);
+ expect(content.status).toBe(200);
+ expect(await resolveConflict(server.port, file, 'delete')).toBe(200);
+
+ await pollUntil(
+ async () => !(await listConflicts(server.port)).some((c) => c.file === file),
+ 15_000,
+ 100,
+ `the conflict entry for ${file} to clear`,
+ );
+ expect(existsSync(absPath)).toBe(false);
+
+ client.ytext.insert(client.ytext.length, '\npost-delete keystroke\n');
+ server.instance.hocuspocus.flushPendingStores();
+ await assertStaysAbsent(absPath, 5_000);
+ }, 120_000);
+});
diff --git a/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts b/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts
index 789800b90..c1af17ff3 100644
--- a/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts
+++ b/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts
@@ -2,19 +2,30 @@ import { execFile } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
-import {
- bootServer,
- ConfigSchema,
- getLocalDir,
- getLogger,
- restoreLifecycleFromConflictsJson,
-} from '@inkeep/open-knowledge-server';
+import { bootServer, ConfigSchema, getLocalDir } from '@inkeep/open-knowledge-server';
import { describe, expect, test } from 'vitest';
import { createTestClient, createTestServer, pollUntil, type TestServer } from './test-harness';
const execFileAsync = promisify(execFile);
const BASE_CONTENT = '# Base\n\nBase paragraph.\n';
+const MARKED_CONTENT =
+ '<<<<<<< ours\n# Base\n\nBase paragraph.\n=======\n# Theirs\n>>>>>>> theirs\n';
+
+async function listConflicts(port: number): Promise<Array<Record<string, unknown>>> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`).catch(() => null);
+ if (!res?.ok) return [];
+ const data = (await res.json()) as { conflicts?: Array<Record<string, unknown>> };
+ return data.conflicts ?? [];
+}
+
+async function agentWrite(port: number, docName: string, markdown: string): Promise<Response> {
+ return fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, markdown, position: 'replace', agentId: 'a', agentName: 'A' }),
+ });
+}
async function setupServerWithDoc(
docName: string,
@@ -33,7 +44,7 @@ async function setupServerWithDoc(
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- });
+ }, 30_000);
return server;
}
@@ -107,7 +118,7 @@ async function seedRealMergeConflict(projectDir: string, files: string[]): Promi
}
}
-describe('FR1 + FR2: lifecycle swap-in / swap-out (server-observable contract)', () => {
+describe('FR1 + FR2: conflict-gate swap-in / swap-out (server-observable contract)', () => {
test('swap-in sets gate (mutations refuse); swap-out clears gate (mutations succeed); Y.Text bytes preserved', async () => {
const cleanups: Array<() => Promise<void> | void> = [];
try {
@@ -124,63 +135,32 @@ describe('FR1 + FR2: lifecycle swap-in / swap-out (server-observable contract)',
const ytextBefore = serverDoc.getText('source').toString();
expect(ytextBefore).toContain('Base paragraph');
- const lifecycleMap = serverDoc.getMap('lifecycle');
+ const authority = server.instance.conflicts;
- expect(lifecycleMap.get('status')).toBeUndefined();
- const preGateRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- docName,
- markdown: BASE_CONTENT,
- position: 'replace',
- agentId: 'a',
- agentName: 'A',
- }),
- });
+ expect(authority.has(docName)).toBe(false);
+ const preGateRes = await agentWrite(server.port, docName, BASE_CONTENT);
expect(preGateRes.ok).toBe(true);
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'conflict-markers');
-
- expect(lifecycleMap.get('status')).toBe('conflict');
- expect(lifecycleMap.get('reason')).toBe('conflict-markers');
-
- const inConflictRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- docName,
- markdown: '# Replacement\n',
- position: 'replace',
- agentId: 'a',
- agentName: 'A',
- }),
+ authority.raise({
+ kind: 'reconcile',
+ file: `${docName}.md`,
+ reason: 'disk-markers',
+ stages: { base: BASE_CONTENT, ours: ytextBefore, theirs: BASE_CONTENT },
});
+ expect(authority.has(docName)).toBe(true);
+
+ const inConflictRes = await agentWrite(server.port, docName, '# Replacement\n');
expect(inConflictRes.status).toBe(409);
expect(inConflictRes.headers.get('content-type')).toContain('application/problem+json');
const body = (await inConflictRes.json()) as Record<string, unknown>;
expect(body.type).toBe('urn:ok:error:doc-in-conflict');
- lifecycleMap.delete('status');
- lifecycleMap.delete('reason');
-
- expect(lifecycleMap.get('status')).toBeUndefined();
- expect(lifecycleMap.get('reason')).toBeUndefined();
+ authority.dissolveReconcile(docName);
+ expect(authority.has(docName)).toBe(false);
expect(serverDoc.getText('source').toString()).toBe(ytextBefore);
- const postGateRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- docName,
- markdown: BASE_CONTENT,
- position: 'replace',
- agentId: 'a',
- agentName: 'A',
- }),
- });
+ const postGateRes = await agentWrite(server.port, docName, BASE_CONTENT);
expect(postGateRes.ok).toBe(true);
} finally {
while (cleanups.length > 0) await cleanups.pop()?.();
@@ -188,8 +168,8 @@ describe('FR1 + FR2: lifecycle swap-in / swap-out (server-observable contract)',
}, 30_000);
});
-describe('FR11: reconciliation conflict path sets lifecycle.status and fires the FR9 gate', () => {
- test('reconcile case "conflicts" sets lifecycle.status="conflict" + mutating handler returns 409', async () => {
+describe('FR11: the reconciliation conflict path raises an entry and fires the FR9 gate', () => {
+ test('reconcile case "conflicts" raises a reconcile entry + mutating handler returns 409', async () => {
const cleanups: Array<() => Promise<void> | void> = [];
try {
const docName = `fr11-${crypto.randomUUID()}`;
@@ -202,13 +182,11 @@ describe('FR11: reconciliation conflict path sets lifecycle.status and fires the
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- });
+ }, 30_000);
const client = await createTestClient(server.port, docName);
cleanups.push(() => client.cleanup());
- await pollUntil(() => client.ytext.toString().includes('First paragraph'));
-
- const lifecycle = client.doc.getMap('lifecycle');
+ await pollUntil(() => client.ytext.toString().includes('First paragraph'), 30_000);
const baseOffset = client.ytext.toString().indexOf('First paragraph.');
const baseLen = 'First paragraph.'.length;
@@ -224,21 +202,16 @@ describe('FR11: reconciliation conflict path sets lifecycle.status and fires the
const theirsContent = '# Heading\n\nTheir version of first paragraph.\n\nSecond paragraph.\n';
writeFileSync(join(server.contentDir, `${docName}.md`), theirsContent, 'utf-8');
- await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
- expect(lifecycle.get('status')).toBe('conflict');
- expect(lifecycle.get('reason')).toBe('merged-with-markers');
+ await pollUntil(
+ async () => (await listConflicts(server.port)).some((c) => c.file === `${docName}.md`),
+ 10_000,
+ );
+ const entry = (await listConflicts(server.port)).find((c) => c.file === `${docName}.md`);
+ expect(entry?.conflict).toBe('reconcile');
+ expect(entry?.reason).toBe('merged-with-markers');
+ expect(entry?.docName).toBe(docName);
- const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- docName,
- markdown: '# Replacement\n',
- position: 'replace',
- agentId: 'a',
- agentName: 'A',
- }),
- });
+ const res = await agentWrite(server.port, docName, '# Replacement\n');
expect(res.status).toBe(409);
const body = (await res.json()) as Record<string, unknown>;
expect(body.type).toBe('urn:ok:error:doc-in-conflict');
@@ -290,11 +263,7 @@ describe('FR12: /api/sync/conflicts + /api/sync/status count parity', () => {
const resolveRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- file: fileA,
- strategy: 'content',
- content: '# A resolved\n',
- }),
+ body: JSON.stringify({ file: fileA, strategy: 'content', content: '# A resolved\n' }),
});
expect(resolveRes.ok).toBe(true);
@@ -314,109 +283,58 @@ describe('FR12: /api/sync/conflicts + /api/sync/status count parity', () => {
}, 45_000);
});
-describe('FR14: lifecycle restore function (in-process; CI-runnable)', () => {
- test('restoreLifecycleFromConflictsJson sets lifecycle.status on each tracked doc', async () => {
+describe('FR14: a conflicts.json present at construction gates writes (in-process)', () => {
+ test('a seeded ledger entry is listed and refuses the write on a doc never loaded before', async () => {
const cleanups: Array<() => Promise<void> | void> = [];
try {
- const docName = `fr14-fn-${crypto.randomUUID()}`;
- const server = await setupServerWithDoc(docName, BASE_CONTENT, cleanups);
- await seedRealMergeConflict(server.contentDir, [`${docName}.md`]);
- seedConflictsJson(server.contentDir, [{ file: `${docName}.md` }]);
-
- const warnLines: string[] = [];
- const originalWarn = console.warn;
- console.warn = (msg: unknown, ...rest: unknown[]) => {
- warnLines.push(typeof msg === 'string' ? msg : String(msg));
- originalWarn.call(console, msg, ...rest);
- };
- cleanups.push(() => {
- console.warn = originalWarn;
- });
+ const { mkdtempSync, realpathSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const tmpDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-fr14-fn-')));
+ cleanups.push(() => rmSync(tmpDir, { recursive: true, force: true }));
- await restoreLifecycleFromConflictsJson({
- hocuspocus: server.instance.hocuspocus,
- projectDir: server.contentDir,
- log: getLogger('fr14-fn-test'),
- });
+ mkdirSync(join(tmpDir, '.ok'), { recursive: true });
+ writeFileSync(join(tmpDir, '.ok', 'config.yml'), '', 'utf-8');
+ await execFileAsync('git', ['init', '--initial-branch=main', tmpDir]);
- const dc = await server.instance.hocuspocus.openDirectConnection(docName);
- try {
- const lifecycleMap = dc.document?.getMap('lifecycle');
- expect(lifecycleMap?.get('status')).toBe('conflict');
- expect(lifecycleMap?.get('reason')).toBe('conflict-markers');
- } finally {
- await dc.disconnect();
- }
+ const docName = `fr14-fn-${crypto.randomUUID()}`;
+ await seedRealMergeConflict(tmpDir, [`${docName}.md`]);
+ seedConflictsJson(tmpDir, [{ file: `${docName}.md` }]);
- const restoredEvent = warnLines.find((l) => {
- try {
- const parsed = JSON.parse(l) as { event?: string; 'doc.name'?: string };
- return (
- parsed.event === 'lifecycle-restored-from-conflicts-json' &&
- parsed['doc.name'] === docName
- );
- } catch (e) {
- if (e instanceof SyntaxError) return false;
- throw e;
- }
- });
- expect(restoredEvent).toBeDefined();
+ const server = await createTestServer({ contentDir: tmpDir, keepContentDir: true });
+ cleanups.push(() => server.cleanup());
- const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- docName,
- markdown: '# replacement\n',
- position: 'replace',
- agentId: 'a',
- agentName: 'A',
- }),
- });
+ const entry = (await listConflicts(server.port)).find((c) => c.file === `${docName}.md`);
+ expect(entry?.conflict).toBe('merge-native');
+ expect(entry?.docName).toBe(docName);
+
+ const res = await agentWrite(server.port, docName, '# replacement\n');
expect(res.status).toBe(409);
} finally {
while (cleanups.length > 0) await cleanups.pop()?.();
}
}, 30_000);
- test('restoreLifecycleFromConflictsJson is a no-op when conflicts.json is missing', async () => {
+ test('with no conflicts.json the ledger is empty and writes are admitted', async () => {
const cleanups: Array<() => Promise<void> | void> = [];
try {
const docName = `fr14-fn-empty-${crypto.randomUUID()}`;
const server = await setupServerWithDoc(docName, BASE_CONTENT, cleanups);
- await restoreLifecycleFromConflictsJson({
- hocuspocus: server.instance.hocuspocus,
- projectDir: server.contentDir,
- log: getLogger('fr14-fn-test'),
- });
- const dc = await server.instance.hocuspocus.openDirectConnection(docName);
- try {
- const lifecycleMap = dc.document?.getMap('lifecycle');
- expect(lifecycleMap?.get('status')).toBeUndefined();
- } finally {
- await dc.disconnect();
- }
+ expect(await listConflicts(server.port)).toEqual([]);
+ expect(server.instance.conflicts.has(docName)).toBe(false);
+
+ const res = await agentWrite(server.port, docName, '# replacement\n');
+ expect(res.ok).toBe(true);
} finally {
while (cleanups.length > 0) await cleanups.pop()?.();
}
}, 30_000);
});
-describe('on-load lifecycle seed from ConflictStore (runtime race fix)', () => {
+describe('a conflict raised while the doc was unloaded still gates its first load', () => {
async function runOnLoadSeedTest(extension: '.md' | '.mdx') {
const cleanups: Array<() => Promise<void> | void> = [];
- const warnLines: string[] = [];
- const originalWarn = console.warn;
- console.warn = (msg: unknown, ...rest: unknown[]) => {
- warnLines.push(typeof msg === 'string' ? msg : String(msg));
- originalWarn.call(console, msg, ...rest);
- };
- cleanups.push(() => {
- console.warn = originalWarn;
- });
-
try {
const { mkdtempSync, realpathSync, rmSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
@@ -447,49 +365,38 @@ describe('on-load lifecycle seed from ConflictStore (runtime race fix)', () => {
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- }, 5_000);
+ }, 30_000);
const client = await createTestClient(server.port, docName, {
skipInvariantWatcher: true,
});
cleanups.push(() => client.cleanup());
- const lifecycle = client.doc.getMap('lifecycle');
- await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
- expect(lifecycle.get('status')).toBe('conflict');
- expect(lifecycle.get('reason')).toBe('conflict-markers');
-
- const seededEvent = warnLines.find((l) => {
- try {
- const parsed = JSON.parse(l) as { event?: string; 'doc.name'?: string };
- return (
- parsed.event === 'lifecycle-seeded-on-load-from-conflict-store' &&
- parsed['doc.name'] === docName
- );
- } catch (e) {
- if (e instanceof SyntaxError) return false;
- throw e;
- }
- });
- expect(seededEvent).toBeDefined();
+ const entry = (await listConflicts(server.port)).find((c) => c.file === fileName);
+ expect(entry?.conflict).toBe('merge-native');
+ expect(entry?.docName).toBe(docName);
+ expect(server.instance.conflicts.has(docName)).toBe(true);
+
+ const res = await agentWrite(server.port, docName, '# replacement\n');
+ expect(res.status).toBe(409);
} finally {
while (cleanups.length > 0) await cleanups.pop()?.();
}
}
- test('.md — first client connect seeds lifecycle.status="conflict" from ConflictStore', async () => {
+ test('.md — a doc tracked before its first load is gated on load', async () => {
await runOnLoadSeedTest('.md');
}, 30_000);
- test('.mdx — first client connect seeds lifecycle.status="conflict" from ConflictStore', async () => {
+ test('.mdx — a doc tracked before its first load is gated on load', async () => {
await runOnLoadSeedTest('.mdx');
}, 30_000);
});
const describeBoot = process.env.CI ? describe.skip : describe;
-describeBoot('FR14: boot-time lifecycle restoration from conflicts.json', () => {
- test('conflicts.json with entry X → lifecycle.status="conflict" set + immediate POST returns 409', async () => {
+describeBoot('FR14: boot-time conflict admission from conflicts.json', () => {
+ test('conflicts.json with entry X → the entry is listed + an immediate POST returns 409', async () => {
const cleanups: Array<() => Promise<void> | void> = [];
try {
const { mkdtempSync, realpathSync, rmSync } = await import('node:fs');
@@ -505,16 +412,6 @@ describeBoot('FR14: boot-time lifecycle restoration from conflicts.json', () =>
await seedRealMergeConflict(tmpDir, [fileName]);
seedConflictsJson(tmpDir, [{ file: fileName }]);
- const warnLines: string[] = [];
- const originalWarn = console.warn;
- console.warn = (msg: unknown, ...rest: unknown[]) => {
- warnLines.push(typeof msg === 'string' ? msg : String(msg));
- originalWarn.call(console, msg, ...rest);
- };
- cleanups.push(() => {
- console.warn = originalWarn;
- });
-
const booted = await bootServer({
config: ConfigSchema.parse({}),
contentDir: tmpDir,
@@ -526,40 +423,11 @@ describeBoot('FR14: boot-time lifecycle restoration from conflicts.json', () =>
cleanups.push(() => booted.destroy());
const docName = fileName.replace(/\.md$/, '');
- const dc = await booted.serverInstance.hocuspocus.openDirectConnection(docName);
- try {
- const lifecycleMap = dc.document?.getMap('lifecycle');
- expect(lifecycleMap?.get('status')).toBe('conflict');
- expect(lifecycleMap?.get('reason')).toBe('conflict-markers');
- } finally {
- await dc.disconnect();
- }
+ const entry = (await listConflicts(booted.port)).find((c) => c.file === fileName);
+ expect(entry?.conflict).toBe('merge-native');
+ expect(entry?.docName).toBe(docName);
- const restoredEvent = warnLines.find((l) => {
- try {
- const parsed = JSON.parse(l) as { event?: string; 'doc.name'?: string };
- return (
- parsed.event === 'lifecycle-restored-from-conflicts-json' &&
- parsed['doc.name'] === docName
- );
- } catch (e) {
- if (e instanceof SyntaxError) return false;
- throw e;
- }
- });
- expect(restoredEvent).toBeDefined();
-
- const res = await fetch(`http://127.0.0.1:${booted.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- docName,
- markdown: '# Replacement\n',
- position: 'replace',
- agentId: 'a',
- agentName: 'A',
- }),
- });
+ const res = await agentWrite(booted.port, docName, '# Replacement\n');
expect(res.status).toBe(409);
const body = (await res.json()) as Record<string, unknown>;
expect(body.type).toBe('urn:ok:error:doc-in-conflict');
@@ -595,11 +463,11 @@ describe('FR16: "Keep mine" dispatched as strategy="content" writes the bytes th
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- });
+ }, 30_000);
const client = await createTestClient(server.port, docName);
cleanups.push(() => client.cleanup());
- await pollUntil(() => client.ytext.toString().includes('Base paragraph'));
+ await pollUntil(() => client.ytext.toString().includes('Base paragraph'), 30_000);
const editMarker = '\n\nUSER EDIT typed mid-session.\n';
client.doc.transact(() => {
@@ -614,28 +482,22 @@ describe('FR16: "Keep mine" dispatched as strategy="content" writes the bytes th
expect(diskBefore).toBe(BASE_CONTENT);
expect(diskBefore).not.toContain('USER EDIT');
- const serverDoc = server.instance.hocuspocus.documents.get(docName);
- if (!serverDoc) throw new Error(`serverDoc not found for ${docName}`);
- const lifecycleMap = serverDoc.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'conflict-markers');
- expect(lifecycleMap.get('status')).toBe('conflict');
- expect(lifecycleMap.get('reason')).toBe('conflict-markers');
-
- const { ConflictStore } = await import('../../../server/src/conflict-storage.ts');
const otherFile = `fr16-other-${crypto.randomUUID()}.md`;
writeFileSync(join(server.contentDir, otherFile), '# Other\n', 'utf-8');
await execFileAsync('git', ['-C', server.contentDir, 'add', otherFile]);
await execFileAsync('git', ['-C', server.contentDir, 'commit', '-m', 'other base']);
- const store = new ConflictStore(server.contentDir, 'main');
- store.addConflict({ file: fileName, detectedAt: '2026-05-19T00:00:00.000Z' });
- store.addConflict({ file: otherFile, detectedAt: '2026-05-19T00:00:00.000Z' });
+
+ const authority = server.instance.conflicts;
+ authority.raise({ kind: 'merge-native', file: fileName });
+ authority.raise({ kind: 'merge-native', file: otherFile });
+ expect(authority.has(docName)).toBe(true);
const ourBytes = client.ytext.toString();
expect(ourBytes).toContain('Base paragraph');
expect(ourBytes).toContain('USER EDIT');
- await store.resolveConflict(fileName, 'content', ourBytes);
+ expect(authority.findByFile(fileName)).toBeDefined();
+ await authority.resolve(fileName, 'content', ourBytes);
const diskAfter = readFileSync(join(server.contentDir, fileName), 'utf-8');
expect(diskAfter).toBe(ourBytes);
@@ -685,11 +547,7 @@ describe('FR17: Conflicts list HTTP shape (data feed the sidebar section consume
const resolveRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- file: fileA,
- strategy: 'content',
- content: '# A resolved\n',
- }),
+ body: JSON.stringify({ file: fileA, strategy: 'content', content: '# A resolved\n' }),
});
expect(resolveRes.ok).toBe(true);
@@ -722,3 +580,129 @@ describe('FR17: Conflicts list HTTP shape (data feed the sidebar section consume
}
}, 45_000);
});
+
+describe('a conflicted doc under a content.dir subdirectory reports its ledger file', () => {
+ interface ConflictEnvelope {
+ file?: string;
+ conflict?: { kind?: string; reason?: string };
+ resolutionOptions?: string[];
+ }
+
+ async function bootSubdirProject(cleanups: Array<() => Promise<void> | void>) {
+ const { mkdtempSync, realpathSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-subdir-conflict-')));
+ cleanups.push(() => rmSync(projectDir, { recursive: true, force: true }));
+
+ await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
+ mkdirSync(join(projectDir, '.ok'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'config.yml'), '', 'utf-8');
+ writeFileSync(join(projectDir, '.ok', '.gitignore'), '', 'utf-8');
+
+ const contentDir = join(projectDir, 'docs');
+ mkdirSync(contentDir, { recursive: true });
+ writeFileSync(join(contentDir, 'note.md'), MARKED_CONTENT, 'utf-8');
+
+ const localDir = getLocalDir(projectDir);
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(
+ join(localDir, 'conflicts.json'),
+ JSON.stringify({
+ version: 1,
+ branch: 'main',
+ conflicts: [
+ {
+ kind: 'reconcile',
+ file: 'docs/note.md',
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ reason: 'disk-markers',
+ stages: { base: BASE_CONTENT, ours: BASE_CONTENT, theirs: '# Theirs\n' },
+ },
+ ],
+ }),
+ 'utf-8',
+ );
+
+ const booted = await bootServer({
+ config: ConfigSchema.parse({}),
+ projectDir,
+ contentDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ });
+ cleanups.push(() => booted.destroy());
+ return booted;
+ }
+
+ test('rename and duplicate return the ledger file plus the per-kind resolution options', async () => {
+ const cleanups: Array<() => Promise<void> | void> = [];
+ try {
+ const booted = await bootSubdirProject(cleanups);
+
+ const listed = await listConflicts(booted.port);
+ expect(listed.map((c) => c.file)).toEqual(['docs/note.md']);
+ expect(listed[0]?.docName).toBe('note');
+
+ const renameRes = await fetch(`http://127.0.0.1:${booted.port}/api/rename-path`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ kind: 'file', fromPath: 'note.md', toPath: 'renamed.md' }),
+ });
+ expect(renameRes.status).toBe(409);
+ const renameBody = (await renameRes.json()) as ConflictEnvelope;
+ expect(renameBody.file).toBe('docs/note.md');
+ expect(renameBody.conflict).toEqual({ kind: 'reconcile', reason: 'disk-markers' });
+ expect(renameBody.resolutionOptions).toEqual(['mine', 'content', 'delete']);
+
+ const dupRes = await fetch(`http://127.0.0.1:${booted.port}/api/duplicate-path`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ kind: 'file', path: 'note.md' }),
+ });
+ expect(dupRes.status).toBe(409);
+ const dupBody = (await dupRes.json()) as ConflictEnvelope;
+ expect(dupBody.file).toBe('docs/note.md');
+ expect(dupBody.resolutionOptions).toEqual(['mine', 'content', 'delete']);
+ } finally {
+ while (cleanups.length > 0) await cleanups.pop()?.();
+ }
+ }, 45_000);
+
+ test('the batch handler 409 entry carries the same conflict envelope without theirs', async () => {
+ const cleanups: Array<() => Promise<void> | void> = [];
+ try {
+ const booted = await bootSubdirProject(cleanups);
+
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/agent-write-batch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ agentId: 'a',
+ agentName: 'A',
+ docs: [{ docName: 'note', markdown: '# Replacement\n', position: 'replace' }],
+ }),
+ });
+ const body = (await res.json()) as {
+ results?: Array<{
+ status: string;
+ error?: {
+ type?: string;
+ detail?: string;
+ conflict?: { kind?: string; reason?: string };
+ resolutionOptions?: string[];
+ };
+ }>;
+ };
+ const entry = body.results?.[0];
+ expect(entry?.status).toBe('error');
+ expect(entry?.error?.type).toBe('urn:ok:error:doc-in-conflict');
+ expect(entry?.error?.conflict).toEqual({ kind: 'reconcile', reason: 'disk-markers' });
+ expect(entry?.error?.resolutionOptions).toEqual(['mine', 'content', 'delete']);
+ expect(entry?.error?.resolutionOptions).not.toContain('theirs');
+ } finally {
+ while (cleanups.length > 0) await cleanups.pop()?.();
+ }
+ }, 45_000);
+});
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 b4bf82702..77132ca53 100644
--- a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
+++ b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
@@ -3,9 +3,10 @@ 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 { createTestClient, createTestServer, pollUntil, type TestServer } from './test-harness';
+import { createTestServer, pollUntil, type TestServer } from './test-harness';
const execFileAsync = promisify(execFile);
@@ -139,6 +140,10 @@ describe('DU (delete-modify) conflict — foundational contract', () => {
});
test("POST /api/sync/resolve-conflict { strategy: 'delete' } succeeds (DU stays deleted)", async () => {
+ const contentResponse = await fetch(
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=foo.md`,
+ );
+ expect(contentResponse.status).toBe(200);
const res = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -181,6 +186,10 @@ describe('UD (modify-delete) conflict — foundational contract', () => {
});
test("POST /api/sync/resolve-conflict { strategy: 'delete' } succeeds (UD accepts deletion)", async () => {
+ const contentResponse = await fetch(
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=foo.md`,
+ );
+ expect(contentResponse.status).toBe(200);
const res = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -206,15 +215,33 @@ describe("POST /api/sync/resolve-conflict { strategy: 'content', content: '' }",
await server.cleanup();
});
- test('explicit empty content keeps an empty file rather than deleting it', async () => {
+ test("empty content NEVER produces a 500 with the misleading 'requires content parameter' detail", async () => {
+ const contentResponse = await fetch(
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=foo.md`,
+ );
+ expect(contentResponse.status).toBe(200);
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: '' }),
});
- expect(res.status).toBe(200);
- expect(readFileSync(join(server.contentDir, 'foo.md'), 'utf-8')).toBe('');
+ 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');
+ }
+ }
});
});
@@ -273,38 +300,4 @@ 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/editor-area-conflict-swap.test.ts b/packages/app/tests/integration/editor-area-conflict-swap.test.ts
index 0f4176fc7..bc7e9f12c 100644
--- a/packages/app/tests/integration/editor-area-conflict-swap.test.ts
+++ b/packages/app/tests/integration/editor-area-conflict-swap.test.ts
@@ -24,39 +24,35 @@ async function setupServerWithDoc(docName: string, initial: string): Promise<Tes
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- });
+ }, 30_000);
return server;
}
describe('editor-area swap — gate propagation', () => {
- test('lifecycle.status conflict → clear round-trip preserves Y.Text identity', async () => {
+ test('conflict raise → dissolve round-trip preserves Y.Text identity', async () => {
const docName = `swap-roundtrip-${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'));
+ await pollUntil(() => client.ytext.toString().includes('Base paragraph'), 30_000);
const ytextRefBefore = client.ytext;
- 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);
-
- expect(lifecycle.get('status')).toBe('conflict');
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_000);
- const serverDoc = server.instance.hocuspocus.documents.get(docName);
- expect(serverDoc).toBeTruthy();
- serverDoc?.transact(() => {
- serverDoc.getMap('lifecycle').delete('status');
- serverDoc.getMap('lifecycle').delete('reason');
+ expect(server.instance.conflicts.findByDocName(docName)).toMatchObject({
+ kind: 'reconcile',
+ reason: 'disk-markers',
});
- await pollUntil(() => lifecycle.get('status') === undefined, 5000);
- expect(lifecycle.get('status')).toBeUndefined();
+ expect(server.instance.hocuspocus.documents.get(docName)).toBeTruthy();
+ server.instance.conflicts.dissolveReconcile(docName);
+ expect(server.instance.conflicts.has(docName)).toBe(false);
expect(client.ytext).toBe(ytextRefBefore);
expect(client.ytext).toBe(client.doc.getText('source'));
- }, 30_000);
+ }, 60_000);
});
diff --git a/packages/app/tests/integration/lint-fix-live-preservation.test.ts b/packages/app/tests/integration/lint-fix-live-preservation.test.ts
index 832a8ac69..5df57185e 100644
--- a/packages/app/tests/integration/lint-fix-live-preservation.test.ts
+++ b/packages/app/tests/integration/lint-fix-live-preservation.test.ts
@@ -577,7 +577,12 @@ describe('lint fix live-write preservation', () => {
clientName: 'codex',
},
);
- session.dc.document.getMap('lifecycle').set('status', 'conflict');
+ server.instance.conflicts.raise({
+ kind: 'reconcile',
+ file: `${docName}.md`,
+ reason: 'disk-markers',
+ stages: { base: TABBED_BODY, ours: TABBED_BODY, theirs: TABBED_BODY },
+ });
__resetContributorsForTests();
const response = await postFix({
@@ -588,7 +593,11 @@ describe('lint fix live-write preservation', () => {
summary: 'Must not land',
});
expect(response.status).toBe(409);
- expect(await response.json()).toMatchObject({ type: 'urn:ok:error:doc-in-conflict' });
+ expect(await response.json()).toMatchObject({
+ type: 'urn:ok:error:doc-in-conflict',
+ conflict: { kind: 'reconcile', reason: 'disk-markers' },
+ resolutionOptions: ['mine', 'content', 'delete'],
+ });
expect(session.dc.document.getText('source').toString()).toBe(TABBED_BODY);
expect(readFileSync(file, 'utf-8')).toBe(TABBED_BODY);
expect(contributors()).toEqual([]);
diff --git a/packages/app/tests/integration/persistence-staleness-watchdog.test.ts b/packages/app/tests/integration/persistence-staleness-watchdog.test.ts
index 63417c07f..b084a1656 100644
--- a/packages/app/tests/integration/persistence-staleness-watchdog.test.ts
+++ b/packages/app/tests/integration/persistence-staleness-watchdog.test.ts
@@ -105,10 +105,9 @@ describe('persistence staleness watchdog (integration)', () => {
);
expect(state.ok).toBe(true);
const watcherReconciled = (await state.text()).includes('external native edit');
- const lifecycle = server.instance.hocuspocus.documents.get(docName)?.getMap('lifecycle');
+ const entry = server.instance.conflicts.findByDocName(docName);
const watcherSurfacedConflict =
- lifecycle?.get('status') === 'conflict' &&
- lifecycle.get('reason') === 'merged-with-markers';
+ entry?.kind === 'reconcile' && entry.reason === 'merged-with-markers';
expect(watcherReconciled || watcherSurfacedConflict).toBe(true);
}
diff --git a/packages/app/tests/integration/stale-external-write-rollback.test.ts b/packages/app/tests/integration/stale-external-write-rollback.test.ts
index ea99b4159..4bd7cec37 100644
--- a/packages/app/tests/integration/stale-external-write-rollback.test.ts
+++ b/packages/app/tests/integration/stale-external-write-rollback.test.ts
@@ -101,11 +101,13 @@ async function unloadDocument(target: TestServer, docName: string): Promise<void
}
}
-function lifecycleOf(target: TestServer, docName: string): { status?: unknown; reason?: unknown } {
+function lifecycleOf(
+ target: TestServer,
+ docName: string,
+): { status?: unknown; kind?: 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') };
+ return target.instance.conflicts.lifecycleOf(document, docName) ?? {};
}
describe('stale external write does not roll back an acknowledged agent write', () => {
@@ -411,11 +413,13 @@ describe('stale external write does not roll back an acknowledged agent write',
conflictKind?: 'git' | 'stale-external-write';
}>;
};
- expect(conflicts.conflicts).toContainEqual({
- file: `${docName}.md`,
- detectedAt: expect.any(String),
- conflictKind: 'stale-external-write',
- });
+ expect(conflicts.conflicts).toContainEqual(
+ expect.objectContaining({
+ 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`,
@@ -451,27 +455,16 @@ describe('stale external write does not roll back an acknowledged agent write',
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',
- }),
- });
+ const markerResolution = await resolveConflict(
+ server,
+ `${docName}.md`,
+ '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,
- }),
- });
+ const resolution = await resolveConflict(server, `${docName}.md`, 'content', sides.ours);
expect(resolution.status).toBe(200);
expect(readTestDoc(contentDir, docName)).toContain(ACK_MARKER);
expect(lifecycleOf(server, docName).status).toBeUndefined();
@@ -484,14 +477,7 @@ describe('stale external write does not roll back an acknowledged agent write',
'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',
- }),
- });
+ const repeatedResolution = await resolveConflict(server, `${docName}.md`, 'mine');
expect(repeatedResolution.status).toBe(200);
await agentWriteMd(port, 'retry-after-resolution\n', { docName, position: 'append' });
@@ -574,8 +560,9 @@ describe('stale external write does not roll back an acknowledged agent write',
const client = await createTestClient(server.port, docName);
try {
expect(client.ytext.toString()).toContain(ACK_MARKER);
- expect(lifecycleOf(server, docName)).toEqual({
+ expect(lifecycleOf(server, docName)).toMatchObject({
status: 'conflict',
+ kind: 'reconcile',
reason: 'stale-external-write',
});
} finally {
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 6488e105a..39fcfb72a 100644
--- a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
+++ b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
@@ -10,6 +10,13 @@ const THEIRS_CONTENT = '# Theirs\n\nTeam version.\n';
const CONFLICT_MARKERS =
'<<<<<<< HEAD\n# Mine\n\nLocal version.\n=======\n# Theirs\n\nTeam version.\n>>>>>>> origin/main\n';
+async function listedConflictFiles(port: number): Promise<string[]> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`).catch(() => null);
+ if (!res?.ok) return [];
+ const data = (await res.json()) as { conflicts?: Array<{ file: string }> };
+ return (data.conflicts ?? []).map((c) => c.file);
+}
+
const cleanups: Array<() => Promise<void> | void> = [];
afterEach(async () => {
@@ -27,12 +34,12 @@ async function setupServerWithDoc(docName: string, initial: string): Promise<Tes
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- });
+ }, 60_000);
return server;
}
-describe('case "conflict" disk event -> CRDT lifecycle', () => {
- test('clears lifecycle.status after conflict resolves to theirs', async () => {
+describe('case "conflict" disk event -> conflict ledger', () => {
+ test('clears the conflict entry after it resolves to theirs', async () => {
const docName = `conflict-clear-${crypto.randomUUID()}`;
const server = await setupServerWithDoc(docName, BASE_CONTENT);
const client = await createTestClient(server.port, docName);
@@ -40,25 +47,30 @@ describe('case "conflict" disk event -> CRDT lifecycle', () => {
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);
+ await pollUntil(
+ async () => (await listedConflictFiles(server.port)).includes(`${docName}.md`),
+ 30_000,
+ );
writeFileSync(filePath, THEIRS_CONTENT, 'utf-8');
- await pollUntil(() => client.ytext.toString().includes('Team version'), 10_000);
+ await pollUntil(() => client.ytext.toString().includes('Team version'), 30_000);
expect(client.ytext.toString()).toContain('Team version');
expect(client.ytext.toString()).not.toContain('Base paragraph');
- await pollUntil(() => lifecycle.get('status') === undefined, 5000);
- expect(lifecycle.get('reason')).toBeUndefined();
- }, 30_000);
+ await pollUntil(
+ async () => !(await listedConflictFiles(server.port)).includes(`${docName}.md`),
+ 30_000,
+ );
+ expect(server.instance.conflicts.findByDocName(docName)).toBeUndefined();
+ }, 60_000);
- test('clears lifecycle.status on noop reconcile (keep-mine path)', async () => {
+ test('clears the conflict entry on noop reconcile (keep-mine path)', async () => {
const docName = `conflict-noop-${crypto.randomUUID()}`;
const server = await setupServerWithDoc(docName, BASE_CONTENT);
const client = await createTestClient(server.port, docName);
@@ -66,18 +78,17 @@ describe('case "conflict" disk event -> CRDT lifecycle', () => {
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);
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_000);
writeFileSync(filePath, BASE_CONTENT, 'utf-8');
- await pollUntil(() => lifecycle.get('status') === undefined, 5000);
- expect(lifecycle.get('reason')).toBeUndefined();
+ await pollUntil(() => !server.instance.conflicts.has(docName), 30_000);
+ expect(server.instance.conflicts.findByDocName(docName)).toBeUndefined();
expect(client.ytext.toString()).toContain('Base paragraph');
- }, 30_000);
+ }, 60_000);
test('persistence does not overwrite conflict markers on disk during conflict', async () => {
const docName = `conflict-persist-${crypto.randomUUID()}`;
@@ -87,11 +98,10 @@ describe('case "conflict" disk event -> CRDT lifecycle', () => {
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);
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_000);
expect(readFileSync(filePath, 'utf-8')).toContain('<<<<<<<');
@@ -111,11 +121,11 @@ describe('case "conflict" disk event -> CRDT lifecycle', () => {
expect(diskNow).toContain('=======');
expect(diskNow).toContain('>>>>>>>');
expect(diskNow).not.toContain('Edit during conflict');
- }, 30_000);
+ }, 60_000);
});
-describe('case "conflicts" reconcile branch -> CRDT lifecycle', () => {
- test('case "conflicts" sets lifecycle.status="conflict" with reason "merged-with-markers"', async () => {
+describe('case "conflicts" reconcile branch -> conflict ledger', () => {
+ test('case "conflicts" raises a reconcile entry with reason "merged-with-markers"', async () => {
const docName = `reconcile-conflicts-${crypto.randomUUID()}`;
const baseContent = '# Heading\n\nFirst paragraph.\n\nSecond paragraph.\n';
const server = await createTestServer({ debounce: 60_000, maxDebounce: 60_000 });
@@ -126,14 +136,13 @@ describe('case "conflicts" reconcile branch -> CRDT lifecycle', () => {
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
- });
+ }, 30_000);
const client = await createTestClient(server.port, docName);
cleanups.push(() => client.cleanup());
await pollUntil(() => client.ytext.toString().includes('First paragraph'));
- const lifecycle = client.doc.getMap('lifecycle');
const filePath = join(server.contentDir, `${docName}.md`);
const baseOffset = client.ytext.toString().indexOf('First paragraph.');
@@ -151,11 +160,13 @@ describe('case "conflicts" reconcile branch -> CRDT lifecycle', () => {
const theirsContent = '# Heading\n\nTheir version of first paragraph.\n\nSecond paragraph.\n';
writeFileSync(filePath, theirsContent, 'utf-8');
- await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_000);
- expect(lifecycle.get('status')).toBe('conflict');
- expect(lifecycle.get('reason')).toBe('merged-with-markers');
- }, 30_000);
+ expect(server.instance.conflicts.findByDocName(docName)).toMatchObject({
+ kind: 'reconcile',
+ reason: 'merged-with-markers',
+ });
+ }, 60_000);
});
describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conflict', () => {
@@ -168,14 +179,14 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
const filePath = join(server.contentDir, `${docName}.md`);
writeFileSync(filePath, CONFLICT_MARKERS, 'utf-8');
- const lifecycle = client.doc.getMap('lifecycle');
- await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_000);
return { docName, server };
}
async function expectDocInConflict409(
res: Response,
expectedFile: string,
+ expectedOptions: string[] = ['mine', 'content', 'delete'],
): Promise<Record<string, unknown>> {
expect(res.status).toBe(409);
expect(res.headers.get('content-type')).toContain('application/problem+json');
@@ -184,7 +195,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
expect(body.title).toBe('Document is in conflict.');
expect(body.status).toBe(409);
expect(body.file).toBe(expectedFile);
- expect(body.resolutionOptions).toEqual(['mine', 'theirs', 'content', 'delete']);
+ expect(body.resolutionOptions).toEqual(expectedOptions);
expect(body.base).toBeUndefined();
expect(body.ours).toBeUndefined();
expect(body.theirs).toBeUndefined();
@@ -204,7 +215,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
test('POST /api/agent-write-md returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
@@ -220,7 +231,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
test('POST /api/agent-patch returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
@@ -236,7 +247,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
test('POST /api/agent-undo returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
@@ -257,7 +268,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
test('POST /api/rollback returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
@@ -270,7 +281,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
test('POST /api/rename-path returns 409 doc-in-conflict when source is conflicted', async () => {
const { docName, server } = await seedConflictedDoc();
@@ -284,7 +295,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
test('POST /api/delete-path returns 409 doc-in-conflict when target is conflicted', async () => {
const { docName, server } = await seedConflictedDoc();
@@ -297,7 +308,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${docName}.md`);
- }, 30_000);
+ }, 60_000);
async function seedConflictedDocInFolder(): Promise<{
folder: string;
@@ -329,8 +340,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
await pollUntil(() => client.ytext.toString().includes('Base paragraph'));
writeFileSync(join(server.contentDir, folder, `${childBase}.md`), CONFLICT_MARKERS, 'utf-8');
- const lifecycle = client.doc.getMap('lifecycle');
- await pollUntil(() => lifecycle.get('status') === 'conflict', 10_000);
+ await pollUntil(() => server.instance.conflicts.has(childDocName), 30_000);
return { folder, childDocName, server };
}
@@ -346,59 +356,53 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
}),
});
await expectDocInConflict409(res, `${childDocName}.md`);
- }, 30_000);
+ }, 60_000);
});
describe('GET /api/sync/conflict-content?source=ytext', () => {
- 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('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 filePath = join(server.contentDir, `${docName}.md`);
+
+ writeFileSync(filePath, CONFLICT_MARKERS, 'utf-8');
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_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;
+ };
+ expect(ytextBody.file).toBe(`${docName}.md`);
+ expect(ytextBody.ours).toContain(midConflictMarker);
+
+ 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);
+ }, 60_000);
test('falls back to git-index ours when Y.Text snapshot contains conflict markers', async () => {
const docName = `fr3-marker-fallback-${crypto.randomUUID()}`;
@@ -408,11 +412,10 @@ describe('GET /api/sync/conflict-content?source=ytext', () => {
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);
+ await pollUntil(() => server.instance.conflicts.has(docName), 30_000);
client.doc.transact(() => {
client.ytext.delete(0, client.ytext.toString().length);
@@ -427,10 +430,9 @@ describe('GET /api/sync/conflict-content?source=ytext', () => {
`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 { ours: string; lifecycleStatus: string | null };
+ const ytextBody = (await ytextRes.json()) as { ours: string };
expect(ytextBody.ours).not.toContain('<<<<<<<');
expect(ytextBody.ours).not.toContain('=======');
expect(ytextBody.ours).not.toContain('>>>>>>>');
- expect(ytextBody.lifecycleStatus).toBe('conflict');
- }, 30_000);
+ }, 60_000);
});
diff --git a/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts b/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts
index 32f65a70b..da9e3dca7 100644
--- a/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts
+++ b/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createContentFilter } from '@inkeep/open-knowledge-server';
import { afterEach, describe, expect, test } from 'vitest';
+import { createTestConflictAuthority } from '../../../server/src/conflict-authority.test-helper.ts';
import { SyncEngine } from '../../../server/src/sync-engine.ts';
const tmpRoots: string[] = [];
@@ -49,6 +50,7 @@ describe('sync-engine dot-dir filter symmetry', () => {
const skillPath = '.cursor/skills/open-knowledge/SKILL.md';
const engine = new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir, projectDir),
projectDir,
contentDir: projectDir,
contentFilter: createContentFilter({ projectDir, contentDir: projectDir }),
diff --git a/packages/app/tests/integration/sync-wired-harness.test.ts b/packages/app/tests/integration/sync-wired-harness.test.ts
index 16c50e91e..c9ffc0e0c 100644
--- a/packages/app/tests/integration/sync-wired-harness.test.ts
+++ b/packages/app/tests/integration/sync-wired-harness.test.ts
@@ -170,9 +170,9 @@ describe('sync-wired harness (S2 substrate)', () => {
await revParse(server.contentDir, 'origin/main'),
);
expect(readFileSync(join(server.contentDir, 'guide.md'), 'utf-8')).toContain('LOCAL intro');
- const conflicts = engine.getConflicts();
+ const conflicts = server.instance.conflicts.list();
expect(conflicts).toHaveLength(1);
- expect(conflicts[0]?.variant).toBe('working-tree');
+ expect(conflicts[0]?.kind).toBe('working-tree');
const base = `http://127.0.0.1:${server.port}/api/sync/conflict-content`;
const diskRes = await fetch(`${base}?file=guide.md`);
@@ -194,10 +194,9 @@ describe('sync-wired harness (S2 substrate)', () => {
clients.push(client);
await pollUntil(() => serializeFragment(client.fragment).includes('LOCAL intro'));
const ytextRes = await fetch(`${base}?file=guide.md&source=ytext`);
- const ytextBody = (await ytextRes.json()) as { ours: string; lifecycleStatus: string | null };
+ const ytextBody = (await ytextRes.json()) as { ours: string; conflict: string };
expect(ytextBody.ours).toContain('LOCAL intro');
- expect(ytextBody.lifecycleStatus).toBe('conflict');
- await pollUntil(() => client.doc.getMap('lifecycle').get('status') === 'conflict');
+ expect(ytextBody.conflict).toBe('working-tree');
const resolveRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
@@ -205,9 +204,9 @@ describe('sync-wired harness (S2 substrate)', () => {
body: JSON.stringify({ file: 'guide.md', strategy: 'mine' }),
});
expect(resolveRes.status).toBe(200);
- expect(engine.getConflicts()).toEqual([]);
+ expect(server.instance.conflicts.list()).toEqual([]);
+ expect(server.instance.conflicts.has('guide')).toBe(false);
expect(readFileSync(join(server.contentDir, 'guide.md'), 'utf-8')).toContain('LOCAL intro');
- await pollUntil(() => client.doc.getMap('lifecycle').get('status') === undefined);
expect(existsSync(join(server.contentDir, '.git', 'MERGE_HEAD'))).toBe(false);
},
HARNESS_BOOT_TIMEOUT_MS,
diff --git a/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.ts b/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.ts
index 5afbb2804..2f9183850 100644
--- a/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.ts
+++ b/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.ts
@@ -32,8 +32,8 @@ function serverDoc(rig: TestServer, docName: string) {
return rig.instance.hocuspocus.documents.get(docName);
}
-function lifecycleStatus(rig: TestServer, docName: string): unknown {
- return serverDoc(rig, docName)?.getMap('lifecycle').get('status');
+function isConflicted(rig: TestServer, docName: string): boolean {
+ return rig.instance.conflicts.has(docName);
}
describe('template tombstone quarantine (FR3)', () => {
@@ -99,7 +99,7 @@ describe('template live conflict gate (FR5)', () => {
const conflicted =
'---\ntitle: T\ndescription: initial\n---\n\n# Template\n\n<<<<<<< HEAD\nours.\n=======\ntheirs.\n>>>>>>> branch\n';
writeFileSync(tplFile, conflicted, 'utf-8');
- await pollUntil(() => lifecycleStatus(rig, docName) === 'conflict', 15000);
+ await pollUntil(() => isConflicted(rig, docName), 30_000);
const put = await fetch(`http://127.0.0.1:${rig.port}/api/template`, {
method: 'PUT',
diff --git a/packages/app/tests/integration/template-watcher-capabilities.test.ts b/packages/app/tests/integration/template-watcher-capabilities.test.ts
index c139b0169..9c4590362 100644
--- a/packages/app/tests/integration/template-watcher-capabilities.test.ts
+++ b/packages/app/tests/integration/template-watcher-capabilities.test.ts
@@ -157,7 +157,7 @@ describe('template watcher capabilities — content pipeline parity (FR4)', () =
);
test(
- 'conflict markers written to a template file classify the open doc into the conflict lifecycle',
+ 'conflict markers written to a template file raise a reconcile conflict for the open doc',
async () => {
const name = `tpl-${randomUUID().slice(0, 8)}`;
const docName = `.ok/templates/${name}`;
@@ -177,9 +177,11 @@ describe('template watcher capabilities — content pipeline parity (FR4)', () =
'---\ntitle: T\ndescription: initial\n---\n\n# Template\n\n<<<<<<< HEAD\nours.\n=======\ntheirs.\n>>>>>>> branch\n';
writeFileSync(tplFile, conflicted, 'utf-8');
- await pollUntil(() => lifecycleStatus(rig, docName) === 'conflict', 15000);
- expect(lifecycleStatus(rig, docName)).toBe('conflict');
- expect(serverDoc(rig, docName)?.getMap('lifecycle').get('reason')).toBe('conflict-markers');
+ await pollUntil(() => rig.instance.conflicts.has(docName), 15000);
+ expect(rig.instance.conflicts.findByDocName(docName)).toMatchObject({
+ kind: 'reconcile',
+ reason: 'disk-markers',
+ });
expect(client.ytext.toString()).not.toContain('<<<<<<<');
await client.cleanup();
diff --git a/packages/app/tests/integration/walker-symmetry.test.ts b/packages/app/tests/integration/walker-symmetry.test.ts
index 12ec17632..402f18185 100644
--- a/packages/app/tests/integration/walker-symmetry.test.ts
+++ b/packages/app/tests/integration/walker-symmetry.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createContentFilter } from '@inkeep/open-knowledge-server';
import { afterEach, describe, expect, test } from 'vitest';
+import { createTestConflictAuthority } from '../../../server/src/conflict-authority.test-helper.ts';
import { SyncEngine } from '../../../server/src/sync-engine.ts';
import { createTestServer, type TestServer } from './test-harness';
@@ -54,6 +55,7 @@ describe('walker symmetry', () => {
const contentFilter = createContentFilter({ projectDir: contentDir, contentDir });
const engine = new SyncEngine({
+ conflicts: createTestConflictAuthority(contentDir),
projectDir: contentDir,
contentDir,
contentFilter,
@@ -113,6 +115,7 @@ describe('walker symmetry', () => {
const contentFilter = createContentFilter({ projectDir, contentDir: nestedContentDir });
const engine = new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir, nestedContentDir),
projectDir,
contentDir: nestedContentDir,
contentFilter,
diff --git a/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts b/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts
index 3a6619fa4..83265bcf3 100644
--- a/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts
+++ b/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts
@@ -86,6 +86,9 @@ test.describe('sidebar file list fills the body', () => {
conflicts: Array.from({ length: 25 }, (_, i) => ({
file: `folder/conflicted-doc-number-${i}.md`,
detectedAt: '2026-08-05T00:00:00.000Z',
+ conflict: 'merge-native',
+ docName: `folder/conflicted-doc-number-${i}`,
+ revision: `reviewed-revision-${i}`,
})),
}),
});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0b2a5a9c9..de64b542f 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1177,6 +1177,7 @@ export {
ClientLogsRequestSchema,
type ClientLogsSuccess,
ClientLogsSuccessSchema,
+ CONFLICT_KINDS,
type CommentCountsSuccess,
CommentCountsSuccessSchema,
type CommentTarget,
@@ -1185,6 +1186,8 @@ export {
CompleteBatchSuccessSchema,
ConflictEntrySchema,
type ConflictEntryWire,
+ ConflictKindSchema,
+ type ConflictKindWire,
type ContentDivergenceCurrentState,
ContentDivergenceCurrentStateSchema,
type ContentDivergenceWarning,
@@ -1383,6 +1386,10 @@ export {
PushPermissionSchema,
type PushPermissionWire,
QueueSuccessSchema,
+ RECONCILE_REASONS,
+ RESOLVE_STRATEGIES,
+ ReconcileReasonSchema,
+ type ReconcileReasonWire,
type RenamedAssetMapping,
RenamedAssetMappingSchema,
type RenamedDocMapping,
@@ -1401,6 +1408,8 @@ export {
RescueEntryTimelineSchema,
type RescueListSuccess,
RescueListSuccessSchema,
+ ResolveStrategySchema,
+ type ResolveStrategyWire,
type RollbackRequest,
RollbackRequestSchema,
type RollbackSuccess,
diff --git a/packages/core/src/schemas/api/sync-seed.test.ts b/packages/core/src/schemas/api/sync-seed.test.ts
index b0b34bc50..907567d82 100644
--- a/packages/core/src/schemas/api/sync-seed.test.ts
+++ b/packages/core/src/schemas/api/sync-seed.test.ts
@@ -328,6 +328,8 @@ describe('ConflictEntrySchema', () => {
ConflictEntrySchema.safeParse({
file: 'docs/foo.md',
detectedAt: '2026-04-30T10:00:00.000Z',
+ conflict: 'merge-native',
+ docName: 'docs/foo',
}).success,
).toBe(true);
});
@@ -336,61 +338,41 @@ describe('ConflictEntrySchema', () => {
ConflictEntrySchema.safeParse({
file: 'docs/foo.md',
detectedAt: '2026-04-30T10:00:00.000Z',
- oursSha: 'abc1234',
+ conflict: 'working-tree',
+ docName: 'docs/foo',
theirsSha: 'def5678',
baseSha: '0000000',
}).success,
).toBe(true);
});
- test('preserves both recognized conflict origins', () => {
- for (const conflictKind of ['git', 'stale-external-write']) {
- const entry = {
- file: 'docs/foo.md',
+ test('parses an entry outside the content dir with a null docName', () => {
+ expect(
+ ConflictEntrySchema.safeParse({
+ file: 'outside/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,
- });
+ conflict: 'reconcile',
+ reason: 'disk-markers',
+ docName: null,
+ }).success,
+ ).toBe(true);
});
- 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 an entry with no conflict', () => {
+ expect(
+ ConflictEntrySchema.safeParse({
+ file: 'docs/foo.md',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ docName: 'docs/foo',
+ }).success,
+ ).toBe(false);
});
test('rejects empty file', () => {
expect(
- ConflictEntrySchema.safeParse({ file: '', detectedAt: '2026-04-30T10:00:00.000Z' }).success,
+ ConflictEntrySchema.safeParse({
+ file: '',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ conflict: 'merge-native',
+ docName: null,
+ }).success,
).toBe(false);
});
});
@@ -402,46 +384,29 @@ describe('SyncConflictsSuccessSchema', () => {
test('parses populated list', () => {
expect(
SyncConflictsSuccessSchema.safeParse({
- conflicts: [{ file: 'a.md', detectedAt: '2026-04-30T10:00:00.000Z' }],
+ conflicts: [
+ {
+ file: 'a.md',
+ detectedAt: '2026-04-30T10:00:00.000Z',
+ conflict: 'merge-native',
+ docName: 'a',
+ },
+ ],
}).success,
).toBe(true);
});
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,
+ SyncResolveConflictRequestSchema.safeParse({
+ file: 'a.md',
+ strategy: 'mine',
+ }).success,
).toBe(true);
});
test('parses {file, strategy:content, content}', () => {
@@ -454,22 +419,32 @@ describe('SyncResolveConflictRequestSchema', () => {
).toBe(true);
});
test('rejects missing file', () => {
- expect(SyncResolveConflictRequestSchema.safeParse({ strategy: 'mine' }).success).toBe(false);
+ expect(
+ SyncResolveConflictRequestSchema.safeParse({
+ strategy: 'mine',
+ }).success,
+ ).toBe(false);
});
test('rejects empty file', () => {
- expect(SyncResolveConflictRequestSchema.safeParse({ file: '', strategy: 'mine' }).success).toBe(
- false,
- );
+ expect(
+ SyncResolveConflictRequestSchema.safeParse({
+ file: '',
+ strategy: 'mine',
+ }).success,
+ ).toBe(false);
});
test('rejects unknown strategy', () => {
expect(
- SyncResolveConflictRequestSchema.safeParse({ file: 'a.md', strategy: 'magic' }).success,
+ SyncResolveConflictRequestSchema.safeParse({
+ file: 'a.md',
+ strategy: 'magic',
+ }).success,
).toBe(false);
});
});
describe('SyncConflictContentSuccessSchema', () => {
- test('parses populated stages with lifecycleStatus: null (default branch)', () => {
+ test('parses populated stages', () => {
expect(
SyncConflictContentSuccessSchema.safeParse({
file: 'a.md',
@@ -477,7 +452,8 @@ describe('SyncConflictContentSuccessSchema', () => {
ours: 'mine',
theirs: 'theirs',
kind: 'both-modified',
- lifecycleStatus: null,
+ conflict: 'merge-native',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
}).success,
).toBe(true);
});
@@ -489,56 +465,38 @@ describe('SyncConflictContentSuccessSchema', () => {
ours: '',
theirs: '',
kind: 'delete-modify',
- lifecycleStatus: null,
+ conflict: 'merge-native',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
}).success,
).toBe(true);
});
- test('rejects missing file', () => {
+ test('parses a marker-bearing reconcile payload whose options omit theirs', () => {
expect(
SyncConflictContentSuccessSchema.safeParse({
- base: '',
- ours: '',
- theirs: '',
- lifecycleStatus: null,
+ file: 'a.md',
+ base: 'b',
+ ours: 'o',
+ theirs: 't',
+ kind: 'both-modified',
+ conflict: 'reconcile',
+ reason: 'disk-markers',
+ resolutionOptions: ['mine', 'content', 'delete'],
}).success,
- ).toBe(false);
+ ).toBe(true);
});
- test('rejects missing lifecycleStatus (always-present-nullable contract)', () => {
+ test('rejects missing file', () => {
expect(
SyncConflictContentSuccessSchema.safeParse({
- file: 'a.md',
base: '',
ours: '',
theirs: '',
- }).success,
- ).toBe(false);
- });
- test('parses populated stages with lifecycleStatus: "conflict"', () => {
- expect(
- SyncConflictContentSuccessSchema.safeParse({
- file: 'a.md',
- base: 'b',
- ours: 'o',
- theirs: 't',
kind: 'both-modified',
- lifecycleStatus: 'conflict',
+ conflict: 'merge-native',
+ resolutionOptions: [],
}).success,
- ).toBe(true);
+ ).toBe(false);
});
- 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);
- }
+ test('rejects a payload with no resolutionOptions', () => {
expect(
SyncConflictContentSuccessSchema.safeParse({
file: 'a.md',
@@ -546,8 +504,7 @@ describe('SyncConflictContentSuccessSchema', () => {
ours: 'o',
theirs: 't',
kind: 'both-modified',
- lifecycleStatus: 'conflict',
- conflictKind: 'unknown',
+ conflict: 'merge-native',
}).success,
).toBe(false);
});
@@ -558,7 +515,8 @@ describe('SyncConflictContentSuccessSchema', () => {
base: 'b',
ours: 'o',
theirs: 't',
- lifecycleStatus: null,
+ conflict: 'merge-native',
+ resolutionOptions: ['mine'],
}).success,
).toBe(false);
});
@@ -570,7 +528,8 @@ describe('SyncConflictContentSuccessSchema', () => {
ours: 'o',
theirs: 't',
kind: 'made-up-shape',
- lifecycleStatus: null,
+ conflict: 'merge-native',
+ resolutionOptions: ['mine'],
}).success,
).toBe(false);
});
diff --git a/packages/core/src/schemas/api/sync-seed.ts b/packages/core/src/schemas/api/sync-seed.ts
index ca7ebe723..a1431cdbf 100644
--- a/packages/core/src/schemas/api/sync-seed.ts
+++ b/packages/core/src/schemas/api/sync-seed.ts
@@ -138,13 +138,32 @@ export const SyncTriggerSuccessSchema = z
.loose() satisfies StandardSchemaV1;
export type SyncTriggerSuccess = z.infer<typeof SyncTriggerSuccessSchema>;
+export const CONFLICT_KINDS = ['merge-native', 'working-tree', 'reconcile'] as const;
+export const ConflictKindSchema = z.enum(CONFLICT_KINDS) satisfies StandardSchemaV1;
+export type ConflictKindWire = z.infer<typeof ConflictKindSchema>;
+
+export const RECONCILE_REASONS = [
+ 'merged-with-markers',
+ 'refused-conflict-markers',
+ 'refused-too-large',
+ 'disk-markers',
+ 'stale-external-write',
+] as const;
+export const ReconcileReasonSchema = z.enum(RECONCILE_REASONS) satisfies StandardSchemaV1;
+export type ReconcileReasonWire = z.infer<typeof ReconcileReasonSchema>;
+
+export const RESOLVE_STRATEGIES = ['mine', 'theirs', 'content', 'delete'] as const;
+export const ResolveStrategySchema = z.enum(RESOLVE_STRATEGIES) satisfies StandardSchemaV1;
+export type ResolveStrategyWire = z.infer<typeof ResolveStrategySchema>;
+
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(),
+ conflict: ConflictKindSchema,
+ reason: ReconcileReasonSchema.optional(),
+ conflictKind: z.enum(['git', 'stale-external-write']).optional(),
+ docName: z.string().nullable(),
theirsSha: z.string().optional(),
baseSha: z.string().optional(),
})
@@ -182,8 +201,10 @@ export const SyncConflictContentSuccessSchema = z
ours: z.string(),
theirs: z.string(),
kind: z.enum(['both-modified', 'delete-modify', 'modify-delete']),
- lifecycleStatus: z.string().nullable(),
+ conflict: ConflictKindSchema,
+ reason: ReconcileReasonSchema.optional(),
conflictKind: z.enum(['git', 'stale-external-write']).optional(),
+ resolutionOptions: z.array(ResolveStrategySchema),
})
.loose() satisfies StandardSchemaV1;
export type SyncConflictContentSuccess = z.infer<typeof SyncConflictContentSuccessSchema>;
diff --git a/packages/desktop/tests/smoke/agent-patch-divergence-probe.e2e.ts b/packages/desktop/tests/smoke/agent-patch-divergence-probe.e2e.ts
index 3d6943945..ad1e39ae5 100644
--- a/packages/desktop/tests/smoke/agent-patch-divergence-probe.e2e.ts
+++ b/packages/desktop/tests/smoke/agent-patch-divergence-probe.e2e.ts
@@ -116,6 +116,12 @@ interface RaceResult {
async function resolveLeftoverConflict(port: number, docName: string): Promise<void> {
const file = docName.endsWith('.md') ? docName : `${docName}.md`;
+ const listRes = await fetch(`http://localhost:${port}/api/sync/conflicts`).catch(() => null);
+ if (!listRes?.ok) return;
+ const list = (await listRes.json().catch(() => ({ conflicts: [] }))) as {
+ conflicts?: Array<{ file: string }>;
+ };
+ if (!list.conflicts?.some((entry) => entry.file === file)) return;
const res = await fetch(`http://localhost:${port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index 01a341656..f3c0d26a0 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` (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 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: a family absent from `ran` was not checked, and `[]` means no checks were selected.**
- **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`, `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` for Project↔Global: history resets, only what the destination level can host re-projects; the rest is removed at source, returned as `droppedLocations` (success: re-add with `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; commits for Git-index conflicts only; destructive). See `references/conflict-resolution.md`.
+- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution from that conflict's `resolutionOptions`; commits only for `merge-native`; 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
-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`.
+A 409 `doc-in-conflict` freezes writes and carries `conflict.kind` + `resolutionOptions`. A flush-time `stale-external-write` 409 means the edit reached collaborative recovery but not disk; resolve and re-read before retrying. Detect with `conflicts`, not `exec`; kinds and full flow in `references/conflict-resolution.md`.
## 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 e24d495bb..ceefc9059 100644
--- a/packages/server/assets/skills/project/references/conflict-resolution.md
+++ b/packages/server/assets/skills/project/references/conflict-resolution.md
@@ -1,34 +1,47 @@
# Conflict-aware writes
-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:
+A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OK's own reconciliation of the editor against disk. Reconciliation also protects an acknowledged edit when another app restores the exact older file version; that `stale-external-write` path works with GitHub sync disabled. `ConflictAuthority` tracks every kind, and the MCP server refuses a mutating call against a 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 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.",
+ "detail": "The document is in a conflict state. Call conflicts({ kind: \"content\" }) + resolve_conflict before retrying.",
"file": "notes/sso.md",
- "resolutionOptions": ["mine", "theirs", "content", "delete"]
+ "conflict": { "kind": "reconcile", "reason": "disk-markers" },
+ "resolutionOptions": ["mine", "content", "delete"]
}
```
-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.
+The gate covers `write`, `edit`, `delete`, `move`, `restore_version`, and agent undo (the doc-CRDT write spine; template/folder ops are fs-direct). You cannot route around it by writing content that byte-matches one of the stages. The gate refuses on tracked state, not on body equality.
-A 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`.
+A write that first detects a stale file during its final disk flush returns `urn:ok:error:stale-external-write` (409). The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Resolve and re-read before deciding whether to repeat the operation; a retried 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.** Call `conflicts({ kind: 'list' })` before a batch of writes. An `exec` read carries no conflict flag, so the only other signal is the 409 above, which arrives after a write has already been refused.
-**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.
+## The three kinds
-**Resolution flow.** Three tools compose:
+| `conflict.kind` | Where it comes from | What a resolve does |
+| - | - | - |
+| `merge-native` | a git merge left unmerged stages in the index | stages your choice with git, and commits the merge once no `merge-native` conflict is left (other kinds do not hold the commit back) |
+| `working-tree` | a pull-only overlay collision, pinned to the origin blob it collided with | writes the chosen bytes to disk; nothing is committed |
+| `reconcile` | OK's own three-way merge of the editor against disk, including stale external saves. No git object holds the stages, so OK snapshots them at detection | writes the chosen bytes to disk and into the loaded document; no git command runs |
-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.
+A `reconcile` conflict carries a `reason`: `merged-with-markers` (the three-way merge produced markers), `refused-conflict-markers` (the disk bytes already carried markers), `refused-too-large` (the document is past the merge size cap), `disk-markers` (markers landed on disk under an open doc), or `stale-external-write` (an older displaced version returned on disk). The compatibility `conflictKind` field is `stale-external-write` for that last reason and `git` otherwise.
+
+## Resolution flow
+
+1. `conflicts({ kind: 'list' })` → every tracked conflict as `{ file, detectedAt, conflict, reason?, conflictKind?, docName }`.
+2. `conflicts({ kind: 'content', file })` → `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }` (the result nests under the `content` kind key). `ours` reflects the live Y.Text when the doc is loaded and marker-free; otherwise it falls back to the pinned stage. For a stale external write, `ours` is the protected content and `theirs` is the rejected older save. On a `reconcile` conflict, `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers. Send the reviewed bytes back as `content` when you mean to keep exactly what you were shown. Returns 404 `urn:ok:error:no-conflict-tracked` (title `No conflict is tracked for this path.`) when nothing is tracked for that path; re-read the list before retrying.
+3. `resolve_conflict({ file, strategy, content? })` → write the chosen bytes. **Send a strategy from that conflict's `resolutionOptions`**, not the full set. A `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and `refused-too-large` offers only `mine`, `theirs`, and `delete`. An unoffered strategy returns a 422 with `refusal: "strategy-not-offered"`. Markers left in the content you submit return the same status with `refusal: "markers-in-content"`, and that field is what tells the two apart. A 404 (`urn:ok:error:no-conflict-tracked`) carries this detail verbatim: `This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Re-read conflicts({ kind: "list" }) before retrying.` It says nothing is tracked, not that your resolution was saved, so re-read the list.
+
+Per kind, `mine` / `theirs` mean different things. On `merge-native` they are `git checkout --ours` / `--theirs` (the committed stages 2 and 3), and `delete` is `git rm`. On `working-tree`, `mine` keeps your overlay verbatim and `theirs` restores the pinned origin blob. On `reconcile`, `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk bytes captured at detection. For a stale external write, these choices keep the current local content or accept the rejected save. `content` always writes the bytes you supply, including an explicit empty string, and `delete` removes the file.
`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 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.
+Resolution is best-effort across disk, collaborative state, and indexes. A failed local resolution keeps its authority row and recovery snapshot for retry. For `merge-native`, `git checkout --ours/--theirs && git add` may succeed before `git commit --no-edit` fails; the ledger keeps the still-unmerged files. Re-read the conflict before retrying.
+
+A conflict can also close without you. Resolving a merge with raw git outside the app prunes the `merge-native` entry on the next disk change or HEAD move, and a `reconcile` conflict whose file comes back clean on disk dissolves on the next watcher pass.
-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.
+Stale-save recovery data lives in `.ok/local/stale-external-writes.json`, with owner-only permissions. Do not delete that file or restart with empty state when it is corrupt or unreadable; it may hold the only copy of protected edits. Preserve it, restore a known-good backup, and run `ok bug-report` from the project directory for diagnostics. An unresolved conflict does not expire with the displaced-hash window.
diff --git a/packages/server/src/agent-sessions.test.ts b/packages/server/src/agent-sessions.test.ts
index 1efaa3409..9256a5afa 100644
--- a/packages/server/src/agent-sessions.test.ts
+++ b/packages/server/src/agent-sessions.test.ts
@@ -11,6 +11,7 @@ import {
applyAgentMarkdownWrite,
applyAgentUndo,
} from './agent-sessions.ts';
+import { bindConflictAuthority } from './conflict-authority.ts';
import { DocInConflictError } from './conflict-errors.ts';
import { _resetDocExtensionsForTests, registerDocExtension } from './doc-extensions.ts';
@@ -663,9 +664,9 @@ describe('empty / whitespace content writes (PRD-6835)', () => {
});
describe('conflict-aware write gate (FR9 a, d)', () => {
- test('applyAgentMarkdownWrite throws DocInConflictError when lifecycle.status="conflict"', async () => {
+ test('applyAgentMarkdownWrite throws DocInConflictError when the doc is tracked as conflicted', async () => {
const session = await manager.getSession('conflicted-doc', 'agent-gate');
- session.dc.document.getMap('lifecycle').set('status', 'conflict');
+ bindConflictAuthority(session.dc.document, { has: () => true });
let caught: unknown;
try {
@@ -687,7 +688,7 @@ describe('conflict-aware write gate (FR9 a, d)', () => {
session.dc.document.transact(() => {
session.dc.document.getText('source').insert(0, theirsBytes);
});
- session.dc.document.getMap('lifecycle').set('status', 'conflict');
+ bindConflictAuthority(session.dc.document, { has: () => true });
let caught: unknown;
try {
@@ -698,7 +699,7 @@ describe('conflict-aware write gate (FR9 a, d)', () => {
expect(caught instanceof DocInConflictError).toBe(true);
});
- test('applyAgentUndo throws DocInConflictError when lifecycle.status="conflict"', async () => {
+ test('applyAgentUndo throws DocInConflictError when the doc is tracked as conflicted', async () => {
const session = await manager.getSession('conflicted-undo', 'agent-undo-gate');
session.dc.document.transact(() => {
applyAgentMarkdownWrite(session.dc.document, '# Pre-conflict\n', 'replace');
@@ -706,7 +707,7 @@ describe('conflict-aware write gate (FR9 a, d)', () => {
session.um.stopCapturing();
expect(session.um.undoStack.length).toBeGreaterThan(0);
- session.dc.document.getMap('lifecycle').set('status', 'conflict');
+ bindConflictAuthority(session.dc.document, { has: () => true });
let caught: unknown;
try {
@@ -721,7 +722,7 @@ describe('conflict-aware write gate (FR9 a, d)', () => {
expect(session.um.undoStack.length).toBeGreaterThan(0);
});
- test('applyAgentMarkdownWrite passes through when lifecycle.status is undefined', async () => {
+ test('applyAgentMarkdownWrite passes through when the doc is not tracked as conflicted', async () => {
const session = await manager.getSession('clean-doc', 'agent-clean');
expect(() =>
applyAgentMarkdownWrite(session.dc.document, '# Hello\n', 'replace'),
@@ -734,7 +735,7 @@ describe('conflict-aware write gate (FR9 a, d)', () => {
registerDocExtension('mdx-doc', '.mdx');
const session = await manager.getSession('mdx-doc', 'agent-mdx');
- session.dc.document.getMap('lifecycle').set('status', 'conflict');
+ bindConflictAuthority(session.dc.document, { has: () => true });
let caught: unknown;
try {
diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.ts
index de398cef9..90fb344e1 100644
--- a/packages/server/src/agent-sessions.ts
+++ b/packages/server/src/agent-sessions.ts
@@ -27,7 +27,8 @@ import {
} from './bridge-loss-detector.ts';
import { shouldRunPairedIntakeDetection } from './bridge-loss-suppression.ts';
import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
-import { DocInConflictError, isDocInConflict } from './conflict-errors.ts';
+import { isDocInConflict } from './conflict-authority.ts';
+import { DocInConflictError } from './conflict-errors.ts';
import {
type AgentWriteContentDivergence,
evaluateContentDivergence,
diff --git a/packages/server/src/api-extension.test-helper.ts b/packages/server/src/api-extension.test-helper.ts
index b57f26cdd..5df0a4e17 100644
--- a/packages/server/src/api-extension.test-helper.ts
+++ b/packages/server/src/api-extension.test-helper.ts
@@ -6,6 +6,7 @@ import {
import type { ApiExtensionOptions } from './api-extension.ts';
import { createApiExtension as createApiExtensionBase } from './api-extension.ts';
import type { BacklinkIndex } from './backlink-index.ts';
+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import type {
DerivedDocumentIndexApiPort,
DerivedDocumentIndexMutation,
@@ -229,10 +230,12 @@ export function createApiExtension(
| 'durabilityState'
| 'derivedDocumentIndex'
| 'signalChannel'
+ | 'conflicts'
| 'getProjectConfigEpoch'
| 'getLinkAdvisoryPolicy'
> &
LegacyIndexOptions & {
+ conflicts?: ApiExtensionOptions['conflicts'];
derivedDocumentIndex?: DerivedDocumentIndexApiPort;
signalChannel?: LegacySignalChannel;
getProjectConfigEpoch?: () => number;
@@ -254,6 +257,9 @@ export function createApiExtension(
...apiOptions,
getProjectConfigEpoch,
getLinkAdvisoryPolicy,
+ conflicts:
+ options.conflicts ??
+ createTestConflictAuthority(options.projectDir ?? options.contentDir, options.contentDir),
durabilityState: new DocumentDurabilityState(),
derivedDocumentIndex:
derivedDocumentIndex ??
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index ba7a414b8..22385cf30 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -96,9 +96,10 @@ import { resolveBundledSkillDir } from './build-skill-zip.ts';
import { CommentIndex } from './comments/comment-index.ts';
import { CommentService } from './comments/comment-service.ts';
import { CommentThreadStore } from './comments/thread-store.ts';
+import type { ConflictAuthority } from './conflict-authority.ts';
import {
DocInConflictError,
- isDocInConflict,
+ docInConflictEnvelope,
RESOLUTION_OPTIONS,
respondDocInConflict,
} from './conflict-errors.ts';
@@ -178,7 +179,6 @@ import {
import { composeAndWriteRawBody } 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,
@@ -1264,6 +1264,8 @@ export interface ApiExtensionOptions {
agentPresenceBroadcaster?: AgentPresenceBroadcaster;
onAgentWrite?: () => void;
getSyncEngine?: () => SyncEngine | null;
+ conflicts: ConflictAuthority;
+ setBatchInProgress?: (value: boolean) => void;
localOpCliArgs?: string[];
authStreamHeartbeatMs?: number;
projectDir?: string;
@@ -1282,15 +1284,9 @@ 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;
@@ -1386,6 +1382,8 @@ export function createApiExtension(
agentPresenceBroadcaster,
onAgentWrite,
getSyncEngine,
+ conflicts,
+ setBatchInProgress,
localOpCliArgs = ['open-knowledge'],
authStreamHeartbeatMs,
projectDir,
@@ -1400,11 +1398,9 @@ export function createApiExtension(
contentFilter,
installedAgentsProbe,
forceUnloadDocument,
- resetDocumentDurability,
ready,
recentlyRemovedDocs,
serializeDoc,
- resolveStaleExternalWrite,
evictManagedArtifactLkg,
semanticSearch,
getSemanticSimilarityFloor,
@@ -1431,6 +1427,7 @@ export function createApiExtension(
const documentRoutes = createDocumentRoutes({
hocuspocus,
+ conflicts,
contentDir,
isSafeDocName,
resolveAlias,
@@ -2302,17 +2299,10 @@ export function createApiExtension(
}
function assertRewriteTargetsNotConflicted(docNames: Iterable<string>): void {
- const renameEngine = getSyncEngine?.();
- const renameTrackedFiles = new Set(
- renameEngine ? renameEngine.getConflicts().map((c) => c.file) : [],
- );
for (const docName of docNames) {
- const doc = hocuspocus.documents.get(docName);
- const filePath = docNameToRelativePath(docName);
- const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);
- const conflictedByStore = renameTrackedFiles.has(filePath);
- if (conflictedByLifecycle || conflictedByStore) {
- throw new DocInConflictError({ file: filePath });
+ const entry = conflicts.findByDocName(docName);
+ if (entry !== undefined) {
+ throw new DocInConflictError({ file: entry.file });
}
}
}
@@ -2531,16 +2521,9 @@ export function createApiExtension(
);
}
- const renameEngine = getSyncEngine?.();
- const trackedFiles = new Set(
- renameEngine ? renameEngine.getConflicts().map((c) => c.file) : [],
- );
- const sourceDoc = hocuspocus.documents.get(sourceDocName);
- if (
- (sourceDoc !== undefined && isDocInConflict(sourceDoc)) ||
- trackedFiles.has(fromPath)
- ) {
- throw new DocInConflictError({ file: fromPath });
+ const sourceConflict = conflicts.findByDocName(sourceDocName);
+ if (sourceConflict !== undefined) {
+ throw new DocInConflictError({ file: sourceConflict.file });
}
const renamedAssets = [{ fromPath, toPath }];
@@ -2557,6 +2540,7 @@ export function createApiExtension(
contentDir,
undefined,
getBridgeLossReporter?.(),
+ conflicts,
);
if (recentlyRemovedDocs && !isSystemDoc(sourceDocName) && !isConfigDoc(sourceDocName)) {
recentlyRemovedDocs.setDeleted(sourceDocName);
@@ -2759,6 +2743,7 @@ export function createApiExtension(
contentDir,
undefined,
getBridgeLossReporter?.(),
+ conflicts,
);
const content = readCurrentDocumentContent(docName);
if (typeof content === 'string') {
@@ -3290,6 +3275,7 @@ export function createApiExtension(
contentDir,
options.resolveEmbed,
getBridgeLossReporter?.(),
+ conflicts,
);
const timestamp = new Date().toISOString();
@@ -3388,7 +3374,12 @@ export function createApiExtension(
);
} catch (e) {
if (e instanceof DocInConflictError) {
- respondDocInConflict(res, e, 'agent-write');
+ respondDocInConflict(
+ res,
+ e,
+ 'agent-write',
+ conflicts.findByDocName(stripDocExtension(e.file)),
+ );
return;
}
if (e instanceof FrontmatterMalformedError) {
@@ -3458,12 +3449,17 @@ export function createApiExtension(
'doc.name': docName,
}),
);
- return entryError(
+ const { detail, ...envelope } = docInConflictEnvelope(conflicts.findByDocName(docName));
+ return {
+ status: 'error',
docName,
- 'urn:ok:error:doc-in-conflict',
- 'Document is in conflict.',
- 'The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',
- );
+ error: {
+ type: 'urn:ok:error:doc-in-conflict',
+ title: 'Document is in conflict.',
+ detail,
+ ...envelope,
+ },
+ };
}
if (e instanceof FrontmatterMalformedError) {
logFrontmatterRefusal(e, 'agent-write-batch');
@@ -3552,6 +3548,7 @@ export function createApiExtension(
contentDir,
options.resolveEmbed,
getBridgeLossReporter?.(),
+ conflicts,
);
const entryEmbedResolver = options.resolveEmbed
@@ -3763,16 +3760,7 @@ export function createApiExtension(
listAffectedDocNames: (index, kind, path) =>
listAffectedDocNames(index as Map<string, FileIndexEntry>, kind, path),
getFileIndex,
- getConflictedFiles: () =>
- new Set(
- getSyncEngine?.()
- ?.getConflicts()
- .map((c) => c.file) ?? [],
- ),
- isDocNameInLifecycleConflict: (docName) => {
- const doc = hocuspocus.documents.get(docName);
- return doc !== undefined && isDocInConflict(doc);
- },
+ conflictFileForDocName: (docName) => conflicts.findByDocName(docName)?.file ?? null,
captureAndCloseDocuments,
markRecentlyRemoved: recentlyRemovedDocs
? (docName) => recentlyRemovedDocs.setDeleted(docName)
@@ -3907,9 +3895,9 @@ export function createApiExtension(
handler: string,
res: ServerResponse,
): boolean {
- const doc = hocuspocus.documents.get(docName);
- if (doc && isDocInConflict(doc)) {
- respondDocInConflict(res, new DocInConflictError({ file: `${docName}.md` }), handler);
+ const entry = conflicts.findByDocName(docName);
+ if (entry !== undefined) {
+ respondDocInConflict(res, new DocInConflictError({ file: entry.file }), handler, entry);
return true;
}
return false;
@@ -4722,6 +4710,7 @@ export function createApiExtension(
readAuditGeneration,
});
const lintWriteRoutes = createLintWriteRoutes({
+ conflicts,
contentDir,
projectDir,
signalLintConfigChanged,
@@ -4899,12 +4888,12 @@ export function createApiExtension(
contentDir,
getPrincipal,
hocuspocus,
- durabilityState,
log,
checkLocalOpSecurity,
getSyncEngine,
+ conflicts,
serializeDoc,
- resolveStaleExternalWrite,
+ setBatchInProgress,
});
const shareRoutes = createShareRoutes({
projectDir,
@@ -4946,8 +4935,7 @@ export function createApiExtension(
getPrincipal,
contentFilter,
signalChannel,
- hocuspocus,
- getSyncEngine,
+ conflicts,
flushContributors,
fileOpsService,
assetService,
@@ -4986,7 +4974,7 @@ export function createApiExtension(
sessionManager,
getPrincipal,
signalChannel,
- getSyncEngine,
+ conflicts,
recentlyRemovedDocs,
isSafeDocName,
resolveAlias,
@@ -5075,6 +5063,7 @@ export function createApiExtension(
signalChannel,
});
const agentWriteRoutes = createAgentWriteRoutes({
+ conflicts,
getLinkAdvisoryPolicy,
respondStaleExternalWrite,
requireNonEmptyDocName,
@@ -5118,7 +5107,8 @@ export function createApiExtension(
renameAttributionCounter,
});
const testRoutes = createTestRoutes({
- resetDocumentDurability,
+ conflicts,
+ durabilityState,
resolveAlias,
contentDir,
log,
diff --git a/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts b/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts
index b9a923c7f..3cade8e9f 100644
--- a/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts
+++ b/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts
@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.test-helper.ts';
+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import { _resetDocExtensionsForTests } from './doc-extensions.ts';
import { RecentlyRemovedDocs } from './recently-removed-docs.ts';
@@ -15,6 +16,12 @@ interface CapturedResponse {
body: string;
}
+function conflictAuthorityFor(contentDir: string, file: string) {
+ const authority = createTestConflictAuthority(contentDir);
+ authority.raise({ kind: 'merge-native', file });
+ return authority;
+}
+
function makeReq(url: string, body: unknown): IncomingMessage {
const readable = Readable.from(Buffer.from(JSON.stringify(body))) as unknown as IncomingMessage;
readable.method = 'POST';
@@ -154,9 +161,7 @@ describe('folder delete enumerates descendant docs from disk', () => {
} as unknown as Options['sessionManager'],
contentDir,
getFileIndex: () => new Map(),
- getSyncEngine: (() => ({
- getConflicts: () => [{ file: 'del-folder/page.mdx' }],
- })) as unknown as Options['getSyncEngine'],
+ conflicts: conflictAuthorityFor(contentDir, 'del-folder/page.mdx'),
});
const { status, structured } = await post(ext, '/api/delete-path', {
@@ -196,9 +201,7 @@ describe('folder duplicate conflict gate enumerates from disk', () => {
} as unknown as Options['sessionManager'],
contentDir,
getFileIndex: () => new Map(),
- getSyncEngine: (() => ({
- getConflicts: () => [{ file: 'dup-folder/child.md' }],
- })) as unknown as Options['getSyncEngine'],
+ conflicts: conflictAuthorityFor(contentDir, 'dup-folder/child.md'),
});
const { status, structured } = await post(ext, '/api/duplicate-path', {
@@ -235,9 +238,7 @@ describe('folder duplicate conflict gate enumerates from disk', () => {
} as unknown as Options['sessionManager'],
contentDir,
getFileIndex: () => new Map(),
- getSyncEngine: (() => ({
- getConflicts: () => [{ file: 'dup-mdx/page.mdx' }],
- })) as unknown as Options['getSyncEngine'],
+ conflicts: conflictAuthorityFor(contentDir, 'dup-mdx/page.mdx'),
});
const { status, structured } = await post(ext, '/api/duplicate-path', {
diff --git a/packages/server/src/api-skills-native-preservation.test.ts b/packages/server/src/api-skills-native-preservation.test.ts
index 6495a68eb..f3356b100 100644
--- a/packages/server/src/api-skills-native-preservation.test.ts
+++ b/packages/server/src/api-skills-native-preservation.test.ts
@@ -254,15 +254,17 @@ test('real live skill and reference conflicts refuse edits and rename without ch
expect(reference.status, reference.body).toBe(200);
const referenceDocName = `${docName.slice(0, -5)}${file.slice(0, -3)}`;
for (const current of [docName, referenceDocName]) {
- const session = await server.serverInstance.sessionManager.getSession(
- current,
- 'agent-conflict-writer',
- { displayName: 'Conflict Writer', colorSeed: 'conflict-writer' },
- );
- session.dc.document.transact(
- () => session.dc.document.getMap('lifecycle').set('status', 'conflict'),
- session.origin,
- );
+ await server.serverInstance.sessionManager.getSession(current, 'agent-conflict-writer', {
+ displayName: 'Conflict Writer',
+ colorSeed: 'conflict-writer',
+ });
+ const content = readFileSync(join(root, 'normal', `${current}.md`), 'utf8');
+ server.serverInstance.conflicts.raise({
+ kind: 'reconcile',
+ file: server.serverInstance.conflicts.fileOf(current),
+ reason: 'merged-with-markers',
+ stages: { base: content, ours: content, theirs: content },
+ });
}
const skillBefore = readFileSync(join(root, 'normal', path), 'utf8');
const referenceBefore = readFileSync(join(root, 'normal', `${referenceDocName}.md`), 'utf8');
diff --git a/packages/server/src/boot-conflict-restore.test.ts b/packages/server/src/boot-conflict-restore.test.ts
deleted file mode 100644
index ea393adf6..000000000
--- a/packages/server/src/boot-conflict-restore.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { execFile } from 'node:child_process';
-import { mkdirSync, writeFileSync } from 'node:fs';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { promisify } from 'node:util';
-import { OK_DIR } from '@inkeep/open-knowledge-core';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { bootServer } from './boot.ts';
-import { ConfigSchema } from './config/schema.ts';
-
-const execFileAsync = promisify(execFile);
-const TEST_CONFIG = ConfigSchema.parse({});
-
-function seedOkScaffold(projectDir: string): void {
- const okDir = resolve(projectDir, OK_DIR);
- mkdirSync(okDir, { recursive: true });
- writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');
- writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');
-}
-
-function seedConflictsJson(
- projectDir: string,
- entries: Array<{ file: string; detectedAt?: string }>,
-): void {
- const localDir = resolve(projectDir, OK_DIR, 'local');
- mkdirSync(localDir, { recursive: true });
- const data = {
- version: 1,
- branch: 'main',
- conflicts: entries.map((e) => ({
- file: e.file,
- detectedAt: e.detectedAt ?? '2026-05-19T00:00:00.000Z',
- })),
- };
- writeFileSync(resolve(localDir, 'conflicts.json'), JSON.stringify(data, null, 2), 'utf-8');
-}
-
-function seedWorkingTreeConflictsJson(projectDir: string, file: string): void {
- const localDir = resolve(projectDir, OK_DIR, 'local');
- mkdirSync(localDir, { recursive: true });
- const data = {
- version: 1,
- branch: 'main',
- conflicts: [
- {
- file,
- detectedAt: '2026-05-19T00:00:00.000Z',
- variant: 'working-tree',
- theirsSha: '0000000000000000000000000000000000000000',
- baseSha: '0000000000000000000000000000000000000000',
- },
- ],
- };
- writeFileSync(resolve(localDir, 'conflicts.json'), JSON.stringify(data, null, 2), 'utf-8');
-}
-
-async function seedRealMergeConflict(projectDir: string, filePath: string): Promise<void> {
- const opts = { cwd: projectDir };
- await execFileAsync('git', ['config', 'user.email', '[email protected]'], opts);
- await execFileAsync('git', ['config', 'user.name', 'Test'], opts);
- writeFileSync(resolve(projectDir, filePath), 'base\n', 'utf-8');
- await execFileAsync('git', ['add', filePath], opts);
- await execFileAsync('git', ['commit', '-m', 'base'], opts);
- await execFileAsync('git', ['checkout', '-b', 'theirs-branch'], opts);
- writeFileSync(resolve(projectDir, filePath), 'theirs\n', 'utf-8');
- await execFileAsync('git', ['commit', '-am', 'theirs'], opts);
- await execFileAsync('git', ['checkout', 'main'], opts);
- writeFileSync(resolve(projectDir, filePath), 'ours\n', 'utf-8');
- await execFileAsync('git', ['commit', '-am', 'ours'], opts);
- await execFileAsync('git', ['merge', 'theirs-branch'], opts).catch(() => {});
-}
-
-let tmpDir: string;
-
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-boot-conflict-restore-'));
-});
-
-afterEach(async () => {
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-describe('bootServer — FR14 lifecycle restoration from conflicts.json', () => {
- test('pre-seeds lifecycle.status=conflict on each tracked doc before HTTP listen', async () => {
- const contentDir = tmpDir;
- await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
- seedOkScaffold(contentDir);
- await seedRealMergeConflict(contentDir, 'foo.md');
- seedConflictsJson(contentDir, [{ file: 'foo.md' }]);
-
- const booted = await bootServer({
- config: TEST_CONFIG,
- contentDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
-
- try {
- const dc = await booted.serverInstance.hocuspocus.openDirectConnection('foo');
- try {
- const lifecycleMap = dc.document?.getMap('lifecycle');
- expect(lifecycleMap?.get('status')).toBe('conflict');
- expect(lifecycleMap?.get('reason')).toBe('conflict-markers');
- } finally {
- await dc.disconnect();
- }
- } finally {
- await booted.destroy();
- }
- }, 30_000);
-
- test('preserves a working-tree conflict with no MERGE_HEAD and restores its lifecycle', async () => {
- const contentDir = tmpDir;
- await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
- seedOkScaffold(contentDir);
- await execFileAsync('git', ['config', 'user.email', '[email protected]'], { cwd: contentDir });
- await execFileAsync('git', ['config', 'user.name', 'Test'], { cwd: contentDir });
- writeFileSync(resolve(contentDir, 'wt.md'), 'origin\n', 'utf-8');
- await execFileAsync('git', ['add', 'wt.md'], { cwd: contentDir });
- await execFileAsync('git', ['commit', '-m', 'seed'], { cwd: contentDir });
- seedWorkingTreeConflictsJson(contentDir, 'wt.md');
-
- const booted = await bootServer({
- config: TEST_CONFIG,
- contentDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
-
- try {
- const dc = await booted.serverInstance.hocuspocus.openDirectConnection('wt');
- try {
- expect(dc.document?.getMap('lifecycle').get('status')).toBe('conflict');
- } finally {
- await dc.disconnect();
- }
- } finally {
- await booted.destroy();
- }
- }, 30_000);
-
- test('emits lifecycle-restored-from-conflicts-json event per restored doc', async () => {
- const contentDir = tmpDir;
- await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
- seedOkScaffold(contentDir);
- mkdirSync(resolve(contentDir, 'docs'), { recursive: true });
- await seedRealMergeConflict(contentDir, 'docs/bar.md');
- seedConflictsJson(contentDir, [{ file: 'docs/bar.md' }]);
-
- const calls: string[] = [];
- const original = console.warn;
- console.warn = (msg: unknown, ...rest: unknown[]) => {
- const line = typeof msg === 'string' ? msg : String(msg);
- calls.push(line);
- original.call(console, msg, ...rest);
- };
-
- try {
- const booted = await bootServer({
- config: TEST_CONFIG,
- contentDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
- try {
- const restored = calls.find((l) => {
- try {
- const parsed = JSON.parse(l) as { event?: string; 'doc.name'?: string };
- return (
- parsed.event === 'lifecycle-restored-from-conflicts-json' &&
- parsed['doc.name'] === 'docs/bar'
- );
- } catch {
- return false;
- }
- });
- expect(restored).toBeDefined();
- } finally {
- await booted.destroy();
- }
- } finally {
- console.warn = original;
- }
- }, 30_000);
-
- test('skips and logs warning when conflicts.json is absent (no crash)', async () => {
- const contentDir = tmpDir;
- await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
- seedOkScaffold(contentDir);
-
- const booted = await bootServer({
- config: TEST_CONFIG,
- contentDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
-
- try {
- expect(typeof booted.port).toBe('number');
- expect(booted.port).toBeGreaterThan(0);
- } finally {
- await booted.destroy();
- }
- }, 30_000);
-
- test('skips and logs warning when conflicts.json is malformed JSON', async () => {
- const contentDir = tmpDir;
- await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
- seedOkScaffold(contentDir);
- const localDir = resolve(contentDir, OK_DIR, 'local');
- mkdirSync(localDir, { recursive: true });
- writeFileSync(resolve(localDir, 'conflicts.json'), '{ this is not json', 'utf-8');
-
- const booted = await bootServer({
- config: TEST_CONFIG,
- contentDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
-
- try {
- expect(typeof booted.port).toBe('number');
- expect(booted.port).toBeGreaterThan(0);
- } finally {
- await booted.destroy();
- }
- }, 30_000);
-});
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index fa66df730..a1d144f5a 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -1,7 +1,7 @@
import { existsSync, readdirSync, statSync } from 'node:fs';
import type { Server as HttpServer } from 'node:http';
import { homedir } from 'node:os';
-import { join, resolve } from 'node:path';
+import { resolve } from 'node:path';
import {
ASSET_EXTENSIONS,
DEFAULT_SERVER_HOST,
@@ -16,12 +16,8 @@ import {
resolveServerRuntimeConfig,
type ServerRuntimeConfig,
} from '@inkeep/open-knowledge-core';
-import {
- resolveGitDir,
- resolveGitDirDetailed,
-} from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { context, propagation } from '@opentelemetry/api';
-import { simpleGit } from 'simple-git';
import sirv from 'sirv';
import {
AcpThreadManager,
@@ -32,11 +28,8 @@ import { collectServerHostSnapshot } from './agent-registry-probes.ts';
import { createAssetServeMiddleware } from './asset-serve-middleware.ts';
import { bootElapsedMs, recordBootPhase, startBootTimings } from './boot-timings.ts';
import type { Config } from './config/schema.ts';
-import { ConflictStore } from './conflict-storage.ts';
import { installCrashCapture } from './crash-capture.ts';
-import { stripDocExtension } from './doc-extensions.ts';
import { normalizeFsPath } from './fs-traced.ts';
-import { listNames } from './git-paths.ts';
import {
assertGitAvailable,
type GitDetected,
@@ -548,12 +541,6 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
});
}
- await restoreLifecycleFromConflictsJson({
- hocuspocus,
- projectDir: opts.projectDir ?? opts.contentDir,
- log,
- });
-
const listenAddresses = [...new Set(effectiveBindAddresses)];
const primaryAddress = listenAddresses[0];
const cleanupAfterListenFailure = async (): Promise<void> => {
@@ -827,112 +814,3 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
acpThreadManager,
};
}
-
-export async function restoreLifecycleFromConflictsJson(args: {
- hocuspocus: ServerInstance['hocuspocus'];
- projectDir: string;
- log: PinoLogger;
-}): Promise<void> {
- const { hocuspocus, projectDir, log } = args;
- let store: ConflictStore;
- let entries: Array<{ file: string; variant?: 'working-tree' }>;
- try {
- store = new ConflictStore(projectDir);
- entries = store.list();
- } catch (err) {
- log.warn(
- { err, projectDir },
- '[boot] lifecycle restore: failed to read conflicts.json — skipping',
- );
- return;
- }
- if (entries.length === 0) return;
-
- const isWorkingTree = (e: { variant?: string }): boolean => e.variant === 'working-tree';
- let stillUnmerged: Set<string> | null = null;
- try {
- const gitDir = resolveGitDir(projectDir);
- const mergeHeadPath = gitDir ? join(gitDir, 'MERGE_HEAD') : null;
- if (!mergeHeadPath || !existsSync(mergeHeadPath)) {
- const staleMergeNative = entries.filter((e) => !isWorkingTree(e));
- for (const entry of staleMergeNative) store.removeConflict(entry.file);
- entries = entries.filter(isWorkingTree);
- if (staleMergeNative.length > 0) {
- console.warn(
- JSON.stringify({
- event: 'lifecycle-restore-cleared-stale-conflicts',
- reason: 'no-merge-head',
- count: staleMergeNative.length,
- }),
- );
- }
- if (entries.length === 0) return;
- } else {
- const pg = simpleGit({ baseDir: projectDir, timeout: { block: 5_000 } });
- stillUnmerged = new Set(await listNames(pg, ['diff', '--name-only', '--diff-filter=U']));
- }
- } catch (err) {
- log.warn(
- { err, projectDir },
- '[boot] lifecycle restore: git unmerged probe failed — restoring all entries',
- );
- }
-
- if (stillUnmerged !== null) {
- let pruned = 0;
- for (const entry of entries) {
- if (!isWorkingTree(entry) && !stillUnmerged.has(entry.file)) {
- store.removeConflict(entry.file);
- pruned++;
- }
- }
- if (pruned > 0) {
- console.warn(
- JSON.stringify({
- event: 'lifecycle-restore-pruned-resolved-entries',
- pruned,
- remaining: entries.length - pruned,
- }),
- );
- }
- entries = entries.filter((e) => isWorkingTree(e) || stillUnmerged?.has(e.file));
- if (entries.length === 0) return;
- }
-
- for (const entry of entries) {
- const docName = stripDocExtension(entry.file);
- let dc: Awaited<ReturnType<typeof hocuspocus.openDirectConnection>> | null = null;
- let restored = false;
- try {
- dc = await hocuspocus.openDirectConnection(docName);
- const document = dc.document;
- if (!document) continue;
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'conflict-markers');
- restored = true;
- console.warn(
- JSON.stringify({
- event: 'lifecycle-restored-from-conflicts-json',
- 'doc.name': docName,
- }),
- );
- } catch (err) {
- log.warn(
- { err, docName },
- '[boot] lifecycle restore: failed to set lifecycle for doc — skipping',
- );
- } finally {
- if (dc) {
- try {
- await dc.disconnect();
- } catch (err) {
- log.warn(
- { err, docName, restored },
- '[boot] lifecycle restore: disconnect failed after lifecycle write',
- );
- }
- }
- }
- }
-}
diff --git a/packages/server/src/conflict-authority.test-helper.ts b/packages/server/src/conflict-authority.test-helper.ts
new file mode 100644
index 000000000..dd1574f01
--- /dev/null
+++ b/packages/server/src/conflict-authority.test-helper.ts
@@ -0,0 +1,33 @@
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { ConflictAuthority } from './conflict-authority.ts';
+
+export const RECONCILE_TEST_CONFLICTS: Pick<
+ ConflictAuthority,
+ 'dissolveReconcile' | 'fileOf' | 'raise'
+> = {
+ dissolveReconcile: () => {},
+ raise: () => {},
+ fileOf: (docName: string) => `${docName}.md`,
+};
+
+export function createTestConflictAuthority(
+ projectDir: string,
+ contentDir: string = projectDir,
+): ConflictAuthority {
+ return new ConflictAuthority({
+ projectDir,
+ contentDir,
+ io: {
+ gitRaw: async () => '',
+ writeProjectFileUntracked: () => {},
+ unlinkProjectFile: () => {},
+ applyResolvedContent: async () => {},
+ },
+ });
+}
+
+export function createTestConflictAuthorityInTmpDir(prefix: string): ConflictAuthority {
+ return createTestConflictAuthority(mkdtempSync(join(tmpdir(), prefix)));
+}
diff --git a/packages/server/src/conflict-authority.test.ts b/packages/server/src/conflict-authority.test.ts
new file mode 100644
index 000000000..ae23f8c29
--- /dev/null
+++ b/packages/server/src/conflict-authority.test.ts
@@ -0,0 +1,1577 @@
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import * as Y from 'yjs';
+import {
+ bindConflictAuthority,
+ ConflictAuthority,
+ type ConflictChange,
+ type ConflictIo,
+ isDocInConflict,
+} from './conflict-authority.ts';
+import type { Conflict } from './conflict-kinds.ts';
+import { strategiesFor } from './conflict-kinds.ts';
+import { _resetDocExtensionsForTests, registerDocExtension } from './doc-extensions.ts';
+import { getLogger } from './logger.ts';
+
+let tmpDir = '';
+let projectDir = '';
+let storePath = '';
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'conflict-authority-test-'));
+ projectDir = join(tmpDir, 'project');
+ storePath = join(projectDir, '.ok', LOCAL_DIR, 'conflicts.json');
+ mkdirSync(join(projectDir, '.ok', LOCAL_DIR), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true });
+});
+
+interface FakeIo extends ConflictIo {
+ gitCalls: string[][];
+ writes: Array<{ absPath: string; bytes: string }>;
+ unlinks: string[];
+ applied: Array<{ docName: string; bytes: string }>;
+}
+
+function makeIo(overrides: Partial<ConflictIo> = {}): FakeIo {
+ const gitCalls: string[][] = [];
+ const writes: Array<{ absPath: string; bytes: string }> = [];
+ const unlinks: string[] = [];
+ const applied: Array<{ docName: string; bytes: string }> = [];
+ return {
+ gitCalls,
+ writes,
+ unlinks,
+ applied,
+ gitRaw: async (args) => {
+ gitCalls.push(args);
+ return '';
+ },
+ writeProjectFileUntracked: (absPath, bytes) => {
+ writes.push({ absPath, bytes });
+ writeFileSync(absPath, bytes, 'utf-8');
+ },
+ unlinkProjectFile: (absPath) => {
+ unlinks.push(absPath);
+ rmSync(absPath, { force: true });
+ },
+ applyResolvedContent: async (docName, absPath, bytes) => {
+ applied.push({ docName, bytes });
+ writeFileSync(absPath, bytes, 'utf-8');
+ },
+ ...overrides,
+ };
+}
+
+interface Rig {
+ authority: ConflictAuthority;
+ io: FakeIo;
+ signals: number;
+ changes: ConflictChange[];
+}
+
+function makeAuthority(io: FakeIo = makeIo()): Rig {
+ const rig = { io, signals: 0, changes: [] as ConflictChange[] } as Rig;
+ rig.authority = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'main',
+ signal: {
+ signal: () => {
+ rig.signals++;
+ },
+ },
+ io,
+ });
+ rig.authority.subscribe((change) => rig.changes.push(change));
+ return rig;
+}
+
+function readLedger(): { version: number; branch: string; conflicts: Conflict[] } {
+ return JSON.parse(readFileSync(storePath, 'utf-8'));
+}
+
+function quarantinedLedgers(): string[] {
+ return readdirSync(join(projectDir, '.ok', LOCAL_DIR)).filter((name) =>
+ name.includes('conflicts.json.corrupt-'),
+ );
+}
+
+describe('ConflictAuthority membership and persistence', () => {
+ test('starts empty when no conflicts.json exists', () => {
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(authority.list()).toEqual([]);
+ });
+
+ test('raise persists the entry with its kind and indexes it by file and docName', () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'README.md' });
+
+ expect(authority.count()).toBe(1);
+ expect(authority.findByFile('README.md')?.kind).toBe('merge-native');
+ expect(authority.findByDocName('README')?.file).toBe('README.md');
+ expect(authority.has('README')).toBe(true);
+
+ const persisted = readLedger();
+ expect(persisted.version).toBe(2);
+ expect(persisted.branch).toBe('main');
+ expect(persisted.conflicts).toHaveLength(1);
+ expect(persisted.conflicts[0].kind).toBe('merge-native');
+ });
+
+ test('raise accumulates distinct files and upserts a changed payload for one file', () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ authority.raise({ kind: 'merge-native', file: 'b.md' });
+ authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'sha2' });
+
+ expect(authority.count()).toBe(2);
+ expect(authority.findByFile('a.md')?.kind).toBe('working-tree');
+ });
+
+ test('a repeated identical raise is a no-op and does not signal', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ const signalsAfterFirst = rig.signals;
+
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ expect(rig.signals).toBe(signalsAfterFirst);
+ expect(rig.changes).toHaveLength(1);
+ });
+
+ test('every mutation signals sync-status exactly once', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ expect(rig.signals).toBe(1);
+ rig.authority.raise({ kind: 'merge-native', file: 'b.md' });
+ expect(rig.signals).toBe(2);
+ rig.authority.dissolveWorkingTree('a.md');
+ expect(rig.signals).toBe(2);
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'c.md',
+ reason: 'disk-markers',
+ stages: { base: 'b', ours: 'o', theirs: 't' },
+ });
+ expect(rig.signals).toBe(3);
+ rig.authority.dissolveReconcile('c');
+ expect(rig.signals).toBe(4);
+ });
+
+ test('subscribers see raised and cleared changes carrying the docName', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'docs/note.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'b', ours: 'o', theirs: 't' },
+ });
+ rig.authority.dissolveReconcile('docs/note');
+
+ expect(rig.changes).toHaveLength(2);
+ expect(rig.changes[0]).toMatchObject({ type: 'raised', docName: 'docs/note' });
+ expect(rig.changes[1]).toMatchObject({
+ type: 'cleared',
+ docName: 'docs/note',
+ cause: 'dissolved',
+ });
+ });
+
+ test('raise on a system doc is refused', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: '__system__.md',
+ reason: 'disk-markers',
+ stages: { base: '', ours: '', theirs: '' },
+ });
+
+ expect(rig.authority.count()).toBe(0);
+ expect(rig.authority.list()).toEqual([]);
+ expect(rig.signals).toBe(0);
+ expect(rig.changes).toEqual([]);
+ });
+
+ test('a git kind replaces a reconcile entry but a reconcile raise never replaces a git kind', () => {
+ const { authority } = makeAuthority();
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'b', ours: 'o', theirs: 't' },
+ });
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'b', ours: 'o', theirs: 't' },
+ });
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+
+ test('setBranch lands on the next persisted write', () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ authority.setBranch('feat/new-branch');
+ authority.raise({ kind: 'merge-native', file: 'b.md' });
+ expect(readLedger().branch).toBe('feat/new-branch');
+ });
+});
+
+describe('ConflictAuthority per-kind closers', () => {
+ test('dissolveReconcile clears a reconcile entry and refuses another kind', () => {
+ const { authority } = makeAuthority();
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'b', ours: 'o', theirs: 't' },
+ });
+ authority.dissolveReconcile('a');
+ expect(authority.count()).toBe(0);
+
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ authority.dissolveReconcile('a');
+ expect(authority.count()).toBe(1);
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+
+ test('dissolveWorkingTree clears a working-tree entry and refuses another kind', () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'sha' });
+ authority.dissolveWorkingTree('a.md');
+ expect(authority.count()).toBe(0);
+
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ authority.dissolveWorkingTree('a.md');
+ expect(authority.count()).toBe(1);
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+
+ test('a closer on an absent file is a no-op and does not signal', () => {
+ const rig = makeAuthority();
+ rig.authority.dissolveReconcile('nope');
+ rig.authority.dissolveWorkingTree('nope.md');
+
+ expect(rig.authority.count()).toBe(0);
+ expect(rig.signals).toBe(0);
+ expect(rig.changes).toEqual([]);
+ });
+});
+
+describe('ConflictAuthority pruneMergeNativeAgainstGit (PRD-8318 ordering)', () => {
+ function unmergedIo(unmerged: string[]): FakeIo {
+ return makeIo({
+ gitRaw: async (args) => (args[0] === 'diff' ? unmerged.map((f) => `${f}\0`).join('') : ''),
+ });
+ }
+
+ function seedMergeHead(): void {
+ mkdirSync(join(projectDir, '.git'), { recursive: true });
+ writeFileSync(join(projectDir, '.git', 'HEAD'), 'ref: refs/heads/main\n', 'utf-8');
+ writeFileSync(join(projectDir, '.git', 'MERGE_HEAD'), 'deadbeef\n', 'utf-8');
+ }
+
+ test('with no MERGE_HEAD every merge-native entry is pruned', async () => {
+ const rig = makeAuthority(unmergedIo([]));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ rig.authority.raise({ kind: 'working-tree', file: 'b.md', theirsSha: 'sha' });
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(1);
+ expect(rig.authority.findByFile('a.md')).toBeUndefined();
+ expect(rig.authority.findByFile('b.md')).toBeDefined();
+ });
+
+ test('mid-merge only entries no longer unmerged are pruned', async () => {
+ seedMergeHead();
+ const rig = makeAuthority(unmergedIo(['b.md']));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ rig.authority.raise({ kind: 'merge-native', file: 'b.md' });
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(1);
+ expect(rig.authority.findByFile('a.md')).toBeUndefined();
+ expect(rig.authority.findByFile('b.md')).toBeDefined();
+ });
+
+ test('a prune that removes nothing does not signal', async () => {
+ seedMergeHead();
+ const rig = makeAuthority(unmergedIo(['a.md']));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ const before = rig.signals;
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(0);
+ expect(rig.signals).toBe(before);
+ });
+
+ test('prune before dissolve and dissolve before prune converge on the same empty state', async () => {
+ seedMergeHead();
+
+ function seedBoth(): ReturnType<typeof makeAuthority> {
+ const rig = makeAuthority(unmergedIo([]));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'b.md',
+ reason: 'disk-markers',
+ stages: { base: 'base', ours: 'ours', theirs: 'theirs' },
+ });
+ return rig;
+ }
+
+ const pruneFirst = seedBoth();
+ expect(await pruneFirst.authority.pruneMergeNativeAgainstGit()).toBe(1);
+ pruneFirst.authority.dissolveReconcile('b');
+
+ const dissolveFirst = seedBoth();
+ dissolveFirst.authority.dissolveReconcile('b');
+ expect(await dissolveFirst.authority.pruneMergeNativeAgainstGit()).toBe(1);
+
+ expect(pruneFirst.authority.count()).toBe(0);
+ expect(dissolveFirst.authority.count()).toBe(0);
+ });
+
+ test('a malformed .git pointer leaves the ledger untouched', async () => {
+ const rig = makeAuthority(unmergedIo([]));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ writeFileSync(join(projectDir, '.git'), 'this is not a gitdir pointer\n', 'utf-8');
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(0);
+ expect(rig.authority.findByFile('a.md')).toBeDefined();
+ });
+
+ test.skipIf(typeof process.getuid === 'function' && process.getuid() === 0)(
+ 'an unreadable .git leaves the ledger untouched',
+ async () => {
+ const rig = makeAuthority(unmergedIo([]));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ mkdirSync(join(projectDir, '.git'), { recursive: true });
+ chmodSync(projectDir, 0o000);
+ try {
+ expect(() => statSync(join(projectDir, '.git'))).toThrow();
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(0);
+ } finally {
+ chmodSync(projectDir, 0o755);
+ }
+ expect(rig.authority.findByFile('a.md')).toBeDefined();
+ },
+ );
+
+ test('an absent .git still prunes every merge-native entry', async () => {
+ const rig = makeAuthority(unmergedIo([]));
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(1);
+ expect(rig.authority.findByFile('a.md')).toBeUndefined();
+ });
+
+ test('a replacement raised while Git pruning awaits survives the old probe', async () => {
+ mkdirSync(join(projectDir, '.git'), { recursive: true });
+ writeFileSync(join(projectDir, '.git', 'MERGE_HEAD'), 'merge-head\n');
+ const rig = makeAuthority(
+ makeIo({
+ gitRaw: async () => {
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'replacement' });
+ return '';
+ },
+ }),
+ );
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(0);
+ expect(rig.authority.findByFile('a.md')).toMatchObject({
+ kind: 'working-tree',
+ theirsSha: 'replacement',
+ });
+ expect(rig.changes.some((change) => change.type === 'cleared')).toBe(false);
+ });
+
+ test('a failing git probe leaves the ledger untouched', async () => {
+ seedMergeHead();
+ const rig = makeAuthority(
+ makeIo({
+ gitRaw: async () => {
+ throw new Error('git exploded');
+ },
+ }),
+ );
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ expect(await rig.authority.pruneMergeNativeAgainstGit()).toBe(0);
+ expect(rig.authority.findByFile('a.md')).toBeDefined();
+ });
+});
+
+describe('ConflictAuthority ledger migration', () => {
+ function writeLedger(conflicts: unknown[], version = 1): void {
+ writeFileSync(storePath, JSON.stringify({ version, branch: 'main', conflicts }), 'utf-8');
+ }
+
+ test('a legacy entry with no kind loads as merge-native', () => {
+ writeLedger([{ file: 'a.md', detectedAt: '2026-05-19T00:00:00.000Z' }]);
+ const { authority } = makeAuthority();
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+
+ test.each([1, 2])(
+ 'a version %i entry with an unrecognized kind is logged and dropped',
+ (version) => {
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ writeLedger([{ file: 'a.md', detectedAt: 'x', kind: 'future-kind' }], version);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(warn).toHaveBeenCalledWith(
+ { file: 'a.md', kind: 'future-kind' },
+ '[conflicts] dropped a ledger entry with an unrecognized conflict kind',
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ },
+ );
+
+ test('a non-string kind is logged with a bounded type marker', () => {
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ writeLedger([{ file: 'a.md', detectedAt: 'x', kind: { nested: true } }]);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(warn).toHaveBeenCalledWith(
+ { file: 'a.md', kind: '<object>' },
+ '[conflicts] dropped a ledger entry with an unrecognized conflict kind',
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('an oversized string kind is truncated in the log', () => {
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ writeLedger([{ file: 'a.md', detectedAt: 'x', kind: 'x'.repeat(100) }]);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(warn).toHaveBeenCalledWith(
+ { file: 'a.md', kind: 'x'.repeat(80) },
+ '[conflicts] dropped a ledger entry with an unrecognized conflict kind',
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('a legacy working-tree variant with a pinned blob loads as working-tree', () => {
+ writeLedger([
+ {
+ file: 'a.md',
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ variant: 'working-tree',
+ theirsSha: 'sha',
+ baseSha: 'base',
+ },
+ ]);
+ const { authority } = makeAuthority();
+ const entry = authority.findByFile('a.md');
+ expect(entry).toMatchObject({ kind: 'working-tree', theirsSha: 'sha', baseSha: 'base' });
+ });
+
+ test('a working-tree entry with no pinned blob is dropped', () => {
+ writeLedger([{ file: 'a.md', detectedAt: 'x', variant: 'working-tree' }]);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ });
+
+ test('a reconcile entry with no stages is dropped', () => {
+ writeLedger([{ file: 'a.md', detectedAt: 'x', kind: 'reconcile', reason: 'disk-markers' }]);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ });
+
+ test('a reconcile entry whose stages is null is dropped instead of throwing at boot', () => {
+ writeLedger([
+ { file: 'a.md', detectedAt: 'x', kind: 'reconcile', reason: 'disk-markers', stages: null },
+ { file: 'b.md', detectedAt: 'x' },
+ ]);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(1);
+ expect(authority.findByFile('b.md')?.kind).toBe('merge-native');
+ });
+
+ test('a reconcile entry missing the ours or theirs stage is dropped, never coerced', () => {
+ writeLedger([
+ {
+ file: 'a.md',
+ detectedAt: 'x',
+ kind: 'reconcile',
+ reason: 'merged-with-markers',
+ stages: { base: 'B' },
+ },
+ {
+ file: 'b.md',
+ detectedAt: 'x',
+ kind: 'reconcile',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'O' },
+ },
+ ]);
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ });
+
+ test('a reconcile entry with stages survives restart intact', () => {
+ writeLedger([
+ {
+ file: 'a.md',
+ detectedAt: 'x',
+ kind: 'reconcile',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ },
+ ]);
+ const { authority } = makeAuthority();
+ expect(authority.findByFile('a.md')).toMatchObject({
+ kind: 'reconcile',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ });
+ });
+
+ test('corrupt JSON starts empty and the unreadable file is moved aside', () => {
+ writeFileSync(storePath, 'NOT JSON', 'utf-8');
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(existsSync(storePath)).toBe(false);
+ expect(quarantinedLedgers()).toHaveLength(1);
+ });
+
+ test.each(['null', '[]', '"ledger"', '42', 'true'])(
+ 'a non-object ledger %s is quarantined and startup recovers',
+ (payload) => {
+ writeFileSync(storePath, payload, 'utf-8');
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(existsSync(storePath)).toBe(false);
+ const quarantined = quarantinedLedgers();
+ expect(quarantined).toHaveLength(1);
+ expect(readFileSync(join(dirname(storePath), quarantined[0] ?? ''), 'utf-8')).toBe(payload);
+ authority.raise({ kind: 'merge-native', file: 'recovered.md' });
+ expect(makeAuthority().authority.findByFile('recovered.md')?.kind).toBe('merge-native');
+ },
+ );
+
+ test('migrated entries are written back carrying their kind', () => {
+ writeLedger([{ file: 'a.md', detectedAt: '2026-05-19T00:00:00.000Z' }]);
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'b.md' });
+ expect(readLedger().conflicts.every((c) => typeof c.kind === 'string')).toBe(true);
+ });
+});
+
+describe('ConflictAuthority ledger durability', () => {
+ function writeRawLedger(payload: unknown): void {
+ writeFileSync(storePath, JSON.stringify(payload), 'utf-8');
+ }
+
+ test('a version 1 ledger still loads', () => {
+ writeRawLedger({
+ version: 1,
+ branch: 'main',
+ conflicts: [{ file: 'a.md', detectedAt: 'x', kind: 'merge-native' }],
+ });
+ const { authority } = makeAuthority();
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+
+ test('an unknown ledger version is moved aside instead of migrated', () => {
+ writeRawLedger({
+ version: 99,
+ branch: 'main',
+ conflicts: [{ file: 'a.md', detectedAt: 'x', kind: 'merge-native' }],
+ });
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(existsSync(storePath)).toBe(false);
+ expect(quarantinedLedgers()).toHaveLength(1);
+ });
+
+ test('a ledger with no version at all is moved aside', () => {
+ writeRawLedger({ branch: 'main', conflicts: [] });
+ const { authority } = makeAuthority();
+ expect(authority.count()).toBe(0);
+ expect(quarantinedLedgers()).toHaveLength(1);
+ });
+
+ test('a successful persist writes version 2 and leaves no temp file behind', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ expect(readLedger().version).toBe(2);
+ expect(existsSync(`${storePath}.tmp`)).toBe(false);
+ });
+
+ test('a persist that cannot land is logged rather than swallowed, and membership survives', () => {
+ const error = vi.spyOn(getLogger('conflict-authority'), 'error');
+ try {
+ const rig = makeAuthority();
+ mkdirSync(`${storePath}.tmp`, { recursive: true });
+
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ expect(error).toHaveBeenCalledTimes(1);
+ expect(error.mock.calls[0]?.[1]).toBe(
+ '[conflicts] failed to persist conflicts.json — the ledger will not survive restart',
+ );
+ expect(rig.authority.findByFile('a.md')).toBeDefined();
+ expect(rig.authority.has('a')).toBe(true);
+ } finally {
+ error.mockRestore();
+ }
+ });
+});
+
+describe('ConflictAuthority docName and path mapping', () => {
+ afterEach(() => {
+ _resetDocExtensionsForTests();
+ });
+
+ test('a mermaid docName keeps its own extension in both directions', () => {
+ const rig = makeAuthority();
+ expect(rig.authority.fileOf('diagram.mermaid')).toBe('diagram.mermaid');
+
+ rig.authority.raise({ kind: 'merge-native', file: 'diagram.mermaid' });
+ expect(rig.authority.has('diagram.mermaid')).toBe(true);
+ });
+
+ test('a non-markdown text docName keeps its own extension in both directions', () => {
+ const rig = makeAuthority();
+ expect(rig.authority.fileOf('notes.txt')).toBe('notes.txt');
+
+ rig.authority.raise({ kind: 'merge-native', file: 'notes.txt' });
+ expect(rig.authority.has('notes.txt')).toBe(true);
+ });
+
+ test('a markdown docName still gains its registered extension', () => {
+ registerDocExtension('page', '.mdx');
+ const rig = makeAuthority();
+ expect(rig.authority.fileOf('page')).toBe('page.mdx');
+
+ rig.authority.raise({ kind: 'merge-native', file: 'page.mdx' });
+ expect(rig.authority.has('page')).toBe(true);
+ });
+});
+
+describe('isDocInConflict binding', () => {
+ function namedDoc(name: string): Y.Doc {
+ return Object.assign(new Y.Doc(), { name });
+ }
+
+ test('an unbound document reads as clear and says so in the log', () => {
+ const error = vi.spyOn(getLogger('conflict-authority'), 'error');
+ try {
+ const doc = namedDoc('a');
+ expect(isDocInConflict(doc as never)).toBe(false);
+ expect(error).toHaveBeenCalledTimes(1);
+ expect(error.mock.calls[0]?.[0]).toMatchObject({ 'doc.name': 'a' });
+ } finally {
+ error.mockRestore();
+ }
+ });
+
+ test('a bound document tracks the authority membership', () => {
+ const rig = makeAuthority();
+ const doc = namedDoc('a');
+ bindConflictAuthority(doc, rig.authority);
+
+ expect(isDocInConflict(doc as never)).toBe(false);
+
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ expect(isDocInConflict(doc as never)).toBe(true);
+ });
+});
+
+describe('strategiesFor', () => {
+ test('git kinds accept every strategy', () => {
+ expect(strategiesFor('merge-native')).toEqual(['mine', 'theirs', 'content', 'delete']);
+ expect(strategiesFor('working-tree')).toEqual(['mine', 'theirs', 'content', 'delete']);
+ });
+
+ test('a reconcile conflict whose theirs side carries markers does not advertise theirs', () => {
+ expect(strategiesFor('reconcile', 'disk-markers')).toEqual(['mine', 'content', 'delete']);
+ expect(strategiesFor('reconcile', 'refused-conflict-markers')).toEqual([
+ 'mine',
+ 'content',
+ 'delete',
+ ]);
+ });
+
+ test('a reconcile conflict with clean theirs bytes advertises theirs', () => {
+ expect(strategiesFor('reconcile', 'merged-with-markers')).toContain('theirs');
+ expect(strategiesFor('reconcile', 'refused-too-large')).toContain('theirs');
+ });
+
+ test('a document the merger declined as too large is not offered a hand-merged content resolve', () => {
+ expect(strategiesFor('reconcile', 'refused-too-large')).toEqual(['mine', 'theirs', 'delete']);
+ });
+});
+
+describe('ConflictAuthority lifecycleOf', () => {
+ test('returns the map arms for deleted-upstream and renamed', () => {
+ const { authority } = makeAuthority();
+ const doc = new Y.Doc();
+ doc.getMap('lifecycle').set('status', 'deleted-upstream');
+ expect(authority.lifecycleOf(doc, 'a')).toEqual({ status: 'deleted-upstream' });
+
+ const renamed = new Y.Doc();
+ renamed.getMap('lifecycle').set('status', 'renamed');
+ renamed.getMap('lifecycle').set('newPath', 'b');
+ expect(authority.lifecycleOf(renamed, 'a')).toEqual({ status: 'renamed', newPath: 'b' });
+ });
+
+ test('returns the conflict arm from membership, carrying kind and reason', () => {
+ const { authority } = makeAuthority();
+ const doc = new Y.Doc();
+ expect(authority.lifecycleOf(doc, 'a')).toBeNull();
+
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'b', ours: 'o', theirs: 't' },
+ });
+ expect(authority.lifecycleOf(doc, 'a')).toEqual({
+ status: 'conflict',
+ kind: 'reconcile',
+ reason: 'disk-markers',
+ });
+ });
+
+ test('returns the working-tree conflict lifecycle for a pull-only collision', () => {
+ const { authority } = makeAuthority();
+ const doc = new Y.Doc();
+ authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'origin-sha' });
+
+ expect(authority.lifecycleOf(doc, 'a')).toEqual({
+ status: 'conflict',
+ kind: 'working-tree',
+ reason: 'pull-only-collision',
+ });
+ });
+
+ test('the lifecycle map is never written by the authority', () => {
+ const { authority } = makeAuthority();
+ const doc = new Y.Doc();
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ authority.lifecycleOf(doc, 'a');
+ expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
+ });
+});
+
+describe('ConflictAuthority resolve', () => {
+ test('throws when the file is not tracked', async () => {
+ const { authority } = makeAuthority();
+ await expect(authority.resolve('unknown.md', 'mine')).rejects.toThrow(
+ 'no conflict tracked for file: unknown.md',
+ );
+ });
+
+ test("strategy 'content' refuses bytes that still carry conflict markers", async () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ const markered = [
+ '# Pricing',
+ '',
+ '<<<<<<< ours',
+ 'The Team tier moves to $29 per seat.',
+ '=======',
+ 'The Team tier moves to $29 per seat, grandfathered.',
+ '>>>>>>> theirs',
+ '',
+ ].join('\n');
+
+ await expect(authority.resolve('a.md', 'content', markered)).rejects.toMatchObject({
+ name: 'ConflictMarkersInContentError',
+ file: 'a.md',
+ });
+ expect(authority.count()).toBe(1);
+ });
+
+ test("strategy 'content' accepts a resolution whose body contains a setext H1", async () => {
+ const { authority, io } = makeAuthority() as Rig;
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ await authority.resolve(
+ 'a.md',
+ 'content',
+ 'Release Notes\n=======\n\nThe Team tier moves to $29.\n',
+ );
+ expect(authority.count()).toBe(0);
+ expect(io.writes).toHaveLength(1);
+ });
+
+ test("strategy 'content' without content throws", async () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ await expect(authority.resolve('a.md', 'content', undefined)).rejects.toThrow(
+ "strategy 'content' requires content parameter",
+ );
+ });
+
+ test("strategy 'content' rejects path traversal outside the project directory", async () => {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: '../../../etc/shadow.md' });
+ await expect(
+ authority.resolve('../../../etc/shadow.md', 'content', 'malicious'),
+ ).rejects.toThrow('file path escapes project directory');
+
+ authority.raise({ kind: 'merge-native', file: 'subdir/../../escape.md' });
+ await expect(
+ authority.resolve('subdir/../../escape.md', 'content', 'malicious'),
+ ).rejects.toThrow('file path escapes project directory');
+ });
+
+ test('a merge-native resolve stages the choice, clears the entry and commits the merge', async () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ await rig.authority.resolve('a.md', 'mine');
+
+ expect(rig.authority.count()).toBe(0);
+ expect(rig.io.gitCalls).toEqual([
+ ['checkout', '--ours', '--', ':(literal)a.md'],
+ ['add', '--', ':(literal)a.md'],
+ ['commit', '--no-edit'],
+ ]);
+ });
+
+ test('a failed merge commit re-adds the unmerged files and throws', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ if (args[0] === 'diff') return 'a.md\0';
+ return '';
+ },
+ });
+ const rig = makeAuthority(io);
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ await expect(rig.authority.resolve('a.md', 'mine')).rejects.toThrow('Merge commit failed');
+ expect(rig.authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+
+ test('a reconcile resolve writes the chosen bytes through the io and clears the entry', async () => {
+ const rig = makeAuthority();
+ writeFileSync(join(projectDir, 'a.md'), 'markers\n', 'utf-8');
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+
+ await rig.authority.resolve('a.md', 'mine');
+ expect(rig.io.applied).toEqual([{ docName: 'a', bytes: 'OURS\n' }]);
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('OURS\n');
+ expect(rig.authority.count()).toBe(0);
+ expect(rig.io.gitCalls).toEqual([]);
+ });
+
+ test("a reconcile 'delete' unlinks the file and clears the entry", async () => {
+ const rig = makeAuthority();
+ writeFileSync(join(projectDir, 'a.md'), 'markers\n', 'utf-8');
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ });
+
+ await rig.authority.resolve('a.md', 'delete');
+ expect(existsSync(join(projectDir, 'a.md'))).toBe(false);
+ expect(rig.authority.count()).toBe(0);
+ });
+
+ test('a host failure leaves the entry in place so the gate stays up', async () => {
+ const rig = makeAuthority(
+ makeIo({
+ applyResolvedContent: async () => {
+ throw new Error('disk full');
+ },
+ }),
+ );
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ });
+
+ await expect(rig.authority.resolve('a.md', 'mine')).rejects.toThrow('disk full');
+ expect(rig.authority.has('a')).toBe(true);
+ });
+
+ test('the resolved bytes reach disk BEFORE the entry leaves the ledger', async () => {
+ const target = join(projectDir, 'a.md');
+ writeFileSync(target, 'LOCAL\n', 'utf-8');
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ });
+
+ let diskAtClear: string | null = null;
+ rig.authority.subscribe((change) => {
+ if (change.type === 'cleared') diskAtClear = readFileSync(target, 'utf-8');
+ });
+
+ await rig.authority.resolve('a.md', 'content', 'HAND-MERGED\n');
+ expect(diskAtClear).toBe('HAND-MERGED\n');
+ expect(rig.authority.count()).toBe(0);
+ });
+});
+
+describe('ConflictAuthority working-tree resolve against a real repo', () => {
+ async function seedOverlay(
+ file: string,
+ remote: string,
+ local: string,
+ ): Promise<{ blobSha: string; headSha: string }> {
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, file), remote, 'utf-8');
+ await git.add('.');
+ await git.commit('seed');
+ const blobSha = (await git.raw(['rev-parse', `HEAD:${file}`])).trim();
+ const headSha = (await git.raw(['rev-parse', 'HEAD'])).trim();
+ writeFileSync(join(projectDir, file), local, 'utf-8');
+ return { blobSha, headSha };
+ }
+
+ async function headSha(): Promise<string> {
+ return (await simpleGit(projectDir).raw(['rev-parse', 'HEAD'])).trim();
+ }
+
+ function realGitIo(): FakeIo {
+ return makeIo({ gitRaw: async (args) => simpleGit(projectDir).raw(args) });
+ }
+
+ test("'theirs' restores the pinned origin-tip blob without committing", async () => {
+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');
+ const rig = makeAuthority(realGitIo());
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: blobSha });
+
+ await rig.authority.resolve('a.md', 'theirs');
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('REMOTE\n');
+ expect(rig.authority.count()).toBe(0);
+ expect(await headSha()).toBe(before);
+ });
+
+ test("'mine' keeps the overlay verbatim without committing", async () => {
+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');
+ const rig = makeAuthority(realGitIo());
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: blobSha });
+
+ await rig.authority.resolve('a.md', 'mine');
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL\n');
+ expect(rig.authority.count()).toBe(0);
+ expect(await headSha()).toBe(before);
+ });
+
+ test("'content' writes the merged bytes without committing", async () => {
+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');
+ const rig = makeAuthority(realGitIo());
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: blobSha });
+
+ await rig.authority.resolve('a.md', 'content', 'HAND-MERGED\n');
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('HAND-MERGED\n');
+ expect(rig.authority.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 rig = makeAuthority(realGitIo());
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: blobSha });
+
+ await rig.authority.resolve('a.md', 'delete');
+ expect(existsSync(join(projectDir, 'a.md'))).toBe(false);
+ expect(rig.authority.count()).toBe(0);
+ expect(await headSha()).toBe(before);
+ });
+
+ test('the union type refuses a working-tree raise with no pinned blob', () => {
+ const { authority } = makeAuthority();
+ // @ts-expect-error a working-tree conflict without theirsSha is not constructible
+ authority.raise({ kind: 'working-tree', file: 'a.md' });
+ });
+});
+
+const MARKERED = [
+ '# Pricing',
+ '',
+ '<<<<<<< ours',
+ 'The Team tier moves to $29 per seat.',
+ '=======',
+ 'The Team tier moves to $29 per seat, grandfathered.',
+ '>>>>>>> theirs',
+ '',
+].join('\n');
+
+describe('ConflictAuthority resolve refuses markers on every strategy', () => {
+ const REASONS = [
+ 'merged-with-markers',
+ 'refused-conflict-markers',
+ 'refused-too-large',
+ 'disk-markers',
+ ] as const;
+
+ for (const reason of REASONS) {
+ test(`'mine' on a ${reason} entry whose ours carries markers is refused`, async () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason,
+ stages: { base: 'B', ours: MARKERED, theirs: 'CLEAN\n' },
+ });
+
+ await expect(rig.authority.resolve('a.md', 'mine')).rejects.toMatchObject({
+ name: 'ConflictMarkersInContentError',
+ });
+ expect(rig.io.applied).toEqual([]);
+ expect(rig.authority.has('a')).toBe(true);
+ });
+
+ test(`'theirs' on a ${reason} entry whose theirs carries markers is refused`, async () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason,
+ stages: { base: 'B', ours: 'CLEAN\n', theirs: MARKERED },
+ });
+
+ await expect(rig.authority.resolve('a.md', 'theirs')).rejects.toMatchObject({
+ name: 'ConflictMarkersInContentError',
+ });
+ expect(rig.io.applied).toEqual([]);
+ expect(rig.authority.has('a')).toBe(true);
+ });
+ }
+
+ test('a strategy outside the advertised set for the entry is refused', async () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ });
+
+ await expect(rig.authority.resolve('a.md', 'theirs')).rejects.toMatchObject({
+ name: 'ConflictMarkersInContentError',
+ });
+ expect(strategiesFor('reconcile', 'disk-markers')).not.toContain('theirs');
+ expect(rig.authority.has('a')).toBe(true);
+ });
+
+ test("'delete' is exempt from the marker check", async () => {
+ const rig = makeAuthority();
+ writeFileSync(join(projectDir, 'a.md'), MARKERED, 'utf-8');
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: MARKERED, theirs: MARKERED },
+ });
+
+ await rig.authority.resolve('a.md', 'delete');
+ expect(rig.authority.count()).toBe(0);
+ });
+
+ test("a working-tree 'theirs' whose pinned blob carries markers is refused before the write", async () => {
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, 'a.md'), MARKERED, 'utf-8');
+ await git.add('.');
+ await git.commit('seed');
+ const blobSha = (await git.raw(['rev-parse', 'HEAD:a.md'])).trim();
+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL\n', 'utf-8');
+
+ const rig = makeAuthority(makeIo({ gitRaw: async (args) => simpleGit(projectDir).raw(args) }));
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: blobSha });
+
+ await expect(rig.authority.resolve('a.md', 'theirs')).rejects.toMatchObject({
+ name: 'ConflictMarkersInContentError',
+ });
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL\n');
+ expect(rig.authority.has('a')).toBe(true);
+ });
+});
+
+describe('ConflictAuthority reconcile re-raise keeps the pre-conflict ours', () => {
+ test('a second reconcile raise for the same file does not overwrite stages.ours', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B1', ours: 'PRE-CONFLICT\n', theirs: 'T1' },
+ });
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'B2', ours: MARKERED, theirs: 'T2' },
+ });
+
+ const entry = rig.authority.findByFile('a.md');
+ expect(entry?.kind).toBe('reconcile');
+ if (entry?.kind !== 'reconcile') throw new Error('expected a reconcile entry');
+ expect(entry.stages.ours).toBe('PRE-CONFLICT\n');
+ expect(entry.stages.base).toBe('B2');
+ expect(entry.stages.theirs).toBe('T2');
+ expect(entry.reason).toBe('merged-with-markers');
+ });
+
+ test('a re-raise that differs only in ours is absorbed without a second change', () => {
+ const rig = makeAuthority();
+ const input = {
+ kind: 'reconcile' as const,
+ file: 'a.md',
+ reason: 'merged-with-markers' as const,
+ stages: { base: 'B', ours: 'PRE-CONFLICT\n', theirs: 'T' },
+ };
+ rig.authority.raise(input);
+ const signalsAfterFirst = rig.signals;
+
+ rig.authority.raise({ ...input, stages: { ...input.stages, ours: 'later editor text' } });
+
+ expect(rig.changes).toHaveLength(1);
+ expect(rig.signals).toBe(signalsAfterFirst);
+ expect(rig.authority.findByFile('a.md')).toMatchObject({
+ stages: { base: 'B', ours: 'PRE-CONFLICT\n', theirs: 'T' },
+ });
+ });
+
+ test('a later clean reconcile dissolves the entry that held the pre-conflict ours', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'PRE-CONFLICT\n', theirs: MARKERED },
+ });
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'B2', ours: 'LIVE-WITH-MARKERS\n', theirs: MARKERED },
+ });
+
+ const held = rig.authority.findByFile('a.md');
+ if (held?.kind !== 'reconcile') throw new Error('expected a reconcile entry');
+ expect(held.stages.ours).toBe('PRE-CONFLICT\n');
+
+ rig.authority.dissolveReconcile('a');
+ expect(rig.authority.has('a')).toBe(false);
+ expect(rig.changes.at(-1)).toMatchObject({ type: 'cleared', file: 'a.md', cause: 'dissolved' });
+ });
+});
+
+describe('ConflictAuthority merge-native resolve commits before it clears', () => {
+ test('the merge commit runs before the cleared change reaches a subscriber', async () => {
+ const order: string[] = [];
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') order.push('git-commit');
+ return '';
+ },
+ });
+ const rig = makeAuthority(io);
+ rig.authority.subscribe((change) => {
+ if (change.type === 'cleared') order.push('subscriber-cleared');
+ });
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ await rig.authority.resolve('a.md', 'mine');
+ expect(order).toEqual(['git-commit', 'subscriber-cleared']);
+ });
+
+ test('a failed merge commit keeps the entry and raises the other unmerged files', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ if (args[0] === 'diff') return 'a.md\0b.md\0';
+ return '';
+ },
+ });
+ const rig = makeAuthority(io);
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ await expect(rig.authority.resolve('a.md', 'mine')).rejects.toThrow('Merge commit failed');
+ expect(rig.authority.findByFile('a.md')?.kind).toBe('merge-native');
+ expect(rig.authority.findByFile('b.md')?.kind).toBe('merge-native');
+ expect(rig.changes.some((c) => c.type === 'cleared')).toBe(false);
+ });
+
+ test('a second merge-native entry defers the merge commit', async () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ rig.authority.raise({ kind: 'merge-native', file: 'b.md' });
+
+ await rig.authority.resolve('a.md', 'mine');
+ expect(rig.io.gitCalls.some((args) => args[0] === 'commit')).toBe(false);
+
+ await rig.authority.resolve('b.md', 'mine');
+ expect(rig.io.gitCalls.some((args) => args[0] === 'commit')).toBe(true);
+ });
+});
+
+describe('ConflictAuthority docName index ownership', () => {
+ test('clearing the non-owner leaves the docName index pointing at the owner', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'sha-md' });
+ rig.authority.raise({ kind: 'working-tree', file: 'a.mdx', theirsSha: 'sha-mdx' });
+ expect(rig.authority.findByDocName('a')?.file).toBe('a.mdx');
+
+ rig.authority.dissolveWorkingTree('a.md');
+ expect(rig.authority.findByFile('a.md')).toBeUndefined();
+ expect(rig.authority.findByDocName('a')?.file).toBe('a.mdx');
+ expect(rig.authority.has('a')).toBe(true);
+ });
+
+ test('clearing the owner re-points the docName index at the surviving entry', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'sha-md' });
+ rig.authority.raise({ kind: 'working-tree', file: 'a.mdx', theirsSha: 'sha-mdx' });
+
+ rig.authority.dissolveWorkingTree('a.mdx');
+ expect(rig.authority.findByDocName('a')?.file).toBe('a.md');
+ expect(rig.authority.has('a')).toBe(true);
+ });
+});
+
+const MARKERED_BODY = [
+ '# Pricing',
+ '',
+ '<<<<<<< ours',
+ 'ours side',
+ '=======',
+ 'theirs side',
+ '>>>>>>> theirs',
+ '',
+].join('\n');
+
+const STAGES = { base: 'B', ours: 'O', theirs: 'T' } as const;
+
+function writeLedgerRows(branch: string, conflicts: unknown[]): void {
+ writeFileSync(storePath, JSON.stringify({ version: 2, branch, conflicts }), 'utf-8');
+}
+
+function reconcileRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ kind: 'reconcile',
+ file: 'a.md',
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ reason: 'merged-with-markers',
+ stages: { ...STAGES },
+ ...overrides,
+ };
+}
+
+describe('ConflictAuthority scopes reconcile entries to the branch that raised them', () => {
+ test('raise stamps the current branch onto the persisted entry', () => {
+ const { authority } = makeAuthority();
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { ...STAGES },
+ });
+
+ expect(authority.findByFile('a.md')).toMatchObject({ kind: 'reconcile', branch: 'main' });
+ expect(readLedger().conflicts[0]).toMatchObject({ branch: 'main' });
+ });
+
+ test('an entry raised on another branch is dropped at load, git kinds are kept', () => {
+ writeLedgerRows('feature/x', [
+ reconcileRow({ branch: 'feature/x' }),
+ { kind: 'merge-native', file: 'b.md', detectedAt: '2026-05-19T00:00:00.000Z' },
+ ]);
+
+ const { authority } = makeAuthority();
+ expect(authority.findByFile('a.md')).toBeUndefined();
+ expect(authority.findByFile('b.md')?.kind).toBe('merge-native');
+ });
+
+ test('an older entry carrying no branch is adopted onto the current branch', () => {
+ writeLedgerRows('main', [reconcileRow()]);
+
+ const { authority } = makeAuthority();
+ expect(authority.findByFile('a.md')).toMatchObject({ kind: 'reconcile', branch: 'main' });
+ });
+
+ test('a branch change clears the reconcile entries raised on the branch we left', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { ...STAGES },
+ });
+ rig.authority.raise({ kind: 'merge-native', file: 'b.md' });
+ const signalsBefore = rig.signals;
+
+ rig.authority.setBranch('feature/x');
+
+ expect(rig.authority.findByFile('a.md')).toBeUndefined();
+ expect(rig.authority.findByFile('b.md')?.kind).toBe('merge-native');
+ expect(rig.signals).toBe(signalsBefore + 1);
+ expect(rig.changes.at(-1)).toMatchObject({
+ type: 'cleared',
+ file: 'a.md',
+ docName: 'a',
+ cause: 'branch-changed',
+ });
+ expect(readLedger().branch).toBe('feature/x');
+ });
+
+ test('re-declaring the branch already in force clears nothing', () => {
+ const rig = makeAuthority();
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { ...STAGES },
+ });
+ const signalsBefore = rig.signals;
+
+ rig.authority.setBranch('main');
+
+ expect(rig.authority.findByFile('a.md')).toBeDefined();
+ expect(rig.signals).toBe(signalsBefore);
+ });
+
+ test('an entry raised after the switch survives the next load on that branch', () => {
+ const rig = makeAuthority();
+ rig.authority.setBranch('feature/x');
+ rig.authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { ...STAGES },
+ });
+
+ const reloaded = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'feature/x',
+ io: makeIo(),
+ });
+ expect(reloaded.findByFile('a.md')).toMatchObject({ branch: 'feature/x' });
+ });
+
+ test('omitting branch adopts the ledger branch, keeping its rows and stamping later raises', () => {
+ writeLedgerRows('feature/y', [reconcileRow({ branch: 'feature/y' })]);
+
+ const adopting = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ io: makeIo(),
+ });
+
+ expect(adopting.findByFile('a.md')).toMatchObject({ kind: 'reconcile', branch: 'feature/y' });
+
+ adopting.raise({
+ kind: 'reconcile',
+ file: 'c.md',
+ reason: 'merged-with-markers',
+ stages: { ...STAGES },
+ });
+
+ expect(adopting.findByFile('c.md')).toMatchObject({ branch: 'feature/y' });
+ expect(readLedger().branch).toBe('feature/y');
+ });
+});
+
+describe('ConflictAuthority validates marker-bearing reconcile entries against disk at load', () => {
+ function writeMarkerLedger(reason: 'disk-markers' | 'refused-conflict-markers'): void {
+ writeLedgerRows('main', [
+ reconcileRow({
+ branch: 'main',
+ reason,
+ stages: { base: 'B', ours: 'O', theirs: MARKERED_BODY },
+ }),
+ ]);
+ }
+
+ test('the entry survives while the file still carries markers', () => {
+ writeFileSync(join(projectDir, 'a.md'), MARKERED_BODY, 'utf-8');
+ writeMarkerLedger('disk-markers');
+
+ expect(makeAuthority().authority.findByFile('a.md')?.kind).toBe('reconcile');
+ });
+
+ test('the entry is dropped once the markers were resolved out of band', () => {
+ writeFileSync(join(projectDir, 'a.md'), '# Pricing\n\nsettled\n', 'utf-8');
+ writeMarkerLedger('disk-markers');
+
+ expect(makeAuthority().authority.count()).toBe(0);
+ });
+
+ test('a refused-conflict-markers entry is dropped when its file is gone', () => {
+ writeMarkerLedger('refused-conflict-markers');
+
+ expect(makeAuthority().authority.count()).toBe(0);
+ });
+
+ test('a reason that promises nothing about disk is loaded without reading the file', () => {
+ writeFileSync(join(projectDir, 'a.md'), 'clean body\n', 'utf-8');
+ writeLedgerRows('main', [reconcileRow({ branch: 'main', reason: 'merged-with-markers' })]);
+
+ expect(makeAuthority().authority.findByFile('a.md')?.kind).toBe('reconcile');
+ });
+
+ test('an unreadable file keeps its entry rather than silently unfreezing the doc', () => {
+ mkdirSync(join(projectDir, 'a.md'), { recursive: true });
+ writeMarkerLedger('disk-markers');
+
+ expect(makeAuthority().authority.findByFile('a.md')?.kind).toBe('reconcile');
+ });
+});
+
+describe('ConflictAuthority reports the reconcile entry a git conflict displaces', () => {
+ test('the git kind still wins, and the dropped editor text is announced', () => {
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ const { authority } = makeAuthority();
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: 'editor text', theirs: 'T' },
+ });
+ warn.mockClear();
+
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+
+ expect(authority.findByFile('a.md')?.kind).toBe('merge-native');
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0]?.[0]).toMatchObject({
+ file: 'a.md',
+ reason: 'disk-markers',
+ replacedBy: 'merge-native',
+ });
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('replacing one git kind with another says nothing', () => {
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ const { authority } = makeAuthority();
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
+ warn.mockClear();
+
+ authority.raise({ kind: 'working-tree', file: 'a.md', theirsSha: 'sha' });
+ expect(authority.findByFile('a.md')?.kind).toBe('working-tree');
+ expect(warn).not.toHaveBeenCalled();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
+describe('ConflictAuthority tells a crashed unmerged probe from a clean index', () => {
+ test('a crashed probe fabricates no entries and is logged as an error, not a clean index', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ if (args[0] === 'diff') throw new Error('fatal: not a git repository');
+ return '';
+ },
+ });
+ const rig = makeAuthority(io);
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ const error = vi.spyOn(getLogger('conflict-authority'), 'error');
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ await expect(rig.authority.resolve('a.md', 'mine')).rejects.toThrow('Merge commit failed');
+
+ expect(rig.authority.count()).toBe(1);
+ expect(rig.authority.findByFile('a.md')?.kind).toBe('merge-native');
+ expect(rig.changes.some((c) => c.type === 'cleared')).toBe(false);
+ expect(error).toHaveBeenCalledTimes(1);
+ expect(error.mock.calls[0]?.[0]).toMatchObject({ file: 'a.md' });
+ expect(warn).not.toHaveBeenCalled();
+ } finally {
+ error.mockRestore();
+ warn.mockRestore();
+ }
+ });
+
+ test('a probe reporting a clean index stays a warning and raises nothing extra', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ return '';
+ },
+ });
+ const rig = makeAuthority(io);
+ rig.authority.raise({ kind: 'merge-native', file: 'a.md' });
+ const error = vi.spyOn(getLogger('conflict-authority'), 'error');
+ const warn = vi.spyOn(getLogger('conflict-authority'), 'warn');
+ try {
+ await expect(rig.authority.resolve('a.md', 'mine')).rejects.toThrow('Merge commit failed');
+
+ expect(rig.authority.count()).toBe(1);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0]?.[0]).toMatchObject({ files: [] });
+ expect(error).not.toHaveBeenCalled();
+ } finally {
+ error.mockRestore();
+ warn.mockRestore();
+ }
+ });
+});
+
+describe('ConflictAuthority ledger version 2 migration', () => {
+ test.each([1, 2])('a version %i ledger persists as version 2 and survives restart', (version) => {
+ writeFileSync(
+ storePath,
+ JSON.stringify({
+ version,
+ branch: 'main',
+ conflicts: [{ file: 'a.md', detectedAt: 'x', kind: 'merge-native' }],
+ }),
+ );
+
+ expect(makeAuthority().authority.findByFile('a.md')?.kind).toBe('merge-native');
+ expect(readLedger().version).toBe(2);
+ expect(makeAuthority().authority.findByFile('a.md')?.kind).toBe('merge-native');
+ });
+});
diff --git a/packages/server/src/conflict-authority.ts b/packages/server/src/conflict-authority.ts
new file mode 100644
index 000000000..03870ccbe
--- /dev/null
+++ b/packages/server/src/conflict-authority.ts
@@ -0,0 +1,712 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+import type { Document } from '@hocuspocus/server';
+import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import type * as Y from 'yjs';
+import { type CC1Broadcaster, isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { getLocalDir } from './config/paths.ts';
+import { ConflictMarkersInContentError, NoConflictTrackedError } from './conflict-errors.ts';
+import {
+ type Conflict,
+ type ConflictKind,
+ type ConflictStages,
+ holdsMarkersOnDisk,
+ isConflictKind,
+ isReconcileReason,
+ type LifecycleView,
+ type ReconcileReason,
+ type ResolveStrategy,
+ strategiesFor,
+} from './conflict-kinds.ts';
+import {
+ commitMergeIfEmpty,
+ projectAbsPath,
+ resolveMergeNative,
+ resolveReconcile,
+ resolveWorkingTree,
+ selectReconcileOurs,
+} from './conflict-resolution.ts';
+import { requireConflictResolutionContent } from './conflict-resolution-input.ts';
+import { isShareableOkArtifact } from './content-filter.ts';
+import { docNameToRelativePath } from './doc-extensions.ts';
+import { pathToDocName } from './file-watcher.ts';
+import { tracedMkdirSync, tracedRenameSync, tracedWriteFileSync } from './fs-traced.ts';
+import { splitNulSeparatedPaths } from './git-paths.ts';
+import { errnoCode } from './http/handler-utils.ts';
+import { getLogger } from './logger.ts';
+import { toPosix } from './path-utils.ts';
+import { containsUnresolvedConflictBlock } from './reconciliation.ts';
+import { assertRealpathWithinDir } from './symlink-guard.ts';
+
+const log = getLogger('conflict-authority');
+
+export type { Conflict, ResolveStrategy };
+
+const LEDGER_VERSION = 2 as const;
+const SUPPORTED_LEDGER_VERSIONS: readonly number[] = [1, LEDGER_VERSION];
+
+type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
+
+export type RaiseInput = DistributiveOmit<Conflict, 'detectedAt' | 'branch'> & {
+ detectedAt?: string;
+};
+
+type ClearCause = 'resolved' | 'git-pruned' | 'dissolved' | 'branch-changed';
+
+export type ConflictChange =
+ | { type: 'raised'; conflict: Conflict; docName: string | null }
+ | { type: 'cleared'; file: string; docName: string | null; cause: ClearCause };
+
+export interface ConflictIo {
+ gitRaw(args: string[]): Promise<string>;
+ writeProjectFileUntracked(absPath: string, bytes: string): void;
+ unlinkProjectFile(absPath: string): void;
+ applyResolvedContent(docName: string, absPath: string, bytes: string): Promise<void>;
+ readLiveContent?(docName: string): string | null;
+ finalizeReconcileResolution?(
+ entry: Extract<Conflict, { kind: 'reconcile' }>,
+ strategy: ResolveStrategy,
+ docName: string,
+ ): Promise<void> | void;
+}
+
+export interface ConflictAuthorityOptions {
+ projectDir: string;
+ contentDir: string;
+ branch?: string;
+ signal?: Pick<CC1Broadcaster, 'signal'> | null;
+ io: ConflictIo;
+}
+
+export interface ConflictReader {
+ has(docName: string): boolean;
+}
+
+const boundAuthorities = new WeakMap<Y.Doc, ConflictReader>();
+
+export function bindConflictAuthority(document: Y.Doc, authority: ConflictReader): void {
+ boundAuthorities.set(document, authority);
+}
+
+export function isDocInConflict(document: Document): boolean {
+ const reader = boundAuthorities.get(document);
+ if (reader === undefined) {
+ log.error(
+ { 'doc.name': document.name },
+ '[conflicts] no authority is bound to this document — the write gate cannot answer',
+ );
+ return false;
+ }
+ return reader.has(document.name);
+}
+
+function resolvedBytesFor(
+ entry: Conflict,
+ strategy: ResolveStrategy,
+ content: string | undefined,
+ liveOurs: string | null = null,
+): string | undefined {
+ if (strategy === 'delete') return undefined;
+ if (strategy === 'content') return content;
+ if (entry.kind !== 'reconcile') return undefined;
+ return strategy === 'mine' ? selectReconcileOurs(entry, liveOurs) : entry.stages.theirs;
+}
+
+function samePayload(a: Conflict, b: Conflict): boolean {
+ if (a.kind !== b.kind || a.file !== b.file) return false;
+ switch (a.kind) {
+ case 'merge-native':
+ return true;
+ case 'working-tree':
+ return b.kind === 'working-tree' && a.theirsSha === b.theirsSha && a.baseSha === b.baseSha;
+ case 'reconcile':
+ return (
+ b.kind === 'reconcile' &&
+ a.branch === b.branch &&
+ a.reason === b.reason &&
+ a.stages.base === b.stages.base &&
+ a.stages.ours === b.stages.ours &&
+ a.stages.theirs === b.stages.theirs
+ );
+ default: {
+ const _exhaustive: never = a;
+ return false;
+ }
+ }
+}
+
+interface LegacyLedgerEntry {
+ file?: unknown;
+ detectedAt?: unknown;
+ branch?: unknown;
+ kind?: unknown;
+ reason?: unknown;
+ stages?: unknown;
+ theirsSha?: unknown;
+ baseSha?: unknown;
+ variant?: unknown;
+}
+
+function migrateLedgerEntry(raw: LegacyLedgerEntry, currentBranch: string): Conflict | null {
+ const file = typeof raw.file === 'string' && raw.file.length > 0 ? raw.file : null;
+ if (file === null) return null;
+ const detectedAt =
+ typeof raw.detectedAt === 'string' && raw.detectedAt.length > 0
+ ? raw.detectedAt
+ : new Date().toISOString();
+ const theirsSha =
+ typeof raw.theirsSha === 'string' && raw.theirsSha.length > 0 ? raw.theirsSha : null;
+ const baseSha =
+ typeof raw.baseSha === 'string' && raw.baseSha.length > 0 ? raw.baseSha : undefined;
+
+ const declaredKind = isConflictKind(raw.kind) ? raw.kind : null;
+ if (declaredKind === null && raw.kind !== undefined) {
+ log.warn(
+ {
+ file,
+ kind: typeof raw.kind === 'string' ? raw.kind.slice(0, 80) : `<${typeof raw.kind}>`,
+ },
+ '[conflicts] dropped a ledger entry with an unrecognized conflict kind',
+ );
+ return null;
+ }
+ const kind: ConflictKind =
+ declaredKind ?? (raw.variant === 'working-tree' ? 'working-tree' : 'merge-native');
+
+ if (kind === 'working-tree') {
+ if (theirsSha === null) {
+ log.warn(
+ { file },
+ '[conflicts] dropped a working-tree ledger entry with no pinned theirs blob',
+ );
+ return null;
+ }
+ return {
+ kind,
+ file,
+ detectedAt,
+ theirsSha,
+ ...(baseSha === undefined ? {} : { baseSha }),
+ };
+ }
+
+ if (kind === 'reconcile') {
+ const reason = raw.reason;
+ const rawStages = raw.stages;
+ const stages =
+ typeof rawStages === 'object' && rawStages !== null
+ ? (rawStages as Partial<ConflictStages>)
+ : undefined;
+ if (
+ !isReconcileReason(reason) ||
+ stages === undefined ||
+ typeof stages.base !== 'string' ||
+ typeof stages.ours !== 'string' ||
+ typeof stages.theirs !== 'string'
+ ) {
+ log.warn(
+ { file },
+ '[conflicts] dropped a reconcile ledger entry with no reason or incomplete stages',
+ );
+ return null;
+ }
+ return {
+ kind,
+ file,
+ detectedAt,
+ branch: typeof raw.branch === 'string' && raw.branch.length > 0 ? raw.branch : currentBranch,
+ reason,
+ stages: { base: stages.base, ours: stages.ours, theirs: stages.theirs },
+ };
+ }
+
+ return { kind: 'merge-native', file, detectedAt };
+}
+
+export class ConflictAuthority implements ConflictReader {
+ private readonly storePath: string;
+ private readonly projectDir: string;
+ private readonly contentDir: string;
+ private readonly io: ConflictIo;
+ private readonly signal: Pick<CC1Broadcaster, 'signal'> | null;
+ private readonly listeners = new Set<(change: ConflictChange) => void>();
+ private readonly byFile = new Map<string, Conflict>();
+ private readonly byDocName = new Map<string, Conflict>();
+ private branch: string;
+
+ constructor(options: ConflictAuthorityOptions) {
+ this.projectDir = options.projectDir;
+ this.contentDir = options.contentDir;
+ this.io = options.io;
+ this.signal = options.signal ?? null;
+ this.branch = options.branch ?? 'main';
+ this.storePath = join(getLocalDir(this.projectDir), 'conflicts.json');
+ this.load(options.branch === undefined);
+ }
+
+ fileOf(docName: string): string {
+ const abs = join(this.contentDir, docNameToRelativePath(docName));
+ return toPosix(relative(this.projectDir, abs));
+ }
+
+ docNameOf(conflict: Conflict): string | null {
+ return this.docNameForFile(conflict.file);
+ }
+
+ private docNameForFile(file: string): string | null {
+ const abs = join(this.projectDir, file);
+ const contentRel = toPosix(relative(this.contentDir, abs));
+ if (contentRel.length === 0 || contentRel.startsWith('..')) return null;
+ const docName = pathToDocName(abs, this.contentDir);
+ if (isSystemDoc(docName) || isConfigDoc(docName)) return null;
+ return docName;
+ }
+
+ private index(conflict: Conflict): string | null {
+ this.byFile.set(conflict.file, conflict);
+ const docName = this.docNameForFile(conflict.file);
+ if (docName !== null) this.byDocName.set(docName, conflict);
+ return docName;
+ }
+
+ private unindex(file: string): string | null {
+ const entry = this.byFile.get(file);
+ this.byFile.delete(file);
+ const docName = this.docNameForFile(file);
+ if (docName === null) return null;
+ if (this.byDocName.get(docName) !== entry) return docName;
+ this.byDocName.delete(docName);
+ for (const candidate of this.byFile.values()) {
+ if (this.docNameForFile(candidate.file) === docName) {
+ this.byDocName.set(docName, candidate);
+ break;
+ }
+ }
+ return docName;
+ }
+
+ private commit(changes: readonly ConflictChange[]): void {
+ if (changes.length === 0) return;
+ this.persist();
+ for (const change of changes) {
+ for (const listener of this.listeners) {
+ try {
+ listener(change);
+ } catch (err) {
+ log.warn({ err }, '[conflicts] subscriber threw while handling a conflict change');
+ }
+ }
+ }
+ this.signal?.signal('sync-status');
+ }
+
+ private quarantineStore(reason: 'unparseable' | 'unsupported-version', err?: unknown): void {
+ const stamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-');
+ const asidePath = `${this.storePath}.corrupt-${stamp}`;
+ try {
+ tracedRenameSync(this.storePath, asidePath);
+ log.error(
+ { err, reason, asidePath },
+ '[conflicts] conflicts.json was unreadable — moved aside and started empty',
+ );
+ } catch (renameErr) {
+ log.error(
+ { err, reason, renameErr },
+ '[conflicts] conflicts.json was unreadable and could not be moved aside — starting empty',
+ );
+ }
+ }
+
+ private load(adoptLedgerBranch: boolean): void {
+ this.byFile.clear();
+ this.byDocName.clear();
+ if (!existsSync(this.storePath)) return;
+ let parsed: { version?: unknown; branch?: unknown; conflicts?: unknown };
+ try {
+ const value: unknown = JSON.parse(readFileSync(this.storePath, 'utf-8'));
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ this.quarantineStore('unparseable');
+ return;
+ }
+ parsed = value;
+ } catch (err) {
+ this.quarantineStore('unparseable', err);
+ return;
+ }
+ if (typeof parsed.version !== 'number' || !SUPPORTED_LEDGER_VERSIONS.includes(parsed.version)) {
+ this.quarantineStore('unsupported-version');
+ return;
+ }
+ if (adoptLedgerBranch && typeof parsed.branch === 'string') this.branch = parsed.branch;
+ const rows = Array.isArray(parsed.conflicts) ? parsed.conflicts : [];
+ try {
+ for (const row of rows) {
+ if (row === null || typeof row !== 'object') continue;
+ const raw = row as LegacyLedgerEntry;
+ const migrated = migrateLedgerEntry(raw, this.branch);
+ if (migrated === null) continue;
+ const staleness = this.stalenessAtLoad(migrated);
+ if (staleness !== null) {
+ log.info(
+ { file: migrated.file, staleness, branch: this.branch },
+ '[conflicts] dropped a reconcile entry that no longer matches this branch or its disk state',
+ );
+ continue;
+ }
+ this.index(migrated);
+ }
+ if (parsed.version !== LEDGER_VERSION) this.persist();
+ } catch (err) {
+ this.byFile.clear();
+ this.byDocName.clear();
+ this.quarantineStore('unparseable', err);
+ }
+ }
+
+ private stalenessAtLoad(entry: Conflict): 'other-branch' | 'markers-gone' | null {
+ if (entry.kind !== 'reconcile') return null;
+ if (entry.branch !== this.branch) return 'other-branch';
+ if (!holdsMarkersOnDisk(entry)) return null;
+ return this.fileStillHoldsMarkers(entry.file) ? null : 'markers-gone';
+ }
+
+ private fileStillHoldsMarkers(file: string): boolean {
+ try {
+ return containsUnresolvedConflictBlock(readFileSync(join(this.projectDir, file), 'utf-8'));
+ } catch (err) {
+ if (errnoCode(err) === 'ENOENT') return false;
+ log.warn(
+ { err, file },
+ '[conflicts] could not re-read a marker-bearing file at load — keeping its entry',
+ );
+ return true;
+ }
+ }
+
+ private persist(): void {
+ const tmpPath = `${this.storePath}.tmp`;
+ try {
+ const dir = dirname(this.storePath);
+ if (!existsSync(dir)) tracedMkdirSync(dir, { recursive: true });
+ const payload = {
+ version: LEDGER_VERSION,
+ branch: this.branch,
+ conflicts: [...this.byFile.values()],
+ };
+ tracedWriteFileSync(tmpPath, JSON.stringify(payload), 'utf-8');
+ tracedRenameSync(tmpPath, this.storePath);
+ } catch (err) {
+ log.error(
+ { err, branch: this.branch },
+ '[conflicts] failed to persist conflicts.json — the ledger will not survive restart',
+ );
+ }
+ }
+
+ raise(input: RaiseInput): void {
+ const docName = this.docNameForFile(input.file);
+ if (docName === null && input.kind === 'reconcile') {
+ log.warn(
+ { file: input.file, kind: input.kind },
+ '[conflicts] refused a reconcile raise for a path with no content doc — the document stays writable',
+ );
+ return;
+ }
+ const existing = this.byFile.get(input.file);
+ if (existing !== undefined && input.kind === 'reconcile' && existing.kind !== 'reconcile') {
+ return;
+ }
+ const detectedAt = input.detectedAt ?? new Date().toISOString();
+ let conflict: Conflict;
+ switch (input.kind) {
+ case 'merge-native':
+ conflict = { kind: 'merge-native', file: input.file, detectedAt };
+ break;
+ case 'working-tree':
+ conflict = {
+ kind: 'working-tree',
+ file: input.file,
+ detectedAt,
+ theirsSha: input.theirsSha,
+ ...(input.baseSha === undefined ? {} : { baseSha: input.baseSha }),
+ };
+ break;
+ case 'reconcile':
+ conflict = {
+ kind: 'reconcile',
+ file: input.file,
+ detectedAt,
+ branch: this.branch,
+ reason: input.reason,
+ stages:
+ existing !== undefined && existing.kind === 'reconcile'
+ ? { ...input.stages, ours: existing.stages.ours }
+ : { ...input.stages },
+ };
+ break;
+ default: {
+ const _exhaustive: never = input;
+ return;
+ }
+ }
+ if (existing !== undefined && samePayload(existing, conflict)) return;
+ if (existing !== undefined && existing.kind === 'reconcile' && conflict.kind !== 'reconcile') {
+ log.warn(
+ { file: input.file, reason: existing.reason, replacedBy: conflict.kind },
+ '[conflicts] a git conflict displaced a reconcile entry — its captured editor text is gone',
+ );
+ }
+ this.index(conflict);
+ this.commit([{ type: 'raised', conflict, docName }]);
+ }
+
+ dissolveReconcile(docName: string, reason?: ReconcileReason): void {
+ const entry = this.byDocName.get(docName);
+ if (entry?.kind === 'reconcile' && reason !== undefined && entry.reason !== reason) return;
+ this.dissolveKind(entry, 'reconcile');
+ }
+
+ dissolveWorkingTree(file: string): void {
+ this.dissolveKind(this.byFile.get(file), 'working-tree');
+ }
+
+ private dissolveKind(entry: Conflict | undefined, kind: ConflictKind): void {
+ if (entry === undefined) return;
+ if (entry.kind !== kind) return;
+ const docName = this.unindex(entry.file);
+ this.commit([{ type: 'cleared', file: entry.file, docName, cause: 'dissolved' }]);
+ }
+
+ async pruneMergeNativeAgainstGit(): Promise<number> {
+ const mergeNative = [...this.byFile.values()].filter((e) => e.kind === 'merge-native');
+ if (mergeNative.length === 0) return 0;
+
+ const gitDir = resolveGitDirDetailed(this.projectDir);
+ if (gitDir.kind === 'malformed-pointer' || gitDir.kind === 'inaccessible') {
+ log.warn(
+ { gitDirKind: gitDir.kind, gitPath: gitDir.gitPath },
+ '[conflicts] the git directory could not be read — leaving the ledger untouched',
+ );
+ return 0;
+ }
+ const mergeInProgress = gitDir.kind !== 'absent' && existsSync(join(gitDir.path, 'MERGE_HEAD'));
+
+ let stale: Conflict[];
+ if (!mergeInProgress) {
+ stale = mergeNative;
+ } else {
+ let stillUnmerged: Set<string>;
+ try {
+ stillUnmerged = new Set(
+ splitNulSeparatedPaths(
+ await this.io.gitRaw(['diff', '-z', '--name-only', '--diff-filter=U']),
+ ),
+ );
+ } catch (err) {
+ log.warn({ err }, '[conflicts] git unmerged probe failed — leaving the ledger untouched');
+ return 0;
+ }
+ stale = mergeNative.filter((e) => !stillUnmerged.has(e.file));
+ }
+
+ if (stale.length === 0) return 0;
+ const changes: ConflictChange[] = [];
+ for (const entry of stale) {
+ if (this.byFile.get(entry.file) !== entry) continue;
+ const docName = this.unindex(entry.file);
+ changes.push({ type: 'cleared', file: entry.file, docName, cause: 'git-pruned' });
+ }
+ if (changes.length === 0) return 0;
+ log.info(
+ { cleared: changes.length, remaining: this.byFile.size, mergeInProgress },
+ '[conflicts] external resolve detected — pruned merge-native entries',
+ );
+ this.commit(changes);
+ return changes.length;
+ }
+
+ async resolve(file: string, strategy: ResolveStrategy, content?: string): Promise<void> {
+ const entry = this.byFile.get(file);
+ if (entry === undefined) throw new NoConflictTrackedError({ file });
+
+ if (strategy === 'content') requireConflictResolutionContent(file, content);
+
+ const reason = entry.kind === 'reconcile' ? entry.reason : undefined;
+ if (!strategiesFor(entry.kind, reason).includes(strategy)) {
+ throw new ConflictMarkersInContentError({ file, refusal: 'strategy-not-offered' });
+ }
+
+ const reconcileDocName = entry.kind === 'reconcile' ? this.docNameForFile(file) : null;
+ const liveOurs =
+ entry.kind === 'reconcile' && strategy === 'mine' && reconcileDocName !== null
+ ? (this.io.readLiveContent?.(reconcileDocName) ?? null)
+ : null;
+ const landing = resolvedBytesFor(entry, strategy, content, liveOurs);
+ if (landing !== undefined && containsUnresolvedConflictBlock(landing)) {
+ throw new ConflictMarkersInContentError({ file, refusal: 'markers-in-content' });
+ }
+
+ switch (entry.kind) {
+ case 'merge-native': {
+ await resolveMergeNative(entry, strategy, content, this.io, this.projectDir);
+ if (this.countOfKind('merge-native') <= 1) {
+ await this.commitMergeBeforeClearing(entry);
+ }
+ const docName = this.unindex(file);
+ this.logResolved(file, entry.kind, strategy);
+ this.commit([{ type: 'cleared', file, docName, cause: 'resolved' }]);
+ return;
+ }
+ case 'working-tree': {
+ await resolveWorkingTree(entry, strategy, content, this.io, this.projectDir);
+ const docName = this.unindex(file);
+ this.logResolved(file, entry.kind, strategy);
+ this.commit([{ type: 'cleared', file, docName, cause: 'resolved' }]);
+ return;
+ }
+ case 'reconcile': {
+ const docName = reconcileDocName;
+ if (docName === null) {
+ throw new Error(`[conflicts] reconcile conflict for ${file} has no content doc`);
+ }
+ const requestedPath = resolve(this.projectDir, file);
+ projectAbsPath(this.projectDir, file);
+ const canonicalPath = assertRealpathWithinDir(requestedPath, this.contentDir, {
+ allowShareableOkArtifact: isShareableOkArtifact,
+ });
+ const absPath = strategy === 'delete' ? requestedPath : canonicalPath;
+ await resolveReconcile(strategy, landing, docName, absPath, this.io);
+ await this.io.finalizeReconcileResolution?.(entry, strategy, docName);
+ this.unindex(file);
+ this.logResolved(file, entry.kind, strategy);
+ this.commit([{ type: 'cleared', file, docName, cause: 'resolved' }]);
+ return;
+ }
+ default: {
+ const exhaustive: never = entry;
+ throw new Error(`[conflicts] unknown conflict kind: ${JSON.stringify(exhaustive)}`);
+ }
+ }
+ }
+
+ private logResolved(file: string, kind: ConflictKind, choice: ResolveStrategy): void {
+ log.info({ file, kind, choice }, '[conflicts] conflict resolved by choice');
+ }
+
+ private async commitMergeBeforeClearing(entry: Conflict): Promise<void> {
+ const resolvedFile = entry.file;
+ const result = await commitMergeIfEmpty(this.io);
+ if (result.ok) {
+ log.info({ file: resolvedFile }, '[conflicts] all conflicts resolved — merge commit created');
+ return;
+ }
+ const causeText = result.cause instanceof Error ? result.cause.message : String(result.cause);
+ if (result.unmerged === null) {
+ log.error(
+ { err: result.cause, probeErr: result.probeError, file: resolvedFile },
+ '[conflicts] merge commit failed and the unmerged probe crashed — the ledger could not be re-synced against git',
+ );
+ throw new Error(
+ `Merge commit failed after resolving ${resolvedFile}; the conflict entry was kept — ${causeText}`,
+ { cause: result.cause },
+ );
+ }
+ const changes: ConflictChange[] = [];
+ for (const file of result.unmerged) {
+ if (this.byFile.has(file)) continue;
+ const conflict: Conflict = {
+ kind: 'merge-native',
+ file,
+ detectedAt: new Date().toISOString(),
+ };
+ const docName = this.index(conflict);
+ changes.push({ type: 'raised', conflict, docName });
+ }
+ this.commit(changes);
+ log.warn(
+ { err: result.cause, files: result.unmerged },
+ '[conflicts] failed to commit merge after all conflicts resolved — the ledger entry stays',
+ );
+ throw new Error(
+ `Merge commit failed after resolving ${resolvedFile}; the conflict entry was kept — ${causeText}`,
+ { cause: result.cause },
+ );
+ }
+
+ list(): readonly Conflict[] {
+ return [...this.byFile.values()];
+ }
+
+ findByFile(file: string): Conflict | undefined {
+ return this.byFile.get(file);
+ }
+
+ findByDocName(docName: string): Conflict | undefined {
+ return this.byDocName.get(docName);
+ }
+
+ has(docName: string): boolean {
+ return this.byDocName.has(docName);
+ }
+
+ count(): number {
+ return this.byFile.size;
+ }
+
+ private countOfKind(kind: ConflictKind): number {
+ let total = 0;
+ for (const entry of this.byFile.values()) if (entry.kind === kind) total++;
+ return total;
+ }
+
+ lifecycleOf(document: Y.Doc, docName: string): LifecycleView | null {
+ const map = document.getMap('lifecycle');
+ const status = map.get('status');
+ if (status === 'deleted-upstream') return { status: 'deleted-upstream' };
+ if (status === 'renamed') {
+ const newPath = map.get('newPath');
+ return { status: 'renamed', newPath: typeof newPath === 'string' ? newPath : '' };
+ }
+ const entry = this.byDocName.get(docName);
+ if (entry === undefined) return null;
+ switch (entry.kind) {
+ case 'reconcile':
+ return { status: 'conflict', kind: entry.kind, reason: entry.reason };
+ case 'merge-native':
+ return { status: 'conflict', kind: entry.kind, reason: 'merge-conflict' };
+ case 'working-tree':
+ return { status: 'conflict', kind: entry.kind, reason: 'pull-only-collision' };
+ default: {
+ const _exhaustive: never = entry;
+ return null;
+ }
+ }
+ }
+
+ setBranch(branch: string): void {
+ if (branch === this.branch) return;
+ this.branch = branch;
+ const changes: ConflictChange[] = [];
+ for (const entry of Array.from(this.byFile.values())) {
+ if (entry.kind !== 'reconcile' || entry.branch === branch) continue;
+ const docName = this.unindex(entry.file);
+ changes.push({ type: 'cleared', file: entry.file, docName, cause: 'branch-changed' });
+ }
+ if (changes.length === 0) {
+ if (this.byFile.size > 0) this.persist();
+ return;
+ }
+ log.info(
+ { branch, cleared: changes.length },
+ '[conflicts] branch changed — dropped the reconcile entries raised on the branch we left',
+ );
+ this.commit(changes);
+ }
+
+ subscribe(listener: (change: ConflictChange) => void): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+}
diff --git a/packages/server/src/conflict-errors.test.ts b/packages/server/src/conflict-errors.test.ts
index a8f6f38d5..9fe495bc4 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 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.',
+ 'The document is in a conflict state. Call 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 58e329864..a70cec236 100644
--- a/packages/server/src/conflict-errors.ts
+++ b/packages/server/src/conflict-errors.ts
@@ -1,7 +1,6 @@
import type { ServerResponse } from 'node:http';
-import type { Document } from '@hocuspocus/server';
-import type * as Y from 'yjs';
-import type { ResolveStrategy } from './conflict-storage.ts';
+import type { Conflict, ConflictKind, ReconcileReason, ResolveStrategy } from './conflict-kinds.ts';
+import { strategiesFor } from './conflict-kinds.ts';
import { stripDocExtension } from './doc-extensions.ts';
import { errorResponse } from './http/error-response.ts';
@@ -21,22 +20,6 @@ type _ExhaustiveResolveStrategy =
];
const _exhaustiveResolveStrategy: _ExhaustiveResolveStrategy = true;
-export function isDocInConflict(document: Document): boolean {
- return frozenDocLifecycleStatus(document) === 'conflict';
-}
-
-export const FROZEN_LIFECYCLE_STATUSES = ['deleted-upstream', 'renamed', 'conflict'] as const;
-export type FrozenLifecycleStatus = (typeof FROZEN_LIFECYCLE_STATUSES)[number];
-
-function isFrozenLifecycleStatus(value: unknown): value is FrozenLifecycleStatus {
- return (FROZEN_LIFECYCLE_STATUSES as readonly unknown[]).includes(value);
-}
-
-export function frozenDocLifecycleStatus(document: Y.Doc): FrozenLifecycleStatus | null {
- const status = document.getMap('lifecycle').get('status');
- return isFrozenLifecycleStatus(status) ? status : null;
-}
-
export class DocInConflictError extends Error {
readonly file: string;
override readonly name = 'DocInConflictError' as const;
@@ -47,10 +30,31 @@ export class DocInConflictError extends Error {
}
}
+export interface DocInConflictEnvelope {
+ detail: string;
+ conflict?: { kind: ConflictKind; reason?: ReconcileReason };
+ resolutionOptions: readonly ResolveStrategy[];
+}
+
+export function docInConflictEnvelope(conflict?: Conflict): DocInConflictEnvelope {
+ const reason: ReconcileReason | undefined =
+ conflict?.kind === 'reconcile' ? conflict.reason : undefined;
+ return {
+ detail:
+ 'The document is in a conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',
+ ...(conflict === undefined
+ ? {}
+ : { conflict: { kind: conflict.kind, ...(reason === undefined ? {} : { reason }) } }),
+ resolutionOptions:
+ conflict === undefined ? RESOLUTION_OPTIONS : strategiesFor(conflict.kind, reason),
+ };
+}
+
export function respondDocInConflict(
res: ServerResponse,
err: DocInConflictError,
handler: string,
+ conflict?: Conflict,
): void {
console.warn(
JSON.stringify({
@@ -59,24 +63,25 @@ export function respondDocInConflict(
'doc.name': stripDocExtension(err.file),
}),
);
+ const { detail, ...envelope } = docInConflictEnvelope(conflict);
errorResponse(res, 409, 'urn:ok:error:doc-in-conflict', 'Document is in conflict.', {
handler,
- 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.',
- extensions: {
- file: err.file,
- resolutionOptions: RESOLUTION_OPTIONS,
- },
+ detail,
+ extensions: { file: conflict?.file ?? err.file, ...envelope },
});
}
+export type ConflictMarkerRefusal = 'strategy-not-offered' | 'markers-in-content';
+
export class ConflictMarkersInContentError extends Error {
readonly file: string;
+ readonly refusal: ConflictMarkerRefusal;
override readonly name = 'ConflictMarkersInContentError' as const;
- constructor(opts: { file: string }) {
+ constructor(opts: { file: string; refusal?: ConflictMarkerRefusal }) {
super(`Resolution for ${opts.file} still contains conflict markers`);
this.file = opts.file;
+ this.refusal = opts.refusal ?? 'markers-in-content';
}
}
diff --git a/packages/server/src/conflict-kinds.ts b/packages/server/src/conflict-kinds.ts
new file mode 100644
index 000000000..9caad0500
--- /dev/null
+++ b/packages/server/src/conflict-kinds.ts
@@ -0,0 +1,123 @@
+import {
+ CONFLICT_KINDS,
+ RECONCILE_REASONS,
+ type RESOLVE_STRATEGIES,
+} from '@inkeep/open-knowledge-core';
+
+export type ConflictKind = (typeof CONFLICT_KINDS)[number];
+
+export type ReconcileReason = (typeof RECONCILE_REASONS)[number];
+
+export type ResolveStrategy = (typeof RESOLVE_STRATEGIES)[number];
+
+export interface ConflictStages {
+ base: string;
+ ours: string;
+ theirs: string;
+}
+
+export type Conflict =
+ | { kind: 'merge-native'; file: string; detectedAt: string }
+ | {
+ kind: 'working-tree';
+ file: string;
+ detectedAt: string;
+ theirsSha: string;
+ baseSha?: string;
+ }
+ | {
+ kind: 'reconcile';
+ file: string;
+ detectedAt: string;
+ branch: string;
+ reason: ReconcileReason;
+ stages: ConflictStages;
+ };
+
+type _ExhaustiveConflictKind =
+ Exclude<ConflictKind, Conflict['kind']> extends never
+ ? true
+ : ['Conflict is missing a ConflictKind member:', Exclude<ConflictKind, Conflict['kind']>];
+const _exhaustiveConflictKind: _ExhaustiveConflictKind = true;
+
+export type LifecycleView =
+ | {
+ status: 'conflict';
+ kind: ConflictKind;
+ reason: ReconcileReason | 'merge-conflict' | 'pull-only-collision';
+ }
+ | { status: 'deleted-upstream' }
+ | { status: 'renamed'; newPath: string };
+
+const FREEZING_LIFECYCLE_STATUSES = [
+ 'conflict',
+ 'deleted-upstream',
+ 'renamed',
+] as const satisfies readonly LifecycleView['status'][];
+
+export type FreezingLifecycleStatus = (typeof FREEZING_LIFECYCLE_STATUSES)[number];
+
+type _ExhaustiveFreezingLifecycleStatus =
+ Exclude<LifecycleView['status'], FreezingLifecycleStatus> extends never
+ ? true
+ : [
+ 'LifecycleView gained a status that does not freeze the disk store:',
+ Exclude<LifecycleView['status'], FreezingLifecycleStatus>,
+ ];
+const _exhaustiveFreezingLifecycleStatus: _ExhaustiveFreezingLifecycleStatus = true;
+
+export function isConflictKind(value: unknown): value is ConflictKind {
+ return (CONFLICT_KINDS as readonly unknown[]).includes(value);
+}
+
+export function isReconcileReason(value: unknown): value is ReconcileReason {
+ return (RECONCILE_REASONS as readonly unknown[]).includes(value);
+}
+
+const RECONCILE_MARKER_REASONS: ReadonlySet<ReconcileReason> = new Set<ReconcileReason>([
+ 'disk-markers',
+ 'refused-conflict-markers',
+]);
+
+const ALL_STRATEGIES = [
+ 'mine',
+ 'theirs',
+ 'content',
+ 'delete',
+] as const satisfies readonly ResolveStrategy[];
+
+const NO_THEIRS_STRATEGIES = [
+ 'mine',
+ 'content',
+ 'delete',
+] as const satisfies readonly ResolveStrategy[];
+
+const WHOLESALE_STRATEGIES = [
+ 'mine',
+ 'theirs',
+ 'delete',
+] as const satisfies readonly ResolveStrategy[];
+
+export function holdsMarkersOnDisk(entry: Conflict): boolean {
+ switch (entry.kind) {
+ case 'merge-native':
+ case 'working-tree':
+ return true;
+ case 'reconcile':
+ return RECONCILE_MARKER_REASONS.has(entry.reason);
+ default: {
+ const _exhaustive: never = entry;
+ return true;
+ }
+ }
+}
+
+export function strategiesFor(
+ kind: ConflictKind,
+ reason?: ReconcileReason,
+): readonly ResolveStrategy[] {
+ if (kind !== 'reconcile' || reason === undefined) return ALL_STRATEGIES;
+ if (RECONCILE_MARKER_REASONS.has(reason)) return NO_THEIRS_STRATEGIES;
+ if (reason === 'refused-too-large') return WHOLESALE_STRATEGIES;
+ return ALL_STRATEGIES;
+}
diff --git a/packages/server/src/conflict-lifecycle-seed.test.ts b/packages/server/src/conflict-lifecycle-seed.test.ts
deleted file mode 100644
index b6b711966..000000000
--- a/packages/server/src/conflict-lifecycle-seed.test.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import type { Document, Extension } from '@hocuspocus/server';
-import { describe, expect, test } from 'vitest';
-import * as Y from 'yjs';
-import { createConflictLifecycleSeedExtension } from './conflict-lifecycle-seed.ts';
-import type { ConflictEntry } from './conflict-storage.ts';
-import type { SyncEngine } from './sync-engine.ts';
-
-type AfterLoadDocumentHook = NonNullable<Extension['afterLoadDocument']>;
-type AfterLoadDocumentPayload = Parameters<AfterLoadDocumentHook>[0];
-
-function makeDoc(): Y.Doc {
- return new Y.Doc();
-}
-
-function makePayload(documentName: string, doc: Y.Doc): AfterLoadDocumentPayload {
- return {
- document: doc as unknown as Document,
- documentName,
- } as unknown as AfterLoadDocumentPayload;
-}
-
-function makeEngine(conflicts: ConflictEntry[]): SyncEngine {
- return { getConflicts: () => conflicts } as unknown as SyncEngine;
-}
-
-const PROJECT_DIR = '/tmp/ok-conflict-seed-test/project';
-const CONTENT_DIR = PROJECT_DIR;
-
-describe('createConflictLifecycleSeedExtension — afterLoadDocument', () => {
- test('sets lifecycle.status="conflict" for a .md doc tracked in ConflictStore', async () => {
- const doc = makeDoc();
- const engine = makeEngine([{ file: 'notes/foo.md', detectedAt: '2026-05-22T00:00:00.000Z' }]);
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => engine,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('notes/foo', doc));
-
- const lifecycle = doc.getMap('lifecycle');
- expect(lifecycle.get('status')).toBe('conflict');
- expect(lifecycle.get('reason')).toBe('conflict-markers');
- });
-
- test('sets lifecycle.status="conflict" for a .mdx doc tracked in ConflictStore', async () => {
- const doc = makeDoc();
- const engine = makeEngine([{ file: 'docs/page.mdx', detectedAt: '2026-05-22T00:00:00.000Z' }]);
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => engine,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('docs/page', doc));
-
- const lifecycle = doc.getMap('lifecycle');
- expect(lifecycle.get('status')).toBe('conflict');
- expect(lifecycle.get('reason')).toBe('conflict-markers');
- });
-
- test('leaves lifecycle unset when no conflicts are tracked', async () => {
- const doc = makeDoc();
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => makeEngine([]),
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('notes/foo', doc));
-
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('leaves lifecycle unset when this docs file is not in the conflicts list', async () => {
- const doc = makeDoc();
- const engine = makeEngine([{ file: 'other.md', detectedAt: '2026-05-22T00:00:00.000Z' }]);
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => engine,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('notes/foo', doc));
-
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('short-circuits when SyncEngine is null (dormant / no remote)', async () => {
- const doc = makeDoc();
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => null,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('notes/foo', doc));
-
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('idempotent — does not rewrite when lifecycle.status is already "conflict"', async () => {
- const doc = makeDoc();
- const lifecycle = doc.getMap('lifecycle');
- lifecycle.set('status', 'conflict');
- lifecycle.set('reason', 'merged-with-markers');
-
- const engine = makeEngine([{ file: 'notes/foo.md', detectedAt: '2026-05-22T00:00:00.000Z' }]);
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => engine,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('notes/foo', doc));
-
- expect(lifecycle.get('status')).toBe('conflict');
- expect(lifecycle.get('reason')).toBe('merged-with-markers');
- });
-
- test('skips synthetic docs (__system__)', async () => {
- const doc = makeDoc();
- const engine = makeEngine([{ file: '__system__.md', detectedAt: '2026-05-22T00:00:00.000Z' }]);
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => engine,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('__system__', doc));
-
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('skips synthetic docs (__config__/project)', async () => {
- const doc = makeDoc();
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => makeEngine([]),
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await ext.afterLoadDocument?.(makePayload('__config__/project', doc));
-
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('does not throw when SyncEngine getter throws (failure isolation)', async () => {
- const doc = makeDoc();
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => {
- throw new Error('sync engine probe failed');
- },
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await expect(ext.afterLoadDocument?.(makePayload('notes/foo', doc))).resolves.toBeUndefined();
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('does not throw when engine.getConflicts() throws (failure isolation)', async () => {
- const doc = makeDoc();
- const brokenEngine = {
- getConflicts: () => {
- throw new Error('conflict store load failed');
- },
- } as unknown as SyncEngine;
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => brokenEngine,
- projectDir: PROJECT_DIR,
- contentDir: CONTENT_DIR,
- });
-
- await expect(ext.afterLoadDocument?.(makePayload('notes/foo', doc))).resolves.toBeUndefined();
- expect(doc.getMap('lifecycle').get('status')).toBeUndefined();
- });
-
- test('handles projectDir-relative ConflictEntry.file with nested contentDir', async () => {
- const doc = makeDoc();
- const engine = makeEngine([{ file: 'content/foo.md', detectedAt: '2026-05-22T00:00:00.000Z' }]);
- const ext = createConflictLifecycleSeedExtension({
- getSyncEngine: () => engine,
- projectDir: PROJECT_DIR,
- contentDir: `${PROJECT_DIR}/content`,
- });
-
- await ext.afterLoadDocument?.(makePayload('foo', doc));
-
- expect(doc.getMap('lifecycle').get('status')).toBe('conflict');
- });
-});
diff --git a/packages/server/src/conflict-lifecycle-seed.ts b/packages/server/src/conflict-lifecycle-seed.ts
deleted file mode 100644
index 0dc845f3c..000000000
--- a/packages/server/src/conflict-lifecycle-seed.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { join, relative } from 'node:path';
-import type { Extension } from '@hocuspocus/server';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
-import type { ConflictEntry } from './conflict-storage.ts';
-import { stripDocExtension } from './doc-extensions.ts';
-import { getLogger } from './logger.ts';
-import { toPosix } from './path-utils.ts';
-import type { SyncEngine } from './sync-engine.ts';
-
-interface ConflictLifecycleSeedOptions {
- getSyncEngine: () => SyncEngine | null;
- projectDir: string;
- contentDir: string;
-}
-
-export function entryMatchesDocName(
- entry: ConflictEntry,
- docName: string,
- projectDir: string,
- contentDir: string,
-): boolean {
- const absPath = join(projectDir, entry.file);
- const contentRelPath = toPosix(relative(contentDir, absPath));
- if (contentRelPath.startsWith('..')) return false;
- return stripDocExtension(contentRelPath) === docName;
-}
-
-export function createConflictLifecycleSeedExtension(
- options: ConflictLifecycleSeedOptions,
-): Extension {
- const { getSyncEngine, projectDir, contentDir } = options;
- return {
- async afterLoadDocument({ documentName, document }) {
- if (isSystemDoc(documentName) || isConfigDoc(documentName)) return;
- try {
- const engine = getSyncEngine();
- if (!engine) return;
- const conflicts = engine.getConflicts();
- if (conflicts.length === 0) return;
- const hit = conflicts.some((entry) =>
- entryMatchesDocName(entry, documentName, projectDir, contentDir),
- );
- if (!hit) return;
- const lifecycleMap = document.getMap('lifecycle');
- if (lifecycleMap.get('status') === 'conflict') return;
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'conflict-markers');
- console.warn(
- JSON.stringify({
- event: 'lifecycle-seeded-on-load-from-conflict-store',
- 'doc.name': documentName,
- }),
- );
- } catch (err) {
- getLogger('conflict-lifecycle-seed').warn(
- { docName: documentName, err: err instanceof Error ? err : new Error(String(err)) },
- `failed to seed lifecycle on load (doc=${documentName})`,
- );
- }
- },
- };
-}
diff --git a/packages/server/src/conflict-resolution.test.ts b/packages/server/src/conflict-resolution.test.ts
new file mode 100644
index 000000000..d034ba594
--- /dev/null
+++ b/packages/server/src/conflict-resolution.test.ts
@@ -0,0 +1,399 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { type Conflict, ConflictAuthority, type ConflictIo } from './conflict-authority.ts';
+import {
+ commitMergeIfEmpty,
+ projectAbsPath,
+ resolveMergeNative,
+ resolveReconcile,
+ resolveWorkingTree,
+ selectReconcileOurs,
+} from './conflict-resolution.ts';
+
+let tmpDir = '';
+let projectDir = '';
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'conflict-resolution-test-'));
+ projectDir = join(tmpDir, 'project');
+ mkdirSync(projectDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true });
+});
+
+interface RecordingIo extends ConflictIo {
+ gitCalls: string[][];
+ applied: Array<{ docName: string; bytes: string }>;
+ unlinks: string[];
+}
+
+function makeIo(overrides: Partial<ConflictIo> = {}): RecordingIo {
+ const gitCalls: string[][] = [];
+ const applied: Array<{ docName: string; bytes: string }> = [];
+ const unlinks: string[] = [];
+ return {
+ gitCalls,
+ applied,
+ unlinks,
+ gitRaw: async (args) => {
+ gitCalls.push(args);
+ return '';
+ },
+ writeProjectFileUntracked: (absPath, bytes) => writeFileSync(absPath, bytes, 'utf-8'),
+ unlinkProjectFile: (absPath) => {
+ unlinks.push(absPath);
+ rmSync(absPath, { force: true });
+ },
+ applyResolvedContent: async (docName, absPath, bytes) => {
+ applied.push({ docName, bytes });
+ writeFileSync(absPath, bytes, 'utf-8');
+ },
+ ...overrides,
+ };
+}
+
+const mergeNative = (file: string): Extract<Conflict, { kind: 'merge-native' }> => ({
+ kind: 'merge-native',
+ file,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+});
+
+const workingTree = (
+ file: string,
+ theirsSha: string,
+): Extract<Conflict, { kind: 'working-tree' }> => ({
+ kind: 'working-tree',
+ file,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ theirsSha,
+});
+
+const reconcile = (
+ file: string,
+ reason: Extract<Conflict, { kind: 'reconcile' }>['reason'],
+): Extract<Conflict, { kind: 'reconcile' }> => ({
+ kind: 'reconcile',
+ file,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ branch: 'main',
+ reason,
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+});
+
+describe('projectAbsPath', () => {
+ test('resolves a project-relative path', () => {
+ expect(projectAbsPath(projectDir, 'a.md')).toBe(join(realpathSync(projectDir), 'a.md'));
+ });
+
+ test('refuses parent traversal and absolute paths', () => {
+ expect(() => projectAbsPath(projectDir, '../../etc/shadow.md')).toThrow(
+ 'file path escapes project directory',
+ );
+ expect(() => projectAbsPath(projectDir, '/etc/shadow.md')).toThrow(
+ 'file path escapes project directory',
+ );
+ });
+});
+
+describe('resolveMergeNative', () => {
+ test("'mine' checks out ours and stages it", async () => {
+ const io = makeIo();
+ await resolveMergeNative(mergeNative('a.md'), 'mine', undefined, io, projectDir);
+ expect(io.gitCalls).toEqual([
+ ['checkout', '--ours', '--', ':(literal)a.md'],
+ ['add', '--', ':(literal)a.md'],
+ ]);
+ });
+
+ test("'theirs' checks out theirs and stages it", async () => {
+ const io = makeIo();
+ await resolveMergeNative(mergeNative('a.md'), 'theirs', undefined, io, projectDir);
+ expect(io.gitCalls).toEqual([
+ ['checkout', '--theirs', '--', ':(literal)a.md'],
+ ['add', '--', ':(literal)a.md'],
+ ]);
+ });
+
+ test("'content' writes the bytes then stages the file", async () => {
+ const io = makeIo();
+ await resolveMergeNative(mergeNative('a.md'), 'content', 'MERGED\n', io, projectDir);
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('MERGED\n');
+ expect(io.gitCalls).toEqual([['add', '--', ':(literal)a.md']]);
+ });
+
+ test("'content' without bytes throws", async () => {
+ const io = makeIo();
+ await expect(
+ resolveMergeNative(mergeNative('a.md'), 'content', undefined, io, projectDir),
+ ).rejects.toThrow("strategy 'content' requires content parameter");
+ });
+
+ test("'delete' stages the removal through git", async () => {
+ const io = makeIo();
+ await resolveMergeNative(mergeNative('a.md'), 'delete', undefined, io, projectDir);
+ expect(io.gitCalls).toEqual([['rm', '--', ':(literal)a.md']]);
+ });
+});
+
+describe('resolveWorkingTree', () => {
+ test("'mine' touches neither disk nor git", async () => {
+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL\n', 'utf-8');
+ const io = makeIo();
+ await resolveWorkingTree(workingTree('a.md', 'sha'), 'mine', undefined, io, projectDir);
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL\n');
+ expect(io.gitCalls).toEqual([]);
+ });
+
+ test("'theirs' writes the pinned blob without committing", async () => {
+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL\n', 'utf-8');
+ const io = makeIo({ gitRaw: async () => 'REMOTE\n' });
+ await resolveWorkingTree(workingTree('a.md', 'sha'), 'theirs', undefined, io, projectDir);
+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('REMOTE\n');
+ });
+
+ test("'theirs' writes to the target validated before the asynchronous blob read", async () => {
+ const originalTarget = join(projectDir, 'original.md');
+ const replacementTarget = join(projectDir, 'replacement.md');
+ const link = join(projectDir, 'a.md');
+ writeFileSync(originalTarget, 'ORIGINAL\n', 'utf-8');
+ writeFileSync(replacementTarget, 'REPLACEMENT\n', 'utf-8');
+ symlinkSync(originalTarget, link);
+ const io = makeIo({
+ gitRaw: async () => {
+ unlinkSync(link);
+ symlinkSync(replacementTarget, link);
+ return 'REMOTE\n';
+ },
+ });
+
+ await resolveWorkingTree(workingTree('a.md', 'sha'), 'theirs', undefined, io, projectDir);
+
+ expect(readFileSync(originalTarget, 'utf-8')).toBe('REMOTE\n');
+ expect(readFileSync(replacementTarget, 'utf-8')).toBe('REPLACEMENT\n');
+ });
+
+ test("'delete' removes the file", async () => {
+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL\n', 'utf-8');
+ const io = makeIo();
+ await resolveWorkingTree(workingTree('a.md', 'sha'), 'delete', undefined, io, projectDir);
+ expect(existsSync(join(projectDir, 'a.md'))).toBe(false);
+ });
+});
+
+describe('resolveReconcile', () => {
+ test("'mine' applies the selected ours bytes through the host", async () => {
+ const io = makeIo();
+ const abs = join(projectDir, 'a.md');
+ await resolveReconcile('mine', 'LIVE\n', 'a', abs, io);
+ expect(io.applied).toEqual([{ docName: 'a', bytes: 'LIVE\n' }]);
+ });
+
+ test("'theirs' applies the snapshotted theirs stage through the host", async () => {
+ const io = makeIo();
+ const abs = join(projectDir, 'a.md');
+ await resolveReconcile('theirs', 'THEIRS\n', 'a', abs, io);
+ expect(io.applied).toEqual([{ docName: 'a', bytes: 'THEIRS\n' }]);
+ });
+
+ test("'content' applies the supplied bytes and never touches git", async () => {
+ const io = makeIo();
+ const abs = join(projectDir, 'a.md');
+ await resolveReconcile('content', 'HAND\n', 'a', abs, io);
+ expect(io.applied).toEqual([{ docName: 'a', bytes: 'HAND\n' }]);
+ expect(io.gitCalls).toEqual([]);
+ });
+
+ test("'delete' unlinks the file and never touches git", async () => {
+ const abs = join(projectDir, 'a.md');
+ writeFileSync(abs, 'markers\n', 'utf-8');
+ const io = makeIo();
+ await resolveReconcile('delete', undefined, 'a', abs, io);
+ expect(io.unlinks).toEqual([abs]);
+ expect(io.gitCalls).toEqual([]);
+ });
+
+ test('a host throw propagates so the caller can keep the entry', async () => {
+ const io = makeIo({
+ applyResolvedContent: async () => {
+ throw new Error('disk full');
+ },
+ });
+ await expect(
+ resolveReconcile('mine', 'OURS\n', 'a', join(projectDir, 'a.md'), io),
+ ).rejects.toThrow('disk full');
+ });
+});
+
+describe('selectReconcileOurs', () => {
+ test('prefers marker-free live content, including an empty document', () => {
+ const entry = reconcile('a.md', 'merged-with-markers');
+ expect(selectReconcileOurs(entry, 'LIVE\n')).toBe('LIVE\n');
+ expect(selectReconcileOurs(entry, '')).toBe('');
+ });
+
+ test('falls back to the captured stage when live content is absent or contains markers', () => {
+ const entry = reconcile('a.md', 'merged-with-markers');
+ expect(selectReconcileOurs(entry, null)).toBe('OURS\n');
+ expect(
+ selectReconcileOurs(entry, '<<<<<<< ours\nLIVE\n=======\nTHEIRS\n>>>>>>> theirs\n'),
+ ).toBe('OURS\n');
+ });
+});
+
+describe('ConflictAuthority live ours selection', () => {
+ test('reads marker-free live content once and lands the selected bytes', async () => {
+ let reads = 0;
+ const io = makeIo({
+ readLiveContent: () => {
+ reads++;
+ return reads === 1 ? 'LIVE\n' : 'CHANGED\n';
+ },
+ });
+ const authority = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'main',
+ io,
+ });
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+
+ await authority.resolve('a.md', 'mine');
+
+ expect(reads).toBe(1);
+ expect(io.applied).toEqual([{ docName: 'a', bytes: 'LIVE\n' }]);
+ });
+
+ test('falls back to captured ours when the optional live reader is absent', async () => {
+ const io = makeIo();
+ const authority = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'main',
+ io,
+ });
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+
+ await authority.resolve('a.md', 'mine');
+
+ expect(io.applied).toEqual([{ docName: 'a', bytes: 'OURS\n' }]);
+ });
+
+ test('validates the selected live bytes instead of a marker-filled captured stage', async () => {
+ const io = makeIo({ readLiveContent: () => 'LIVE\n' });
+ const authority = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'main',
+ io,
+ });
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: {
+ base: 'BASE\n',
+ ours: '<<<<<<< ours\nOURS\n=======\nTHEIRS\n>>>>>>> theirs\n',
+ theirs: 'THEIRS\n',
+ },
+ });
+
+ await authority.resolve('a.md', 'mine');
+
+ expect(io.applied).toEqual([{ docName: 'a', bytes: 'LIVE\n' }]);
+ });
+
+ test('rejects mine when live and captured ours both contain markers', async () => {
+ const markers = '<<<<<<< ours\nOURS\n=======\nTHEIRS\n>>>>>>> theirs\n';
+ const io = makeIo({ readLiveContent: () => markers });
+ const authority = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'main',
+ io,
+ });
+ authority.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'BASE\n', ours: markers, theirs: 'THEIRS\n' },
+ });
+
+ await expect(authority.resolve('a.md', 'mine')).rejects.toMatchObject({
+ name: 'ConflictMarkersInContentError',
+ });
+ expect(io.applied).toEqual([]);
+ });
+});
+
+describe('commitMergeIfEmpty', () => {
+ test('reports ok when the merge commit lands', async () => {
+ const io = makeIo();
+ expect(await commitMergeIfEmpty(io)).toEqual({ ok: true });
+ expect(io.gitCalls).toEqual([['commit', '--no-edit']]);
+ });
+
+ test('reports the still-unmerged files when the commit fails', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ return 'a.md\0b.md\0';
+ },
+ });
+ const result = await commitMergeIfEmpty(io);
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.unmerged).toEqual(['a.md', 'b.md']);
+ });
+
+ test('a crashed probe is not reported as a clean index', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ throw new Error('git exploded');
+ },
+ });
+ const result = await commitMergeIfEmpty(io);
+
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.unmerged).toBeNull();
+ expect(result.unmerged === null ? result.probeError : undefined).toBeInstanceOf(Error);
+ expect(result.cause).toBeInstanceOf(Error);
+ });
+
+ test('a probe reporting nothing unmerged stays distinguishable as an empty list', async () => {
+ const io = makeIo({
+ gitRaw: async (args) => {
+ if (args[0] === 'commit') throw new Error('nothing to commit');
+ return '';
+ },
+ });
+ const result = await commitMergeIfEmpty(io);
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.unmerged).toEqual([]);
+ });
+});
diff --git a/packages/server/src/conflict-resolution.ts b/packages/server/src/conflict-resolution.ts
new file mode 100644
index 000000000..d6f958cd3
--- /dev/null
+++ b/packages/server/src/conflict-resolution.ts
@@ -0,0 +1,158 @@
+import { existsSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { pathspecArgs } from '@inkeep/open-knowledge-core';
+import type { Conflict, ConflictIo, ResolveStrategy } from './conflict-authority.ts';
+import { ConflictMarkersInContentError } from './conflict-errors.ts';
+import { isShareableOkArtifact } from './content-filter.ts';
+import { splitNulSeparatedPaths } from './git-paths.ts';
+import { isWithinDir } from './path-utils.ts';
+import { containsUnresolvedConflictBlock } from './reconciliation.ts';
+import { assertRealpathWithinDir } from './symlink-guard.ts';
+
+export function selectReconcileOurs(
+ entry: Extract<Conflict, { kind: 'reconcile' }>,
+ liveOurs: string | null,
+): string {
+ return liveOurs !== null && !containsUnresolvedConflictBlock(liveOurs)
+ ? liveOurs
+ : entry.stages.ours;
+}
+
+export function projectAbsPath(projectDir: string, file: string): string {
+ const projectRoot = resolve(projectDir);
+ const absPath = resolve(projectRoot, file);
+ if (!isWithinDir(absPath, projectRoot)) {
+ throw new Error(`[conflicts] file path escapes project directory: ${file}`);
+ }
+ return assertRealpathWithinDir(absPath, projectRoot, {
+ allowShareableOkArtifact: isShareableOkArtifact,
+ });
+}
+
+function requireContent(content: string | undefined): string {
+ if (content === undefined) {
+ throw new Error(`[conflicts] strategy 'content' requires content parameter`);
+ }
+ return content;
+}
+
+export async function resolveMergeNative(
+ entry: Extract<Conflict, { kind: 'merge-native' }>,
+ strategy: ResolveStrategy,
+ content: string | undefined,
+ io: ConflictIo,
+ projectDir: string,
+): Promise<void> {
+ switch (strategy) {
+ case 'mine':
+ await io.gitRaw(['checkout', '--ours', ...pathspecArgs([entry.file])]);
+ await io.gitRaw(['add', ...pathspecArgs([entry.file])]);
+ return;
+
+ case 'theirs':
+ await io.gitRaw(['checkout', '--theirs', ...pathspecArgs([entry.file])]);
+ await io.gitRaw(['add', ...pathspecArgs([entry.file])]);
+ return;
+
+ case 'content': {
+ const bytes = requireContent(content);
+ io.writeProjectFileUntracked(projectAbsPath(projectDir, entry.file), bytes);
+ await io.gitRaw(['add', ...pathspecArgs([entry.file])]);
+ return;
+ }
+
+ case 'delete':
+ await io.gitRaw(['rm', ...pathspecArgs([entry.file])]);
+ return;
+
+ default: {
+ const exhaustive: never = strategy;
+ throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);
+ }
+ }
+}
+
+export async function resolveWorkingTree(
+ entry: Extract<Conflict, { kind: 'working-tree' }>,
+ strategy: ResolveStrategy,
+ content: string | undefined,
+ io: ConflictIo,
+ projectDir: string,
+): Promise<void> {
+ const requestedPath = resolve(projectDir, entry.file);
+ const canonicalPath = projectAbsPath(projectDir, entry.file);
+ switch (strategy) {
+ case 'mine':
+ return;
+
+ case 'theirs': {
+ const theirsBytes = await io.gitRaw(['cat-file', 'blob', entry.theirsSha]);
+ if (containsUnresolvedConflictBlock(theirsBytes)) {
+ throw new ConflictMarkersInContentError({ file: entry.file });
+ }
+ io.writeProjectFileUntracked(canonicalPath, theirsBytes);
+ return;
+ }
+
+ case 'content': {
+ io.writeProjectFileUntracked(canonicalPath, requireContent(content));
+ return;
+ }
+
+ case 'delete':
+ if (existsSync(requestedPath)) io.unlinkProjectFile(requestedPath);
+ return;
+
+ default: {
+ const exhaustive: never = strategy;
+ throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);
+ }
+ }
+}
+
+export async function resolveReconcile(
+ strategy: ResolveStrategy,
+ resolvedBytes: string | undefined,
+ docName: string,
+ absPath: string,
+ io: ConflictIo,
+): Promise<void> {
+ switch (strategy) {
+ case 'mine':
+ case 'theirs':
+ case 'content': {
+ await io.applyResolvedContent(docName, absPath, requireContent(resolvedBytes));
+ return;
+ }
+
+ case 'delete':
+ if (existsSync(absPath)) io.unlinkProjectFile(absPath);
+ return;
+
+ default: {
+ const exhaustive: never = strategy;
+ throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);
+ }
+ }
+}
+
+export type CommitMergeResult =
+ | { ok: true }
+ | { ok: false; unmerged: string[]; cause: unknown }
+ | { ok: false; unmerged: null; probeError: unknown; cause: unknown };
+
+export async function commitMergeIfEmpty(io: ConflictIo): Promise<CommitMergeResult> {
+ try {
+ await io.gitRaw(['commit', '--no-edit']);
+ return { ok: true };
+ } catch (cause) {
+ try {
+ const unmerged = splitNulSeparatedPaths(
+ await io.gitRaw(['diff', '-z', '--name-only', '--diff-filter=U']),
+ );
+ return { ok: false, unmerged, cause };
+ } catch (probeError) {
+ return { ok: false, unmerged: null, probeError, cause };
+ }
+ }
+}
diff --git a/packages/server/src/conflict-storage.test.ts b/packages/server/src/conflict-storage.test.ts
deleted file mode 100644
index 0dd49d0ff..000000000
--- a/packages/server/src/conflict-storage.test.ts
+++ /dev/null
@@ -1,521 +0,0 @@
-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, 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 = '';
-let storePath = '';
-
-beforeEach(() => {
- tmpDir = mkdtempSync(join(tmpdir(), 'conflict-store-test-'));
- projectDir = join(tmpDir, 'project');
- storePath = join(projectDir, '.ok', LOCAL_DIR, 'conflicts.json');
- mkdirSync(projectDir, { recursive: true });
- mkdirSync(join(projectDir, '.ok', LOCAL_DIR), { recursive: true });
-});
-
-afterEach(() => {
- rmSync(tmpDir, { recursive: true, force: true });
-});
-
-function makeEntry(file: string, overrides: Partial<ConflictEntry> = {}): ConflictEntry {
- return {
- file,
- detectedAt: new Date().toISOString(),
- ...overrides,
- };
-}
-
-function readStore(): { version: number; branch: string; conflicts: ConflictEntry[] } {
- 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');
- expect(store.count()).toBe(0);
- expect(store.hasConflicts()).toBe(false);
- expect(store.list()).toEqual([]);
- });
-
- test('addConflict() persists entry to disk', () => {
- const store = new ConflictStore(projectDir, 'main');
- const entry = makeEntry('README.md');
- store.addConflict(entry);
-
- expect(store.count()).toBe(1);
- expect(store.list()[0].file).toBe('README.md');
-
- const persisted = readStore();
- expect(persisted.version).toBe(1);
- expect(persisted.branch).toBe('main');
- expect(persisted.conflicts).toHaveLength(1);
- expect(persisted.conflicts[0].file).toBe('README.md');
- });
-
- test('addConflict() is idempotent — updates existing entry', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md', { oursSha: 'sha1' }));
- store.addConflict(makeEntry('a.md', { oursSha: 'sha2' }));
-
- expect(store.count()).toBe(1);
- expect(store.list()[0].oursSha).toBe('sha2');
- });
-
- test('addConflict() accumulates multiple distinct entries', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- store.addConflict(makeEntry('b.md'));
- store.addConflict(makeEntry('docs/c.md'));
-
- expect(store.count()).toBe(3);
- expect(store.list().map((e) => e.file)).toEqual(['a.md', 'b.md', 'docs/c.md']);
- });
-
- test('removeConflict() removes by file path', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- store.addConflict(makeEntry('b.md'));
-
- store.removeConflict('a.md');
-
- expect(store.count()).toBe(1);
- expect(store.list()[0].file).toBe('b.md');
- expect(readStore().conflicts).toHaveLength(1);
- });
-
- test('removeConflict() is a no-op for unknown file', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- store.removeConflict('nonexistent.md');
- expect(store.count()).toBe(1);
- });
-
- test('clear() removes all conflicts', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- store.addConflict(makeEntry('b.md'));
- store.clear();
-
- expect(store.count()).toBe(0);
- expect(readStore().conflicts).toHaveLength(0);
- });
-
- test('load() restores from persisted JSON', () => {
- const data = {
- version: 1,
- branch: 'feat/test',
- conflicts: [makeEntry('notes.md', { oursSha: 'abc', theirsSha: 'def' })],
- };
- writeFileSync(storePath, JSON.stringify(data), 'utf-8');
-
- const store = new ConflictStore(projectDir, 'main');
- expect(store.count()).toBe(1);
- expect(store.list()[0].file).toBe('notes.md');
- expect(store.list()[0].oursSha).toBe('abc');
- });
-
- test('load() handles corrupt JSON gracefully — starts empty', () => {
- writeFileSync(storePath, 'NOT JSON', 'utf-8');
- const store = new ConflictStore(projectDir, 'main');
- expect(store.count()).toBe(0);
- });
-
- test('load() handles unknown schema version — starts empty', () => {
- writeFileSync(storePath, JSON.stringify({ version: 99, branch: 'x', conflicts: [] }));
- const store = new ConflictStore(projectDir, 'main');
- expect(store.count()).toBe(0);
- });
-
- test('setBranch() updates the stored branch on next save', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- store.setBranch('feat/new-branch');
- store.addConflict(makeEntry('b.md'));
-
- expect(readStore().branch).toBe('feat/new-branch');
- });
-});
-
-describe('ConflictStore resolveConflict()', () => {
- test('throws when file is not tracked as a conflict', async () => {
- const store = new ConflictStore(projectDir, 'main');
- await expect(store.resolveConflict('unknown.md', 'mine')).rejects.toThrow(
- 'no conflict tracked for file: unknown.md',
- );
- });
-
- test("strategy 'content': refuses content that still carries conflict markers", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
-
- const markered = [
- '# Pricing',
- '',
- '<<<<<<< ours',
- 'The Team tier moves to $29 per seat.',
- '=======',
- 'The Team tier moves to $29 per seat, grandfathered.',
- '>>>>>>> theirs',
- '',
- ].join('\n');
-
- await expect(store.resolveConflict('a.md', 'content', markered)).rejects.toThrow(
- ConflictMarkersInContentError,
- );
- await expect(store.resolveConflict('a.md', 'content', markered)).rejects.toMatchObject({
- name: 'ConflictMarkersInContentError',
- file: 'a.md',
- });
- expect(store.count()).toBe(1);
- });
-
- test("strategy 'content': accepts a genuine resolution mentioning no markers", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- await expect(
- store.resolveConflict('a.md', 'content', '# Pricing\n\nThe Team tier moves to $29.\n'),
- ).rejects.not.toThrow(/contains conflict markers/);
- });
-
- test("strategy 'content': accepts a resolution whose body contains a setext H1", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- await expect(
- store.resolveConflict(
- 'a.md',
- 'content',
- 'Release Notes\n=======\n\nThe Team tier moves to $29.\n',
- ),
- ).rejects.not.toThrow(/contains conflict markers/);
- expect(store.count()).toBe(1);
- });
-
- test("strategy 'mine'/'theirs': removes conflict from store when git succeeds", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
-
- store.removeConflict('a.md');
- expect(store.count()).toBe(0);
- expect(readStore().conflicts).toHaveLength(0);
- });
-
- test("strategy 'content': writes content to disk and removes conflict", async () => {
- const testFile = 'notes.md';
- const absPath = join(projectDir, testFile);
- writeFileSync(absPath, '<<<<<<< HEAD\nmy version\n=======\ntheir version\n>>>>>>>\n', 'utf-8');
-
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry(testFile));
-
- const resolvedContent = '# Resolved\n\nManually merged content.\n';
- writeFileSync(absPath, resolvedContent, 'utf-8');
-
- const actualContent = readFileSync(absPath, 'utf-8');
- expect(actualContent).toBe(resolvedContent);
-
- store.removeConflict(testFile);
- expect(store.count()).toBe(0);
- expect(existsSync(storePath)).toBe(true);
- expect(readStore().conflicts).toHaveLength(0);
- });
-
- test("strategy 'content' rejects path-traversal via parent components", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('../../../etc/shadow.md'));
-
- await expect(
- store.resolveConflict('../../../etc/shadow.md', 'content', 'malicious'),
- ).rejects.toThrow('file path escapes project directory');
- });
-
- test("strategy 'content' rejects absolute path", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('/etc/shadow.md'));
-
- await expect(store.resolveConflict('/etc/shadow.md', 'content', 'malicious')).rejects.toThrow(
- 'file path escapes project directory',
- );
- });
-
- test("strategy 'content' rejects sneaky parent traversal that resolves outside projectDir", async () => {
- const store = new ConflictStore(projectDir, 'main');
- const sneaky = 'subdir/../../escape.md';
- store.addConflict(makeEntry(sneaky));
-
- await expect(store.resolveConflict(sneaky, 'content', 'malicious')).rejects.toThrow(
- 'file path escapes project directory',
- );
- });
-
- test("strategy 'content' without content throws", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
-
- await expect(store.resolveConflict('a.md', 'content', undefined)).rejects.toThrow(
- "strategy 'content' requires content parameter",
- );
- });
-
- test("strategy 'delete' removes the file from disk and stages the deletion", async () => {
- const store = new ConflictStore(projectDir, 'main');
-
- const testFile = 'foo.md';
- const absPath = join(projectDir, testFile);
- writeFileSync(absPath, 'their modification\n', 'utf-8');
- store.addConflict(makeEntry(testFile));
-
- // biome-ignore lint/suspicious/noExplicitAny: 'delete' is the new variant the test pins
- await store.resolveConflict(testFile, 'delete' as any).catch((e) => {
- if (e instanceof Error && e.message.includes('unknown resolve strategy')) {
- throw e;
- }
- });
-
- expect(store.count()).toBeLessThanOrEqual(1);
- });
-
- test("strategy 'delete' is structurally accepted (does not throw 'unknown resolve strategy')", async () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
-
- let thrown: Error | undefined;
- try {
- // biome-ignore lint/suspicious/noExplicitAny: pinning the new variant pre-fix
- await store.resolveConflict('a.md', 'delete' as any);
- } catch (e) {
- thrown = e as Error;
- }
- if (thrown !== undefined) {
- expect(thrown.message).not.toContain('unknown resolve strategy');
- }
- });
-
- test("strategy 'content' with empty string '' must NOT throw the misleading 'requires content parameter' error", async () => {
- const store = new ConflictStore(projectDir, 'main');
- const testFile = 'a.md';
- const absPath = join(projectDir, testFile);
- writeFileSync(absPath, 'whatever\n', 'utf-8');
- store.addConflict(makeEntry(testFile));
-
- let caught: Error | undefined;
- try {
- await store.resolveConflict(testFile, 'content', '');
- } catch (e) {
- caught = e as Error;
- }
- if (caught !== undefined) {
- expect(caught.message).not.toContain('requires content parameter');
- }
- });
-
- test('hasConflicts() returns false after all are removed', () => {
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md'));
- store.addConflict(makeEntry('b.md'));
-
- store.removeConflict('a.md');
- expect(store.hasConflicts()).toBe(true);
-
- store.removeConflict('b.md');
- expect(store.hasConflicts()).toBe(false);
- });
-});
-
-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,
- local: string,
- ): Promise<{ blobSha: string; headSha: string }> {
- const git = simpleGit(projectDir);
- await git.init(['--initial-branch=main']);
- await git.raw('config', 'user.name', 'Test');
- await git.raw('config', 'user.email', '[email protected]');
- writeFileSync(join(projectDir, file), remote, 'utf-8');
- await git.add('.');
- await git.commit('seed');
- const blobSha = (await git.raw(['rev-parse', `HEAD:${file}`])).trim();
- const headSha = (await git.raw(['rev-parse', 'HEAD'])).trim();
- writeFileSync(join(projectDir, file), local, 'utf-8');
- return { blobSha, headSha };
- }
-
- async function headSha(): Promise<string> {
- return (await simpleGit(projectDir).raw(['rev-parse', 'HEAD'])).trim();
- }
-
- test("'theirs' restores the pinned origin-tip blob 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', 'theirs');
-
- expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('REMOTE\n');
- expect(store.count()).toBe(0);
- expect(await headSha()).toBe(before);
- });
-
- test("'mine' keeps the overlay verbatim 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', 'mine');
-
- expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL\n');
- expect(store.count()).toBe(0);
- expect(await headSha()).toBe(before);
- });
-
- test('the entry leaves the store BEFORE the resolved bytes reach disk', async () => {
- const { blobSha } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));
-
- const target = join(projectDir, 'a.md');
- let diskAtRemoval: string | null = null;
- const realRemove = store.removeConflict.bind(store);
- store.removeConflict = (f: string) => {
- diskAtRemoval = readFileSync(target, 'utf-8');
- return realRemove(f);
- };
-
- await store.resolveConflict('a.md', 'content', 'HAND-MERGED\n');
-
- expect(diskAtRemoval).toBe('LOCAL\n');
- expect(readFileSync(target, 'utf-8')).toBe('HAND-MERGED\n');
- expect(store.count()).toBe(0);
- });
-
- test("'content' writes the merged bytes 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', 'HAND-MERGED\n');
-
- expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('HAND-MERGED\n');
- expect(store.count()).toBe(0);
- 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');
- store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));
-
- await store.resolveConflict('a.md', 'delete');
-
- expect(existsSync(join(projectDir, 'a.md'))).toBe(false);
- expect(store.count()).toBe(0);
- expect(await headSha()).toBe(before);
- });
-
- test('addConflict rejects a working-tree entry with no pinned blob', () => {
- const store = new ConflictStore(projectDir, 'main');
- expect(() => store.addConflict(makeEntry('a.md', { variant: 'working-tree' }))).toThrow(
- 'no pinned theirs blob',
- );
- });
-
- test("'theirs' still throws for a blob-less entry from a corrupt store", async () => {
- const store = new ConflictStore(projectDir, 'main');
- (store as unknown as { conflicts: unknown[] }).conflicts.push(
- makeEntry('a.md', { variant: 'working-tree' }),
- );
- await expect(store.resolveConflict('a.md', 'theirs')).rejects.toThrow('no pinned theirs blob');
- });
-});
diff --git a/packages/server/src/conflict-storage.ts b/packages/server/src/conflict-storage.ts
deleted file mode 100644
index 6310170c9..000000000
--- a/packages/server/src/conflict-storage.ts
+++ /dev/null
@@ -1,331 +0,0 @@
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
-import { dirname, join, resolve } from 'node:path';
-import { pathspecArgs } from '@inkeep/open-knowledge-core';
-import { getLocalDir } from './config/paths.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 { assertRealpathWithinDir } from './symlink-guard.ts';
-
-const log = getLogger('conflict-storage');
-
-export interface ConflictEntry {
- file: string;
- detectedAt: string;
- oursSha?: string;
- theirsSha?: string;
- baseSha?: string;
- variant?: 'working-tree';
-}
-
-export type ResolveStrategy = 'mine' | 'theirs' | 'content' | 'delete';
-
-interface ConflictsJson {
- version: 1;
- branch: string;
- conflicts: ConflictEntry[];
-}
-
-export class ConflictStore {
- private readonly storePath: string;
- private readonly projectDir: string;
- private branch: string;
- private conflicts: ConflictEntry[] = [];
-
- constructor(projectDir: string, branch = 'main') {
- this.storePath = join(getLocalDir(projectDir), 'conflicts.json');
- this.projectDir = projectDir;
- this.branch = branch;
- this.load();
- }
-
- load(): void {
- if (!existsSync(this.storePath)) {
- this.conflicts = [];
- return;
- }
- try {
- const raw = readFileSync(this.storePath, 'utf-8');
- const data = JSON.parse(raw) as Partial<ConflictsJson>;
- if (data.version !== 1) {
- log.warn({ path: this.storePath }, '[conflicts] unknown schema version — resetting');
- this.conflicts = [];
- return;
- }
- 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 = [];
- }
- }
-
- save(): boolean {
- try {
- const dir = dirname(this.storePath);
- if (!existsSync(dir)) {
- mkdirSync(dir, { recursive: true });
- }
- const data: ConflictsJson = {
- version: 1,
- branch: this.branch,
- conflicts: this.conflicts,
- };
- writeFileSync(this.storePath, JSON.stringify(data, null, 2), 'utf-8');
- return true;
- } catch (e) {
- log.warn({ err: e }, '[conflicts] failed to save conflicts.json');
- return false;
- }
- }
-
- addConflict(entry: ConflictEntry): boolean {
- if (entry.variant === 'working-tree' && !entry.theirsSha) {
- throw new Error(
- `[conflicts] working-tree conflict for ${entry.file} has no pinned theirs blob`,
- );
- }
- const existing = this.conflicts.findIndex((c) => c.file === entry.file);
- if (existing !== -1) {
- this.conflicts[existing] = entry;
- } else {
- this.conflicts.push(entry);
- }
- return this.save();
- }
-
- removeConflict(file: string): boolean {
- this.conflicts = this.conflicts.filter((c) => c.file !== file);
- return this.save();
- }
-
- clear(): void {
- this.conflicts = [];
- if (!this.save()) {
- log.error(
- { branch: this.branch },
- '[conflicts] cleared conflicts in memory but conflicts.json persist failed — the ledger will resurrect them on restart',
- );
- }
- }
-
- count(): number {
- return this.conflicts.length;
- }
-
- list(): ConflictEntry[] {
- return [...this.conflicts];
- }
-
- hasConflicts(): boolean {
- return this.conflicts.length > 0;
- }
-
- setBranch(branch: string): void {
- this.branch = branch;
- }
-
- async resolveConflict(file: string, strategy: ResolveStrategy, content?: string): Promise<void> {
- const entry = this.conflicts.find((c) => c.file === file);
- if (!entry) {
- throw new NoConflictTrackedError({ file });
- }
-
- if (strategy === 'content') requireConflictResolutionContent(file, content);
-
- if (entry.variant === 'working-tree') {
- await this.resolveWorkingTreeConflict(entry, strategy, content);
- return;
- }
-
- const { createGitInstance } = await import('./git-handle.ts');
- const handle = createGitInstance(this.projectDir, { credentialConfig: [] });
-
- switch (strategy) {
- case 'mine':
- await handle.git.raw(['checkout', '--ours', ...pathspecArgs([file])]);
- await handle.git.raw(['add', ...pathspecArgs([file])]);
- break;
-
- case 'theirs':
- await handle.git.raw(['checkout', '--theirs', ...pathspecArgs([file])]);
- await handle.git.raw(['add', ...pathspecArgs([file])]);
- break;
-
- case 'content': {
- 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}`);
- }
- const target = assertRealpathWithinDir(absPath, projectRoot, {
- allowShareableOkArtifact: isShareableOkArtifact,
- });
- tracedWriteFileSync(target, resolved, 'utf-8');
- await handle.git.raw(['add', ...pathspecArgs([file])]);
- break;
- }
-
- case 'delete': {
- await handle.git.raw(['rm', ...pathspecArgs([file])]);
- break;
- }
-
- default: {
- const exhaustive: never = strategy;
- throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);
- }
- }
-
- const priorDetectedAt = new Map<string, string>(
- this.list().map((entry) => [entry.file, entry.detectedAt] as const),
- );
-
- if (!this.removeConflict(file)) {
- log.error(
- { file },
- '[conflicts] resolve dropped the conflict in memory but conflicts.json persist failed — the ledger will resurrect this conflict on restart',
- );
- }
-
- if (!this.hasConflicts()) {
- try {
- await handle.git.raw(['commit', '--no-edit']);
- log.info({ file }, '[conflicts] all conflicts resolved — merge commit created');
- } catch (e) {
- const fallbackDetectedAt = new Date().toISOString();
- let reAdded = false;
- try {
- const unmerged = await listNames(handle.git, ['diff', '--name-only', '--diff-filter=U']);
- for (const f of unmerged) {
- this.addConflict({
- file: f,
- detectedAt: priorDetectedAt.get(f) ?? fallbackDetectedAt,
- });
- }
- reAdded = unmerged.length > 0;
- } catch (scanErr) {
- log.warn(
- { err: scanErr },
- '[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add',
- );
- }
- if (!reAdded) {
- this.addConflict({ file, detectedAt: priorDetectedAt.get(file) ?? fallbackDetectedAt });
- }
- log.warn(
- { err: e },
- '[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added',
- );
- const causeText = e instanceof Error ? e.message : String(e);
- throw new Error(
- `Merge commit failed after resolving ${file}; ${reAdded ? 'unmerged files re-added' : 'original file re-added'} — ${causeText}`,
- { cause: e },
- );
- }
- }
- }
-
- private async resolveWorkingTreeConflict(
- entry: ConflictEntry,
- strategy: ResolveStrategy,
- content: string | undefined,
- ): Promise<void> {
- const projectRoot = resolve(this.projectDir);
- const absPath = resolve(projectRoot, entry.file);
- if (!isWithinDir(absPath, projectRoot)) {
- throw new Error(`[conflicts] file path escapes project directory: ${entry.file}`);
- }
- const target = assertRealpathWithinDir(absPath, projectRoot, {
- allowShareableOkArtifact: isShareableOkArtifact,
- });
-
- const restoreOnFailure = { ...entry };
- if (!this.removeConflict(entry.file)) {
- log.error(
- { file: entry.file },
- '[conflicts] resolve dropped the conflict in memory but conflicts.json persist failed — the ledger will resurrect this conflict on restart',
- );
- }
-
- try {
- await this.applyWorkingTreeStrategy(absPath, target, projectRoot, entry, strategy, content);
- } catch (err) {
- if (!this.addConflict(restoreOnFailure)) {
- log.error(
- { file: entry.file, err },
- '[conflicts] resolve rolled back in memory but conflicts.json persist failed — the ledger will lose this conflict on restart',
- );
- }
- throw err;
- }
- }
-
- private async applyWorkingTreeStrategy(
- absPath: string,
- target: string,
- projectRoot: string,
- entry: ConflictEntry,
- strategy: ResolveStrategy,
- content: string | undefined,
- ): Promise<void> {
- switch (strategy) {
- case 'mine':
- break;
-
- case 'theirs': {
- if (!entry.theirsSha) {
- throw new Error(
- `[conflicts] working-tree conflict for ${entry.file} has no pinned theirs blob`,
- );
- }
- const { createGitInstance } = await import('./git-handle.ts');
- const handle = createGitInstance(this.projectDir, { credentialConfig: [] });
- const theirsBytes = await handle.git.raw(['cat-file', 'blob', entry.theirsSha]);
- const writeTarget = assertRealpathWithinDir(target, projectRoot, {
- allowShareableOkArtifact: isShareableOkArtifact,
- });
- tracedWriteFileSync(writeTarget, theirsBytes, 'utf-8');
- break;
- }
-
- case 'content': {
- const writeTarget = assertRealpathWithinDir(target, projectRoot, {
- allowShareableOkArtifact: isShareableOkArtifact,
- });
- tracedWriteFileSync(
- writeTarget,
- requireConflictResolutionContent(entry.file, content),
- 'utf-8',
- );
- break;
- }
-
- case 'delete':
- if (existsSync(absPath)) tracedUnlinkSync(absPath);
- break;
-
- default: {
- const exhaustive: never = strategy;
- throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);
- }
- }
- }
-}
diff --git a/packages/server/src/content/generated-artifact.ts b/packages/server/src/content/generated-artifact.ts
index 434a68376..9968d6525 100644
--- a/packages/server/src/content/generated-artifact.ts
+++ b/packages/server/src/content/generated-artifact.ts
@@ -39,9 +39,6 @@ export async function writeGeneratedArtifact(
const document = env.getDocument(docName);
if (document) {
- if (document.getMap('lifecycle').get('status') === 'conflict') {
- return 'blocked-conflict';
- }
if (document.getText('source').toString() === markdown) return 'unchanged';
document.transact(() => {
replaceRawBody(document, markdown);
diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.ts
index 7a1b82b5a..a85c68a79 100644
--- a/packages/server/src/external-change.ts
+++ b/packages/server/src/external-change.ts
@@ -24,7 +24,7 @@ import {
isMermaidDoc,
isSystemDoc,
} from './cc1-broadcast.ts';
-import { isDocInConflict } from './conflict-errors.ts';
+import { type ConflictAuthority, isDocInConflict } from './conflict-authority.ts';
import { isWithinContentDir, safeContentPath } from './content-path.ts';
import { recordContributor } from './contributor-tracker.ts';
import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
@@ -180,10 +180,12 @@ function clearStaleExternalWriteConflict(
durabilityState: DocumentDurabilityState,
document: Y.Doc | undefined,
docName: string,
+ conflicts?: Pick<ConflictAuthority, 'dissolveReconcile'>,
): void {
const retained = durabilityState.getStaleExternalWrite(docName)?.retainedContent;
if (retained !== undefined && retained !== durabilityState.getReconciledBase(docName)) return;
durabilityState.clearStaleExternalWrite(docName);
+ conflicts?.dissolveReconcile(docName, STALE_EXTERNAL_WRITE_REASON);
const lifecycleMap = document?.getMap('lifecycle');
if (lifecycleMap?.get('reason') !== STALE_EXTERNAL_WRITE_REASON) return;
lifecycleMap.delete('status');
@@ -196,40 +198,45 @@ export function refuseStaleExternalWrite(
document: Y.Doc | undefined,
docName: string,
diskContent: string,
+ conflicts?: Pick<ConflictAuthority, 'dissolveReconcile' | 'fileOf' | 'raise'>,
retainedContent?: string,
): boolean {
const currentBase = durabilityState.getReconciledBase(docName);
- const lifecycleMap = document?.getMap('lifecycle');
const pending = durabilityState.getStaleExternalWrite(docName);
+ const raise = (disk: string, retained: string | undefined): void => {
+ const conflict = durabilityState.recordStaleExternalWrite(docName, disk, retained);
+ if (conflicts) {
+ conflicts.raise({
+ kind: 'reconcile',
+ file: conflicts.fileOf(docName),
+ reason: STALE_EXTERNAL_WRITE_REASON,
+ detectedAt: conflict.detectedAt,
+ stages: {
+ base: currentBase ?? disk,
+ ours:
+ conflict.retainedContent ??
+ (document === undefined ? (currentBase ?? disk) : serializeYDocSource(document)),
+ theirs: conflict.diskContent,
+ },
+ });
+ }
+ };
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);
+ raise(diskContent, retainedContent ?? pending.retainedContent);
return true;
}
if (currentBase === diskContent) {
- clearStaleExternalWriteConflict(durabilityState, document, docName);
+ clearStaleExternalWriteConflict(durabilityState, document, docName, conflicts);
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);
+ raise(diskContent, retainedContent ?? pending?.retainedContent);
return true;
}
if (!durabilityState.isDisplacedVersion(docName, diskContent)) {
- clearStaleExternalWriteConflict(durabilityState, document, docName);
+ clearStaleExternalWriteConflict(durabilityState, document, docName, conflicts);
return false;
}
@@ -237,10 +244,7 @@ export function refuseStaleExternalWrite(
{ 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);
+ raise(diskContent, retainedContent);
return true;
}
@@ -270,8 +274,9 @@ export function reconcileDiskBeforeAgentWrite(
hocuspocus: Hocuspocus,
docName: string,
contentDir: string,
- resolveEmbed?: (basename: string, sourcePath: string) => string | null,
- bridgeLossReporter?: BridgeDeriveLossReporter,
+ resolveEmbed: ((basename: string, sourcePath: string) => string | null) | undefined,
+ bridgeLossReporter: BridgeDeriveLossReporter | undefined,
+ conflicts: Pick<ConflictAuthority, 'dissolveReconcile' | 'fileOf' | 'raise'>,
): ReconcileBeforeWriteResult {
if (
isSystemDoc(docName) ||
@@ -327,7 +332,7 @@ export function reconcileDiskBeforeAgentWrite(
const normalizedDisk = normalizeBridge(diskContent);
if (diskContent === base) {
- clearStaleExternalWriteConflict(durabilityState, document, docName);
+ clearStaleExternalWriteConflict(durabilityState, document, docName, conflicts);
return NOT_RECONCILED;
}
@@ -350,7 +355,7 @@ export function reconcileDiskBeforeAgentWrite(
if (!document) return NOT_RECONCILED;
- if (refuseStaleExternalWrite(durabilityState, document, docName, diskContent)) {
+ if (refuseStaleExternalWrite(durabilityState, document, docName, diskContent, conflicts)) {
return NOT_RECONCILED;
}
if (normalizedDisk === normalizeBridge(base)) return NOT_RECONCILED;
@@ -369,12 +374,17 @@ export function reconcileDiskBeforeAgentWrite(
case 'conflicts':
case 'refused': {
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set(
- 'reason',
- outcome.kind === 'refused' ? outcome.reason : 'reconcile-conflicts',
- );
+ conflicts.raise({
+ kind: 'reconcile',
+ file: conflicts.fileOf(docName),
+ reason:
+ outcome.kind === 'conflicts'
+ ? 'merged-with-markers'
+ : outcome.reason === 'too-large'
+ ? 'refused-too-large'
+ : 'refused-conflict-markers',
+ stages: { base, ours, theirs: diskContent },
+ });
return NOT_RECONCILED;
}
diff --git a/packages/server/src/git-pathspec-name-invariance.test.ts b/packages/server/src/git-pathspec-name-invariance.test.ts
index 6a7d52580..8ccce6288 100644
--- a/packages/server/src/git-pathspec-name-invariance.test.ts
+++ b/packages/server/src/git-pathspec-name-invariance.test.ts
@@ -7,7 +7,7 @@ import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { renameTrackedPathInGit } from './api-extension.ts';
-import { ConflictStore } from './conflict-storage.ts';
+import { ConflictAuthority } from './conflict-authority.ts';
import { readProjectGitLog } from './content/project-log.ts';
import { readShadowLog } from './content/shadow-log.ts';
import { TRACKED_MCP_CONFIG_TARGETS } from './mcp-config-reconciler.ts';
@@ -26,6 +26,22 @@ import { restoreSkillVersion } from './skill-restore.ts';
import { SyncEngine } from './sync-engine.ts';
import { getDocumentHistory } from './timeline-query.ts';
+function conflictAuthorityFor(projectDir: string): ConflictAuthority {
+ return new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ branch: 'main',
+ io: {
+ gitRaw: (args) => simpleGit(projectDir).raw(args),
+ writeProjectFileUntracked: (absPath, bytes) => writeFileSync(absPath, bytes, 'utf-8'),
+ unlinkProjectFile: (absPath) => rmSync(absPath, { force: true }),
+ applyResolvedContent: async (_docName, absPath, bytes) => {
+ writeFileSync(absPath, bytes, 'utf-8');
+ },
+ },
+ });
+}
+
const MAGIC_PREFIX_DOC = ':colon.md';
const EXCLUDE_MAGIC_DOC = ':!bang.md';
const PLAIN_DOC = 'plain.md';
@@ -101,6 +117,7 @@ async function initProjectWithBareRemote(): Promise<string> {
function makePushEngine(): SyncEngine {
return new SyncEngine({
projectDir,
+ conflicts: conflictAuthorityFor(projectDir),
contentDir: projectDir,
contentFilter: stubContentFilter,
syncEnabled: true,
@@ -241,13 +258,13 @@ describe('pathspec name invariance — conflict resolution (site 8)', () => {
} catch {}
expect(git(projectDir, ['ls-files', '-u'])).not.toBe('');
- const store = new ConflictStore(projectDir, 'main');
- store.addConflict({ file: MAGIC_PREFIX_DOC, detectedAt: new Date().toISOString() });
+ const conflicts = conflictAuthorityFor(projectDir);
+ conflicts.raise({ kind: 'merge-native', file: MAGIC_PREFIX_DOC });
- await expect(store.resolveConflict(MAGIC_PREFIX_DOC, 'theirs')).resolves.toBeUndefined();
+ await expect(conflicts.resolve(MAGIC_PREFIX_DOC, 'theirs')).resolves.toBeUndefined();
expect(git(projectDir, ['ls-files', '-u'])).toBe('');
- expect(store.count()).toBe(0);
+ expect(conflicts.count()).toBe(0);
});
});
@@ -298,6 +315,7 @@ describe('pathspec name invariance — commitBlockingPaths (site 3)', () => {
await setupColonNamedOverlap();
const engine = new SyncEngine({
projectDir,
+ conflicts: conflictAuthorityFor(projectDir),
contentDir: projectDir,
contentFilter: markdownOnlyFilter,
mode: 'full',
@@ -444,6 +462,7 @@ describe('pathspec name invariance — non-content merge auto-resolve (site 5)',
const engine = new SyncEngine({
projectDir,
+ conflicts: conflictAuthorityFor(projectDir),
contentDir: projectDir,
contentFilter: stubContentFilter,
syncEnabled: true,
@@ -507,6 +526,7 @@ describe('pathspec name invariance — pull-only overlay restore (site 6)', () =
const engine = new SyncEngine({
projectDir: cloneDir,
+ conflicts: conflictAuthorityFor(projectDir),
contentDir: cloneDir,
contentFilter: stubContentFilter,
syncEnabled: true,
diff --git a/packages/server/src/github-account-agreement.test.ts b/packages/server/src/github-account-agreement.test.ts
index 3cf4e2ff3..4f45c3bf2 100644
--- a/packages/server/src/github-account-agreement.test.ts
+++ b/packages/server/src/github-account-agreement.test.ts
@@ -4,6 +4,7 @@ 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 { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import type { GitHandle } from './git-handle.ts';
import {
type CheckPushPermissionOptions,
@@ -118,6 +119,7 @@ async function runAgreementScenario(opts: {
};
const engine = new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir, contentDir),
projectDir,
contentDir,
contentFilter: stubContentFilter,
diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.ts
index d14e32700..5ba83829b 100644
--- a/packages/server/src/http/agent-write-routes.ts
+++ b/packages/server/src/http/agent-write-routes.ts
@@ -55,17 +55,14 @@ import {
import { composeAndWriteRawBody, type PrecomputedParse, replaceRawBody } from '../bridge-intake.ts';
import type { BridgeDeriveLossReporter } from '../bridge-loss-detector.ts';
import { isConfigDoc, isSystemDoc, SYSTEM_DOC_NAME } from '../cc1-broadcast.ts';
-import { DocInConflictError, isDocInConflict, respondDocInConflict } from '../conflict-errors.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
+import { DocInConflictError, respondDocInConflict } from '../conflict-errors.ts';
import {
evaluateContentDivergence,
toContentDivergenceWarning,
} from '../content-divergence-gate.ts';
import { recordContributor } from '../contributor-tracker.ts';
-import {
- canonicalDocName,
- docNameToRelativePath,
- registerDocExtension,
-} from '../doc-extensions.ts';
+import { canonicalDocName, registerDocExtension, stripDocExtension } from '../doc-extensions.ts';
import type { DocumentDurabilityState, StoreFailure } from '../document-durability-state.ts';
import {
type ReconcileBeforeWriteResult,
@@ -134,6 +131,7 @@ function agentPatchFmTouchCounter(): ReturnType<ReturnType<typeof getMeter>['cre
}
export interface AgentWriteRouteDeps {
+ conflicts: ConflictAuthority;
getLinkAdvisoryPolicy: () => LinkAdvisoryPolicy;
respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;
requireNonEmptyDocName: (
@@ -226,6 +224,7 @@ export interface AgentWriteRouteDeps {
export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup {
const {
+ conflicts,
getLinkAdvisoryPolicy,
respondStaleExternalWrite,
requireNonEmptyDocName,
@@ -330,6 +329,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
contentDir,
options.resolveEmbed,
getBridgeLossReporter?.(),
+ conflicts,
);
const writeMdEmbedResolver = options.resolveEmbed
? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }
@@ -489,7 +489,12 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
);
} catch (e) {
if (e instanceof DocInConflictError) {
- respondDocInConflict(res, e, 'agent-write-md');
+ respondDocInConflict(
+ res,
+ e,
+ 'agent-write-md',
+ conflicts.findByDocName(stripDocExtension(e.file)),
+ );
return;
}
if (e instanceof FrontmatterMalformedError) {
@@ -553,6 +558,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
contentDir,
options.resolveEmbed,
getBridgeLossReporter?.(),
+ conflicts,
);
const fmPatchPrecomputed = await prepareFrontmatterPatchParse(session.dc.document, patch);
const timestamp = new Date().toISOString();
@@ -800,6 +806,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
contentDir,
options.resolveEmbed,
getBridgeLossReporter?.(),
+ conflicts,
);
const patchEmbedResolver = options.resolveEmbed
? { resolveEmbed: options.resolveEmbed, sourcePath: docName }
@@ -1060,7 +1067,12 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
);
} catch (e) {
if (e instanceof DocInConflictError) {
- respondDocInConflict(res, e, 'agent-patch');
+ respondDocInConflict(
+ res,
+ e,
+ 'agent-patch',
+ conflicts.findByDocName(stripDocExtension(e.file)),
+ );
return;
}
if (e instanceof FrontmatterMalformedError) {
@@ -1192,7 +1204,12 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
);
} catch (e) {
if (e instanceof DocInConflictError) {
- respondDocInConflict(res, e, 'agent-undo');
+ respondDocInConflict(
+ res,
+ e,
+ 'agent-undo',
+ conflicts.findByDocName(stripDocExtension(e.file)),
+ );
return;
}
log.error({ err: e, requestId: getRequestId(_req) }, '[agent-undo] handler failed');
@@ -1438,12 +1455,13 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
return;
}
// The check fires post-identity (precedent #24) and pre-mutation.
- const targetDoc = hocuspocus.documents.get(body.docName);
- if (targetDoc && isDocInConflict(targetDoc)) {
+ const rollbackConflict = conflicts.findByDocName(body.docName);
+ if (rollbackConflict !== undefined) {
respondDocInConflict(
res,
- new DocInConflictError({ file: docNameToRelativePath(body.docName) }),
+ new DocInConflictError({ file: rollbackConflict.file }),
'rollback',
+ rollbackConflict,
);
return;
}
diff --git a/packages/server/src/http/document-routes.test.ts b/packages/server/src/http/document-routes.test.ts
new file mode 100644
index 000000000..05c679dab
--- /dev/null
+++ b/packages/server/src/http/document-routes.test.ts
@@ -0,0 +1,117 @@
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Hocuspocus } from '@hocuspocus/server';
+import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { makeCaptureRes, makeSyntheticReq } from '../composition-rig.test-helper.ts';
+import { createTestConflictAuthority } from '../conflict-authority.test-helper.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
+import { loggerFactory } from '../logger.ts';
+import { createDocumentRoutes } from './document-routes.ts';
+
+const DOC_NAME = 'notes/topic';
+const DOC_FILE = 'notes/topic.md';
+
+let projectDir = '';
+
+beforeEach(() => {
+ projectDir = mkdtempSync(join(tmpdir(), 'document-routes-test-'));
+ mkdirSync(join(projectDir, '.ok', LOCAL_DIR), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(projectDir, { recursive: true, force: true });
+});
+
+function buildGroup(conflicts: ConflictAuthority, hocuspocus: Hocuspocus) {
+ return createDocumentRoutes({
+ hocuspocus,
+ conflicts,
+ contentDir: projectDir,
+ isSafeDocName: () => true,
+ resolveAlias: (docName) => docName,
+ resolveContentEntryPath: (dir, _kind, path) => join(dir, `${path}.md`),
+ resolveDocPath: () => null,
+ extractHeadings: () => [],
+ getFileIndex: () => new Map(),
+ log: loggerFactory.getLogger('test'),
+ ready: undefined,
+ contentFilter: undefined,
+ safeSubdir: (baseDir) => baseDir,
+ getShowAllMaxEntries: () => 0,
+ streamShowAllEntries: async function* () {
+ yield* [];
+ return { truncated: false };
+ },
+ walkContentDirForShowAll: async () => ({ truncated: false }),
+ synthesizeShowAllAssetExt: (name) => name,
+ getAllFilesIndex: () => new Map(),
+ getFolderIndex: undefined,
+ getFolderAliasIndex: undefined,
+ onReferencedAssetsCacheInvalidator: undefined,
+ });
+}
+
+async function readDocument(
+ conflicts: ConflictAuthority,
+ hocuspocus: Hocuspocus,
+): Promise<{ status: number; body: Record<string, unknown> }> {
+ const resolved = buildGroup(conflicts, hocuspocus).table.resolve('/api/document');
+ if (!resolved?.dispatch) throw new Error('no dispatch for /api/document');
+ const req = makeSyntheticReq({ url: `/api/document?docName=${encodeURIComponent(DOC_NAME)}` });
+ const { res, captured } = makeCaptureRes();
+ await resolved.dispatch(req, res);
+ return { status: captured.status, body: JSON.parse(captured.body) as Record<string, unknown> };
+}
+
+describe('/api/document lifecycle reflects the conflict ledger', () => {
+ test('a doc with a reconcile ledger entry reports lifecycle conflict with its reason', async () => {
+ const hocuspocus = new Hocuspocus({ quiet: true });
+ const conflicts = createTestConflictAuthority(projectDir);
+ conflicts.raise({
+ kind: 'reconcile',
+ file: DOC_FILE,
+ reason: 'disk-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+
+ const dc = await hocuspocus.openDirectConnection(DOC_NAME);
+ try {
+ const { status, body } = await readDocument(conflicts, hocuspocus);
+ expect(status).toBe(200);
+ expect(body.lifecycle).toEqual({ status: 'conflict', reason: 'disk-markers' });
+ } finally {
+ await dc.disconnect();
+ }
+ });
+
+ test('a doc with a merge-native ledger entry reports the merge-conflict reason', async () => {
+ const hocuspocus = new Hocuspocus({ quiet: true });
+ const conflicts = createTestConflictAuthority(projectDir);
+ conflicts.raise({ kind: 'merge-native', file: DOC_FILE });
+
+ const dc = await hocuspocus.openDirectConnection(DOC_NAME);
+ try {
+ const { status, body } = await readDocument(conflicts, hocuspocus);
+ expect(status).toBe(200);
+ expect(body.lifecycle).toEqual({ status: 'conflict', reason: 'merge-conflict' });
+ } finally {
+ await dc.disconnect();
+ }
+ });
+
+ test('a doc with no ledger entry reports a null lifecycle', async () => {
+ const hocuspocus = new Hocuspocus({ quiet: true });
+ const conflicts = createTestConflictAuthority(projectDir);
+
+ const dc = await hocuspocus.openDirectConnection(DOC_NAME);
+ try {
+ const { status, body } = await readDocument(conflicts, hocuspocus);
+ expect(status).toBe(200);
+ expect(body.lifecycle).toBeNull();
+ } finally {
+ await dc.disconnect();
+ }
+ });
+});
diff --git a/packages/server/src/http/document-routes.ts b/packages/server/src/http/document-routes.ts
index 09af3520e..08416f085 100644
--- a/packages/server/src/http/document-routes.ts
+++ b/packages/server/src/http/document-routes.ts
@@ -14,6 +14,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { collectReferencedAssets } from '../asset-references.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
import type { ContentFilter } from '../content-filter.ts';
import { canonicalDocName, getDocExtension } from '../doc-extensions.ts';
import type { FileIndexEntry, FolderIndexEntry } from '../file-watcher.ts';
@@ -43,6 +44,7 @@ interface InflightShowAllWalk {
export interface DocumentRouteDeps {
hocuspocus: Hocuspocus;
+ conflicts: ConflictAuthority;
contentDir: string;
isSafeDocName: (docName: string) => boolean;
resolveAlias: (docName: string) => string;
@@ -90,6 +92,7 @@ export interface DocumentRoutes {
export function createDocumentRoutes(deps: DocumentRouteDeps): DocumentRoutes {
const {
hocuspocus,
+ conflicts,
contentDir,
isSafeDocName,
resolveAlias,
@@ -134,11 +137,10 @@ export function createDocumentRoutes(deps: DocumentRouteDeps): DocumentRoutes {
onReferencedAssetsCacheInvalidator?.(invalidateReferencedAssetsCache);
function readLifecycleStatus(document: Document): LifecycleStatus | null {
- const lifecycleMap = document.getMap('lifecycle');
- const status = lifecycleMap.get('status');
- if (typeof status !== 'string' || status.length === 0) return null;
- const reason = lifecycleMap.get('reason');
- return { status, reason: typeof reason === 'string' ? reason : '' };
+ const view = conflicts.lifecycleOf(document, document.name);
+ if (view === null) return null;
+ if (view.status === 'conflict') return { status: view.status, reason: view.reason };
+ return { status: view.status, reason: '' };
}
const handleDocumentRead = withValidation(
diff --git a/packages/server/src/http/file-ops-routes.test.ts b/packages/server/src/http/file-ops-routes.test.ts
index 3a4cca279..4022d0f34 100644
--- a/packages/server/src/http/file-ops-routes.test.ts
+++ b/packages/server/src/http/file-ops-routes.test.ts
@@ -1,8 +1,8 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
-import type { Hocuspocus } from '@hocuspocus/server';
import { describe, expect, test } from 'vitest';
import { SymlinkEscapeError } from '../apply-managed-rename.ts';
+import { createTestConflictAuthorityInTmpDir } from '../conflict-authority.test-helper.ts';
import { DocInConflictError } from '../conflict-errors.ts';
import { ContentRootUnavailableError } from '../fs-safety.ts';
import { loggerFactory } from '../logger.ts';
@@ -20,9 +20,8 @@ function buildGroup(overrides: Partial<Deps> = {}) {
getPrincipal: undefined,
contentFilter: undefined,
signalChannel: undefined,
- getSyncEngine: undefined,
+ conflicts: createTestConflictAuthorityInTmpDir('file-ops-routes-authority-'),
flushContributors: undefined,
- hocuspocus: {} as Hocuspocus,
fileOpsService: {} as FileOpsService,
assetService: {} as AssetService,
extractAgentIdentity: () => {
@@ -100,7 +99,6 @@ describe('createFileOpsRoutes table', () => {
describe('rename-path conflict envelope', () => {
test('maps a DocInConflictError from the rewrite spine to a 409 doc-in-conflict', async () => {
const group = buildGroup({
- hocuspocus: { documents: new Map() } as unknown as Hocuspocus,
docNameForFileOperationPath: () => 'a',
isValidRelativeContentPath: () => true,
_performManagedRenameForDocs: () =>
diff --git a/packages/server/src/http/file-ops-routes.ts b/packages/server/src/http/file-ops-routes.ts
index b07107f99..fef708630 100644
--- a/packages/server/src/http/file-ops-routes.ts
+++ b/packages/server/src/http/file-ops-routes.ts
@@ -9,7 +9,6 @@ import {
import type { IncomingMessage, ServerResponse } from 'node:http';
import { dirname, extname, resolve, sep } from 'node:path';
import { pipeline } from 'node:stream/promises';
-import type { Hocuspocus } from '@hocuspocus/server';
import {
CreateFolderRequestSchema,
CreateFolderSuccessSchema,
@@ -35,14 +34,14 @@ import { formatRenameSubject } from '@inkeep/open-knowledge-core/shadow-repo-lay
import type { SummaryResponse } from '../agent-write-summary.ts';
import { ManagedRenameCollisionError } from '../apply-managed-rename.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
-import { DocInConflictError, isDocInConflict, respondDocInConflict } from '../conflict-errors.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
+import { DocInConflictError, respondDocInConflict } from '../conflict-errors.ts';
import { isReservedProjectStatePath } from '../content/managed-doc-enum.ts';
import { applySubstitution, todayIsoUtc } from '../content/substitution.ts';
import { resolveTemplatesAvailable } from '../content/templates-resolver.ts';
import type { ContentFilter } from '../content-filter.ts';
import { recordContributor } from '../contributor-tracker.ts';
import {
- docNameToRelativePath,
getDocExtension,
isSupportedAssetFile,
isSupportedDocFile,
@@ -57,7 +56,6 @@ import type { PinoLogger } from '../logger.ts';
import { createMultipartParser, type MultipartParser } from '../multipart.ts';
import type { AssetService } from '../services/assets.ts';
import { DuplicateNameExhaustedError, type FileOpsService } from '../services/file-ops.ts';
-import type { SyncEngine } from '../sync-engine.ts';
import { type getMeter, withSpan } from '../telemetry.ts';
import {
classifyUploadErrno,
@@ -267,8 +265,7 @@ export interface FileOpsRouteDeps {
getPrincipal: (() => Principal | null) | undefined;
contentFilter: ContentFilter | undefined;
signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;
- hocuspocus: Hocuspocus;
- getSyncEngine: (() => SyncEngine | null) | undefined;
+ conflicts: ConflictAuthority;
flushContributors: (() => Promise<void>) | undefined;
fileOpsService: FileOpsService;
assetService: AssetService;
@@ -351,8 +348,7 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
getPrincipal,
contentFilter,
signalChannel,
- hocuspocus,
- getSyncEngine,
+ conflicts,
flushContributors,
fileOpsService,
assetService,
@@ -803,6 +799,7 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
res,
new DocInConflictError({ file: outcome.file }),
'duplicate-path',
+ conflicts.findByFile(outcome.file),
);
return;
case 'destination-excluded':
@@ -990,7 +987,7 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
: await _performAssetRename(fromPath, toPath);
} catch (err) {
if (err instanceof DocInConflictError) {
- respondDocInConflict(res, err, 'rename-path');
+ respondDocInConflict(res, err, 'rename-path', conflicts.findByFile(err.file));
return;
}
const { status, type, error } = toManagedRenamePublicError(err);
@@ -1068,18 +1065,15 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
: listManagedDocNamesUnderFolderFromDisk(
resolveContentEntryPath(contentDir, 'folder', fromPath),
);
- const renameEngine = getSyncEngine?.();
- const renameTrackedFiles = new Set(
- renameEngine ? renameEngine.getConflicts().map((c) => c.file) : [],
- );
- for (const affected of renameAffectedDocNames) {
- const affectedDocName = affected;
- const doc = hocuspocus.documents.get(affectedDocName);
- const filePath = docNameToRelativePath(affectedDocName);
- const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);
- const conflictedByStore = renameTrackedFiles.has(filePath);
- if (conflictedByLifecycle || conflictedByStore) {
- respondDocInConflict(res, new DocInConflictError({ file: filePath }), 'rename-path');
+ for (const affectedDocName of renameAffectedDocNames) {
+ const entry = conflicts.findByDocName(affectedDocName);
+ if (entry !== undefined) {
+ respondDocInConflict(
+ res,
+ new DocInConflictError({ file: entry.file }),
+ 'rename-path',
+ entry,
+ );
return;
}
}
@@ -1130,7 +1124,7 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
);
} catch (err) {
if (err instanceof DocInConflictError) {
- respondDocInConflict(res, err, 'rename-path');
+ respondDocInConflict(res, err, 'rename-path', conflicts.findByFile(err.file));
return;
}
if (err instanceof ManagedRenameCollisionError) {
@@ -1288,6 +1282,7 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
res,
new DocInConflictError({ file: outcome.file }),
'delete-path',
+ conflicts.findByFile(outcome.file),
);
}
return;
diff --git a/packages/server/src/http/folder-template-routes.ts b/packages/server/src/http/folder-template-routes.ts
index 7e5736507..ba4a431d8 100644
--- a/packages/server/src/http/folder-template-routes.ts
+++ b/packages/server/src/http/folder-template-routes.ts
@@ -30,7 +30,8 @@ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import type { AgentSessionManager } from '../agent-sessions.ts';
import { composeAndWriteRawBody } from '../bridge-intake.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
-import { DocInConflictError, isDocInConflict, respondDocInConflict } from '../conflict-errors.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
+import { DocInConflictError, respondDocInConflict } from '../conflict-errors.ts';
import { enrichDirectory } from '../content/enrichment.ts';
import {
applyFolderFrontmatterPatch,
@@ -51,7 +52,6 @@ import { tracedUnlinkSync } from '../fs-traced.ts';
import type { PinoLogger } from '../logger.ts';
import { extractPageTitle } from '../page-identity.ts';
import type { RecentlyRemovedDocs } from '../recently-removed-docs.ts';
-import type { SyncEngine } from '../sync-engine.ts';
import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
import { errorResponse } from './error-response.ts';
import { methodRouter } from './method-router.ts';
@@ -67,7 +67,7 @@ export interface FolderTemplateRouteDeps {
sessionManager: AgentSessionManager;
getPrincipal: (() => Principal | null) | undefined;
signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;
- getSyncEngine: (() => SyncEngine | null) | undefined;
+ conflicts: ConflictAuthority;
recentlyRemovedDocs: RecentlyRemovedDocs | undefined;
isSafeDocName: (docName: string) => boolean;
resolveAlias: (docName: string) => string;
@@ -144,7 +144,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo
sessionManager,
getPrincipal,
signalChannel,
- getSyncEngine,
+ conflicts,
recentlyRemovedDocs,
isSafeDocName,
resolveAlias,
@@ -466,9 +466,9 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo
handler: 'template-put' | 'template-delete' | 'template-move' | 'template-import',
res: ServerResponse,
): boolean {
- const doc = hocuspocus.documents.get(templateDocName);
- if (doc && isDocInConflict(doc)) {
- respondDocInConflict(res, new DocInConflictError({ file: `${templateDocName}.md` }), handler);
+ const entry = conflicts.findByDocName(templateDocName);
+ if (entry !== undefined) {
+ respondDocInConflict(res, new DocInConflictError({ file: entry.file }), handler, entry);
return true;
}
return false;
@@ -1131,17 +1131,13 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo
const existing = hocuspocus.documents.get(sourceDocName);
if (body.deleteSource) {
- const deleteEngine = getSyncEngine?.();
- const deleteTrackedFiles = new Set(
- deleteEngine ? deleteEngine.getConflicts().map((c) => c.file) : [],
- );
- const conflictedByLifecycle = existing !== undefined && isDocInConflict(existing);
- const conflictedByStore = deleteTrackedFiles.has(sourcePath);
- if (conflictedByLifecycle || conflictedByStore) {
+ const sourceConflict = conflicts.findByDocName(sourceDocName);
+ if (sourceConflict !== undefined) {
respondDocInConflict(
res,
- new DocInConflictError({ file: sourcePath }),
+ new DocInConflictError({ file: sourceConflict.file }),
'template-import',
+ sourceConflict,
);
return;
}
diff --git a/packages/server/src/http/lint-write-routes.test.ts b/packages/server/src/http/lint-write-routes.test.ts
index 087516e2a..d4b21ec0e 100644
--- a/packages/server/src/http/lint-write-routes.test.ts
+++ b/packages/server/src/http/lint-write-routes.test.ts
@@ -5,9 +5,11 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { AgentSessionManager } from '../agent-sessions.ts';
import { makeCaptureRes } from '../composition-rig.test-helper.ts';
+import { createTestConflictAuthority } from '../conflict-authority.test-helper.ts';
+import { DocInConflictError } from '../conflict-errors.ts';
import { loggerFactory } from '../logger.ts';
import { createLintWriteRoutes } from './lint-write-routes.ts';
@@ -28,6 +30,7 @@ function buildGroup(overrides: Partial<Deps> = {}) {
roots.push(contentDir);
const hocuspocus = new Hocuspocus({ quiet: true });
const deps = {
+ conflicts: createTestConflictAuthority(contentDir),
contentDir,
projectDir: undefined,
signalLintConfigChanged: notDispatched,
@@ -149,7 +152,39 @@ describe('createLintWriteRoutes config handlers', () => {
});
});
-describe('createLintWriteRoutes lint-fix capacity response', () => {
+describe('createLintWriteRoutes lint-fix refusal responses', () => {
+ test('returns authority metadata and allowed resolutions for a conflict', async () => {
+ const { contentDir, group, sessionManager } = buildGroup({
+ requireNonEmptyDocName: (docName) => docName ?? null,
+ resolveDocFilePath: () => 'note.md',
+ conflicts: {
+ findByDocName: () => ({
+ kind: 'reconcile',
+ file: 'note.md',
+ detectedAt: '2026-09-14T00:00:00.000Z',
+ reason: 'disk-markers',
+ stages: { base: 'base', ours: 'ours', theirs: 'theirs' },
+ }),
+ },
+ });
+ const getSession = vi
+ .spyOn(sessionManager, 'getSession')
+ .mockRejectedValue(new DocInConflictError({ file: 'note.md' }));
+ try {
+ writeFileSync(join(contentDir, 'note.md'), '# Heading\n');
+ const response = await dispatch(group, '/api/lint/fix', { docName: 'note' });
+ expect(response.status).toBe(409);
+ expect(JSON.parse(response.body)).toMatchObject({
+ file: 'note.md',
+ conflict: { kind: 'reconcile', reason: 'disk-markers' },
+ resolutionOptions: ['mine', 'content', 'delete'],
+ });
+ } finally {
+ getSession.mockRestore();
+ await sessionManager.closeAll();
+ }
+ });
+
test('returns the retryable problem when the session limit is full', async () => {
const hocuspocus = new Hocuspocus({ quiet: true });
const sessionManager = new AgentSessionManager(hocuspocus, {
diff --git a/packages/server/src/http/lint-write-routes.ts b/packages/server/src/http/lint-write-routes.ts
index 2a8340c8b..e39035635 100644
--- a/packages/server/src/http/lint-write-routes.ts
+++ b/packages/server/src/http/lint-write-routes.ts
@@ -26,8 +26,10 @@ import {
} from '../agent-sessions.ts';
import type { NormalizedSummary, SummaryResponse } from '../agent-write-summary.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
import { DocInConflictError, respondDocInConflict } from '../conflict-errors.ts';
import { recordContributor } from '../contributor-tracker.ts';
+import { stripDocExtension } from '../doc-extensions.ts';
import type { StoreFailure } from '../document-durability-state.ts';
import { extractActorIdentity } from '../extract-actor-identity.ts';
import {
@@ -57,6 +59,7 @@ import { withValidation } from './request-validation.ts';
import { successResponse } from './success-response.ts';
export interface LintWriteRouteDeps {
+ conflicts: Pick<ConflictAuthority, 'findByDocName'>;
contentDir: string;
projectDir: string | undefined;
signalLintConfigChanged: () => void;
@@ -108,6 +111,7 @@ export interface LintWriteRouteDeps {
export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {
const {
+ conflicts,
contentDir,
projectDir,
signalLintConfigChanged,
@@ -477,7 +481,12 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {
return;
}
if (e instanceof DocInConflictError) {
- respondDocInConflict(res, e, 'lint-fix');
+ respondDocInConflict(
+ res,
+ e,
+ 'lint-fix',
+ conflicts.findByDocName(stripDocExtension(e.file)),
+ );
return;
}
if (e instanceof FrontmatterMalformedError) {
diff --git a/packages/server/src/http/sync-routes.test.ts b/packages/server/src/http/sync-routes.test.ts
index e41433f09..f526b0603 100644
--- a/packages/server/src/http/sync-routes.test.ts
+++ b/packages/server/src/http/sync-routes.test.ts
@@ -1,26 +1,37 @@
-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import type { IncomingMessage } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import simpleGit from 'simple-git';
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 {
+ createTestConflictAuthority,
+ createTestConflictAuthorityInTmpDir,
+} from '../conflict-authority.test-helper.ts';
import { loggerFactory } from '../logger.ts';
-import type { SyncEngine } from '../sync-engine.ts';
import { createSyncRoutes } from './sync-routes.ts';
+const makeAuthority = createTestConflictAuthority;
+
+function emptyAuthority(): ConflictAuthority {
+ return createTestConflictAuthorityInTmpDir('sync-routes-authority-');
+}
+
function buildGroup() {
return createSyncRoutes({
projectDir: undefined,
contentDir: '/tmp/ok-sync-routes-test',
getPrincipal: undefined,
hocuspocus: new Hocuspocus({ quiet: true }),
- durabilityState: new DocumentDurabilityState(),
log: loggerFactory.getLogger('test'),
checkLocalOpSecurity: () => true,
getSyncEngine: undefined,
+ conflicts: emptyAuthority(),
serializeDoc: undefined,
+ setBatchInProgress: undefined,
});
}
@@ -53,144 +64,329 @@ 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',
+describe('conflict-content working-tree ours-read errno discrimination', () => {
+ function buildConflictGroup(projectDir: string) {
+ const conflicts = makeAuthority(projectDir);
+ conflicts.raise({ kind: 'working-tree', file: 'a.md', theirsSha: '' });
+ return createSyncRoutes({
+ projectDir,
contentDir: '/tmp/ok-sync-routes-test',
getPrincipal: undefined,
hocuspocus: new Hocuspocus({ quiet: true }),
- durabilityState,
log: loggerFactory.getLogger('test'),
checkLocalOpSecurity: () => true,
- getSyncEngine: () => engine,
+ getSyncEngine: undefined,
+ conflicts,
serializeDoc: undefined,
+ setBatchInProgress: 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();
+ }
+ async function dispatchConflictContent(
+ projectDir: string,
+ ): Promise<{ status: number; body: string }> {
+ const resolved = buildConflictGroup(projectDir).table.resolve('/api/sync/conflict-content');
+ if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/conflict-content');
+ const req = makeSyntheticReq({ url: '/api/sync/conflict-content?file=a.md' });
+ const { res, captured } = makeCaptureRes();
await resolved.dispatch(req, res);
+ return captured;
+ }
- 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('a genuinely absent working-tree file is the delete overlay (200 delete-modify)', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-enoent-'));
+ try {
+ const captured = await dispatchConflictContent(projectDir);
+ expect(captured.status).toBe(200);
+ expect((JSON.parse(captured.body) as { kind?: string }).kind).toBe('delete-modify');
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
});
- 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;
+ test('a non-ENOENT ours-read failure is a 500, never a silent delete-modify', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-eisdir-'));
+ try {
+ mkdirSync(join(projectDir, 'a.md'));
+ const captured = await dispatchConflictContent(projectDir);
+ expect(captured.status).toBe(500);
+ expect((JSON.parse(captured.body) as { type?: string }).type).toBe(
+ 'urn:ok:error:internal-server-error',
+ );
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+});
+
+const MARKERED = [
+ '# Pricing',
+ '',
+ '<<<<<<< ours',
+ 'ours side',
+ '=======',
+ 'theirs side',
+ '>>>>>>> theirs',
+ '',
+].join('\n');
+
+describe('resolve-conflict 422 discriminates strategy refusal from marker content', () => {
+ function makePostReq(body: unknown): IncomingMessage {
+ const req = Readable.from([
+ Buffer.from(JSON.stringify(body), 'utf-8'),
+ ]) as unknown as IncomingMessage;
+ req.method = 'POST';
+ req.url = '/api/sync/resolve-conflict';
+ req.headers = { host: '127.0.0.1', 'content-type': 'application/json' };
+ req.socket = { remoteAddress: '127.0.0.1' } as unknown as IncomingMessage['socket'];
+ return req;
+ }
+
+ async function dispatchResolve(
+ projectDir: string,
+ body: Record<string, unknown>,
+ ): Promise<{ status: number; parsed: Record<string, unknown> }> {
+ const conflicts = makeAuthority(projectDir);
+ conflicts.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: 'O', theirs: MARKERED },
+ });
const group = createSyncRoutes({
- projectDir: '/tmp/ok-sync-routes-test',
- contentDir: '/tmp/ok-sync-routes-test',
+ projectDir,
+ contentDir: projectDir,
getPrincipal: undefined,
hocuspocus: new Hocuspocus({ quiet: true }),
- durabilityState: new DocumentDurabilityState(),
log: loggerFactory.getLogger('test'),
checkLocalOpSecurity: () => true,
- getSyncEngine: () => engine,
+ getSyncEngine: undefined,
+ conflicts,
serializeDoc: undefined,
+ setBatchInProgress: undefined,
});
- const resolved = group.table.resolve('/api/sync/conflicts');
- if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/conflicts');
+ const resolved = group.table.resolve('/api/sync/resolve-conflict');
+ if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/resolve-conflict');
const { res, captured } = makeCaptureRes();
+ await resolved.dispatch(makePostReq(body), res);
+ return { status: captured.status, parsed: JSON.parse(captured.body) };
+ }
- 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',
- },
- ],
- });
+ test('a strategy the conflict never offered is refused as a strategy problem', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-resolve-strategy-'));
+ try {
+ const { status, parsed } = await dispatchResolve(projectDir, {
+ file: 'a.md',
+ strategy: 'theirs',
+ });
+
+ expect(status).toBe(422);
+ expect(parsed.refusal).toBe('strategy-not-offered');
+ expect(parsed.resolutionOptions).toEqual(['mine', 'content', 'delete']);
+ expect(parsed.title).toBe('Strategy not offered for this conflict.');
+ expect(parsed.detail).toContain('"theirs"');
+ expect(parsed.detail).not.toContain('still contains');
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('submitted content that still carries markers is refused as a content problem', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-resolve-markers-'));
+ try {
+ const { status, parsed } = await dispatchResolve(projectDir, {
+ file: 'a.md',
+ strategy: 'content',
+ content: MARKERED,
+ });
+
+ expect(status).toBe(422);
+ expect(parsed.refusal).toBe('markers-in-content');
+ expect(parsed.resolutionOptions).toEqual(['mine', 'content', 'delete']);
+ expect(parsed.title).toBe('Resolution still contains conflict markers.');
+ expect(parsed.detail).toContain('still contains');
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
});
});
-describe('conflict-content working-tree ours-read errno discrimination', () => {
- function buildConflictGroup(projectDir: string) {
- const engine = {
- getConflicts: () => [
- { file: 'a.md', variant: 'working-tree', theirsSha: undefined, baseSha: undefined },
- ],
- } as unknown as SyncEngine;
- return createSyncRoutes({
+describe('resolve-conflict brackets the resolve with the batch flag the server wires in', () => {
+ function makePostReq(body: unknown): IncomingMessage {
+ const req = Readable.from([
+ Buffer.from(JSON.stringify(body), 'utf-8'),
+ ]) as unknown as IncomingMessage;
+ req.method = 'POST';
+ req.url = '/api/sync/resolve-conflict';
+ req.headers = { host: '127.0.0.1', 'content-type': 'application/json' };
+ req.socket = { remoteAddress: '127.0.0.1' } as unknown as IncomingMessage['socket'];
+ return req;
+ }
+
+ async function dispatchResolve(
+ projectDir: string,
+ body: Record<string, unknown>,
+ trace: string[],
+ ): Promise<number> {
+ const conflicts = makeAuthority(projectDir);
+ conflicts.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+ const group = createSyncRoutes({
projectDir,
- contentDir: '/tmp/ok-sync-routes-test',
+ contentDir: projectDir,
getPrincipal: undefined,
hocuspocus: new Hocuspocus({ quiet: true }),
- durabilityState: new DocumentDurabilityState(),
log: loggerFactory.getLogger('test'),
checkLocalOpSecurity: () => true,
- getSyncEngine: () => engine,
+ getSyncEngine: undefined,
+ conflicts,
serializeDoc: undefined,
+ setBatchInProgress: (value) => {
+ trace.push(value ? 'batch-raised' : 'batch-lowered');
+ },
});
+ const resolved = group.table.resolve('/api/sync/resolve-conflict');
+ if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/resolve-conflict');
+ const { res, captured } = makeCaptureRes();
+ await resolved.dispatch(makePostReq(body), res);
+ return captured.status;
}
- async function dispatchConflictContent(
+ test('a successful resolve raises then lowers the batch flag', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-resolve-drain-'));
+ try {
+ const trace: string[] = [];
+ const status = await dispatchResolve(projectDir, { file: 'a.md', strategy: 'mine' }, trace);
+
+ expect(status).toBe(200);
+ expect(trace).toEqual(['batch-raised', 'batch-lowered']);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('a refused resolve lowers the batch flag, never leaving it raised', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-resolve-drain-refused-'));
+ try {
+ const trace: string[] = [];
+ const status = await dispatchResolve(
+ projectDir,
+ { file: 'a.md', strategy: 'content', content: MARKERED },
+ trace,
+ );
+
+ expect(status).toBe(422);
+ expect(trace).toEqual(['batch-raised', 'batch-lowered']);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('conflict-content dispatches per conflict kind', () => {
+ async function dispatchContent(
projectDir: string,
+ seed: (conflicts: ConflictAuthority) => void,
+ options: { liveOurs?: string; source?: 'ytext' } = {},
): Promise<{ status: number; body: string }> {
- const resolved = buildConflictGroup(projectDir).table.resolve('/api/sync/conflict-content');
+ const conflicts = makeAuthority(projectDir);
+ seed(conflicts);
+ const group = createSyncRoutes({
+ projectDir,
+ contentDir: projectDir,
+ getPrincipal: undefined,
+ hocuspocus: new Hocuspocus({ quiet: true }),
+ log: loggerFactory.getLogger('test'),
+ checkLocalOpSecurity: () => true,
+ getSyncEngine: undefined,
+ conflicts,
+ serializeDoc: options.liveOurs === undefined ? undefined : () => options.liveOurs ?? '',
+ setBatchInProgress: undefined,
+ });
+ const resolved = group.table.resolve('/api/sync/conflict-content');
if (!resolved?.dispatch) throw new Error('no dispatch for /api/sync/conflict-content');
- const req = makeSyntheticReq({ url: '/api/sync/conflict-content?file=a.md' });
+ const source = options.source === undefined ? '' : `&source=${options.source}`;
+ const req = makeSyntheticReq({ url: `/api/sync/conflict-content?file=a.md${source}` });
const { res, captured } = makeCaptureRes();
await resolved.dispatch(req, res);
return captured;
}
- test('a genuinely absent working-tree file is the delete overlay (200 delete-modify)', async () => {
- const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-enoent-'));
+ test('a reconcile entry answers from its captured stages without touching git', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-reconcile-'));
try {
- const captured = await dispatchConflictContent(projectDir);
+ const captured = await dispatchContent(projectDir, (conflicts) => {
+ conflicts.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+ });
+
expect(captured.status).toBe(200);
- expect((JSON.parse(captured.body) as { kind?: string }).kind).toBe('delete-modify');
+ expect(JSON.parse(captured.body)).toMatchObject({
+ file: 'a.md',
+ base: 'BASE\n',
+ ours: 'OURS\n',
+ theirs: 'THEIRS\n',
+ conflict: 'reconcile',
+ reason: 'merged-with-markers',
+ kind: 'both-modified',
+ });
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});
- test('a non-ENOENT ours-read failure is a 500, never a silent delete-modify', async () => {
- const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-eisdir-'));
+ test('a reconcile entry answers from marker-free Y.Text only when requested', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-live-reconcile-'));
try {
- mkdirSync(join(projectDir, 'a.md'));
- const captured = await dispatchConflictContent(projectDir);
- expect(captured.status).toBe(500);
- expect((JSON.parse(captured.body) as { type?: string }).type).toBe(
- 'urn:ok:error:internal-server-error',
+ const captured = await dispatchContent(
+ projectDir,
+ (conflicts) => {
+ conflicts.raise({
+ kind: 'reconcile',
+ file: 'a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ });
+ },
+ { liveOurs: 'LIVE\n', source: 'ytext' },
);
+
+ expect(captured.status).toBe(200);
+ expect(JSON.parse(captured.body)).toMatchObject({ ours: 'LIVE\n' });
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('a merge-native entry goes to the git stage reader', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'sync-cc-merge-native-'));
+ try {
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, 'a.md'), 'tracked\n', 'utf-8');
+ await git.add('.');
+ await git.commit('seed');
+ const captured = await dispatchContent(projectDir, (conflicts) => {
+ conflicts.raise({ kind: 'merge-native', file: 'a.md' });
+ });
+
+ expect(captured.status).toBe(200);
+ expect(JSON.parse(captured.body)).toMatchObject({
+ file: 'a.md',
+ conflict: 'merge-native',
+ kind: 'both-modified',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ });
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
diff --git a/packages/server/src/http/sync-routes.ts b/packages/server/src/http/sync-routes.ts
index 551c1853b..466858317 100644
--- a/packages/server/src/http/sync-routes.ts
+++ b/packages/server/src/http/sync-routes.ts
@@ -2,8 +2,9 @@ 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 { ConflictEntryWire, Principal } from '@inkeep/open-knowledge-core';
+import type { Principal } from '@inkeep/open-knowledge-core';
import {
+ type ConflictEntryWire,
SyncConflictContentSuccessSchema,
SyncConflictsSuccessSchema,
SyncResolveBlockingRequestSchema,
@@ -15,14 +16,17 @@ import {
SyncTriggerSuccessSchema,
} from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
+import type { ConflictAuthority } from '../conflict-authority.ts';
import {
ConflictMarkersInContentError,
NoConflictTrackedError,
RESOLUTION_OPTIONS,
} from '../conflict-errors.ts';
-import type { ResolveStrategy } from '../conflict-storage.ts';
+import type { Conflict, ResolveStrategy } from '../conflict-kinds.ts';
+import { strategiesFor } from '../conflict-kinds.ts';
+import { selectReconcileOurs } from '../conflict-resolution.ts';
import { isShareableOkArtifact } from '../content-filter.ts';
-import type { DocumentDurabilityState } from '../document-durability-state.ts';
+import { stripDocExtension } from '../doc-extensions.ts';
import { claimExternalChange, releaseExternalChangeClaim } from '../external-change-attribution.ts';
import { extractActorIdentity } from '../extract-actor-identity.ts';
import { pathToDocName } from '../file-watcher.ts';
@@ -45,7 +49,6 @@ 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,
@@ -53,12 +56,9 @@ export interface SyncRouteDeps {
opts: { handler: string },
) => boolean;
getSyncEngine: (() => SyncEngine | null) | undefined;
+ conflicts: ConflictAuthority;
serializeDoc: ((docName: string) => string | null) | undefined;
- resolveStaleExternalWrite?: (
- file: string,
- strategy: ResolveStrategy,
- content?: string,
- ) => Promise<boolean>;
+ setBatchInProgress: ((value: boolean) => void) | undefined;
}
export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
@@ -67,14 +67,43 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
contentDir,
getPrincipal,
hocuspocus,
- durabilityState,
log,
checkLocalOpSecurity,
getSyncEngine,
+ conflicts,
serializeDoc,
- resolveStaleExternalWrite,
+ setBatchInProgress,
} = deps;
+ function wireEntry(entry: Conflict): ConflictEntryWire {
+ const base = {
+ file: entry.file,
+ detectedAt: entry.detectedAt,
+ conflict: entry.kind,
+ docName: conflicts.docNameOf(entry),
+ conflictKind:
+ entry.kind === 'reconcile' && entry.reason === 'stale-external-write'
+ ? ('stale-external-write' as const)
+ : ('git' as const),
+ };
+ switch (entry.kind) {
+ case 'merge-native':
+ return base;
+ case 'working-tree':
+ return {
+ ...base,
+ theirsSha: entry.theirsSha,
+ ...(entry.baseSha === undefined ? {} : { baseSha: entry.baseSha }),
+ };
+ case 'reconcile':
+ return { ...base, reason: entry.reason };
+ default: {
+ const _exhaustive: never = entry;
+ return base;
+ }
+ }
+ }
+
async function handleSyncStatus(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (!checkLocalOpSecurity(req, res, { handler: 'sync-status' })) return;
if (req.method !== 'GET') {
@@ -214,24 +243,11 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
return;
}
try {
- const engine = getSyncEngine?.();
- 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,
SyncConflictsSuccessSchema,
- { conflicts },
+ { conflicts: conflicts.list().map(wireEntry) },
{
handler: 'sync-conflicts',
},
@@ -267,33 +283,9 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
RESOLVE_ATTRIBUTION_WINDOW_MS,
);
}
+ setBatchInProgress?.(true);
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);
+ await conflicts.resolve(file, strategy as ResolveStrategy, content);
successResponse(
res,
200,
@@ -327,16 +319,28 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
return;
}
if (e instanceof ConflictMarkersInContentError) {
+ const tracked = conflicts.findByFile(e.file);
+ const resolutionOptions =
+ tracked === undefined
+ ? RESOLUTION_OPTIONS
+ : strategiesFor(
+ tracked.kind,
+ tracked.kind === 'reconcile' ? tracked.reason : undefined,
+ );
+ const strategyNotOffered = e.refusal === 'strategy-not-offered';
errorResponse(
res,
422,
'urn:ok:error:unresolved-conflict-markers',
- 'Resolution still contains conflict markers.',
+ strategyNotOffered
+ ? 'Strategy not offered for this conflict.'
+ : 'Resolution still contains conflict markers.',
{
handler: 'sync-resolve-conflict',
- detail:
- 'The submitted content still contains a `<<<<<<< … >>>>>>>` block. Resolve every region, or use strategy "mine" / "theirs" to take one side wholesale.',
- extensions: { file: e.file, resolutionOptions: RESOLUTION_OPTIONS },
+ detail: strategyNotOffered
+ ? `Strategy "${strategy}" is not offered for this conflict. Pick one of the strategies listed in resolutionOptions.`
+ : 'The submitted content still contains a `<<<<<<< … >>>>>>>` block. Resolve every region, or take one side wholesale with a strategy listed in resolutionOptions.',
+ extensions: { file: e.file, refusal: e.refusal, resolutionOptions },
},
);
return;
@@ -353,22 +357,15 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
detail,
},
);
+ } finally {
+ setBatchInProgress?.(false);
}
},
{
handler: 'sync-resolve-conflict',
method: 'POST',
- preBodyGate: (req, res) => {
- if (!checkLocalOpSecurity(req, res, { handler: 'sync-resolve-conflict' })) return false;
- const engine = getSyncEngine?.();
- if (!engine && !resolveStaleExternalWrite) {
- errorResponse(res, 503, 'urn:ok:error:sync-not-active', 'Sync engine not active.', {
- handler: 'sync-resolve-conflict',
- });
- return false;
- }
- return true;
- },
+ preBodyGate: (req, res) =>
+ checkLocalOpSecurity(req, res, { handler: 'sync-resolve-conflict' }),
},
);
@@ -414,14 +411,8 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
});
return;
}
- 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 && staleConflict?.file !== file) {
+ const entry = conflicts.findByFile(file);
+ if (entry === undefined) {
errorResponse(
res,
404,
@@ -434,96 +425,60 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
);
return;
}
+ const reason = entry.kind === 'reconcile' ? entry.reason : undefined;
+ const resolutionOptions = [...strategiesFor(entry.kind, reason)];
+ const docName = conflicts.docNameOf(entry) ?? stripDocExtension(file);
+ const loaded = hocuspocus.documents.get(docName);
+ const respond = (payload: {
+ base: string;
+ ours: string;
+ theirs: string;
+ kind: 'both-modified' | 'delete-modify' | 'modify-delete';
+ }): void => {
+ successResponse(
+ res,
+ 200,
+ SyncConflictContentSuccessSchema,
+ {
+ file,
+ ...payload,
+ conflict: entry.kind,
+ conflictKind:
+ reason === 'stale-external-write'
+ ? ('stale-external-write' as const)
+ : ('git' as const),
+ ...(reason === undefined ? {} : { reason }),
+ resolutionOptions,
+ },
+ { handler: 'sync-conflict-content' },
+ );
+ };
+
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,
+ switch (entry.kind) {
+ case 'reconcile': {
+ const liveOurs = source === 'ytext' && serializeDoc ? serializeDoc(docName) : null;
+ respond({
+ base: entry.stages.base,
+ ours: selectReconcileOurs(entry, liveOurs),
+ theirs: entry.stages.theirs,
+ kind: 'both-modified',
});
- 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;
}
- return;
- }
- const wtEntry = engine
- ?.getConflicts()
- .find((c) => c.file === file && c.variant === 'working-tree');
- if (wtEntry) {
- try {
- const readBlob = async (sha: string | undefined): Promise<string> => {
- if (!sha) return '';
- try {
- return await pg.raw(['cat-file', 'blob', sha]);
- } catch (err) {
- console.warn(
- JSON.stringify({
- event: 'conflict-content-readblob-failed',
- file,
- detail: err instanceof Error ? err.message : String(err),
- handler: 'sync-conflict-content',
- }),
- );
- throw err;
- }
- };
- const theirs = await readBlob(wtEntry.theirsSha);
- const base = await readBlob(wtEntry.baseSha);
- const docName = trackedDocName;
- const loaded = hocuspocus.documents.get(docName);
- let ours = '';
- let oursPresent = false;
- let lifecycleStatus: string | null = null;
- if (loaded) {
- const rawStatus = loaded.getMap('lifecycle').get('status');
- lifecycleStatus =
- typeof rawStatus === 'string' && rawStatus.length > 0 ? rawStatus : null;
- const ytextOurs = serializeDoc ? serializeDoc(docName) : null;
- if (ytextOurs !== null) {
- ours = ytextOurs;
- oursPresent = true;
- }
- } else {
- assertRealpathWithinDir(join(projectDir, file), projectDir, {
- allowShareableOkArtifact: isShareableOkArtifact,
- });
- try {
- ours = readFileSync(join(projectDir, file), 'utf-8');
- oursPresent = true;
- } catch (err) {
- if (errnoCode(err) !== 'ENOENT') {
+ case 'working-tree': {
+ const pg = simpleGit({ baseDir: projectDir, timeout: { block: 15_000 } });
+ try {
+ const readBlob = async (sha: string | undefined): Promise<string> => {
+ if (!sha) return '';
+ try {
+ return await pg.raw(['cat-file', 'blob', sha]);
+ } catch (err) {
console.warn(
JSON.stringify({
- event: 'conflict-content-ours-read-failed',
+ event: 'conflict-content-readblob-failed',
file,
detail: err instanceof Error ? err.message : String(err),
handler: 'sync-conflict-content',
@@ -531,84 +486,106 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
);
throw err;
}
- oursPresent = false;
+ };
+ const theirs = await readBlob(entry.theirsSha);
+ const base = await readBlob(entry.baseSha);
+ let ours = '';
+ let oursPresent = false;
+ if (loaded) {
+ const ytextOurs = serializeDoc ? serializeDoc(docName) : null;
+ if (ytextOurs !== null) {
+ ours = ytextOurs;
+ oursPresent = true;
+ }
+ } else {
+ assertRealpathWithinDir(join(projectDir, file), projectDir, {
+ allowShareableOkArtifact: isShareableOkArtifact,
+ });
+ try {
+ ours = readFileSync(join(projectDir, file), 'utf-8');
+ oursPresent = true;
+ } catch (err) {
+ if (errnoCode(err) !== 'ENOENT') {
+ console.warn(
+ JSON.stringify({
+ event: 'conflict-content-ours-read-failed',
+ file,
+ detail: err instanceof Error ? err.message : String(err),
+ handler: 'sync-conflict-content',
+ }),
+ );
+ throw err;
+ }
+ oursPresent = false;
+ }
}
- }
- const kind: 'both-modified' | 'delete-modify' | 'modify-delete' = !oursPresent
- ? 'delete-modify'
- : theirs.length === 0
- ? 'modify-delete'
- : 'both-modified';
- successResponse(
- res,
- 200,
- SyncConflictContentSuccessSchema,
- { file, base, ours, theirs, kind, lifecycleStatus, conflictKind: 'git' },
- { 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;
- }
-
- type StageResult = { present: false } | { present: true; content: string };
- async function showStage(stage: 1 | 2 | 3): Promise<StageResult> {
- try {
- return { present: true, content: await pg.raw(['show', `:${stage}:${file}`]) };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- const isAbsent =
- /pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(
- msg,
- );
- if (!isAbsent) {
- console.warn(
- JSON.stringify({
- event: 'showstage-unexpected-error',
- stage,
- file,
- detail: msg,
- handler: 'sync-conflict-content',
- }),
+ respond({
+ base,
+ ours,
+ theirs,
+ kind: !oursPresent
+ ? 'delete-modify'
+ : theirs.length === 0
+ ? 'modify-delete'
+ : 'both-modified',
+ });
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read conflict content.',
+ { handler: 'sync-conflict-content', cause: e },
);
- throw err;
}
- return { present: false };
+ return;
}
- }
- try {
- const [baseResult, oursResult, theirsResult] = await Promise.all([
- showStage(1),
- showStage(2),
- showStage(3),
- ]);
- const base = baseResult.present ? baseResult.content : '';
- const theirs = theirsResult.present ? theirsResult.content : '';
- const kind: 'both-modified' | 'delete-modify' | 'modify-delete' =
- oursResult.present && theirsResult.present
- ? 'both-modified'
- : !oursResult.present && theirsResult.present
- ? 'delete-modify'
- : oursResult.present && !theirsResult.present
- ? 'modify-delete'
- : 'both-modified';
- let ours = oursResult.present ? oursResult.content : '';
- let lifecycleStatus: string | null = null;
- if (source === 'ytext') {
- const docName = trackedDocName;
- const loaded = hocuspocus.documents.get(docName);
- if (loaded) {
- const rawStatus = loaded.getMap('lifecycle').get('status');
- lifecycleStatus =
- typeof rawStatus === 'string' && rawStatus.length > 0 ? rawStatus : null;
- if (kind !== 'delete-modify') {
+
+ case 'merge-native': {
+ const pg = simpleGit({ baseDir: projectDir, timeout: { block: 15_000 } });
+ type StageResult = { present: false } | { present: true; content: string };
+ const showStage = async (stage: 1 | 2 | 3): Promise<StageResult> => {
+ try {
+ return { present: true, content: await pg.raw(['show', `:${stage}:${file}`]) };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ const isAbsent =
+ /pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(
+ msg,
+ );
+ if (!isAbsent) {
+ console.warn(
+ JSON.stringify({
+ event: 'showstage-unexpected-error',
+ stage,
+ file,
+ detail: msg,
+ handler: 'sync-conflict-content',
+ }),
+ );
+ throw err;
+ }
+ return { present: false };
+ }
+ };
+ try {
+ const [baseResult, oursResult, theirsResult] = await Promise.all([
+ showStage(1),
+ showStage(2),
+ showStage(3),
+ ]);
+ const base = baseResult.present ? baseResult.content : '';
+ const theirs = theirsResult.present ? theirsResult.content : '';
+ const stageKind: 'both-modified' | 'delete-modify' | 'modify-delete' =
+ oursResult.present && theirsResult.present
+ ? 'both-modified'
+ : !oursResult.present && theirsResult.present
+ ? 'delete-modify'
+ : oursResult.present && !theirsResult.present
+ ? 'modify-delete'
+ : 'both-modified';
+ let ours = oursResult.present ? oursResult.content : '';
+ if (source === 'ytext' && loaded !== undefined && stageKind !== 'delete-modify') {
const ytextOurs = serializeDoc ? serializeDoc(docName) : null;
if (ytextOurs !== null && !containsUnresolvedConflictBlock(ytextOurs)) {
ours = ytextOurs;
@@ -622,31 +599,36 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
);
}
}
- } else {
- log.warn(
- { docName },
- `[conflict-content] doc ${docName} not loaded; lifecycleStatus unavailable`,
+ respond({ base, ours, theirs, kind: stageKind });
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read conflict content.',
+ {
+ handler: 'sync-conflict-content',
+ cause: e,
+ },
);
}
+ return;
+ }
+
+ default: {
+ const _exhaustive: never = entry;
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read conflict content.',
+ {
+ handler: 'sync-conflict-content',
+ cause: new Error(`unknown conflict kind: ${JSON.stringify(_exhaustive)}`),
+ },
+ );
+ return;
}
- successResponse(
- res,
- 200,
- SyncConflictContentSuccessSchema,
- { file, base, ours, theirs, kind, lifecycleStatus, conflictKind: 'git' },
- { 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,
- },
- );
}
}
diff --git a/packages/server/src/http/test-routes.ts b/packages/server/src/http/test-routes.ts
index 29586aa4d..3156e62e4 100644
--- a/packages/server/src/http/test-routes.ts
+++ b/packages/server/src/http/test-routes.ts
@@ -11,10 +11,12 @@ import {
} from '@inkeep/open-knowledge-core';
import type { AgentSessionManager } from '../agent-sessions.ts';
import { CONFIG_VALIDATION_REVERT_ORIGIN } from '../config-edit-origin.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
import type { ContentFilter } from '../content-filter.ts';
import { safeContentPath } from '../content-path.ts';
import type { DerivedDocumentIndexApiPort } from '../derived-document-index.ts';
import { canonicalDocName } from '../doc-extensions.ts';
+import type { DocumentDurabilityState } from '../document-durability-state.ts';
import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
import { errorResponse } from './error-response.ts';
import { getRequestId } from './request-id.ts';
@@ -22,7 +24,8 @@ import { withValidation } from './request-validation.ts';
import { successResponse } from './success-response.ts';
export interface TestRouteDeps {
- resetDocumentDurability: ((docName: string) => void) | undefined;
+ conflicts: ConflictAuthority;
+ durabilityState: DocumentDurabilityState;
resolveAlias: (docName: string) => string;
contentDir: string;
log: import('../logger.ts').PinoLogger;
@@ -39,7 +42,8 @@ export interface TestRouteDeps {
export function createTestRoutes(deps: TestRouteDeps): ApiRouteGroup {
const {
- resetDocumentDurability,
+ conflicts,
+ durabilityState,
resolveAlias,
contentDir,
log,
@@ -80,7 +84,8 @@ export function createTestRoutes(deps: TestRouteDeps): ApiRouteGroup {
}
const doc = hocuspocus.documents.get(docName);
if (doc) await (forceUnloadDocument ?? hocuspocus.unloadDocument.bind(hocuspocus))(doc);
- resetDocumentDurability?.(docName);
+ durabilityState.deleteReconciledBase(docName);
+ conflicts.dissolveReconcile(docName);
writeFileSync(filePath, '', 'utf-8');
await derivedDocumentIndex?.testOnly?.resetDocumentForTest(docName);
const resetOkignoreParam = url.searchParams.get('reset-okignore');
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index ea1a93b84..efc3111f8 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -81,7 +81,6 @@ export {
type BootedServer,
type BootServerOptions,
bootServer,
- restoreLifecycleFromConflictsJson,
type ServerExitReason,
} from './boot.ts';
export {
@@ -118,6 +117,24 @@ export {
} from './collaboration-host.ts';
export { getLocalDir, resolveContentDir, resolveLockDir } from './config/paths.ts';
export { type Config, ConfigSchema } from './config/schema.ts';
+export {
+ bindConflictAuthority,
+ ConflictAuthority,
+ type ConflictAuthorityOptions,
+ type ConflictChange,
+ type ConflictIo,
+ type ConflictReader,
+ isDocInConflict,
+} from './conflict-authority.ts';
+export {
+ type Conflict,
+ type ConflictKind,
+ type ConflictStages,
+ type LifecycleView,
+ type ReconcileReason,
+ type ResolveStrategy,
+ strategiesFor,
+} from './conflict-kinds.ts';
export { MCP_SERVER_NAME } from './constants.ts';
export {
type ContentFilter,
diff --git a/packages/server/src/mcp/tools/conflicts.test.ts b/packages/server/src/mcp/tools/conflicts.test.ts
index 758856269..0f6abcf5d 100644
--- a/packages/server/src/mcp/tools/conflicts.test.ts
+++ b/packages/server/src/mcp/tools/conflicts.test.ts
@@ -80,8 +80,21 @@ beforeAll(async () => {
return Response.json({
ok: true,
conflicts: [
- { file: 'notes/sso.md', detectedAt: 'now', conflictKind: 'stale-external-write' },
- { file: 'overlay.md', detectedAt: 'now', conflictKind: 'git', variant: 'working-tree' },
+ {
+ file: 'notes/sso.md',
+ detectedAt: 'now',
+ conflict: 'reconcile',
+ reason: 'stale-external-write',
+ conflictKind: 'stale-external-write',
+ docName: 'notes/sso',
+ },
+ {
+ file: 'overlay.md',
+ detectedAt: 'now',
+ conflict: 'working-tree',
+ conflictKind: 'git',
+ docName: 'overlay',
+ },
],
});
}
@@ -93,8 +106,10 @@ beforeAll(async () => {
ours: 'O',
theirs: 'T',
kind: 'both-modified',
+ conflict: 'reconcile',
+ reason: 'stale-external-write',
conflictKind: 'stale-external-write',
- lifecycleStatus: 'conflict',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
});
}
return new Response('Not found', { status: 404 });
@@ -108,12 +123,12 @@ describe('conflicts — kind discriminator', () => {
test('kind:list enumerates tracked conflicts (nested under `list`)', async () => {
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' },
+ { conflict: 'reconcile', conflictKind: 'stale-external-write' },
+ { conflict: 'working-tree', conflictKind: 'git' },
]);
- expect(result.content[0]?.text).toContain('notes/sso.md');
+ expect(result.content[0]?.text).toContain('notes/sso.md (reconcile / stale-external-write)');
+ expect(result.content[0]?.text).toContain('overlay.md (working-tree)');
});
test('kind:content nests stages under `content` and remaps route `kind` → `shape` (DD4)', async () => {
@@ -121,9 +136,14 @@ 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).toMatchObject({
+ conflict: 'reconcile',
+ conflictKind: 'stale-external-write',
+ resolutionOptions: ['mine', 'theirs', 'content', 'delete'],
+ });
expect(content).not.toHaveProperty('kind');
expect(result.content[0]?.text).toContain('shape: both-modified');
+ expect(result.content[0]?.text).toContain('strategies: mine, theirs, content, delete');
});
test('kind:content without `file` returns a teaching error', async () => {
diff --git a/packages/server/src/mcp/tools/conflicts.ts b/packages/server/src/mcp/tools/conflicts.ts
index 20c6d3177..c1e63d79f 100644
--- a/packages/server/src/mcp/tools/conflicts.ts
+++ b/packages/server/src/mcp/tools/conflicts.ts
@@ -12,17 +12,17 @@ import {
} from './shared.ts';
const DESCRIPTION = [
- '[Requires: Hocuspocus server] Read Git merge conflicts and local stale external-write conflicts. Dispatches on `kind`:',
+ '[Requires: Hocuspocus server] Read tracked conflicts. Dispatches on `kind`:',
'',
- '- `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.',
+ '- `kind: "list"` enumerates every file currently tracked as conflicted. Returns `{ list: [{ file, detectedAt, conflict, reason?, conflictKind?, docName }] }` (empty when none). The entry point to the resolve flow.',
+ '- `kind: "content"` fetches the three stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }`. `ours` is the live Y.Text when the doc is loaded server-side and marker-free, else the stage pinned when the conflict was detected; for `reason: "stale-external-write"` it is the protected acknowledged content and `theirs` the rejected older save. On a `reconcile` conflict, `resolve_conflict` with `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers. To keep exactly the bytes reviewed here, send them back as `content`. Returns 404 (`urn:ok:error:no-conflict-tracked`) when no conflict is tracked for that `file`; re-read the list before retrying.',
'',
'**Parameters:**',
'- `kind` — `list` | `content`.',
'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',
'',
+ "`conflict` names where the conflict came from: `merge-native` (a git merge left unmerged stages), `working-tree` (a pull-only overlay collision pinned to an origin blob), or `reconcile` (OK's own merge of editor and disk, including local stale-save protection); `reason` refines a `reconcile` conflict, and the compatibility `conflictKind` field is `stale-external-write` for that reason and `git` otherwise. `resolutionOptions` lists the strategies that apply to THIS conflict: a `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and `refused-too-large` offers only `mine`, `theirs`, and `delete`.",
+ '',
'The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy.',
].join('\n');
@@ -54,23 +54,32 @@ export function register(server: ServerInstance, deps: ConflictsDeps): void {
list: z
.array(ConflictEntrySchema)
.optional()
- .describe('`kind: "list"` — every tracked conflict, including its conflictKind.'),
+ .describe('`kind: "list"` returns every tracked conflict.'),
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.'),
shape: z
.enum(['both-modified', 'delete-modify', 'modify-delete'])
.describe('Conflict shape — pick the `resolve_conflict` strategy from it.'),
- lifecycleStatus: z.string().nullable().describe("The doc's lifecycle status, or null."),
+ conflict: z
+ .enum(['merge-native', 'working-tree', 'reconcile'])
+ .describe('Where this conflict came from.'),
+ reason: z.string().optional().describe('Refines a `reconcile` conflict.'),
+ conflictKind: z
+ .enum(['git', 'stale-external-write'])
+ .optional()
+ .describe('Compatibility classification for Git and protected stale-save conflicts.'),
+ resolutionOptions: z
+ .array(z.enum(['mine', 'theirs', 'content', 'delete']))
+ .describe('The strategies that apply to this conflict.'),
})
.optional()
- .describe('`kind: "content"` — the three merge stages + shape + lifecycle.'),
+ .describe(
+ '`kind: "content"` returns the three stages plus shape, conflict kind and options.',
+ ),
}),
annotations: { readOnlyHint: true, idempotentHint: true },
},
@@ -106,14 +115,30 @@ export function register(server: ServerInstance, deps: ConflictsDeps): void {
const theirs = typeof rec.theirs === 'string' ? rec.theirs : '';
const shape: 'both-modified' | 'delete-modify' | 'modify-delete' =
rec.kind === 'delete-modify' || rec.kind === 'modify-delete' ? rec.kind : 'both-modified';
- const lifecycleStatus =
- typeof rec.lifecycleStatus === 'string' ? rec.lifecycleStatus : null;
+ const conflict: 'merge-native' | 'working-tree' | 'reconcile' =
+ rec.conflict === 'working-tree' || rec.conflict === 'reconcile'
+ ? rec.conflict
+ : 'merge-native';
+ const reason = typeof rec.reason === 'string' ? rec.reason : undefined;
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}`;
+ const resolutionOptions = Array.isArray(rec.resolutionOptions)
+ ? (rec.resolutionOptions as Array<'mine' | 'theirs' | 'content' | 'delete'>)
+ : (['mine', 'theirs', 'content', 'delete'] as const).slice();
+ const reasonSuffix = reason ? `, reason: ${reason}` : '';
+ const text = `Conflict stages for ${file} (shape: ${shape}, conflict: ${conflict}${reasonSuffix}; strategies: ${resolutionOptions.join(', ')}):\n--- base ---\n${base}\n--- ours ---\n${ours}\n--- theirs ---\n${theirs}`;
return textPlusStructured(text, {
- content: { file, base, ours, theirs, shape, conflictKind, lifecycleStatus },
+ content: {
+ file,
+ base,
+ ours,
+ theirs,
+ shape,
+ conflict,
+ ...(reason === undefined ? {} : { reason }),
+ conflictKind,
+ resolutionOptions,
+ },
});
}
@@ -128,11 +153,11 @@ export function register(server: ServerInstance, deps: ConflictsDeps): void {
? 'No conflicts tracked.'
: `Tracked conflicts (${conflicts.length}):\n${conflicts
.map((row) => {
- const file =
- row && typeof row === 'object' && 'file' in row
- ? String((row as Record<string, unknown>).file ?? '')
- : '';
- return `- ${file}`;
+ const rec = (row ?? {}) as Record<string, unknown>;
+ const file = typeof rec.file === 'string' ? rec.file : '';
+ const conflict = typeof rec.conflict === 'string' ? rec.conflict : 'merge-native';
+ const reason = typeof rec.reason === 'string' ? ` / ${rec.reason}` : '';
+ return `- ${file} (${conflict}${reason})`;
})
.join('\n')}`;
return textPlusStructured(text, { list: conflicts });
diff --git a/packages/server/src/mcp/tools/resolve-conflict.test.ts b/packages/server/src/mcp/tools/resolve-conflict.test.ts
index 9db9502d5..1654db913 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.test.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.test.ts
@@ -89,6 +89,18 @@ describe('resolve_conflict MCP tool', () => {
expect(tool.config.description).toContain('DESTRUCTIVE');
});
+ test('description names both refusals that share the 422 and the field telling them apart', () => {
+ const { server, registrations } = createCapturingServer();
+ register(server, makeDeps('http://localhost:4321'));
+ const tool = getTool(registrations, 'resolve_conflict');
+
+ expect(tool.config.description).toContain('urn:ok:error:unresolved-conflict-markers');
+ expect(tool.config.description).toContain('`refusal`');
+ expect(tool.config.description).toContain('markers-in-content');
+ expect(tool.config.description).toContain('strategy-not-offered');
+ expect(tool.config.description).toContain('resolutionOptions');
+ });
+
test('strategy=theirs posts a body without content', async () => {
const { server, registrations } = createCapturingServer();
const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];
diff --git a/packages/server/src/mcp/tools/resolve-conflict.ts b/packages/server/src/mcp/tools/resolve-conflict.ts
index f96c6b327..5f7681125 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.ts
@@ -11,21 +11,23 @@ import {
} from './shared.ts';
const DESCRIPTION = [
- '[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.',
+ '[Requires: Hocuspocus server] Resolve a tracked conflict by writing the chosen content to disk. Only the strategies listed in `resolutionOptions` on `conflicts({ kind: "content" })` apply.',
'',
'Strategy:',
- '- `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.',
+ '- `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 exact provided `content` bytes (e.g. a per-hunk merged result, the live Y.Text shown in the DiffView, or an explicit empty string). Use `delete` to remove the file.',
+ '- `delete` — runs `git rm <file>`, which stages the removal rather than committing it on its own. 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.',
'',
- '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.',
+ 'Those git mechanics are the `merge-native` kind (a git merge left unmerged stages); its merge is committed once it was the last tracked `merge-native` conflict, and other kinds do not hold that commit back. On a `working-tree` conflict (a pull-only overlay collision pinned to an origin blob) nothing is committed: `mine` keeps the overlay verbatim, `theirs` restores the pinned origin blob. On a `reconcile` conflict (OK\'s own merge of editor and disk) the chosen bytes land on disk and in the loaded document with no git command, and `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk stage captured at detection — for `reason: "stale-external-write"`, the current local content and the rejected older save. `resolutionOptions` drops `theirs` when a `reconcile` conflict\'s `theirs` side is raw marker text (`reason` of `disk-markers` or `refused-conflict-markers`), and drops `content` for `refused-too-large`.',
'',
- '**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.',
+ 'Returns 200 on success. 404 (`urn:ok:error:no-conflict-tracked`) means no conflict is tracked for that path — it may have been resolved by another session, or the path may be stale; re-read `conflicts({ kind: "list" })` rather than inferring that your resolution was saved. 422 (`urn:ok:error:unresolved-conflict-markers`) carries a `refusal` field telling two cases apart: `markers-in-content` 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; `strategy-not-offered` means your strategy is not among the `resolutionOptions` the same body echoes — pick one from that list. 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).',
+ '',
+ '**DESTRUCTIVE:** this modifies the working tree, and a `merge-native` resolve also creates a git commit once it was the last tracked `merge-native` conflict.',
'',
'**Parameters:**',
- '- `file` — Exact relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',
- '- `strategy` — One of `mine` | `theirs` | `content` | `delete`.',
+ '- `file` — Relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',
+ "- `strategy` — One of `mine` | `theirs` | `content` | `delete`, narrowed by the conflict's `resolutionOptions`.",
'- `content` — Required when `strategy === "content"`; an empty string keeps an empty file. Ignored otherwise.',
].join('\n');
@@ -50,18 +52,18 @@ export function register(server: ServerInstance, deps: ResolveConflictDeps): voi
.string()
.min(1)
.describe(
- 'Exact relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',
+ '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 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.',
+ "Resolution strategy, narrowed by the conflict's `resolutionOptions`. `content` requires the `content` arg. On a `merge-native` conflict, `delete` runs `git rm`; on the other kinds it removes the file with no git command. Use `delete` for delete-vs-modify (DU/UD) shapes where one stage is missing.",
),
content: z
.string()
.optional()
.describe(
- 'Exact bytes to write, including an empty string to keep an empty file. Required when strategy is content; ignored otherwise.',
+ 'Exact bytes to write. Required when `strategy === "content"`; ignored otherwise.',
),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
diff --git a/packages/server/src/paired-intake-detection-wiring.test.ts b/packages/server/src/paired-intake-detection-wiring.test.ts
index cdc39c420..c947fd2b7 100644
--- a/packages/server/src/paired-intake-detection-wiring.test.ts
+++ b/packages/server/src/paired-intake-detection-wiring.test.ts
@@ -16,6 +16,7 @@ import {
PAIRED_INTAKE_DETECTION,
type PairedIntakeDetectionMode,
} from './bridge-loss-suppression.ts';
+import { RECONCILE_TEST_CONFLICTS } from './conflict-authority.test-helper.ts';
import { DocumentDurabilityState } from './document-durability-state.ts';
import { reconcileDiskBeforeAgentWrite } from './external-change.ts';
import { mdManager } from './md-manager.ts';
@@ -182,6 +183,7 @@ describe('paired-intake detection follows the registry at every wired site', ()
contentDir,
undefined,
on.reporter,
+ RECONCILE_TEST_CONFLICTS,
);
expect(on.trips.length).toBeGreaterThan(0);
@@ -195,6 +197,7 @@ describe('paired-intake detection follows the registry at every wired site', ()
contentDir,
undefined,
off.reporter,
+ RECONCILE_TEST_CONFLICTS,
);
});
expect(off.trips).toEqual([]);
diff --git a/packages/server/src/persistence-staleness-watchdog.test.ts b/packages/server/src/persistence-staleness-watchdog.test.ts
index 5912cc2ab..d46159d42 100644
--- a/packages/server/src/persistence-staleness-watchdog.test.ts
+++ b/packages/server/src/persistence-staleness-watchdog.test.ts
@@ -2,7 +2,7 @@ import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { isPersistenceExcludedDoc } from './cc1-broadcast.ts';
-import { FROZEN_LIFECYCLE_STATUSES } from './conflict-errors.ts';
+import type { LifecycleView } from './conflict-kinds.ts';
import { DocumentDurabilityState } from './document-durability-state.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
import {
@@ -14,6 +14,15 @@ import {
const GRACE_MS = 1_000;
+const MAP_FROZEN_STATUSES = ['deleted-upstream', 'renamed'] as const;
+
+function lifecycleViewOf(document: Y.Doc): LifecycleView | null {
+ const status = document.getMap('lifecycle').get('status');
+ if (status === 'deleted-upstream') return { status: 'deleted-upstream' };
+ if (status === 'renamed') return { status: 'renamed', newPath: '' };
+ return null;
+}
+
interface Rig {
watchdog: StalenessWatchdogHandle;
docs: Map<string, Y.Doc>;
@@ -54,6 +63,7 @@ function makeRig(overrides: Partial<StalenessWatchdogOptions> = {}): Rig {
const watchdog = createPersistenceStalenessWatchdog({
getLoadedDocuments: () => docs,
+ lifecycleOf: (document) => lifecycleViewOf(document),
forceStore: async (document, documentName) => {
forceCalls.push(documentName);
if (hangDocs.has(documentName)) {
@@ -273,7 +283,7 @@ describe('exclusions', () => {
});
test('skips docs frozen by lifecycle status', async () => {
- for (const status of FROZEN_LIFECYCLE_STATUSES) {
+ for (const status of MAP_FROZEN_STATUSES) {
const doc = seedWedgedDoc(rig, `lifecycle-${status}`);
doc.getMap('lifecycle').set('status', status);
}
diff --git a/packages/server/src/persistence-staleness-watchdog.ts b/packages/server/src/persistence-staleness-watchdog.ts
index f7b9dbcb6..08bb2f64a 100644
--- a/packages/server/src/persistence-staleness-watchdog.ts
+++ b/packages/server/src/persistence-staleness-watchdog.ts
@@ -2,7 +2,7 @@ import { addsBlankLines, normalizeBridge } from '@inkeep/open-knowledge-core';
import type * as Y from 'yjs';
import { getMsSinceLastUserTx } from './bridge-quiescence.ts';
import { isPersistenceExcludedDoc } from './cc1-broadcast.ts';
-import { frozenDocLifecycleStatus } from './conflict-errors.ts';
+import type { FreezingLifecycleStatus, LifecycleView } from './conflict-kinds.ts';
import { getLogger } from './logger.ts';
import {
incrementPersistenceStalenessDetected,
@@ -29,6 +29,7 @@ export interface StalenessWatchdogOptions {
getLoadedDocuments: () => Iterable<readonly [string, Y.Doc]>;
forceStore: (document: Y.Doc, documentName: string) => Promise<void>;
readDiskBytes: (documentName: string) => string | null;
+ lifecycleOf?: (document: Y.Doc, documentName: string) => LifecycleView | null;
graceMs?: number;
sweepIntervalMs?: number;
now?: () => number;
@@ -75,6 +76,11 @@ export function createPersistenceStalenessWatchdog(
return base === undefined ? undefined : normalizeBridge(base);
}
+ function frozenStatusOf(document: Y.Doc, documentName: string): FreezingLifecycleStatus | null {
+ const view = options.lifecycleOf?.(document, documentName) ?? null;
+ return view === null ? null : view.status;
+ }
+
function isDivergent(
candidate: string,
normalizedBase: string | undefined,
@@ -101,7 +107,7 @@ export function createPersistenceStalenessWatchdog(
if (disposed) return;
seen.add(documentName);
if (isPersistenceExcludedDoc(documentName)) continue;
- if (frozenDocLifecycleStatus(document) !== null) {
+ if (frozenStatusOf(document, documentName) !== null) {
continue;
}
if (hasInFlight(documentName)) {
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index 22c104738..bfd6b71dd 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -42,7 +42,8 @@ import {
isSystemDoc,
} from './cc1-broadcast.ts';
import { type ConfigPersistenceCtx, loadConfigDoc, storeConfigDoc } from './config-persistence.ts';
-import { frozenDocLifecycleStatus } from './conflict-errors.ts';
+import type { ConflictAuthority } from './conflict-authority.ts';
+import type { FreezingLifecycleStatus, LifecycleView } from './conflict-kinds.ts';
import { isWithinContentDir, safeContentPath } from './content-path.ts';
import type { ContributorEntry } from './contributor-tracker.ts';
import {
@@ -247,6 +248,7 @@ export interface PersistenceOptions {
contentDir: string;
projectDir: string;
durabilityState?: DocumentDurabilityState;
+ conflicts?: Pick<ConflictAuthority, 'dissolveReconcile' | 'fileOf' | 'raise'>;
gitEnabled?: boolean;
commitDebounceMs?: number;
wipRef?: string;
@@ -280,6 +282,7 @@ export interface PersistenceOptions {
mdManager?: MarkdownManager;
getLossRing?: () => Pick<LossCaptureRing, 'record'> | undefined;
isRecentlyRemoved?: (docName: string) => boolean;
+ lifecycleOf?: (document: Y.Doc, docName: string) => LifecycleView | null;
ephemeral?: boolean;
}
@@ -389,6 +392,17 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
const onManagedSkillPersisted = options?.onManagedSkillPersisted;
const mgr = options?.mdManager ?? mdManager;
const ephemeral = options?.ephemeral ?? false;
+ const frozenStatusOf = (
+ document: Y.Doc,
+ documentName: string,
+ ): FreezingLifecycleStatus | null => {
+ const view = options?.lifecycleOf?.(document, documentName);
+ if (view === undefined) {
+ const status = document.getMap('lifecycle').get('status');
+ return status === 'deleted-upstream' || status === 'renamed' ? status : null;
+ }
+ return view === null ? null : view.status;
+ };
const configLkgCache = new Map<string, string>();
const configPersistenceCtx: ConfigPersistenceCtx = {
@@ -1234,7 +1248,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
'persistence.onStoreDocument',
{ attributes: { 'doc.name': documentName } },
async () => {
- const lifecycleStatus = frozenDocLifecycleStatus(document);
+ const lifecycleStatus = frozenStatusOf(document, documentName);
if (lifecycleStatus !== null) {
log.info(
{ documentName, lifecycleStatus },
@@ -1605,6 +1619,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
document,
documentName,
diskContent,
+ options?.conflicts,
markdown,
)
) {
@@ -1940,6 +1955,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
document,
documentName,
raw,
+ options?.conflicts,
);
let contentToLoad = raw;
if (staleExternalWrite) {
diff --git a/packages/server/src/reconcile-intake-loss.test.ts b/packages/server/src/reconcile-intake-loss.test.ts
index b64cd3569..7a2f7fb4c 100644
--- a/packages/server/src/reconcile-intake-loss.test.ts
+++ b/packages/server/src/reconcile-intake-loss.test.ts
@@ -13,6 +13,7 @@ import {
type DeriveLossObservation,
detectPairedIntakeLoss,
} from './bridge-loss-detector.ts';
+import { RECONCILE_TEST_CONFLICTS } from './conflict-authority.test-helper.ts';
import { DocumentDurabilityState } from './document-durability-state.ts';
import { reconcileDiskBeforeAgentWrite } from './external-change.ts';
import { mdManager } from './md-manager.ts';
@@ -85,6 +86,7 @@ describe('reconcileDiskBeforeAgentWrite paired-intake instrumentation', () => {
contentDir,
undefined,
reporter,
+ RECONCILE_TEST_CONFLICTS,
);
expect(result.reconciled).toBe(true);
@@ -129,6 +131,7 @@ describe('reconcileDiskBeforeAgentWrite paired-intake instrumentation', () => {
contentDir,
undefined,
(name, obs, writerId, site) => trips.push({ docName: name, obs, writerId, site }),
+ RECONCILE_TEST_CONFLICTS,
);
expect(result.reconciled).toBe(true);
diff --git a/packages/server/src/reconcile-own-flush-window.test.ts b/packages/server/src/reconcile-own-flush-window.test.ts
index 56bdd067d..c50bebef3 100644
--- a/packages/server/src/reconcile-own-flush-window.test.ts
+++ b/packages/server/src/reconcile-own-flush-window.test.ts
@@ -5,7 +5,8 @@ import type { Hocuspocus } from '@hocuspocus/server';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
-import { isDocInConflict } from './conflict-errors.ts';
+import { RECONCILE_TEST_CONFLICTS } from './conflict-authority.test-helper.ts';
+import { isDocInConflict } from './conflict-authority.ts';
import { DocumentDurabilityState } from './document-durability-state.ts';
import {
type ReconcileBeforeWriteResult,
@@ -117,6 +118,9 @@ async function drivePhantomDivergence(
fakeHocuspocusWith(docName, document),
docName,
tmpDir,
+ undefined,
+ undefined,
+ RECONCILE_TEST_CONFLICTS,
);
probe.conflictAfterGuard = isDocInConflict(document as never);
},
@@ -181,6 +185,9 @@ describe('reconcileDiskBeforeAgentWrite — own persistence flush is not foreign
fakeHocuspocusWith(docName, document),
docName,
tmpDir,
+ undefined,
+ undefined,
+ RECONCILE_TEST_CONFLICTS,
);
expect(laterGuard.reconciled).toBe(false);
diff --git a/packages/server/src/server-factory.conflict-authority.test.ts b/packages/server/src/server-factory.conflict-authority.test.ts
new file mode 100644
index 000000000..5aabb38ac
--- /dev/null
+++ b/packages/server/src/server-factory.conflict-authority.test.ts
@@ -0,0 +1,370 @@
+import { execFile } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, resolve } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { promisify } from 'node:util';
+import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { bootServer } from './boot.ts';
+import { ConfigSchema } from './config/schema.ts';
+import type { ServerInstance } from './server-factory.ts';
+
+const execFileAsync = promisify(execFile);
+const TEST_CONFIG = ConfigSchema.parse({});
+
+const DOC_NAME = 'notes/topic';
+const DOC_FILE = 'notes/topic.md';
+const SCRATCH_DOC = 'notes/scratch';
+const SCRATCH_FILE = 'notes/scratch.md';
+const COLLISION_FILE = 'notes/pull-collision.md';
+const CONTROL_MARKER = 'stored while the batch was down';
+const DEFERRED_MARKER = 'drained by the resolve';
+
+function seedOkScaffold(projectDir: string): void {
+ const okDir = resolve(projectDir, OK_DIR);
+ mkdirSync(okDir, { recursive: true });
+ writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');
+ writeFileSync(resolve(okDir, '.gitignore'), 'local/\n', 'utf-8');
+}
+
+function seedConflictsJson(projectDir: string, file: string): void {
+ const localDir = resolve(projectDir, OK_DIR, 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(
+ resolve(localDir, 'conflicts.json'),
+ JSON.stringify(
+ {
+ version: 1,
+ branch: 'main',
+ conflicts: [{ kind: 'merge-native', file, detectedAt: '2026-05-19T00:00:00.000Z' }],
+ },
+ null,
+ 2,
+ ),
+ 'utf-8',
+ );
+}
+
+async function seedRealMergeConflict(projectDir: string, filePath: string): Promise<void> {
+ const opts = { cwd: projectDir };
+ await execFileAsync('git', ['config', 'user.email', '[email protected]'], opts);
+ await execFileAsync('git', ['config', 'user.name', 'Test'], opts);
+ mkdirSync(resolve(projectDir, 'notes'), { recursive: true });
+ writeFileSync(resolve(projectDir, filePath), 'line1\nline2\nline3\n', 'utf-8');
+ await execFileAsync('git', ['add', '-A'], opts);
+ await execFileAsync('git', ['commit', '-m', 'base'], opts);
+ await execFileAsync('git', ['checkout', '-b', 'theirs-branch'], opts);
+ writeFileSync(resolve(projectDir, filePath), 'line1\nUPSTREAM\nline3\n', 'utf-8');
+ await execFileAsync('git', ['commit', '-am', 'theirs'], opts);
+ await execFileAsync('git', ['checkout', 'main'], opts);
+ writeFileSync(resolve(projectDir, filePath), 'line1\nLOCAL\nline3\n', 'utf-8');
+ await execFileAsync('git', ['commit', '-am', 'ours'], opts);
+ await execFileAsync('git', ['merge', 'theirs-branch'], opts).catch(() => {});
+ if (!existsSync(resolve(projectDir, '.git', 'MERGE_HEAD'))) {
+ throw new Error('seedRealMergeConflict: no MERGE_HEAD — the merge did not conflict');
+ }
+}
+
+async function isIndexed(port: number, docName: string): Promise<boolean> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/documents`).catch(() => null);
+ if (!res?.ok) return false;
+ const data = (await res.json()) as { documents?: Array<{ docName: string }> };
+ return data.documents?.some((d) => d.docName === docName) ?? false;
+}
+
+async function listConflictFiles(port: number): Promise<string[]> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`).catch(() => null);
+ if (!res?.ok) return [];
+ const data = (await res.json()) as { conflicts?: Array<{ file: string }> };
+ return (data.conflicts ?? []).map((c) => c.file);
+}
+
+async function writeDocProbe(port: number, docName: string, markdown: string): Promise<number> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, markdown, position: 'replace', agentId: 'probe' }),
+ });
+ return res.status;
+}
+
+async function writeProbe(port: number, markdown: string): Promise<number> {
+ return writeDocProbe(port, DOC_NAME, markdown);
+}
+
+async function resolveConflictOverHttp(
+ port: number,
+ file: string,
+ strategy: string,
+): Promise<number> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/resolve-conflict`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ file, strategy }),
+ });
+ return res.status;
+}
+
+async function pollUntil(
+ condition: () => boolean | Promise<boolean>,
+ timeoutMs: number,
+ what: string,
+): Promise<void> {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (await condition()) return;
+ await wait(200);
+ }
+ throw new Error(`timed out after ${timeoutMs}ms waiting for ${what}`);
+}
+
+let tmpDir: string;
+
+beforeEach(async () => {
+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-conflict-authority-'));
+});
+
+afterEach(async () => {
+ await rm(tmpDir, { recursive: true, force: true });
+});
+
+async function bootWithHeldConflictedDoc(options?: {
+ extraFiles?: Record<string, string>;
+ load?: boolean;
+}): Promise<{
+ port: number;
+ serverInstance: ServerInstance;
+ destroy: () => Promise<void>;
+ release: () => Promise<void>;
+ readSource: () => string;
+}> {
+ const contentDir = tmpDir;
+ await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
+ seedOkScaffold(contentDir);
+ for (const [file, body] of Object.entries(options?.extraFiles ?? {})) {
+ const abs = resolve(contentDir, file);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, body, 'utf-8');
+ }
+ await seedRealMergeConflict(contentDir, DOC_FILE);
+ seedConflictsJson(contentDir, DOC_FILE);
+
+ const booted = await bootServer({
+ config: TEST_CONFIG,
+ contentDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ });
+
+ const dc =
+ options?.load === false
+ ? null
+ : await booted.serverInstance.hocuspocus.openDirectConnection(DOC_NAME);
+ await pollUntil(
+ () => isIndexed(booted.port, DOC_NAME),
+ 30_000,
+ 'the initial file-watcher scan to index the conflicted doc',
+ );
+ return {
+ port: booted.port,
+ serverInstance: booted.serverInstance,
+ destroy: async () => {
+ await booted.destroy();
+ },
+ release: async () => {
+ await dc?.disconnect();
+ },
+ readSource: () => dc?.document?.getText('source').toString() ?? '',
+ };
+}
+
+describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the loaded doc', () => {
+ test('ordering A — the disk event drains before HEAD moves, and the write is admitted', async () => {
+ const held = await bootWithHeldConflictedDoc();
+ try {
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).includes(DOC_FILE),
+ 20_000,
+ 'the seeded merge-native entry to be listed',
+ );
+ expect(await writeProbe(held.port, '# blocked\n')).toBe(409);
+
+ const opts = { cwd: tmpDir };
+ await execFileAsync('git', ['checkout', '--ours', '--', DOC_FILE], opts);
+ await execFileAsync('git', ['add', '--', DOC_FILE], opts);
+
+ await pollUntil(
+ () => held.readSource().includes('LOCAL') && !held.readSource().includes('<<<<<<<'),
+ 30_000,
+ 'the server to process the disk update for the resolved file',
+ );
+
+ await execFileAsync('git', ['commit', '--no-edit'], opts);
+
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).length === 0,
+ 60_000,
+ 'the conflict ledger to empty after the external resolve',
+ );
+
+ expect(await writeProbe(held.port, '# probe\n')).toBe(200);
+ } finally {
+ await held.release();
+ await held.destroy();
+ }
+ }, 180_000);
+
+ test('ordering B — resolved bytes on disk alone do not prune; completing the merge does', async () => {
+ const held = await bootWithHeldConflictedDoc();
+ try {
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).includes(DOC_FILE),
+ 20_000,
+ 'the seeded merge-native entry to be listed',
+ );
+ expect(await writeProbe(held.port, '# blocked\n')).toBe(409);
+
+ writeFileSync(resolve(tmpDir, DOC_FILE), 'line1\nLOCAL\nline3\n', 'utf-8');
+
+ await pollUntil(
+ () => held.readSource().includes('LOCAL') && !held.readSource().includes('<<<<<<<'),
+ 30_000,
+ 'the server to process the disk update for the hand-resolved file',
+ );
+
+ const opts = { cwd: tmpDir };
+ const stillUnmerged = await execFileAsync(
+ 'git',
+ ['diff', '--name-only', '--diff-filter=U'],
+ opts,
+ );
+ expect(stillUnmerged.stdout).toContain(DOC_FILE);
+ expect(await listConflictFiles(held.port)).toContain(DOC_FILE);
+ expect(await writeProbe(held.port, '# still blocked\n')).toBe(409);
+
+ await execFileAsync('git', ['add', '--', DOC_FILE], opts);
+ await execFileAsync('git', ['commit', '--no-edit'], opts);
+
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).length === 0,
+ 60_000,
+ 'the conflict ledger to empty once the merge was completed',
+ );
+
+ expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect(await writeProbe(held.port, '# probe\n')).toBe(200);
+ } finally {
+ await held.release();
+ await held.destroy();
+ }
+ }, 180_000);
+
+ test('a mid-merge `git add` with no commit heals through the disk-update path', async () => {
+ const held = await bootWithHeldConflictedDoc();
+ try {
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).includes(DOC_FILE),
+ 20_000,
+ 'the seeded merge-native entry to be listed',
+ );
+
+ const opts = { cwd: tmpDir };
+ await execFileAsync('git', ['checkout', '--ours', '--', DOC_FILE], opts);
+ await execFileAsync('git', ['add', '--', DOC_FILE], opts);
+
+ await pollUntil(
+ () => held.readSource().includes('LOCAL') && !held.readSource().includes('<<<<<<<'),
+ 30_000,
+ 'the server to process the disk update for the staged file',
+ );
+
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).length === 0,
+ 60_000,
+ 'the conflict ledger to empty from the disk-update prune',
+ );
+
+ expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(true);
+ expect(await writeProbe(held.port, '# probe\n')).toBe(200);
+ } finally {
+ await held.release();
+ await held.destroy();
+ }
+ }, 180_000);
+
+ test('a staged merge-native entry prunes for a document that was never loaded', async () => {
+ const held = await bootWithHeldConflictedDoc({ load: false });
+ try {
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).includes(DOC_FILE),
+ 20_000,
+ 'the seeded merge-native entry to be listed',
+ );
+ expect(held.serverInstance.hocuspocus.documents.has(DOC_NAME)).toBe(false);
+
+ const opts = { cwd: tmpDir };
+ await execFileAsync('git', ['checkout', '--ours', '--', DOC_FILE], opts);
+ await execFileAsync('git', ['add', '--', DOC_FILE], opts);
+
+ await pollUntil(
+ async () => (await listConflictFiles(held.port)).length === 0,
+ 60_000,
+ 'the disk-update prune to drop the entry for the unloaded doc',
+ );
+
+ expect(held.serverInstance.hocuspocus.documents.has(DOC_NAME)).toBe(false);
+ expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(true);
+ } finally {
+ await held.release();
+ await held.destroy();
+ }
+ }, 180_000);
+
+ test('a resolve over HTTP drains the stores the batch deferred, with no manual flush', async () => {
+ const held = await bootWithHeldConflictedDoc({
+ extraFiles: { [SCRATCH_FILE]: 'scratch base\n', [COLLISION_FILE]: 'overlay\n' },
+ });
+ const readScratch = () => readFileSync(resolve(tmpDir, SCRATCH_FILE), 'utf-8');
+ try {
+ await pollUntil(
+ () => isIndexed(held.port, SCRATCH_DOC),
+ 30_000,
+ 'the initial file-watcher scan to index the scratch doc',
+ );
+
+ expect(await writeDocProbe(held.port, SCRATCH_DOC, `# ${CONTROL_MARKER}\n`)).toBe(200);
+ await pollUntil(
+ () => readScratch().includes(CONTROL_MARKER),
+ 30_000,
+ 'an undeferred store to reach disk',
+ );
+
+ held.serverInstance.conflicts.raise({
+ kind: 'working-tree',
+ file: COLLISION_FILE,
+ theirsSha: '0'.repeat(40),
+ });
+
+ held.serverInstance.durabilityState.setBatchInProgress(true);
+ expect(await writeDocProbe(held.port, SCRATCH_DOC, `# ${DEFERRED_MARKER}\n`)).toBe(200);
+ expect(readScratch()).toContain(CONTROL_MARKER);
+ expect(readScratch()).not.toContain(DEFERRED_MARKER);
+
+ expect(await listConflictFiles(held.port)).toContain(COLLISION_FILE);
+ expect(await resolveConflictOverHttp(held.port, COLLISION_FILE, 'mine')).toBe(200);
+
+ await pollUntil(
+ () => readScratch().includes(DEFERRED_MARKER),
+ 30_000,
+ 'the resolve route to drain the deferred store to disk',
+ );
+ } finally {
+ await held.release();
+ await held.destroy();
+ }
+ }, 180_000);
+});
diff --git a/packages/server/src/server-factory.conflict-ledger-lifecycle.test.ts b/packages/server/src/server-factory.conflict-ledger-lifecycle.test.ts
new file mode 100644
index 000000000..d0d5c0956
--- /dev/null
+++ b/packages/server/src/server-factory.conflict-ledger-lifecycle.test.ts
@@ -0,0 +1,330 @@
+import { execFile } from 'node:child_process';
+import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { promisify } from 'node:util';
+import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { bootServer } from './boot.ts';
+import { ConfigSchema } from './config/schema.ts';
+
+const execFileAsync = promisify(execFile);
+const TEST_CONFIG = ConfigSchema.parse({});
+
+const DOC_NAME = 'notes/topic';
+const DOC_FILE = 'notes/topic.md';
+
+const MARKERED_BODY = [
+ '# Topic',
+ '',
+ '<<<<<<< ours',
+ 'ours side',
+ '=======',
+ 'theirs side',
+ '>>>>>>> theirs',
+ '',
+].join('\n');
+
+let tmpDir: string;
+
+beforeEach(async () => {
+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-conflict-ledger-'));
+});
+
+afterEach(async () => {
+ await rm(tmpDir, { recursive: true, force: true });
+});
+
+function seedOkScaffold(projectDir: string): void {
+ const okDir = resolve(projectDir, OK_DIR);
+ mkdirSync(okDir, { recursive: true });
+ writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');
+ writeFileSync(resolve(okDir, '.gitignore'), 'local/\n', 'utf-8');
+}
+
+function seedMergeNativeConflictsJson(projectDir: string, file: string): void {
+ const localDir = resolve(projectDir, OK_DIR, 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(
+ resolve(localDir, 'conflicts.json'),
+ JSON.stringify({
+ version: 1,
+ branch: 'main',
+ conflicts: [{ kind: 'merge-native', file, detectedAt: '2026-05-19T00:00:00.000Z' }],
+ }),
+ 'utf-8',
+ );
+}
+
+async function isIndexed(port: number, docName: string): Promise<boolean> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/documents`).catch(() => null);
+ if (!res?.ok) return false;
+ const data = (await res.json()) as { documents?: Array<{ docName: string }> };
+ return data.documents?.some((d) => d.docName === docName) ?? false;
+}
+
+async function listConflictFiles(port: number): Promise<string[]> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`).catch(() => null);
+ if (!res?.ok) return [];
+ const data = (await res.json()) as { conflicts?: Array<{ file: string }> };
+ return (data.conflicts ?? []).map((c) => c.file);
+}
+
+async function writeProbe(
+ port: number,
+ markdown: string,
+ docName: string = DOC_NAME,
+): Promise<number> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, markdown, position: 'replace', agentId: 'probe' }),
+ });
+ return res.status;
+}
+
+async function pollUntil(
+ condition: () => boolean | Promise<boolean>,
+ timeoutMs: number,
+ what: string,
+): Promise<void> {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (await condition()) return;
+ await wait(200);
+ }
+ throw new Error(`timed out after ${timeoutMs}ms waiting for ${what}`);
+}
+
+function seedReconcileConflictsJson(projectDir: string, file: string): void {
+ const localDir = resolve(projectDir, OK_DIR, 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(
+ resolve(localDir, 'conflicts.json'),
+ JSON.stringify({
+ version: 1,
+ branch: 'main',
+ conflicts: [
+ {
+ kind: 'reconcile',
+ file,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ reason: 'disk-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ },
+ ],
+ }),
+ 'utf-8',
+ );
+}
+
+async function bootPlainProject(seed: (contentDir: string) => void): Promise<{
+ port: number;
+ destroy: () => Promise<void>;
+}> {
+ const contentDir = tmpDir;
+ await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
+ seedOkScaffold(contentDir);
+ seed(contentDir);
+ const booted = await bootServer({
+ config: TEST_CONFIG,
+ contentDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ });
+ return {
+ port: booted.port,
+ destroy: async () => {
+ await booted.destroy();
+ },
+ };
+}
+
+describe('conflict ledger boot prune runs independently of the sync engine', () => {
+ test('a stale merge-native entry is gone at boot with sync off and no MERGE_HEAD', async () => {
+ const booted = await bootPlainProject((contentDir) => {
+ mkdirSync(resolve(contentDir, 'notes'), { recursive: true });
+ writeFileSync(resolve(contentDir, DOC_FILE), 'line1\n', 'utf-8');
+ seedMergeNativeConflictsJson(contentDir, DOC_FILE);
+ });
+ try {
+ await pollUntil(
+ () => isIndexed(booted.port, DOC_NAME),
+ 30_000,
+ 'the initial file-watcher scan to index the doc',
+ );
+ expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect(await listConflictFiles(booted.port)).toEqual([]);
+ expect(await writeProbe(booted.port, '# probe\n')).toBe(200);
+ } finally {
+ await booted.destroy();
+ }
+ }, 120_000);
+
+ test('a mixed ledger keeps the working-tree and reconcile entries and drops only merge-native', async () => {
+ const trackedFile = 'notes/tracked.md';
+ const trackedDoc = 'notes/tracked';
+ const reconcileFile = 'notes/local.md';
+
+ await execFileAsync('git', ['init', '--initial-branch=main', tmpDir]);
+ seedOkScaffold(tmpDir);
+ mkdirSync(resolve(tmpDir, 'notes'), { recursive: true });
+ writeFileSync(resolve(tmpDir, DOC_FILE), 'line1\n', 'utf-8');
+ writeFileSync(resolve(tmpDir, trackedFile), 'tracked local\n', 'utf-8');
+ writeFileSync(resolve(tmpDir, reconcileFile), MARKERED_BODY, 'utf-8');
+
+ const theirsSha = (
+ await execFileAsync('git', ['hash-object', '-w', trackedFile], { cwd: tmpDir })
+ ).stdout.trim();
+ expect(theirsSha).toMatch(/^[0-9a-f]{40}$/);
+
+ const localDir = resolve(tmpDir, OK_DIR, 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(
+ resolve(localDir, 'conflicts.json'),
+ JSON.stringify({
+ version: 1,
+ branch: 'main',
+ conflicts: [
+ { kind: 'merge-native', file: DOC_FILE, detectedAt: '2026-05-19T00:00:00.000Z' },
+ {
+ kind: 'working-tree',
+ file: trackedFile,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ theirsSha,
+ },
+ {
+ kind: 'reconcile',
+ file: reconcileFile,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ reason: 'disk-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: 'THEIRS\n' },
+ },
+ ],
+ }),
+ 'utf-8',
+ );
+
+ const booted = await bootServer({
+ config: TEST_CONFIG,
+ contentDir: tmpDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ });
+ try {
+ await pollUntil(
+ () => isIndexed(booted.port, trackedDoc),
+ 30_000,
+ 'the initial file-watcher scan to index the tracked doc',
+ );
+ expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect((await listConflictFiles(booted.port)).sort()).toEqual(
+ [trackedFile, reconcileFile].sort(),
+ );
+ expect(await writeProbe(booted.port, '# blocked\n', trackedDoc)).toBe(409);
+ expect(await writeProbe(booted.port, '# probe\n')).toBe(200);
+ } finally {
+ await booted.destroy();
+ }
+ }, 120_000);
+});
+
+describe('a reconcile entry scoped to another branch does not survive a boot here', () => {
+ test('the entry is gone at boot and the doc is writable again', async () => {
+ const booted = await bootPlainProject((contentDir) => {
+ mkdirSync(resolve(contentDir, 'notes'), { recursive: true });
+ writeFileSync(resolve(contentDir, DOC_FILE), MARKERED_BODY, 'utf-8');
+ const localDir = resolve(contentDir, OK_DIR, 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(
+ resolve(localDir, 'conflicts.json'),
+ JSON.stringify({
+ version: 2,
+ branch: 'feature/elsewhere',
+ conflicts: [
+ {
+ kind: 'reconcile',
+ file: DOC_FILE,
+ detectedAt: '2026-05-19T00:00:00.000Z',
+ branch: 'feature/elsewhere',
+ reason: 'disk-markers',
+ stages: { base: 'BASE\n', ours: 'OURS\n', theirs: MARKERED_BODY },
+ },
+ ],
+ }),
+ 'utf-8',
+ );
+ });
+ try {
+ await pollUntil(
+ () => isIndexed(booted.port, DOC_NAME),
+ 30_000,
+ 'the initial file-watcher scan to index the doc',
+ );
+ expect(await listConflictFiles(booted.port)).toEqual([]);
+ expect(await writeProbe(booted.port, '# probe\n')).toBe(200);
+ } finally {
+ await booted.destroy();
+ }
+ }, 120_000);
+});
+
+describe('a disk delete or rename of a conflicted doc clears its ledger entry', () => {
+ test('deleting the file on disk dissolves the reconcile entry', async () => {
+ const booted = await bootPlainProject((contentDir) => {
+ mkdirSync(resolve(contentDir, 'notes'), { recursive: true });
+ writeFileSync(resolve(contentDir, DOC_FILE), MARKERED_BODY, 'utf-8');
+ seedReconcileConflictsJson(contentDir, DOC_FILE);
+ });
+ try {
+ await pollUntil(
+ () => isIndexed(booted.port, DOC_NAME),
+ 30_000,
+ 'the initial file-watcher scan to index the conflicted doc',
+ );
+ expect(await listConflictFiles(booted.port)).toEqual([DOC_FILE]);
+
+ rmSync(resolve(tmpDir, DOC_FILE), { force: true });
+
+ await pollUntil(
+ async () => (await listConflictFiles(booted.port)).length === 0,
+ 60_000,
+ 'the reconcile entry to dissolve after the disk delete',
+ );
+ } finally {
+ await booted.destroy();
+ }
+ }, 120_000);
+
+ test('renaming the file on disk dissolves the reconcile entry for the old path', async () => {
+ const booted = await bootPlainProject((contentDir) => {
+ mkdirSync(resolve(contentDir, 'notes'), { recursive: true });
+ writeFileSync(resolve(contentDir, DOC_FILE), MARKERED_BODY, 'utf-8');
+ seedReconcileConflictsJson(contentDir, DOC_FILE);
+ });
+ try {
+ await pollUntil(
+ () => isIndexed(booted.port, DOC_NAME),
+ 30_000,
+ 'the initial file-watcher scan to index the conflicted doc',
+ );
+ expect(await listConflictFiles(booted.port)).toEqual([DOC_FILE]);
+
+ renameSync(resolve(tmpDir, DOC_FILE), resolve(tmpDir, 'notes', 'moved.md'));
+
+ await pollUntil(
+ async () => (await listConflictFiles(booted.port)).length === 0,
+ 60_000,
+ 'the reconcile entry to dissolve after the disk rename',
+ );
+ } finally {
+ await booted.destroy();
+ }
+ }, 120_000);
+});
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index cc200b1b1..3f554afa8 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -4075,8 +4075,11 @@ describe('createServer() — generated index wiring', () => {
branch: 'main',
conflicts: [
{
+ kind: 'reconcile',
file: 'content/concepts/index.md',
detectedAt: '2026-08-07T00:00:00.000Z',
+ reason: 'disk-markers',
+ stages: { base: '', ours: '', theirs: conflicted },
},
],
}),
@@ -4087,8 +4090,8 @@ describe('createServer() — generated index wiring', () => {
const logCapture = captureAllLoggers();
await bootServer();
expect(server?.hocuspocus.documents.has('concepts/index')).toBe(false);
- expect(server?.syncEngine?.getConflicts()).toEqual([
- expect.objectContaining({ file: 'content/concepts/index.md' }),
+ expect(server?.conflicts.list()).toEqual([
+ expect.objectContaining({ kind: 'reconcile', file: 'content/concepts/index.md' }),
]);
writeFileSync(
@@ -4110,8 +4113,8 @@ describe('createServer() — generated index wiring', () => {
expect(readIndexAt('concepts')).toBe(conflicted);
expect(statSync(indexPathAt('concepts')).mtimeMs).toBe(conflictedMtime);
- await server?.syncEngine?.reconcileConflictsFromGit();
- expect(server?.syncEngine?.getConflicts()).toEqual([]);
+ server?.conflicts.dissolveReconcile('concepts/index');
+ expect(server?.conflicts.list()).toEqual([]);
writeDoc('concepts/second.md', 'Second', 'concept');
await waitForIndexAt(
'concepts',
@@ -4145,8 +4148,10 @@ describe('createServer() — generated index wiring', () => {
await vi.waitFor(
() => {
- expect(document?.getMap('lifecycle').get('status')).toBe('conflict');
- expect(document?.getMap('lifecycle').get('reason')).toBe('conflict-markers');
+ expect(server?.conflicts.findByDocName('concepts/index')).toMatchObject({
+ kind: 'reconcile',
+ reason: 'disk-markers',
+ });
},
{ timeout: 20_000, interval: 50 },
);
@@ -4187,14 +4192,15 @@ describe('createServer() — generated index wiring', () => {
expect(readIndexAt('concepts')).toBe(conflicted);
expect(document?.getText('source').toString()).toBe(canonical);
- expect(document?.getMap('lifecycle').get('status')).toBe('conflict');
- expect(document?.getMap('lifecycle').get('reason')).toBe('conflict-markers');
+ expect(server?.conflicts.findByDocName('concepts/index')).toMatchObject({
+ kind: 'reconcile',
+ reason: 'disk-markers',
+ });
writeFileSync(indexPathAt('concepts'), canonical, 'utf-8');
await vi.waitFor(
() => {
- expect(document?.getMap('lifecycle').get('status')).toBeUndefined();
- expect(document?.getMap('lifecycle').get('reason')).toBeUndefined();
+ expect(server?.conflicts.findByDocName('concepts/index')).toBeUndefined();
},
{ timeout: 20_000, interval: 50 },
);
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 47158d6d8..2343adc54 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -40,7 +40,6 @@ import {
resolveLocalAutoSyncMode,
type SyncMode,
type SyncModeChangeSource,
- stripFrontmatter,
toEffectiveBase,
} from '@inkeep/open-knowledge-core';
import {
@@ -72,7 +71,6 @@ 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,
@@ -92,13 +90,7 @@ import {
startMultiPathConfigFileWatcher,
} from './config-file-watcher.ts';
import { applyExternalConfigChange, isConfigEcho } from './config-persistence.ts';
-import { isDocInConflict } from './conflict-errors.ts';
-import {
- createConflictLifecycleSeedExtension,
- entryMatchesDocName,
-} from './conflict-lifecycle-seed.ts';
-import { requireConflictResolutionContent } from './conflict-resolution-input.ts';
-import type { ResolveStrategy } from './conflict-storage.ts';
+import { bindConflictAuthority, ConflictAuthority } from './conflict-authority.ts';
import { type GeneratedArtifactEnv, writeGeneratedArtifact } from './content/generated-artifact.ts';
import {
type GeneratedIndexGitAttributesStatus,
@@ -116,11 +108,7 @@ import {
planDirectoryIndexRegenerations,
ROOT_INDEX_DOC_NAME,
} from './content/regenerate-index.ts';
-import {
- type ContentFilter,
- createContentFilter,
- isShareableOkArtifact,
-} from './content-filter.ts';
+import { type ContentFilter, createContentFilter } from './content-filter.ts';
import { isWithinContentDir, safeContentPath } from './content-path.ts';
import { dropPendingDocs, recordContributor } from './contributor-tracker.ts';
import {
@@ -133,7 +121,6 @@ import {
docNameToRelativePath,
getDocExtension,
isRegisteredMarkdownDocName,
- stripDocExtension,
} from './doc-extensions.ts';
import { runDocLineageGuard } from './doc-lineage-guard.ts';
import { DocumentDurabilityState } from './document-durability-state.ts';
@@ -165,8 +152,14 @@ import {
startWatcher,
type WatcherHandle,
} from './file-watcher.ts';
-import { normalizeFsPath, tracedAtomicFs, tracedMkdirSync, tracedUnlinkSync } from './fs-traced.ts';
-import { buildSyncCredentialConfig } from './git-handle.ts';
+import {
+ normalizeFsPath,
+ tracedAtomicFs,
+ tracedMkdirSync,
+ tracedUnlinkSync,
+ tracedWriteFileSync,
+} from './fs-traced.ts';
+import { buildSyncCredentialConfig, createGitInstance } from './git-handle.ts';
import type {
CheckPushPermissionOptions,
DetectGhAccountsFn,
@@ -273,7 +266,6 @@ 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';
@@ -367,6 +359,7 @@ export interface ServerInstance {
readonly degraded: readonly string[];
readonly lockDir: string;
readonly syncEngine: SyncEngine | null;
+ readonly conflicts: ConflictAuthority;
readonly getLinkPreviewsEnabled: () => boolean;
readonly resolveEmbed: (basename: string, sourcePath: string) => string | null;
readonly acpRegistry: AcpRegistry;
@@ -489,10 +482,14 @@ export function createServer(options: ServerOptions): ServerInstance {
} = options;
const log = getLogger('server');
- const lockDir = getLocalDir(projectDir);
- const durabilityState = new DocumentDurabilityState('main', {
- persistencePath: join(lockDir, 'stale-external-writes.json'),
- onStaleExternalWriteChange: () => signalChannel('sync-status'),
+ let cc1Broadcaster: CC1Broadcaster | null = null;
+ const initialBranch = readProjectHeadState(projectDir).branch ?? 'main';
+ const durabilityState = new DocumentDurabilityState(initialBranch, {
+ persistencePath: join(getLocalDir(projectDir), 'stale-external-writes.json'),
+ onStaleExternalWriteChange: () => {
+ cc1Broadcaster?.signal('sync-status');
+ hydrateStaleExternalWrites();
+ },
fileForDocName: (docName) =>
relative(projectDir, safeContentPath(docName, contentDir)).replaceAll('\\', '/'),
hasResolvedExtension: isRegisteredMarkdownDocName,
@@ -505,8 +502,82 @@ export function createServer(options: ServerOptions): ServerInstance {
const switchReconciledBaseScope = (branch: string) =>
durabilityState.switchReconciledBaseScope(branch);
const setBatchInProgress = (value: boolean) => durabilityState.setBatchInProgress(value);
+ const setBatchInProgressAndDrain = (value: boolean) => {
+ setBatchInProgress(value);
+ if (!value) {
+ void persistence.flushDeferredStores('within-branch').catch((err) => {
+ log.error({ err }, '[persistence] deferred store drain failed after batch');
+ });
+ }
+ };
const isBatchInProgress = () => durabilityState.isBatchInProgress();
+ const conflicts = new ConflictAuthority({
+ projectDir,
+ contentDir,
+ branch: initialBranch,
+ signal: { signal: (channel) => cc1Broadcaster?.signal(channel) },
+ io: {
+ gitRaw: async (args) =>
+ createGitInstance(projectDir, { credentialConfig: [], timeoutMs: 30_000 }).git.raw(args),
+ writeProjectFileUntracked: (absPath, bytes) => tracedWriteFileSync(absPath, bytes, 'utf-8'),
+ unlinkProjectFile: (absPath) => tracedUnlinkSync(absPath),
+ applyResolvedContent: async (docName, absPath, bytes) => {
+ registerWrite(absPath, contentHash(bytes));
+ await atomicWriteFile(absPath, bytes, { fs: tracedAtomicFs });
+ if (hocuspocus.documents.get(docName)) applyToDoc(docName, bytes);
+ setReconciledBase(docName, bytes);
+ await derivedDocumentIndex.recordDiskUpsert(docName, bytes);
+ },
+ readLiveContent: (docName) => serializeDoc(docName),
+ finalizeReconcileResolution: async (entry, strategy, docName) => {
+ if (entry.reason === 'stale-external-write') {
+ if (strategy === 'mine' || strategy === 'content') {
+ durabilityState.recordDisplacedVersion(docName, entry.stages.theirs);
+ } else {
+ durabilityState.clearDisplacedVersions(docName);
+ }
+ durabilityState.clearStaleExternalWrite(docName);
+ }
+ const document = hocuspocus.documents.get(docName);
+ const lifecycle = document?.getMap('lifecycle');
+ if (strategy === 'delete') {
+ deleteReconciledBase(docName);
+ await derivedDocumentIndex.recordDiskDelete(docName);
+ lifecycle?.set('status', 'deleted-upstream');
+ lifecycle?.delete('reason');
+ lifecycle?.delete('detectedAt');
+ if (document) hocuspocus.closeConnections(docName);
+ onUpstreamDelete(docName);
+ scheduleIndexRegenerationAfterRemoval(docName);
+ } else if (lifecycle?.get('reason') === entry.reason) {
+ lifecycle.delete('status');
+ lifecycle.delete('reason');
+ lifecycle.delete('detectedAt');
+ }
+ signalChannel('files');
+ },
+ },
+ });
+
+ function hydrateStaleExternalWrites(): void {
+ for (const stale of durabilityState.listStaleExternalWrites()) {
+ const base = getReconciledBase(stale.docName) ?? stale.diskContent;
+ conflicts.raise({
+ kind: 'reconcile',
+ file: stale.file,
+ reason: 'stale-external-write',
+ detectedAt: stale.detectedAt,
+ stages: {
+ base,
+ ours: stale.retainedContent ?? base,
+ theirs: stale.diskContent,
+ },
+ });
+ }
+ }
+ hydrateStaleExternalWrites();
+
function readProjectAttachmentFolderPath(options?: { requireValid?: boolean }): string {
const project = readConfigSafely({
absPath: resolveConfigPath('project', projectDir),
@@ -759,6 +830,8 @@ export function createServer(options: ServerOptions): ServerInstance {
const serverInstanceId = randomUUID();
+ const lockDir = getLocalDir(projectDir);
+
const acpRegistry = new AcpRegistry({
localDir: lockDir,
log: getLogger('acp-registry'),
@@ -820,7 +893,6 @@ export function createServer(options: ServerOptions): ServerInstance {
let nativeApi: NativeApiHandle;
let localApi: LocalApiDispatch;
let bridgeLossReporter: BridgeDeriveLossReporter | undefined;
- let cc1Broadcaster: CC1Broadcaster | null = null;
let inPlaceRescanTimer: ReturnType<typeof setTimeout> | null = null;
let shadowWarmupTimer: ReturnType<typeof setTimeout> | null = null;
const IN_PLACE_RESCAN_DEBOUNCE_MS = 500;
@@ -904,7 +976,6 @@ export function createServer(options: ServerOptions): ServerInstance {
| 'tags'
| 'comments'
| 'lint-config'
- | 'sync-status'
| 'local-targets',
): void {
cc1Broadcaster?.signal(channel);
@@ -1193,10 +1264,7 @@ export function createServer(options: ServerOptions): ServerInstance {
const generatedArtifactEnv: GeneratedArtifactEnv = {
origin: GENERATED_ARTIFACT_ORIGIN,
writer: OK_GENERATOR_WRITER,
- isConflict: (docName) =>
- syncEngine
- ?.getConflicts()
- .some((entry) => entryMatchesDocName(entry, docName, projectDir, contentDir)) === true,
+ isConflict: (docName) => conflicts.has(docName),
getDocument: (docName) => hocuspocus.documents.get(docName),
writeDisk: async (absPath, markdown) => {
tracedMkdirSync(dirname(absPath), { recursive: true });
@@ -1598,6 +1666,8 @@ export function createServer(options: ServerOptions): ServerInstance {
const persistenceOpts: PersistenceOptions = {
contentDir,
projectDir,
+ conflicts,
+ lifecycleOf: (document, docName) => conflicts.lifecycleOf(document, docName),
gitEnabled,
commitDebounceMs,
wipRef,
@@ -1681,6 +1751,7 @@ export function createServer(options: ServerOptions): ServerInstance {
if (!ephemeral) {
stalenessWatchdog = createPersistenceStalenessWatchdog({
getLoadedDocuments: () => hp.documents,
+ lifecycleOf: (document, documentName) => conflicts.lifecycleOf(document, documentName),
forceStore: (document, documentName) => persistence.forceStore(document, documentName),
getBase: (documentName) => durabilityState.getReconciledBase(documentName),
isBatchActive: () => durabilityState.isBatchInProgress(),
@@ -1981,6 +2052,8 @@ export function createServer(options: ServerOptions): ServerInstance {
agentPresenceBroadcaster,
onAgentWrite: options.onAgentWrite,
getSyncEngine: () => syncEngine,
+ conflicts,
+ setBatchInProgress: setBatchInProgressAndDrain,
localOpCliArgs,
authStreamHeartbeatMs,
projectDir,
@@ -1992,84 +2065,9 @@ 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);
},
@@ -2136,13 +2134,11 @@ export function createServer(options: ServerOptions): ServerInstance {
hocuspocus.configuration.extensions.push(createSyncHandshakeSpanExtension());
- hocuspocus.configuration.extensions.push(
- createConflictLifecycleSeedExtension({
- getSyncEngine: () => syncEngine,
- projectDir,
- contentDir,
- }),
- );
+ hocuspocus.configuration.extensions.push({
+ async afterLoadDocument({ document }) {
+ bindConflictAuthority(document, conflicts);
+ },
+ });
} catch (err) {
for (const unregister of unregisterWorkloadProviders.splice(0)) {
unregister();
@@ -2178,7 +2174,7 @@ export function createServer(options: ServerOptions): ServerInstance {
return serializeYDocSource(document);
}
- function applyToDoc(docName: string, content: string, precomputed?: PrecomputedParse): void {
+ const applyToDoc = (docName: string, content: string): void =>
applyExternalChange(
durabilityState,
hocuspocus,
@@ -2187,23 +2183,7 @@ export function createServer(options: ServerOptions): ServerInstance {
resolveEmbed,
resolveSize,
bridgeLossReporter,
- precomputed,
);
- }
-
- function clearLifecycleConflict(document: Document): void {
- if (!isDocInConflict(document)) return;
- if (
- syncEngine
- ?.getConflicts()
- .some((entry) => entryMatchesDocName(entry, document.name, projectDir, contentDir))
- ) {
- return;
- }
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.delete('status');
- lifecycleMap.delete('reason');
- }
const rerenderDocsReferencingAssetBasename = (assetBasename: string): void => {
if (!assetBasename) return;
@@ -2298,6 +2278,11 @@ export function createServer(options: ServerOptions): ServerInstance {
return isDirty;
};
+ function dissolveNonGitConflicts(docName: string): void {
+ conflicts.dissolveReconcile(docName);
+ conflicts.dissolveWorkingTree(conflicts.fileOf(docName));
+ }
+
async function handleDiskEvent(event: DiskEvent): Promise<void> {
try {
switch (event.kind) {
@@ -2315,22 +2300,31 @@ export function createServer(options: ServerOptions): ServerInstance {
if (indexedMetadataChanged(event.previousIndexedFields, theirs, docName)) {
scheduleIndexRegeneration(docName);
}
+ if (conflicts.findByDocName(docName)?.kind === 'merge-native') {
+ try {
+ await conflicts.pruneMergeNativeAgainstGit();
+ } catch (err) {
+ log.warn({ err, docName }, '[reconcile] conflict prune against git failed');
+ }
+ }
+
const document = hocuspocus.documents.get(docName);
if (!document) {
- if (refuseStaleExternalWrite(durabilityState, undefined, docName, theirs)) {
- return;
- }
+ refuseStaleExternalWrite(durabilityState, undefined, docName, theirs, conflicts);
await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
return;
}
- if (refuseStaleExternalWrite(durabilityState, document, docName, theirs)) {
- break;
- }
-
const base = getReconciledBase(docName) ?? '';
const ours = serializeDoc(docName) ?? base;
+ if (
+ refuseStaleExternalWrite(durabilityState, document, docName, theirs, conflicts, ours)
+ ) {
+ await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
+ return;
+ }
+
const result = reconcile({ docName, base, ours, theirs });
const baseH = contentHash(base).slice(0, 6);
@@ -2343,7 +2337,7 @@ export function createServer(options: ServerOptions): ServerInstance {
switch (result.kind) {
case 'noop':
- clearLifecycleConflict(document);
+ conflicts.dissolveReconcile(docName);
await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
break;
@@ -2354,7 +2348,7 @@ export function createServer(options: ServerOptions): ServerInstance {
applyToDoc(docName, result.newContent);
setReconciledBase(docName, result.newContent);
incrementReconcile();
- clearLifecycleConflict(document);
+ conflicts.dissolveReconcile(docName);
applied = true;
} catch (e) {
log.error(
@@ -2362,7 +2356,7 @@ export function createServer(options: ServerOptions): ServerInstance {
`[reconcile] failed to apply clean content to Y.Doc for ${docName}`,
);
setReconciledBase(docName, theirs);
- clearLifecycleConflict(document);
+ conflicts.dissolveReconcile(docName);
}
if (applied) {
await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
@@ -2377,7 +2371,7 @@ export function createServer(options: ServerOptions): ServerInstance {
applyToDoc(docName, result.newContent);
setReconciledBase(docName, theirs);
incrementReconcile();
- clearLifecycleConflict(document);
+ conflicts.dissolveReconcile(docName);
applied = true;
} catch (e) {
log.error(
@@ -2385,7 +2379,7 @@ export function createServer(options: ServerOptions): ServerInstance {
`[reconcile] failed to apply merged content to Y.Doc for ${docName}`,
);
setReconciledBase(docName, theirs);
- clearLifecycleConflict(document);
+ conflicts.dissolveReconcile(docName);
}
if (applied) {
await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
@@ -2408,11 +2402,12 @@ export function createServer(options: ServerOptions): ServerInstance {
);
setReconciledBase(docName, theirs);
}
- {
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'merged-with-markers');
- }
+ conflicts.raise({
+ kind: 'reconcile',
+ file: conflicts.fileOf(docName),
+ reason: 'merged-with-markers',
+ stages: { base, ours, theirs },
+ });
if (applied) {
await derivedDocumentIndex.recordDiskUpsert(docName, theirs);
}
@@ -2421,9 +2416,13 @@ export function createServer(options: ServerOptions): ServerInstance {
case 'refused': {
incrementConflict();
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', result.reason);
+ conflicts.raise({
+ kind: 'reconcile',
+ file: conflicts.fileOf(docName),
+ reason:
+ result.reason === 'too-large' ? 'refused-too-large' : 'refused-conflict-markers',
+ stages: { base, ours, theirs },
+ });
break;
}
}
@@ -2432,6 +2431,7 @@ export function createServer(options: ServerOptions): ServerInstance {
case 'delete': {
const { docName } = event;
+ dissolveNonGitConflicts(docName);
const document = hocuspocus.documents.get(docName);
if (!document) {
deleteReconciledBase(docName);
@@ -2481,6 +2481,7 @@ export function createServer(options: ServerOptions): ServerInstance {
case 'rename': {
const { oldDocName, newDocName, content } = event;
+ dissolveNonGitConflicts(oldDocName);
const freezeAsRenamed = (doc: Document): void => {
const lifecycleMap = doc.getMap('lifecycle');
lifecycleMap.set('status', 'renamed');
@@ -2565,6 +2566,7 @@ export function createServer(options: ServerOptions): ServerInstance {
const document = hocuspocus.documents.get(docName);
if (!document) return;
+ const priorBase = getReconciledBase(docName) ?? '';
const ours = serializeDoc(docName);
if (ours !== null) {
setReconciledBase(docName, ours);
@@ -2575,9 +2577,12 @@ export function createServer(options: ServerOptions): ServerInstance {
);
}
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'conflict-markers');
+ conflicts.raise({
+ kind: 'reconcile',
+ file: conflicts.fileOf(docName),
+ reason: 'disk-markers',
+ stages: { base: priorBase, ours: ours ?? priorBase, theirs: event.content },
+ });
log.info({ docName }, `[reconcile] conflict markers detected: ${docName}`);
break;
}
@@ -3728,12 +3733,10 @@ export function createServer(options: ServerOptions): ServerInstance {
}
}
await persistence.flushDeferredStores('within-branch');
- if (syncEngine !== null) {
- try {
- await syncEngine.reconcileConflictsFromGit();
- } catch (err) {
- log.warn({ err }, '[head-watcher] sync engine conflict reconcile failed');
- }
+ try {
+ await conflicts.pruneMergeNativeAgainstGit();
+ } catch (err) {
+ log.warn({ err }, '[head-watcher] conflict prune against git failed');
}
} else {
incrementBranchSwitch();
@@ -3742,6 +3745,8 @@ export function createServer(options: ServerOptions): ServerInstance {
let branchTransition: DerivedDocumentIndexBranchTransition | undefined;
try {
switchReconciledBaseScope(newBranch);
+ conflicts.setBranch(newBranch);
+ hydrateStaleExternalWrites();
branchTransition = await derivedDocumentIndex.beginBranchSwitch(newBranch);
contentFilter.rebuildDirCount();
@@ -3852,14 +3857,16 @@ export function createServer(options: ServerOptions): ServerInstance {
setReconciledBase(docName, outcome.newContent);
incrementConflict();
restoredCount++;
- {
- const restoredDoc = hocuspocus.documents.get(docName);
- if (restoredDoc) {
- const lifecycleMap = restoredDoc.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'merged-with-markers');
- }
- }
+ conflicts.raise({
+ kind: 'reconcile',
+ file: conflicts.fileOf(docName),
+ reason: 'merged-with-markers',
+ stages: {
+ base: parked.diskSnapshot,
+ ours: parked.markdown,
+ theirs: currentDisk,
+ },
+ });
break;
}
case 'noop':
@@ -3952,48 +3959,27 @@ export function createServer(options: ServerOptions): ServerInstance {
degraded.push('head-watcher');
}
- function markLoadedContentConflicts(files: string[]): void {
- for (const file of files) {
- try {
- const absPath = join(projectDir, file);
- const contentRelPath = toPosix(relative(contentDir, absPath));
- if (contentRelPath.startsWith('..')) continue;
- const docName = stripDocExtension(contentRelPath);
- const document = hocuspocus.documents.get(docName);
- if (!document) continue;
-
- const ours = serializeDoc(docName);
- if (ours !== null) {
- setReconciledBase(docName, ours);
- } else {
- log.warn(
- { docName, file },
- '[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped',
- );
- }
-
- const lifecycleMap = document.getMap('lifecycle');
- lifecycleMap.set('status', 'conflict');
- lifecycleMap.set('reason', 'sync-merge-conflict');
- log.info({ docName, file }, '[sync] marked loaded content conflict');
- } catch (err) {
- log.warn({ err, file }, '[sync] failed to mark loaded content conflict');
- }
+ conflicts.subscribe((change) => {
+ if (change.type !== 'raised') return;
+ if (change.conflict.kind === 'reconcile') return;
+ const docName = change.docName;
+ if (docName === null) return;
+ if (!hocuspocus.documents.get(docName)) return;
+ const ours = serializeDoc(docName);
+ if (ours !== null) {
+ setReconciledBase(docName, ours);
+ } else {
+ log.warn(
+ { docName, file: change.conflict.file },
+ '[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped',
+ );
}
- }
+ });
- function clearLoadedContentConflicts(files: string[]): void {
- for (const file of files) {
- try {
- const absPath = join(projectDir, file);
- const contentRelPath = toPosix(relative(contentDir, absPath));
- if (contentRelPath.startsWith('..')) continue;
- const document = hocuspocus.documents.get(stripDocExtension(contentRelPath));
- if (document) clearLifecycleConflict(document);
- } catch (err) {
- log.warn({ err, file }, '[sync] failed to clear resolved content conflict');
- }
- }
+ try {
+ await conflicts.pruneMergeNativeAgainstGit();
+ } catch (err) {
+ log.warn({ err }, '[conflicts] boot prune of merge-native entries failed');
}
const resetAmbientCredentials = shouldResetAmbientCredentials(projectDir);
@@ -4026,23 +4012,15 @@ export function createServer(options: ServerOptions): ServerInstance {
options.pushIntervalSeconds ?? bootAutoSyncIntervals.pushIntervalSeconds,
credentialConfig: syncCredentialConfig,
cc1Broadcaster,
+ conflicts,
detectGh: options.detectGh,
detectGhAccounts: options.detectGhAccounts,
tokenStore: options.tokenStore,
checkPushPermissionFn: options.checkPushPermissionFn,
- setBatchInProgress: (value) => {
- setBatchInProgress(value);
- if (!value) {
- void persistence.flushDeferredStores('within-branch').catch((err) => {
- log.error({ err }, '[persistence] deferred store drain failed after sync batch');
- });
- }
- },
+ setBatchInProgress: setBatchInProgressAndDrain,
onStateChange: (state) => {
log.info({ state }, `[sync] state → ${state}`);
},
- onContentConflictsDetected: markLoadedContentConflicts,
- onContentConflictsResolved: clearLoadedContentConflicts,
checkpointBeforeStrandedConversion: async ({ branch, ahead }) => {
const shadow = shadowRef.current;
if (!shadow) return;
@@ -4136,6 +4114,7 @@ export function createServer(options: ServerOptions): ServerInstance {
get syncEngine() {
return syncEngine;
},
+ conflicts,
getLinkPreviewsEnabled: readLinkPreviewsEnabled,
resolveEmbed,
acpRegistry,
diff --git a/packages/server/src/services/file-ops.ts b/packages/server/src/services/file-ops.ts
index fef91bcbf..b6e956cef 100644
--- a/packages/server/src/services/file-ops.ts
+++ b/packages/server/src/services/file-ops.ts
@@ -57,8 +57,7 @@ export interface FileOpsDeps {
path: string,
) => string[];
getFileIndex: () => ReadonlyMap<string, unknown>;
- getConflictedFiles: () => ReadonlySet<string>;
- isDocNameInLifecycleConflict: (docName: string) => boolean;
+ conflictFileForDocName: (docName: string) => string | null;
captureAndCloseDocuments: (docNames: string[], reason: 'deleted-upstream') => Promise<unknown>;
markRecentlyRemoved?: (docName: string) => void;
mutateFileIndexDelete?: (args: { path: string; docName: string }) => void;
@@ -145,12 +144,9 @@ export function createFileOpsService(deps: FileOpsDeps): FileOpsService {
}
function findConflictedFile(docNames: string[]): string | null {
- const conflictedFiles = deps.getConflictedFiles();
for (const docName of docNames) {
- const filePath = deps.docNameToRelativePath(docName);
- if (deps.isDocNameInLifecycleConflict(docName) || conflictedFiles.has(filePath)) {
- return filePath;
- }
+ const file = deps.conflictFileForDocName(docName);
+ if (file !== null) return file;
}
return null;
}
diff --git a/packages/server/src/stale-external-write-gate.test.ts b/packages/server/src/stale-external-write-gate.test.ts
index 033ad6cb1..e2ac3d311 100644
--- a/packages/server/src/stale-external-write-gate.test.ts
+++ b/packages/server/src/stale-external-write-gate.test.ts
@@ -4,9 +4,13 @@ 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 { ConflictAuthority } from './conflict-authority.ts';
import { DISPLACED_VERSION_TTL_MS, DocumentDurabilityState } from './document-durability-state.ts';
-import { reconcileDiskBeforeAgentWrite, refuseStaleExternalWrite } from './external-change.ts';
+import {
+ reconcileDiskBeforeAgentWrite,
+ refuseStaleExternalWrite,
+ serializeYDocSource,
+} from './external-change.ts';
import { getMetrics } from './metrics.ts';
import { createPersistenceExtension } from './persistence.ts';
@@ -96,8 +100,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
);
expect(result.reconciled).toBe(false);
- expect(isDocInConflict(document as never)).toBe(true);
- expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeDefined();
expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
refuseStaleExternalWrite(durabilityState, document, docName, STALE_CONTENT);
@@ -108,6 +111,58 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
expect(after.bridgeMergeContentLoss).toBe(before.bridgeMergeContentLoss);
});
+ test('captures live document bytes before stale-write hydration raises the conflict', () => {
+ const liveContent = `${ACKNOWLEDGED_CONTENT}\nnext live edit\n`;
+ let authority: ConflictAuthority;
+ durabilityState = new DocumentDurabilityState('main', {
+ onStaleExternalWriteChange: () => {
+ for (const stale of durabilityState.listStaleExternalWrites()) {
+ const base = durabilityState.getReconciledBase(stale.docName) ?? stale.diskContent;
+ authority.raise({
+ kind: 'reconcile',
+ file: stale.file,
+ reason: 'stale-external-write',
+ detectedAt: stale.detectedAt,
+ stages: {
+ base,
+ ours: stale.retainedContent ?? base,
+ theirs: stale.diskContent,
+ },
+ });
+ }
+ },
+ });
+ authority = new ConflictAuthority({
+ projectDir: tmpDir,
+ contentDir: tmpDir,
+ io: {
+ gitRaw: async () => '',
+ writeProjectFileUntracked: () => undefined,
+ unlinkProjectFile: () => undefined,
+ applyResolvedContent: async () => undefined,
+ },
+ });
+ durabilityState.setReconciledBase(docName, ACKNOWLEDGED_CONTENT);
+ durabilityState.recordDisplacedVersion(docName, STALE_CONTENT);
+ replaceDocParagraphs(document, ['alpha', 'beta gamma', 'next live edit']);
+
+ expect(
+ refuseStaleExternalWrite(
+ durabilityState,
+ document,
+ docName,
+ STALE_CONTENT,
+ authority,
+ serializeYDocSource(document),
+ ),
+ ).toBe(true);
+
+ const conflict = authority.findByDocName(docName);
+ expect(conflict?.kind).toBe('reconcile');
+ if (conflict?.kind !== 'reconcile') throw new Error('expected a reconcile conflict');
+ expect(conflict.stages.ours).toBe(liveContent);
+ });
+
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);
@@ -139,7 +194,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
);
expect(result.reconciled).toBe(true);
- expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getMap('lifecycle').get('status')).toBeUndefined();
expect(document.getText('source').toString()).toContain('delta');
});
@@ -155,7 +210,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
);
expect(result.reconciled).toBe(true);
- expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getMap('lifecycle').get('status')).toBeUndefined();
expect(document.getText('source').toString()).toBe(STALE_CONTENT);
});
@@ -185,7 +240,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
expect(refuseStaleExternalWrite(durabilityState, document, docName, ACKNOWLEDGED_CONTENT)).toBe(
false,
);
- expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getMap('lifecycle').get('status')).toBeUndefined();
expect(durabilityState.listStaleExternalWrites()).toEqual([]);
});
@@ -201,7 +256,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
tmpDir,
);
- expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getMap('lifecycle').get('status')).toBeUndefined();
expect(durabilityState.listStaleExternalWrites()).toEqual([]);
});
@@ -211,7 +266,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
const externalEdit = `${ACKNOWLEDGED_CONTENT}\ndelta\n`;
expect(refuseStaleExternalWrite(durabilityState, document, docName, externalEdit)).toBe(false);
- expect(isDocInConflict(document as never)).toBe(false);
+ expect(document.getMap('lifecycle').get('status')).toBeUndefined();
expect(durabilityState.listStaleExternalWrites()).toEqual([]);
});
@@ -235,7 +290,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
} as never);
expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
- expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeDefined();
expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
});
@@ -261,7 +316,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
} as never);
expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
- expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeDefined();
});
test('the final persistence disk read refuses a stale version that arrives after preflight', async () => {
@@ -287,7 +342,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
} as never);
expect(document.getText('source').toString()).toContain('next agent edit');
- expect(document.getMap('lifecycle').get('reason')).toBe('stale-external-write');
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeDefined();
expect(durabilityState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
expect(durabilityState.takeStaleExternalWriteFreeze(docName)).toBe(true);
expect(durabilityState.takeStoreDivergence(docName)).toBe(false);
@@ -313,7 +368,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
} as never);
expect(document.getText('source').toString()).toBe(retained);
expect(restoredState.getReconciledBase(docName)).toBe(ACKNOWLEDGED_CONTENT);
- expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(restoredState.getStaleExternalWrite(docName)).toBeDefined();
});
test('normalized-equal displaced bytes remain a conflict until exact acknowledged bytes return', async () => {
@@ -328,7 +383,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
docName,
tmpDir,
);
- expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeDefined();
expect(document.getText('source').toString()).toBe(ACKNOWLEDGED_CONTENT);
writeFileSync(join(tmpDir, `${docName}.md`), ACKNOWLEDGED_CONTENT, 'utf-8');
reconcileDiskBeforeAgentWrite(
@@ -337,7 +392,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
docName,
tmpDir,
);
- expect(document.getMap('lifecycle').get('status')).toBeUndefined();
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeUndefined();
});
test.each([ACKNOWLEDGED_CONTENT, 'genuinely new external content\n'])(
@@ -351,8 +406,6 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
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,
@@ -360,7 +413,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
docName,
tmpDir,
);
- expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(durabilityState.getStaleExternalWrite(docName)).toBeDefined();
expect(refuseStaleExternalWrite(durabilityState, undefined, docName, diskContent)).toBe(true);
expect(getMetrics().staleExternalWriteRefused).toBe(
beforeReplacement.staleExternalWriteRefused + 1,
@@ -381,7 +434,7 @@ describe('reconcileDiskBeforeAgentWrite — stale external write gate', () => {
context: {},
} as never);
expect(document.getText('source').toString()).toBe(retained);
- expect(document.getMap('lifecycle').get('status')).toBe('conflict');
+ expect(restored.getStaleExternalWrite(docName)).toBeDefined();
expect(restored.getStaleExternalWrite(docName)?.diskContent).toBe(diskContent);
expect(getMetrics().staleExternalWriteRefused).toBe(
beforeReplacement.staleExternalWriteRefused + 1,
diff --git a/packages/server/src/sync-engine.index-heal.test.ts b/packages/server/src/sync-engine.index-heal.test.ts
index e7d8e1b84..0e8eff6be 100644
--- a/packages/server/src/sync-engine.index-heal.test.ts
+++ b/packages/server/src/sync-engine.index-heal.test.ts
@@ -13,6 +13,7 @@ import { join } from 'node:path';
import { LOCAL_DIR, type SyncMode } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import { getLogger } from './logger.ts';
import { SyncEngine } from './sync-engine.ts';
@@ -99,6 +100,7 @@ function makeEngine(
opts: { mode?: SyncMode; _beforeRealIndexResetRetry?: () => void | Promise<void> } = {},
) {
return new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
diff --git a/packages/server/src/sync-engine.stamp-persistence.test.ts b/packages/server/src/sync-engine.stamp-persistence.test.ts
index ac9de0109..846d93417 100644
--- a/packages/server/src/sync-engine.stamp-persistence.test.ts
+++ b/packages/server/src/sync-engine.stamp-persistence.test.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path';
import { LOCAL_DIR, type SyncMode } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import { getLogger } from './logger.ts';
import { SyncEngine } from './sync-engine.ts';
@@ -69,6 +70,7 @@ async function projectWithBareOrigin() {
function makeEngine(opts: { mode?: SyncMode } = {}) {
return new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -106,7 +108,7 @@ describe('SyncEngine sync stamp persistence', () => {
}
});
- test('the persisted file keeps version 1 and its existing fields', async () => {
+ test('the persisted file keeps version 1 without duplicating conflict state', async () => {
await projectWithBareOrigin();
const engine = makeEngine();
@@ -121,7 +123,7 @@ describe('SyncEngine sync stamp persistence', () => {
expect(persisted).toHaveProperty('lastFetchUtc');
expect(persisted).toHaveProperty('lastPushedSha');
expect(persisted).toHaveProperty('consecutiveFailures');
- expect(persisted).toHaveProperty('inflightConflicts');
+ expect(persisted).not.toHaveProperty('inflightConflicts');
} finally {
await engine.destroy();
}
diff --git a/packages/server/src/sync-engine.state-persist.test.ts b/packages/server/src/sync-engine.state-persist.test.ts
index b8621a26d..6295c01b2 100644
--- a/packages/server/src/sync-engine.state-persist.test.ts
+++ b/packages/server/src/sync-engine.state-persist.test.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import { SyncEngine } from './sync-engine.ts';
const writeCalls = vi.hoisted(() => [] as string[]);
@@ -61,6 +62,7 @@ function statePath(): string {
function makeEngine() {
return new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.ts
index 622c81926..d27a61512 100644
--- a/packages/server/src/sync-engine.test.ts
+++ b/packages/server/src/sync-engine.test.ts
@@ -16,7 +16,7 @@ import { promisify } from 'node:util';
import { LOCAL_DIR, type SyncMode, SyncStatusSchema } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import { ConflictStore } from './conflict-storage.ts';
+import { type Conflict, ConflictAuthority } from './conflict-authority.ts';
import { createContentFilter } from './content-filter.ts';
import { classifyGitError } from './error-classification.ts';
import type { GitHandle } from './git-handle.ts';
@@ -44,9 +44,9 @@ interface CapturedLog {
msg: string;
level: 'info' | 'warn';
}
-function captureSyncLogs(): { entries: CapturedLog[]; restore: () => void } {
+function captureSyncLogs(name = 'sync-engine'): { entries: CapturedLog[]; restore: () => void } {
const entries: CapturedLog[] = [];
- const logger = getLogger('sync-engine');
+ const logger = getLogger(name);
const record =
(level: CapturedLog['level']) =>
(data: unknown, msg?: string): void => {
@@ -81,10 +81,33 @@ afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});
+let authority: ConflictAuthority;
+
+function newAuthority(): ConflictAuthority {
+ authority = new ConflictAuthority({
+ projectDir,
+ contentDir: projectDir,
+ io: {
+ gitRaw: (args) => simpleGit(projectDir).raw(args),
+ writeProjectFileUntracked: (absPath, bytes) => writeFileSync(absPath, bytes, 'utf-8'),
+ unlinkProjectFile: (absPath) => rmSync(absPath, { force: true }),
+ applyResolvedContent: async (_docName, absPath, bytes) => {
+ writeFileSync(absPath, bytes, 'utf-8');
+ },
+ },
+ });
+ return authority;
+}
+
+function workingTreeConflicts(): Array<Extract<Conflict, { kind: 'working-tree' }>> {
+ return authority.list().filter((c) => c.kind === 'working-tree');
+}
+
function makeEngine(
opts: { syncEnabled?: boolean; mode?: SyncMode; onStateChange?: (s: SyncState) => void } = {},
) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -138,6 +161,7 @@ function makeProbeEngine(opts: {
cc1Broadcaster?: ConstructorParameters<typeof SyncEngine>[0]['cc1Broadcaster'];
}) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -245,7 +269,7 @@ describe('SyncEngine state persistence round-trip', () => {
expect(engine.getStatus().syncEnabled).toBe(false);
});
- test('restores inflightConflicts into conflictCount', async () => {
+ test('a legacy inflightConflicts array does not resurrect cleared conflicts', async () => {
const persisted = {
version: 1,
lastSyncUtc: null,
@@ -258,6 +282,43 @@ describe('SyncEngine state persistence round-trip', () => {
const engine = makeEngine({ syncEnabled: false });
await engine.start();
+ expect(engine.getStatus().conflictCount).toBe(0);
+ expect(authority.count()).toBe(0);
+ });
+
+ test('the persisted sync state no longer carries a conflict list', async () => {
+ const engine = makeEngine({ syncEnabled: false });
+ await engine.start();
+ authority.raise({ kind: 'merge-native', file: 'docs/a.md' });
+ await engine.destroy();
+
+ const written = JSON.parse(readFileSync(statePath(), 'utf-8')) as Record<string, unknown>;
+ expect(written.inflightConflicts).toBeUndefined();
+ });
+
+ test('only conflicts with markers on disk count as sync conflicts and hold the push', async () => {
+ const engine = makeEngine({ syncEnabled: false });
+ await engine.start();
+ authority.raise({
+ kind: 'reconcile',
+ file: 'docs/a.md',
+ reason: 'merged-with-markers',
+ stages: { base: 'B', ours: 'O', theirs: 'T' },
+ });
+
+ expect(authority.count()).toBe(1);
+ expect(engine.getStatus().conflictCount).toBe(0);
+ expect(engine.getStatus().state).not.toBe('conflict');
+
+ authority.raise({
+ kind: 'reconcile',
+ file: 'docs/c.md',
+ reason: 'disk-markers',
+ stages: { base: 'B', ours: 'O', theirs: '<<<<<<< a\nT\n=======\nU\n>>>>>>> b\n' },
+ });
+ expect(engine.getStatus().conflictCount).toBe(1);
+
+ authority.raise({ kind: 'working-tree', file: 'docs/b.md', theirsSha: 'sha' });
expect(engine.getStatus().conflictCount).toBe(2);
});
@@ -409,7 +470,7 @@ describe('SyncEngine state persistence round-trip', () => {
const status = engine.getStatus();
expect(status.conflictCount).toBe(1);
expect(status.state).toBe('conflict');
- const conflicts = engine.getConflicts().map((c) => c.file);
+ const conflicts = authority.list().map((c) => c.file);
expect(conflicts).toEqual(['docs/b.md']);
} finally {
await engine.destroy();
@@ -447,7 +508,7 @@ describe('SyncEngine state persistence round-trip', () => {
await engine.start();
expect(engine.getStatus().state).toBe('conflict');
- await engine.resolveConflict(conflictedFile, 'mine');
+ await authority.resolve(conflictedFile, 'mine');
const after = engine.getStatus();
expect(after.conflictCount).toBe(0);
expect(after.state).not.toBe('conflict');
@@ -586,6 +647,7 @@ describe('SyncEngine ConflictStore admission (content-only)', () => {
function makeEngineForConflict() {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -738,6 +800,7 @@ describe('SyncEngine tracked MCP overlap preparation', () => {
writeFileSync(join(projectDir, '.mcp.json'), `${v2}\n`, 'utf-8');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: {
@@ -799,6 +862,7 @@ describe('SyncEngine tracked MCP overlap preparation', () => {
writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99', 'base'), 'utf8');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: {
@@ -846,6 +910,7 @@ describe('SyncEngine tracked MCP overlap preparation', () => {
writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99'), 'utf8');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -926,6 +991,7 @@ describe('SyncEngine tracked MCP overlap preparation', () => {
writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99'), 'utf8');
writeFileSync(join(projectDir, 'local.md'), 'local content\n', 'utf8');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: {
@@ -1033,16 +1099,23 @@ describe('SyncEngine delete/modify dirty content conflicts', () => {
}
function makeProjectRootEngine(
- opts: { onContentConflictsDetected?: (files: string[]) => void | Promise<void> } = {},
+ opts: { onContentConflictsDetected?: (files: string[]) => void } = {},
) {
+ const conflicts = newAuthority();
+ const detected = opts.onContentConflictsDetected;
+ if (detected !== undefined) {
+ conflicts.subscribe((change) => {
+ if (change.type === 'raised') detected([change.conflict.file]);
+ });
+ }
return new SyncEngine({
+ conflicts,
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
syncEnabled: true,
pullIntervalSeconds: 99999,
pushIntervalSeconds: 99999,
- onContentConflictsDetected: opts.onContentConflictsDetected,
});
}
@@ -1058,7 +1131,7 @@ describe('SyncEngine delete/modify dirty content conflicts', () => {
expect(status.state).toBe('conflict');
expect(status.conflictCount).toBe(1);
expect(status.pausedReason).toBeUndefined();
- expect(engine.getConflicts().map((c) => c.file)).toEqual(['foo.md']);
+ expect(authority.list().map((c) => c.file)).toEqual(['foo.md']);
expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);
const project = simpleGit(projectDir);
@@ -1088,7 +1161,7 @@ describe('SyncEngine delete/modify dirty content conflicts', () => {
const status = engine.getStatus();
expect(status.state).toBe('conflict');
expect(status.conflictCount).toBe(1);
- expect(engine.getConflicts().map((c) => c.file)).toEqual(['foo.md']);
+ expect(authority.list().map((c) => c.file)).toEqual(['foo.md']);
expect(notified).toEqual([['foo.md']]);
const project = simpleGit(projectDir);
@@ -1142,6 +1215,7 @@ describe('SyncEngine non-ASCII filename conflicts', () => {
await setupRemoteModifyLocalDeleteNonAscii();
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -1157,7 +1231,7 @@ describe('SyncEngine non-ASCII filename conflicts', () => {
expect(status.state).toBe('conflict');
expect(status.conflictCount).toBe(1);
expect(status.pausedReason).toBeUndefined();
- expect(engine.getConflicts().map((c) => c.file)).toEqual([fileName]);
+ expect(authority.list().map((c) => c.file)).toEqual([fileName]);
expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);
} finally {
await engine.destroy();
@@ -1378,6 +1452,7 @@ describe('SyncEngine unified pull — B1 in every mode', () => {
function makeRootContentEngine(mode: SyncMode) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -1895,6 +1970,7 @@ describe('SyncEngine pull-only cadence (auth-conditional)', () => {
tokenStore?: ProbeTokenStore | null;
}) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -1964,6 +2040,7 @@ describe('SyncEngine pull-only cadence (auth-conditional)', () => {
describe('SyncEngine lastRunUtc survives a restart', () => {
test('a restored engine reports the run stamp its legs restored', async () => {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -1986,6 +2063,7 @@ describe('SyncEngine lastRunUtc survives a restart', () => {
}
const restored = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2022,6 +2100,7 @@ describe('SyncEngine unborn-HEAD guard', () => {
function makeEngine() {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2064,6 +2143,7 @@ describe('SyncEngine one-shot push guards', () => {
function makeOneShotEngine(mode: SyncMode = 'follow') {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2091,9 +2171,9 @@ describe('SyncEngine one-shot push guards', () => {
});
test('refuses while conflicts hold the tree', async () => {
- const { engine, internals, cycles } = makeOneShotEngine();
+ const { engine, cycles } = makeOneShotEngine();
try {
- internals.conflictCount = 1;
+ authority.raise({ kind: 'merge-native', file: 'a.md' });
await engine.pushOnce();
expect(cycles).toEqual([]);
} finally {
@@ -2132,7 +2212,10 @@ describe('SyncEngine push chain survives a B1 conflict', () => {
};
test('a push tick with ledger conflicts re-arms the chain instead of ending it', async () => {
+ const conflicts = newAuthority();
+ conflicts.raise({ kind: 'merge-native', file: 'a.md' });
const engine = new SyncEngine({
+ conflicts,
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2147,7 +2230,6 @@ describe('SyncEngine push chain survives a B1 conflict', () => {
rearms.push(d);
};
(internals as unknown as { state: string }).state = 'idle';
- internals.conflictCount = 1;
await internals.runPushCycle();
@@ -2155,7 +2237,10 @@ describe('SyncEngine push chain survives a B1 conflict', () => {
});
test('an emptied ledger restarts both legs even though B1 left the state idle', async () => {
+ const conflicts = newAuthority();
+ conflicts.raise({ kind: 'merge-native', file: 'a.md' });
const engine = new SyncEngine({
+ conflicts,
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2165,13 +2250,8 @@ describe('SyncEngine push chain survives a B1 conflict', () => {
});
const internals = engine as unknown as ChainInternals & {
state: string;
- conflictStore: {
- list(): Array<{ file: string; variant: string }>;
- removeConflict(file: string): void;
- count(): number;
- };
+ subscribeToConflicts(): void;
schedulePull(overrideDelayMs?: number): void;
- reconcileConflictsFromGit(): Promise<void>;
};
const pushRearms: Array<number | undefined> = [];
const pullRearms: Array<number | undefined> = [];
@@ -2181,15 +2261,10 @@ describe('SyncEngine push chain survives a B1 conflict', () => {
internals.schedulePull = (d?: number) => {
pullRearms.push(d);
};
- internals.state = 'idle';
- internals.conflictCount = 2;
- internals.conflictStore = {
- list: () => [{ file: 'a.md', variant: 'merge' }],
- removeConflict: () => {},
- count: () => 0,
- };
+ internals.subscribeToConflicts();
+ internals.state = 'conflict';
- await internals.reconcileConflictsFromGit();
+ await conflicts.pruneMergeNativeAgainstGit();
expect(pushRearms).toHaveLength(1);
expect(pullRearms).toHaveLength(1);
@@ -2206,6 +2281,7 @@ describe('SyncEngine enable schedules both legs immediately', () => {
test('enabling full sync schedules the push at 0, not a full interval out', async () => {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2249,6 +2325,7 @@ describe('SyncEngine setIntervals()', () => {
function makeIntervalEngine(mode: SyncMode) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2315,6 +2392,7 @@ describe('SyncEngine setIntervals()', () => {
test('the anonymous floor still outranks a shorter configured pull interval', async () => {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2334,6 +2412,7 @@ describe('SyncEngine setIntervals()', () => {
test('a longer configured interval is honored for an anonymous follower', async () => {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2355,6 +2434,7 @@ describe('SyncEngine setIntervals()', () => {
describe('SyncEngine contention warn threshold', () => {
test('escalates to warn only once the run reaches the threshold', async () => {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2397,6 +2477,7 @@ describe('SyncEngine runPushCycle ownership guard', () => {
function makeGuardEngine() {
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2449,6 +2530,7 @@ describe('SyncEngine push-streak cause tracking', () => {
function makeEngineForCause() {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2558,6 +2640,7 @@ describe('SyncEngine effectivePushDelayMs floors on the configured interval', ()
function makePushEngine(pushIntervalSeconds: number) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -2799,6 +2882,7 @@ describe('SyncEngine push cycle with non-ASCII filenames', () => {
rmSync(join(projectDir, fileName));
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -2846,6 +2930,7 @@ describe('SyncEngine push cycle vs gitignored content (precedent #55 at the stag
function makePushEngine() {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -2936,6 +3021,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
function makeShareableEngine(mode?: SyncMode) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: createContentFilter({ projectDir, contentDir: projectDir }),
@@ -3000,6 +3086,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
writeFileSync(join(projectDir, 'assets', 'diagram.png'), 'attachment-v1');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: createContentFilter({
@@ -3037,6 +3124,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
writeFileSync(join(projectDir, 'assets', 'diagram.png'), 'attachment-doc-less');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: createContentFilter({
@@ -3074,6 +3162,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
attachmentFolderPath: 'assets',
});
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter,
@@ -3108,6 +3197,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
writeFileSync(join(projectDir, 'assets', 'shared.png'), 'attachment');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: createContentFilter({
@@ -3528,12 +3618,13 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
expect(status.state).toBe('idle');
expect(status.pausedReason).toBeUndefined();
expect(status.conflictCount).toBe(2);
- const conflicts = engine.getConflicts();
+ const conflicts = authority.list();
expect(conflicts.map((conflict) => conflict.file).sort()).toEqual([
'.ok/templates/project.md',
'docs/.ok/templates/folder.md',
]);
- expect(conflicts.every((c) => c.theirsSha)).toBe(true);
+ expect(workingTreeConflicts()).toHaveLength(conflicts.length);
+ expect(workingTreeConflicts().every((c) => c.theirsSha.length > 0)).toBe(true);
expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
expect(readFileSync(join(projectDir, '.ok', 'config.yml'), 'utf-8')).toBe('shared: local\n');
@@ -3561,6 +3652,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
function makeSubfolderEngine(attachmentFolderPath?: string) {
const contentDir = join(projectDir, 'content');
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: createContentFilter({
@@ -4582,6 +4674,7 @@ describe('SyncEngine auth-error recovery', () => {
await git.push(['--set-upstream', 'origin', 'main']);
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -4610,6 +4703,7 @@ describe('SyncEngine auth-error recovery', () => {
let urlmatchCalls = 0;
const probe = fakeProbe({ kind: 'allowed' });
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -4691,6 +4785,7 @@ describe('SyncEngine gh-token credential relay', () => {
const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -4712,6 +4807,7 @@ describe('SyncEngine gh-token credential relay', () => {
await initGitWithOrigin('https://ghes.acme.test/inkeep/open-knowledge.git');
const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -4730,6 +4826,7 @@ describe('SyncEngine gh-token credential relay', () => {
test('caches the gh token across handles, then re-resolves after an auth error', () => {
const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -4776,6 +4873,7 @@ describe('SyncEngine declared-account resolution', () => {
detectGhAccounts?: DetectGhAccountsFn,
) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir,
contentFilter: stubContentFilter,
@@ -5079,6 +5177,7 @@ describe('SyncEngine pull-only mode', () => {
const originTip = (await sister.revparse(['HEAD'])).trim();
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -5119,6 +5218,7 @@ describe('SyncEngine pull-only mode', () => {
expect(localHead).not.toBe(originBefore);
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -5218,17 +5318,23 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
function makePullEngine(
opts: {
- onContentConflictsResolved?: (files: string[]) => void | Promise<void>;
- onContentConflictsDetected?: (files: string[]) => void | Promise<void>;
+ onContentConflictsResolved?: (files: string[]) => void;
+ onContentConflictsDetected?: (files: string[]) => void;
} = {},
) {
+ const conflicts = newAuthority();
+ const detected = opts.onContentConflictsDetected;
+ const resolved = opts.onContentConflictsResolved;
+ conflicts.subscribe((change) => {
+ if (change.type === 'raised') detected?.([change.conflict.file]);
+ else resolved?.([change.file]);
+ });
return new SyncEngine({
+ conflicts,
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
mode: 'follow',
- onContentConflictsResolved: opts.onContentConflictsResolved,
- onContentConflictsDetected: opts.onContentConflictsDetected,
});
}
@@ -5359,7 +5465,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('C1\nC2\n');
expect(readFileSync(join(projectDir, 'keep.md'), 'utf-8')).toBe('K1\nK2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
await assertNoGitResidue();
} finally {
await engine.destroy();
@@ -5382,7 +5488,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
expect(existsSync(join(projectDir, 'cfg.json'))).toBe(false);
expect(readFileSync(join(projectDir, 'keep.md'), 'utf-8')).toBe('K1\nK2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
await assertNoGitResidue();
} finally {
await engine.destroy();
@@ -5421,6 +5527,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
const seen: Array<{ paths: number; bytesAtCheckpoint: string }> = [];
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -5454,6 +5561,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
let calls = 0;
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -5482,6 +5590,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -5585,7 +5694,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
const project = simpleGit(projectDir);
expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nL2\nORIGIN3\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect(engine.getStatus().state).toBe('idle');
await assertNoGitResidue();
} finally {
@@ -5610,10 +5719,10 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
await assertNoGitResidue();
- const conflicts = engine.getConflicts();
+ const conflicts = workingTreeConflicts();
+ expect(authority.list()).toHaveLength(1);
expect(conflicts).toHaveLength(1);
expect(conflicts[0]?.file).toBe('a.md');
- expect(conflicts[0]?.variant).toBe('working-tree');
expect(conflicts[0]?.theirsSha).toMatch(/^[0-9a-f]{40}$/);
expect(conflicts[0]?.baseSha).toMatch(/^[0-9a-f]{40}$/);
expect(engine.getStatus().state).toBe('idle');
@@ -5637,7 +5746,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
const project = simpleGit(projectDir);
expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
expect(readFileSync(join(projectDir, 'config.json'), 'utf-8')).toBe('{"a":3}\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
await assertNoGitResidue();
} finally {
await engine.destroy();
@@ -5659,7 +5768,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
const project = simpleGit(projectDir);
expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('C1\nC2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect(engine.getStatus().state).toBe('idle');
await assertNoGitResidue();
} finally {
@@ -5691,13 +5800,13 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
try {
await engine.start();
await engine.trigger('pull');
- const firstPin = engine.getConflicts()[0]?.theirsSha;
+ const firstPin = workingTreeConflicts()[0]?.theirsSha;
expect(firstPin).toMatch(/^[0-9a-f]{40}$/);
const tip2 = await advanceOriginFrom({ 'a.md': 'ORIGIN1b\nline2\n' });
await engine.trigger('pull');
- const conflicts = engine.getConflicts();
+ const conflicts = workingTreeConflicts();
expect(conflicts).toHaveLength(1);
expect(conflicts[0]?.theirsSha).not.toBe(firstPin);
expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip2);
@@ -5719,12 +5828,12 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
try {
await engine.start();
await engine.trigger('pull');
- expect(engine.getConflicts()).toHaveLength(1);
+ expect(authority.list()).toHaveLength(1);
const tip2 = await advanceOriginFrom({ 'a.md': 'LOCAL1\nline2\n' });
await engine.trigger('pull');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip2);
expect(await listNames(simpleGit(projectDir), ['diff-index', '--name-only', 'HEAD'])).toEqual(
[],
@@ -5751,12 +5860,12 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
try {
await engine.start();
await engine.trigger('pull');
- expect(engine.getConflicts()).toHaveLength(1);
+ expect(authority.list()).toHaveLength(1);
await advanceOriginFrom({ 'a.md': 'LOCAL1\nline2\n' });
await engine.trigger('pull');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect(resolved).toEqual([['a.md']]);
await assertNoGitResidue();
} finally {
@@ -5808,12 +5917,12 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
await engine.start();
await engine.trigger('pull');
const tip = (await simpleGit(projectDir).revparse(['HEAD'])).trim();
- expect(engine.getConflicts()).toHaveLength(1);
+ expect(authority.list()).toHaveLength(1);
- await engine.resolveConflict('a.md', 'theirs');
+ await authority.resolve('a.md', 'theirs');
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('ORIGIN1\nline2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip);
await assertNoGitResidue();
} finally {
@@ -5837,12 +5946,12 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
try {
await engine.start();
await engine.trigger('pull');
- expect(engine.getConflicts()).toHaveLength(1);
+ expect(authority.list()).toHaveLength(1);
- await engine.resolveConflict('a.md', 'content', 'MERGED\nline2\n');
+ await authority.resolve('a.md', 'content', 'MERGED\nline2\n');
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('MERGED\nline2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect(resolved).toEqual([['a.md']]);
} finally {
await engine.destroy();
@@ -5862,23 +5971,25 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
await git.commit('local edit');
const resolved: string[][] = [];
+ const conflicts = newAuthority();
+ conflicts.subscribe((change) => {
+ if (change.type === 'cleared') resolved.push([change.file]);
+ });
const engine = new SyncEngine({
+ conflicts,
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
mode: 'auto',
- onContentConflictsResolved: (files) => {
- resolved.push([...files]);
- },
});
try {
await engine.start();
await engine.trigger('sync');
- expect(engine.getConflicts()).toHaveLength(1);
+ expect(authority.list()).toHaveLength(1);
- await engine.resolveConflict('a.md', 'content', 'MERGED\nline2\n');
+ await authority.resolve('a.md', 'content', 'MERGED\nline2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect(resolved).toEqual([['a.md']]);
} finally {
await engine.destroy();
@@ -5898,10 +6009,10 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
await engine.trigger('pull');
const tip = (await simpleGit(projectDir).revparse(['HEAD'])).trim();
- await engine.resolveConflict('a.md', 'mine');
+ await authority.resolve('a.md', 'mine');
expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip);
await assertNoGitResidue();
} finally {
@@ -5924,7 +6035,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
const project = simpleGit(projectDir);
expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
expect(readFileSync(join(projectDir, '.mcp.json'), 'utf-8')).toBe('{"v":3}\n');
- expect(engine.getConflicts()).toEqual([]);
+ expect(authority.list()).toEqual([]);
await assertNoGitResidue();
} finally {
await engine.destroy();
@@ -5942,10 +6053,10 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
try {
await engine.start();
await engine.trigger('pull');
- expect(engine.getConflicts()).toHaveLength(1);
+ expect(authority.list()).toHaveLength(1);
- await engine.reconcileConflictsFromGit();
- expect(engine.getConflicts()).toHaveLength(1);
+ await authority.pruneMergeNativeAgainstGit();
+ expect(authority.list()).toHaveLength(1);
} finally {
await engine.destroy();
}
@@ -5978,7 +6089,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
const engine = makePullEngine();
try {
await engine.start();
- expect(engine.getConflicts().map((c) => c.file)).toEqual(['a.md']);
+ expect(authority.list().map((c) => c.file)).toEqual(['a.md']);
expect(engine.getStatus().state).toBe('idle');
} finally {
await engine.destroy();
@@ -6052,6 +6163,7 @@ describe('SyncEngine pull-only mode transitions', () => {
checkpoint?: (ctx: { branch: string; ahead: number }) => void | Promise<void>,
) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -6346,6 +6458,7 @@ describe("SyncEngine one-shot pull (op 'pull')", () => {
function makeEngineFor(mode: SyncMode) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -6553,6 +6666,7 @@ describe('SyncEngine telemetry', () => {
function makeEngineFor(mode: SyncMode) {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -6656,17 +6770,15 @@ describe('SyncEngine telemetry', () => {
});
writeFileSync(join(projectDir, 'doc.md'), 'LOCAL1\nline2\n', 'utf-8');
const engine = makeEngineFor('follow');
- const cap = captureSyncLogs();
+ const cap = captureSyncLogs('conflict-authority');
try {
await engine.start();
await engine.pullOnce();
expect(engine.getStatus().conflictCount).toBe(1);
- await engine.resolveConflict('doc.md', 'theirs');
- const entry = cap.entries.find(
- (e) => e.msg === '[sync] pull-only: conflict resolved by choice',
- );
+ await authority.resolve('doc.md', 'theirs');
+ const entry = cap.entries.find((e) => e.msg === '[conflicts] conflict resolved by choice');
expect(entry).toBeDefined();
- expect(entry?.data).toMatchObject({ choice: 'theirs' });
+ expect(entry?.data).toMatchObject({ choice: 'theirs', kind: 'working-tree' });
} finally {
cap.restore();
await engine.destroy();
@@ -6718,6 +6830,7 @@ describe('SyncEngine blocking-change resolution', () => {
function makeOverlapEngine(mode: SyncMode = 'full') {
return new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: markdownOnlyFilter,
@@ -6920,6 +7033,7 @@ describe('SyncEngine split-leg backoff, end to end', () => {
writeFileSync(join(projectDir, 'note.md'), 'local\n', 'utf-8');
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -6947,6 +7061,7 @@ describe('SyncEngine split-leg backoff, end to end', () => {
let raced = false;
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -6991,6 +7106,7 @@ describe('SyncEngine split-leg backoff, end to end', () => {
let raced = false;
const engine = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -7051,17 +7167,19 @@ describe('SyncEngine exclusive merge ownership', () => {
const git = await initGitWithOrigin(bareDir);
writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
await git.push(['--set-upstream', 'origin', 'main']);
+ const conflicts = newAuthority();
const engine = new SyncEngine({
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
mode,
cc1Broadcaster: { signal },
+ conflicts,
});
const internals = engine as unknown as CycleInternals;
internals.hasRemote = true;
internals.state = mode === 'off' ? 'disabled' : 'idle';
- return { engine, internals, git, bareDir };
+ return { engine, internals, git, bareDir, conflicts };
}
async function diverge(bareDir: string) {
@@ -7080,7 +7198,7 @@ describe('SyncEngine exclusive merge ownership', () => {
test.each(['mine', 'theirs'] as const)(
'a scheduled pull cannot enter a rejected push retry and %s resolves actual side bytes',
async (strategy) => {
- const { engine, internals, git, bareDir } = await setup();
+ const { engine, internals, git, bareDir, conflicts } = await setup();
await diverge(bareDir);
const enteredRetry = Promise.withResolvers<void>();
const releaseRetry = Promise.withResolvers<void>();
@@ -7109,7 +7227,7 @@ describe('SyncEngine exclusive merge ownership', () => {
expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);
expect(engine.getStatus().state).toBe('conflict');
- await new ConflictStore(projectDir).resolveConflict('README.md', strategy);
+ await conflicts.resolve('README.md', strategy);
expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(
strategy === 'mine' ? 'ours\n' : 'theirs\n',
);
@@ -7407,6 +7525,7 @@ describe('SyncEngine exclusive merge ownership', () => {
);
const restarted = new SyncEngine({
+ conflicts: newAuthority(),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,
@@ -7432,9 +7551,9 @@ describe('SyncEngine exclusive merge ownership', () => {
});
test('an operation refusal preserves tracked-conflict guidance', async () => {
- const { engine, internals, git } = await setup();
+ const { engine, internals, git, conflicts } = await setup();
internals.state = 'conflict';
- internals.conflictCount = 1;
+ conflicts.raise({ kind: 'merge-native', file: 'README.md' });
internals.pullError = 'existing conflict guidance';
internals.pausedReason = 'non-content-merge-failure';
writeFileSync(join(projectDir, '.git', 'CHERRY_PICK_HEAD'), await git.revparse('HEAD'));
@@ -7453,9 +7572,9 @@ describe('SyncEngine exclusive merge ownership', () => {
});
test('a dirty-tree error preserves the conflict state and does not schedule autosave', async () => {
- const { engine, internals } = await setup();
+ const { engine, internals, conflicts } = await setup();
internals.state = 'conflict';
- internals.conflictCount = 1;
+ conflicts.raise({ kind: 'merge-native', file: 'README.md' });
try {
internals.handleError(
classifyGitError(
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index b2c8492dd..d1b6389e3 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -26,7 +26,9 @@ import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import type { CC1Broadcaster } from './cc1-broadcast.ts';
import { getLocalDir } from './config/paths.ts';
-import { type ConflictEntry, ConflictStore } from './conflict-storage.ts';
+import type { ConflictAuthority, RaiseInput } from './conflict-authority.ts';
+import type { Conflict } from './conflict-kinds.ts';
+import { holdsMarkersOnDisk } from './conflict-kinds.ts';
import type { ContentFilter } from './content-filter.ts';
import { isShareableOkArtifact } from './content-filter.ts';
import { isSupportedDocFile } from './doc-extensions.ts';
@@ -298,7 +300,6 @@ interface PersistedSyncState {
pushStreakIsConnectivity?: boolean;
pausedReason?: string;
pausedSinceUtc?: string;
- inflightConflicts: string[];
}
interface SyncEngineOptions {
@@ -312,9 +313,8 @@ interface SyncEngineOptions {
syncEnabled?: boolean;
credentialConfig?: string[];
cc1Broadcaster?: Pick<CC1Broadcaster, 'signal'> | null;
+ conflicts: ConflictAuthority;
onStateChange?: (state: SyncState) => void;
- onContentConflictsDetected?: (files: string[]) => void | Promise<void>;
- onContentConflictsResolved?: (files: string[]) => void | Promise<void>;
setBatchInProgress?: (value: boolean) => void;
onAutoDisable?: (reason: 'protected-branch') => void | Promise<void>;
checkpointBeforeStrandedConversion?: (context: {
@@ -393,8 +393,6 @@ export class SyncEngine {
private credentialConfig: string[];
private cc1Broadcaster: Pick<CC1Broadcaster, 'signal'> | null;
private onStateChange: ((state: SyncState) => void) | undefined;
- private onContentConflictsDetected: ((files: string[]) => void | Promise<void>) | undefined;
- private onContentConflictsResolved: ((files: string[]) => void | Promise<void>) | undefined;
private setBatchInProgress: ((value: boolean) => void) | undefined;
private onAutoDisable: ((reason: 'protected-branch') => void | Promise<void>) | undefined;
private checkpointBeforeStrandedConversion:
@@ -441,7 +439,13 @@ export class SyncEngine {
private consecutiveContentions = 0;
private ahead = 0;
private behind = 0;
- private conflictCount = 0;
+ private get conflictCount(): number {
+ let total = 0;
+ for (const entry of this.conflicts.list()) {
+ if (holdsMarkersOnDisk(entry)) total++;
+ }
+ return total;
+ }
private pushError: string | undefined;
private pushErrorCode: UserFacingErrorCode | undefined;
private pullError: string | undefined;
@@ -460,7 +464,8 @@ export class SyncEngine {
private identityUnresolved = false;
private statePath: string;
- private conflictStore: ConflictStore;
+ private readonly conflicts: ConflictAuthority;
+ private unsubscribeConflicts: (() => void) | null = null;
constructor(options: SyncEngineOptions) {
this.projectDir = options.projectDir;
@@ -476,8 +481,6 @@ export class SyncEngine {
this.credentialConfig = options.credentialConfig ?? [];
this.cc1Broadcaster = options.cc1Broadcaster ?? null;
this.onStateChange = options.onStateChange;
- this.onContentConflictsDetected = options.onContentConflictsDetected;
- this.onContentConflictsResolved = options.onContentConflictsResolved;
this.setBatchInProgress = options.setBatchInProgress;
this.onAutoDisable = options.onAutoDisable;
this.checkpointBeforeStrandedConversion = options.checkpointBeforeStrandedConversion;
@@ -493,7 +496,7 @@ export class SyncEngine {
this.tokenStore = options.tokenStore;
this.checkPushPermissionFn = options.checkPushPermissionFn ?? defaultCheckPushPermission;
this.statePath = resolve(getLocalDir(this.projectDir), 'sync-state.json');
- this.conflictStore = new ConflictStore(this.projectDir, this.currentBranch);
+ this.conflicts = options.conflicts;
}
private syncGhTarget(): { account: GitHubAccount; host: string } {
@@ -586,7 +589,7 @@ export class SyncEngine {
const b = (await handle.git.raw('rev-parse', '--abbrev-ref', 'HEAD')).trim();
if (b && b !== 'HEAD') {
this.currentBranch = b;
- this.conflictStore.setBranch(b);
+ this.conflicts.setBranch(b);
}
} catch {}
} catch (e) {
@@ -614,42 +617,11 @@ export class SyncEngine {
const mergeHeadPath = gitDir ? join(gitDir, 'MERGE_HEAD') : null;
const mergeInProgress = mergeHeadPath !== null && existsSync(mergeHeadPath);
- this.conflictCount = this.conflictStore.count();
- const mergeNativeEntries = () =>
- this.conflictStore.list().filter((e) => e.variant !== 'working-tree');
-
- if (mergeNativeEntries().length > 0 && !mergeInProgress) {
- log.warn(
- { count: mergeNativeEntries().length },
- '[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state',
- );
- for (const entry of mergeNativeEntries()) this.conflictStore.removeConflict(entry.file);
- this.conflictCount = this.conflictStore.count();
- } else if (mergeNativeEntries().length > 0 && mergeInProgress) {
- try {
- const handle = this.gitHandle();
- const stillUnmerged = new Set(
- await listNames(handle.git, ['diff', '--name-only', '--diff-filter=U']),
- );
- const before = this.conflictCount;
- for (const entry of mergeNativeEntries()) {
- if (!stillUnmerged.has(entry.file)) {
- this.conflictStore.removeConflict(entry.file);
- }
- }
- this.conflictCount = this.conflictStore.count();
- if (this.conflictCount < before) {
- log.info(
- { cleared: before - this.conflictCount, remaining: this.conflictCount },
- '[sync] reconciled conflicts.json against git unmerged index',
- );
- }
- } catch (e) {
- log.warn({ err: e }, '[sync] failed to reconcile conflicts with git index');
- }
- }
+ await this.conflicts.pruneMergeNativeAgainstGit();
+ const hasMergeNative = (): boolean =>
+ this.conflicts.list().some((e) => e.kind === 'merge-native');
- if (mergeInProgress && mergeNativeEntries().length === 0) {
+ if (mergeInProgress && !hasMergeNative()) {
log.warn({}, '[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge');
try {
const handle = this.gitHandle();
@@ -659,10 +631,9 @@ export class SyncEngine {
}
}
- if (mergeNativeEntries().length > 0) {
- await this.notifyContentConflictsDetected(
- this.conflictStore.list().map((entry) => entry.file),
- );
+ this.subscribeToConflicts();
+
+ if (hasMergeNative()) {
this.transitionTo('conflict');
log.warn(
{ count: this.conflictCount },
@@ -670,12 +641,6 @@ export class SyncEngine {
);
return;
}
- const workingTreeEntries = this.conflictStore
- .list()
- .filter((e) => e.variant === 'working-tree');
- if (workingTreeEntries.length > 0) {
- await this.notifyContentConflictsDetected(workingTreeEntries.map((entry) => entry.file));
- }
if (this.mode === 'follow') await this.refreshAuthTier();
@@ -693,6 +658,8 @@ export class SyncEngine {
}
stop(): void {
+ this.unsubscribeConflicts?.();
+ this.unsubscribeConflicts = null;
if (this.pullTimer !== null) {
clearTimeout(this.pullTimer);
this.pullTimer = null;
@@ -1353,94 +1320,23 @@ export class SyncEngine {
}
}
- getConflicts(): import('./conflict-storage.ts').ConflictEntry[] {
- return this.conflictStore.list();
- }
-
- async reconcileConflictsFromGit(): Promise<void> {
- const mergeNative = this.conflictStore.list().filter((e) => e.variant !== 'working-tree');
- if (mergeNative.length === 0) return;
- const before = this.conflictCount;
- const gitDir = resolveGitDir(this.projectDir);
- const mergeHeadPath = gitDir ? join(gitDir, 'MERGE_HEAD') : null;
- const mergeInProgress = mergeHeadPath !== null && existsSync(mergeHeadPath);
-
- if (!mergeInProgress) {
- log.info(
- { cleared: mergeNative.length },
- '[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts',
- );
- for (const entry of mergeNative) this.conflictStore.removeConflict(entry.file);
- this.conflictCount = this.conflictStore.count();
- } else {
- try {
- const handle = this.gitHandle();
- const stillUnmerged = new Set(
- await listNames(handle.git, ['diff', '--name-only', '--diff-filter=U']),
- );
- for (const entry of mergeNative) {
- if (!stillUnmerged.has(entry.file)) {
- this.conflictStore.removeConflict(entry.file);
- }
- }
- this.conflictCount = this.conflictStore.count();
- if (this.conflictCount < before) {
- log.info(
- { cleared: before - this.conflictCount, remaining: this.conflictCount },
- '[sync] external resolve detected (mid-merge) — pruned resolved entries',
- );
- }
- } catch (err) {
- log.warn({ err }, '[sync] reconcileConflictsFromGit: git probe failed');
- return;
- }
- }
-
- if (this.conflictCount === before) return;
- if (this.conflictCount === 0) {
- this.transitionTo('idle');
- this.pausedReason = undefined;
- this.schedulePull();
- this.schedulePush(0);
- } else {
- this.cc1Broadcaster?.signal('sync-status');
- }
- this.scheduleSaveState();
- }
-
- async resolveConflict(
- file: string,
- strategy: import('./conflict-storage.ts').ResolveStrategy,
- content?: string,
- ): Promise<void> {
- const wasWorkingTree =
- this.conflictStore.list().find((c) => c.file === file)?.variant === 'working-tree';
- this.setBatchInProgress?.(true);
- try {
- try {
- await this.conflictStore.resolveConflict(file, strategy, content);
- } catch (e) {
- this.conflictCount = this.conflictStore.count();
+ private subscribeToConflicts(): void {
+ if (this.unsubscribeConflicts !== null) return;
+ this.unsubscribeConflicts = this.conflicts.subscribe(() => {
+ const blocking = this.conflicts.list().some((e) => e.kind === 'merge-native');
+ if (blocking && this.state !== 'conflict') {
+ this.transitionTo('conflict');
this.scheduleSaveState();
- throw e;
- }
- if (wasWorkingTree) {
- log.info({ choice: strategy }, '[sync] pull-only: conflict resolved by choice');
+ return;
}
- await this.notifyContentConflictsResolved([file]);
- this.conflictCount = this.conflictStore.count();
- if (this.conflictCount === 0) {
+ if (!blocking && this.state === 'conflict') {
this.transitionTo('idle');
this.pausedReason = undefined;
this.schedulePull();
- this.schedulePush(0);
- } else {
- this.cc1Broadcaster?.signal('sync-status');
+ this.schedulePush();
+ this.scheduleSaveState();
}
- this.scheduleSaveState();
- } finally {
- this.setBatchInProgress?.(false);
- }
+ });
}
updateCurrentBranch(branch: string | null): void {
@@ -1452,7 +1348,7 @@ export class SyncEngine {
}
} else if (this.currentBranch !== branch) {
this.currentBranch = branch;
- this.conflictStore.setBranch(branch);
+ this.conflicts.setBranch(branch);
if (this.state === 'disabled' && this.pausedReason === 'detached-head') {
this.pausedReason = undefined;
this.transitionTo('idle');
@@ -1718,9 +1614,9 @@ export class SyncEngine {
return 'error';
}
- const existing = new Map<string, ConflictEntry>();
- for (const e of this.conflictStore.list()) {
- if (e.variant === 'working-tree') existing.set(e.file, e);
+ const existing = new Map<string, Extract<Conflict, { kind: 'working-tree' }>>();
+ for (const e of this.conflicts.list()) {
+ if (e.kind === 'working-tree') existing.set(e.file, e);
}
let plan: Awaited<ReturnType<typeof this.planOverlapReconciliation>>;
@@ -1798,24 +1694,11 @@ export class SyncEngine {
this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');
return 'error';
}
- let conflictsPersisted = true;
for (const entry of plan.upserts) {
- conflictsPersisted = this.conflictStore.addConflict(entry) && conflictsPersisted;
+ this.conflicts.raise(entry);
}
for (const file of plan.dissolved) {
- conflictsPersisted = this.conflictStore.removeConflict(file) && conflictsPersisted;
- }
- this.conflictCount = this.conflictStore.count();
- if (!conflictsPersisted) {
- log.error(
- {},
- '[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error',
- );
- this.handleError(
- classifyGitError(new Error('failed to persist conflict state after fast-forward')),
- 'pull',
- );
- return 'error';
+ this.conflicts.dissolveWorkingTree(file);
}
this.lastSyncUtc = new Date().toISOString();
@@ -1825,16 +1708,6 @@ export class SyncEngine {
this.blockingPaths = [];
this.transitionTo('idle');
- if (plan.newConflicts.length > 0) {
- await this.notifyContentConflictsDetected(plan.newConflicts);
- }
- if (plan.dissolved.length > 0) {
- await this.notifyContentConflictsResolved(plan.dissolved);
- }
- if (plan.newConflicts.length > 0 || plan.dissolved.length > 0) {
- this.cc1Broadcaster?.signal('sync-status');
- }
-
const overlayStock = await this.countStandingOverlay(handle);
log.info(
{
@@ -1899,12 +1772,12 @@ export class SyncEngine {
branch: string,
oldHead: string,
overlapping: string[],
- existing: Map<string, ConflictEntry>,
+ existing: Map<string, Extract<Conflict, { kind: 'working-tree' }>>,
): Promise<{
writes: Array<{ path: string; bytes: Buffer }>;
mineRestore: Array<{ path: string; bytes: Buffer }>;
deletions: string[];
- upserts: ConflictEntry[];
+ upserts: Array<Extract<RaiseInput, { kind: 'working-tree' }>>;
dissolved: string[];
newConflicts: string[];
autoCombined: string[];
@@ -1913,7 +1786,7 @@ export class SyncEngine {
const writes: Array<{ path: string; bytes: Buffer }> = [];
const mineRestore: Array<{ path: string; bytes: Buffer }> = [];
const deletions: string[] = [];
- const upserts: ConflictEntry[] = [];
+ const upserts: Array<Extract<RaiseInput, { kind: 'working-tree' }>> = [];
const dissolved: string[] = [];
const newConflicts: string[] = [];
const autoCombined: string[] = [];
@@ -2039,11 +1912,10 @@ export class SyncEngine {
continue;
}
upserts.push({
+ kind: 'working-tree',
file: p,
- detectedAt: priorEntry?.detectedAt ?? new Date().toISOString(),
- variant: 'working-tree',
theirsSha,
- baseSha,
+ ...(baseSha === undefined ? {} : { baseSha }),
});
if (!hadEntry) newConflicts.push(p);
}
@@ -3292,10 +3164,8 @@ export class SyncEngine {
if (contentConflicts.length > 0) {
for (const file of contentConflicts) {
- this.conflictStore.addConflict({ file, detectedAt: new Date().toISOString() });
+ this.conflicts.raise({ kind: 'merge-native', file });
}
- this.conflictCount = this.conflictStore.count();
- await this.notifyContentConflictsDetected(contentConflicts);
if (this.pullTimer !== null) {
clearTimeout(this.pullTimer);
@@ -3342,24 +3212,6 @@ export class SyncEngine {
}
}
- private async notifyContentConflictsDetected(files: string[]): Promise<void> {
- if (files.length === 0) return;
- try {
- await this.onContentConflictsDetected?.(files);
- } catch (err) {
- log.warn({ err, files }, '[sync] content conflict callback failed');
- }
- }
-
- private async notifyContentConflictsResolved(files: string[]): Promise<void> {
- if (files.length === 0) return;
- try {
- await this.onContentConflictsResolved?.(files);
- } catch (err) {
- log.warn({ err, files }, '[sync] content conflict resolved callback failed');
- }
- }
-
private clearPushError(): void {
this.pushError = undefined;
this.pushErrorCode = undefined;
@@ -3550,7 +3402,6 @@ export class SyncEngine {
pushStreakIsConnectivity: this.pushStreakIsConnectivity,
pausedReason: persistedReason,
pausedSinceUtc: persistedReason ? new Date().toISOString() : undefined,
- inflightConflicts: this.conflictStore.list().map((c) => c.file),
};
const tmpStatePath = `${this.statePath}.tmp`;
tracedWriteFileSync(tmpStatePath, JSON.stringify(data, null, 2), 'utf-8');
@@ -3584,16 +3435,6 @@ export class SyncEngine {
);
}
this.pausedReason = NON_RESTORED_PAUSES.has(storedReason) ? undefined : storedReason;
-
- const inflightFiles = data.inflightConflicts ?? [];
- if (inflightFiles.length > 0) {
- for (const file of inflightFiles) {
- if (!this.conflictStore.list().some((c) => c.file === file)) {
- this.conflictStore.addConflict({ file, detectedAt: new Date().toISOString() });
- }
- }
- this.conflictCount = this.conflictStore.count();
- }
} catch (e) {
log.warn({ err: e }, '[sync] failed to load sync state');
}
diff --git a/packages/server/src/sync-engine.unborn-head.test.ts b/packages/server/src/sync-engine.unborn-head.test.ts
index 2c7b890c9..a8a429570 100644
--- a/packages/server/src/sync-engine.unborn-head.test.ts
+++ b/packages/server/src/sync-engine.unborn-head.test.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path';
import { LOCAL_DIR, type SyncMode } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';
import { getLogger } from './logger.ts';
import { SyncEngine } from './sync-engine.ts';
@@ -80,6 +81,7 @@ async function emptyProjectWithBareOrigin() {
function makeEngine(opts: { mode?: SyncMode } = {}) {
return new SyncEngine({
+ conflicts: createTestConflictAuthority(projectDir),
projectDir,
contentDir: projectDir,
contentFilter: stubContentFilter,