Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Refresh staged conflicts after file replacement (#5593)
Nick Gomez3876dd7d7736
diff --git a/.changeset/refresh-staged-conflicts.md b/.changeset/refresh-staged-conflicts.mdnew file mode 100644index 000000000..9173038f7--- /dev/null+++ b/.changeset/refresh-staged-conflicts.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Allow editing again after resolving and staging a Git conflict, including when Git replaces the file.diff --git a/packages/server/src/head-watcher.ts b/packages/server/src/head-watcher.tsindex a8d0637c6..0021004fd 100644--- a/packages/server/src/head-watcher.ts+++ b/packages/server/src/head-watcher.ts@@ -35,7 +35,7 @@ export interface HeadWatcherHandle {const QUIET_WINDOW_MS = 100;const BATCH_TIMEOUT_MS = 30_000;-const WATCHED_FILES = new Set(['HEAD', 'MERGE_HEAD', 'ORIG_HEAD', 'index.lock']);+const WATCHED_FILES = new Set(['HEAD', 'MERGE_HEAD', 'ORIG_HEAD', 'index', 'index.lock']);export interface ProjectHeadState {readonly branch: string | null;diff --git a/packages/server/src/server-factory.conflict-authority.test.ts b/packages/server/src/server-factory.conflict-authority.test.tsindex 5aabb38ac..2f44bd712 100644--- a/packages/server/src/server-factory.conflict-authority.test.ts+++ b/packages/server/src/server-factory.conflict-authority.test.ts@@ -5,10 +5,16 @@ 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 {+ DocumentListSuccessSchema,+ DocumentReadSuccessSchema,+ OK_DIR,+ SyncConflictsSuccessSchema,+} from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { bootServer } from './boot.ts';import { ConfigSchema } from './config/schema.ts';+import * as headWatcher from './head-watcher.ts';import type { ServerInstance } from './server-factory.ts';const execFileAsync = promisify(execFile);@@ -49,6 +55,7 @@ function seedConflictsJson(projectDir: string, file: string): void {async function seedRealMergeConflict(projectDir: string, filePath: string): Promise<void> {const opts = { cwd: projectDir };+ await execFileAsync('git', ['config', 'maintenance.auto', 'false'], opts);await execFileAsync('git', ['config', 'user.email', '[email protected]'], opts);await execFileAsync('git', ['config', 'user.name', 'Test'], opts);mkdirSync(resolve(projectDir, 'notes'), { recursive: true });@@ -68,17 +75,17 @@ async function seedRealMergeConflict(projectDir: string, filePath: string): Prom}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;+ const res = await fetch(`http://127.0.0.1:${port}/api/documents`);+ expect(res.ok).toBe(true);+ const data = DocumentListSuccessSchema.parse(await res.json());+ return data.documents.some((d) => d.docName === docName);}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);+ const res = await fetch(`http://127.0.0.1:${port}/api/sync/conflicts`);+ expect(res.ok).toBe(true);+ const data = SyncConflictsSuccessSchema.parse(await res.json());+ return data.conflicts.map((c) => c.file);}async function writeDocProbe(port: number, docName: string, markdown: string): Promise<number> {@@ -120,13 +127,35 @@ async function pollUntil(throw new Error(`timed out after ${timeoutMs}ms waiting for ${what}`);}+function awaitWithin<T>(+ promise: Promise<T>,+ timeoutMs: number,+ what: string,+ signal: AbortSignal,+): Promise<T> {+ const stopped = Promise.withResolvers<never>();+ const timer = setTimeout(+ () => stopped.reject(new Error(`timed out after ${timeoutMs}ms waiting for ${what}`)),+ timeoutMs,+ );+ const abandon = () => stopped.reject(signal.reason);+ if (signal.aborted) abandon();+ else signal.addEventListener('abort', abandon, { once: true });+ return Promise.race([promise, stopped.promise]).finally(() => {+ clearTimeout(timer);+ signal.removeEventListener('abort', abandon);+ });+}+let tmpDir: string;+let pendingTeardown: Promise<void> = Promise.resolve();beforeEach(async () => {tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-conflict-authority-'));});afterEach(async () => {+ await pendingTeardown;await rm(tmpDir, { recursive: true, force: true });});@@ -138,7 +167,7 @@ async function bootWithHeldConflictedDoc(options?: {serverInstance: ServerInstance;destroy: () => Promise<void>;release: () => Promise<void>;- readSource: () => string;+ readSource: () => Promise<string>;}> {const contentDir = tmpDir;await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);@@ -178,45 +207,70 @@ async function bootWithHeldConflictedDoc(options?: {release: async () => {await dc?.disconnect();},- readSource: () => dc?.document?.getText('source').toString() ?? '',+ readSource: async () => {+ const res = await fetch(+ `http://127.0.0.1:${booted.port}/api/document?docName=${encodeURIComponent(DOC_NAME)}`,+ );+ expect(res.ok).toBe(true);+ return DocumentReadSuccessSchema.parse(await res.json()).content;+ },};}-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',- );+async function checkoutOurs(port: number, replacement: string): Promise<void> {+ if (replacement === 'separated delete/create') {+ await rm(resolve(tmpDir, DOC_FILE));+ await pollUntil(+ async () => !(await isIndexed(port, DOC_NAME)),+ 30_000,+ 'the server to observe the removal before recreation',+ );+ }+ await execFileAsync('git', ['checkout', '--ours', '--', DOC_FILE], { cwd: tmpDir });+}- expect(await writeProbe(held.port, '# probe\n')).toBe(200);- } finally {- await held.release();- await held.destroy();- }- }, 180_000);+describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the loaded doc', () => {+ test.each(['checkout', 'separated delete/create'])(+ 'ordering A — the disk event drains before HEAD moves, and the write is admitted (%s)',+ async (replacement) => {+ 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 checkoutOurs(held.port, replacement);+ await execFileAsync('git', ['add', '--', DOC_FILE], opts);++ await pollUntil(+ async () => {+ const source = await held.readSource();+ return source.includes('LOCAL') && !source.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();@@ -231,7 +285,10 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes thewriteFileSync(resolve(tmpDir, DOC_FILE), 'line1\nLOCAL\nline3\n', 'utf-8');await pollUntil(- () => held.readSource().includes('LOCAL') && !held.readSource().includes('<<<<<<<'),+ async () => {+ const source = await held.readSource();+ return source.includes('LOCAL') && !source.includes('<<<<<<<');+ },30_000,'the server to process the disk update for the hand-resolved file',);@@ -263,64 +320,148 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the}}, 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);+ test.each(['checkout', 'separated delete/create'])(+ 'a mid-merge `git add` with no commit heals through the disk-update path (%s)',+ async (replacement) => {+ 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 checkoutOurs(held.port, replacement);+ await execFileAsync('git', ['add', '--', DOC_FILE], opts);++ await pollUntil(+ async () => {+ const source = await held.readSource();+ return source.includes('LOCAL') && !source.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,+ );- await pollUntil(- () => held.readSource().includes('LOCAL') && !held.readSource().includes('<<<<<<<'),- 30_000,- 'the server to process the disk update for the staged file',- );+ test.each(['checkout', 'separated delete/create'])(+ 'a staged merge-native entry prunes for a document that was never loaded (%s)',+ async (replacement) => {+ 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 checkoutOurs(held.port, replacement);+ 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,+ );- await pollUntil(- async () => (await listConflictFiles(held.port)).length === 0,- 60_000,- 'the conflict ledger to empty from the disk-update prune',+ test('staging a recreated unloaded document prunes from the persistent index notification', async ({+ onTestFinished,+ signal,+ }) => {+ const notification = Promise.withResolvers<(path: string) => void>();+ const batchEnded = Promise.withResolvers<void>();+ const startHeadWatcher = headWatcher.startHeadWatcher;+ const subscription = vi+ .spyOn(headWatcher, 'startHeadWatcher')+ .mockImplementation((projectRoot, begin, end, options) =>+ startHeadWatcher(+ projectRoot,+ begin,+ async (info) => {+ try {+ await end(info);+ } finally {+ batchEnded.resolve();+ }+ },+ {+ ...options,+ subscribeForTest: async (_gitDir, dispatch) => {+ notification.resolve(dispatch);+ return async () => {};+ },+ },+ ),);-- 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 () => {+ onTestFinished(() => subscription.mockRestore());const held = await bootWithHeldConflictedDoc({ load: false });+ const tornDown = Promise.withResolvers<void>();+ pendingTeardown = tornDown.promise;try {- await pollUntil(- async () => (await listConflictFiles(held.port)).includes(DOC_FILE),- 20_000,- 'the seeded merge-native entry to be listed',+ const dispatch = await awaitWithin(+ notification.promise,+ 30_000,+ 'the head watcher to subscribe',+ signal,);+ expect(await listConflictFiles(held.port)).toContain(DOC_FILE);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 checkoutOurs(held.port, 'separated delete/create');await pollUntil(- async () => (await listConflictFiles(held.port)).length === 0,- 60_000,- 'the disk-update prune to drop the entry for the unloaded doc',+ () => isIndexed(held.port, DOC_NAME),+ 30_000,+ 'the server to index the recreated file before staging',);+ expect(await listConflictFiles(held.port)).toContain(DOC_FILE);+ await execFileAsync('git', ['add', '--', DOC_FILE], { cwd: tmpDir });+ dispatch(resolve(tmpDir, '.git', 'index'));++ await awaitWithin(+ batchEnded.promise,+ 30_000,+ 'the batch started by the index notification to end',+ signal,+ );+ expect(await listConflictFiles(held.port)).toEqual([]);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();+ try {+ await held.release();+ await held.destroy();+ } finally {+ tornDown.resolve();+ }}}, 180_000);