Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ci): retry OK validation only for chartered flake evidence (#4453)
Nick Gomezf08c1650b421
diff --git a/.changeset/conflict-identical-version-controls.md b/.changeset/conflict-identical-version-controls.mdnew file mode 100644index 000000000..2d37b4421--- /dev/null+++ b/.changeset/conflict-identical-version-controls.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Fix the Accept current / Accept incoming buttons on a stale-write conflict where both versions are identical: clicking one as soon as it appeared did nothing, and the conflict could not be resolved until the view was reopened.diff --git a/packages/app/src/components/ConflictView.tsx b/packages/app/src/components/ConflictView.tsxindex d2b78a7f5..2491ae78b 100644--- a/packages/app/src/components/ConflictView.tsx+++ b/packages/app/src/components/ConflictView.tsx@@ -105,11 +105,11 @@ export function ConflictView({>(null);const handleUndoRef = useRef<(() => void) | null>(null);const handleRedoRef = useRef<(() => void) | null>(null);- const handleIdenticalChoiceRef = useRef<((selection: MergeConflictResolution) => void) | null>(- null,- );const handleApplyRef = useRef<(() => void | Promise<void>) | null>(null);const [controls, setControls] = useState<ConflictControl[]>([]);+ const [identicalChoiceHandler, setIdenticalChoiceHandler] = useState<+ ((selection: MergeConflictResolution) => void) | null+ >(null);const [canUndo, setCanUndo] = useState(false);const [canRedo, setCanRedo] = useState(false);const [allResolved, setAllResolved] = useState(false);@@ -273,7 +273,7 @@ export function ConflictView({rerenderAndRestore(snapshot);};- handleIdenticalChoiceRef.current = (selection) => {+ const handleIdenticalChoice = (selection: MergeConflictResolution) => {if (parseMismatched) {console.warn(JSON.stringify({@@ -290,6 +290,7 @@ export function ConflictView({syncState(snapshot);rerenderAndRestore(snapshot);};+ setIdenticalChoiceHandler(() => handleIdenticalChoice);handleApplyRef.current = () => {const content = matchTrailingNewline(history.current.file.contents, ours, theirs);@@ -328,7 +329,7 @@ export function ConflictView({handleActionRef.current = null;handleUndoRef.current = null;handleRedoRef.current = null;- handleIdenticalChoiceRef.current = null;+ setIdenticalChoiceHandler(null);handleApplyRef.current = null;setControls([]);setCanUndo(false);@@ -418,11 +419,9 @@ export function ConflictView({</Button>) : null}</div>- {identicalStaleVersions && !parseMismatch && !allResolved && (+ {identicalStaleVersions && identicalChoiceHandler && !parseMismatch && !allResolved && (<div className="shrink-0 px-3 py-2">- <ConflictActions- onSelect={(selection) => handleIdenticalChoiceRef.current?.(selection)}- />+ <ConflictActions onSelect={identicalChoiceHandler} /></div>)}<sectiondiff --git a/packages/app/src/components/DiffViewBoundary.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.dom.test.tsxindex 3c701928c..421385133 100644--- a/packages/app/src/components/DiffViewBoundary.dom.test.tsx+++ b/packages/app/src/components/DiffViewBoundary.dom.test.tsx@@ -339,6 +339,58 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {},);+ 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',+ },+ ),+ );+ };++ 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();+ }+ },+ );+test('emits editor-area-swap-to-diffview on mount and -from on unmount', async () => {const provider = makeProvider('seed\n');const { unmount } = render(<DiffViewBoundary docName="logs/entry" provider={provider} />);diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsxindex 5eb29065c..e99eba573 100644--- a/packages/app/src/components/EditorArea.dom.test.tsx+++ b/packages/app/src/components/EditorArea.dom.test.tsx@@ -216,6 +216,7 @@ vi.doMock('react-resizable-panels', () => ({current: {getLayout: () => groupLayout,setLayout: (layout: Record<string, number>) => {+ groupLayout = layout;groupSetLayoutCalls.push(layout);},},@@ -926,6 +927,12 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {test('a view with no document pane pins the slot shut and ignores the toggle', async () => {setViewportWidth(1400);docCtx = ASSET_DOC_CTX;+ groupLayout = {+ 'editor-main': 100 - pctOf(480),+ 'doc-panel': 0,+ 'terminal-column': 0,+ 'agents-column': pctOf(480),+ };render(<EditorArea {...baseProps} agentsVisible />);groupSetLayoutCalls = [];groupLayout = {diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 2530995d2..404507b2d 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -2925,9 +2925,10 @@ describe('ThreadView drop-notice for unattachable files', () => {model = makeModel({ items: [], turnActive: false });render(<ThreadView info={makeInfo({ status: 'ready' })} />);fireDrop([makeFile('foo.ts', 'text/typescript')]);- await vi.waitFor(() =>- expect(screen.getByTestId('agent-thread-drop-notice').textContent).toContain('Skipped'),- );+ await act(async () => {+ await Promise.resolve();+ });+ expect(screen.getByTestId('agent-thread-drop-notice').textContent).toContain('Skipped');act(() => {vi.advanceTimersByTime(4100);});diff --git a/packages/app/tests/integration/teardown-fs-errno.test.ts b/packages/app/tests/integration/teardown-fs-errno.test.tsindex eb0bd1668..91b9cb6c5 100644--- a/packages/app/tests/integration/teardown-fs-errno.test.ts+++ b/packages/app/tests/integration/teardown-fs-errno.test.ts@@ -2,7 +2,11 @@ import { existsSync, mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';-import { removeAllDuringTeardown } from '../stress/_helpers/teardown-fs.ts';+import {+ removeAllDuringTeardown,+ removeAllStrictDuringTeardown,+ runTeardownPhases,+} from '../stress/_helpers/teardown-fs.ts';vi.mock('node:fs', async (importOriginal) => {const actual = await importOriginal<typeof import('node:fs')>();@@ -121,3 +125,67 @@ describe('removeAllDuringTeardown removal policy', () => {expect(mockedRm).not.toHaveBeenCalled();});});++describe('removeAllStrictDuringTeardown', () => {+ test('attempts every target even after one throws, and rethrows the first failure', () => {+ const first = errnoError('EBUSY');+ const second = errnoError('EPERM');+ const seen: string[] = [];+ mockedRm.mockImplementation((target) => {+ seen.push(target as string);+ if (target === '/tmp/one') throw first;+ if (target === '/tmp/two') throw second;+ });+ expect(() => removeAllStrictDuringTeardown('/tmp/one', '/tmp/two', '/tmp/three')).toThrow(+ first,+ );+ expect(seen).toEqual(['/tmp/one', '/tmp/two', '/tmp/three']);+ });++ test('tolerates nothing, unlike its sibling', () => {+ const tolerated = errnoError('ENOTEMPTY');+ mockedRm.mockImplementation(() => {+ throw tolerated;+ });+ expect(() => removeAllStrictDuringTeardown('/tmp/one')).toThrow(tolerated);+ expect(() => removeAllDuringTeardown('/tmp/one')).not.toThrow();+ });++ test('retries a removal rather than giving it one attempt', () => {+ mockedRm.mockImplementation(() => {});+ removeAllStrictDuringTeardown('/tmp/one');+ expect(mockedRm).toHaveBeenCalledWith('/tmp/one', expect.objectContaining({ maxRetries: 3 }));+ });+});++describe('runTeardownPhases', () => {+ test('runs every phase even after one throws, and rethrows the first failure', async () => {+ const first = new Error('phase one');+ const ran: string[] = [];+ await expect(+ runTeardownPhases(+ async () => {+ ran.push('one');+ throw first;+ },+ () => {+ ran.push('two');+ throw new Error('phase two');+ },+ () => {+ ran.push('three');+ },+ ),+ ).rejects.toBe(first);+ expect(ran).toEqual(['one', 'two', 'three']);+ });++ test('resolves when every phase succeeds', async () => {+ await expect(+ runTeardownPhases(+ () => {},+ async () => {},+ ),+ ).resolves.toBeUndefined();+ });+});diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.tsindex 3e18b8f3b..2b77d358b 100644--- a/packages/app/tests/integration/test-harness.ts+++ b/packages/app/tests/integration/test-harness.ts@@ -1,5 +1,5 @@import { execFile } from 'node:child_process';-import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';import { createServer as createHttpServer } from 'node:http';import { createServer as createNetServer, type Socket } from 'node:net';import { tmpdir } from 'node:os';@@ -52,6 +52,11 @@ import type { ProviderPool } from '../../src/editor/provider-pool';import { dispatchCC1Stateless, SYSTEM_DOC_NAME } from '../../src/lib/cc1';import { createSyncedReconnectGate, refreshServerInfo } from '../../src/lib/server-info-refresh';import { getFreePort } from '../free-port.test-helper.ts';+import {+ removeAllDuringTeardown,+ removeAllStrictDuringTeardown,+ runTeardownPhases,+} from '../stress/_helpers/teardown-fs.ts';import { ControllableWebSocket } from './network-control';export const mdManager = new MarkdownManager({ extensions: sharedExtensions });@@ -212,15 +217,16 @@ export async function createTestServer(options: CreateTestServerOptions = {}): Pawait srv.destroy();mount.wss.close();await new Promise<void>((resolve) => httpServer.close(() => resolve()));- if (createdProjectDir) {- rmSync(projectDir, { recursive: true, force: true });- }- if (!options.keepContentDir) {- rmSync(contentDir, { recursive: true, force: true });- }- if (ownedHomeDir !== null) {- rmSync(ownedHomeDir, { recursive: true, force: true });- }+ await runTeardownPhases(+ () => {+ if (createdProjectDir) removeAllStrictDuringTeardown(projectDir);+ },+ () =>+ removeAllDuringTeardown(+ ...(options.keepContentDir ? [] : [contentDir]),+ ...(ownedHomeDir !== null ? [ownedHomeDir] : []),+ ),+ );},};}@@ -1162,7 +1168,7 @@ export async function createRestartableServer(} catch {}}if (!options.keepContentDir) {- rmSync(contentDir, { recursive: true, force: true });+ removeAllStrictDuringTeardown(contentDir);}};@@ -1456,9 +1462,7 @@ export async function createSyncWiredTestServer();const removeScratch = (): void => {- rmSync(originDir, { recursive: true, force: true });- rmSync(authorDir, { recursive: true, force: true });- rmSync(cloneParent, { recursive: true, force: true });+ removeAllStrictDuringTeardown(originDir, authorDir, cloneParent);};const testServer = await createTestServer({@@ -1471,8 +1475,7 @@ export async function createSyncWiredTestServer(const engine = testServer.instance.syncEngine;if (engine === null) {- await testServer.cleanup();- removeScratch();+ await runTeardownPhases(() => testServer.cleanup(), removeScratch);throw new Error('createSyncWiredTestServer: SyncEngine did not attach — expected an origin remote on the cloned contentDir',);@@ -1492,8 +1495,7 @@ export async function createSyncWiredTestServer(...testServer,sync: { originDir, pushToOrigin, engine },cleanup: async () => {- await testServer.cleanup();- removeScratch();+ await runTeardownPhases(() => testServer.cleanup(), removeScratch);},};}diff --git a/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts b/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.tsindex b12a7cb1a..3e38d3a0b 100644--- a/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts+++ b/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';import { resolve } from 'node:path';import { bootServer, ConfigSchema } from '@inkeep/open-knowledge-server';import { afterEach, describe, expect, test } from 'vitest';+import { removeAllDuringTeardown } from '../stress/_helpers/teardown-fs.ts';import { createLinkedWorktree, type LinkedWorktreeHandle } from './worktree-test-harness.ts';const TEST_CONFIG = ConfigSchema.parse({});@@ -14,9 +15,7 @@ const adhocDirs: string[] = [];afterEach(() => {handle?.cleanup();handle = null;- for (const d of adhocDirs.splice(0)) {- rmSync(d, { recursive: true, force: true });- }+ removeAllDuringTeardown(...adhocDirs.splice(0));});describe('git worktree remove cleans up the per-worktree shadow (FR6)', () => {diff --git a/packages/app/tests/integration/worktree-concurrent.test.ts b/packages/app/tests/integration/worktree-concurrent.test.tsindex cbeb1545f..d5214991f 100644--- a/packages/app/tests/integration/worktree-concurrent.test.ts+++ b/packages/app/tests/integration/worktree-concurrent.test.ts@@ -67,9 +67,8 @@ describe('Two linked worktrees boot in parallel with isolated state (D13)', () =expect(existsSync(lockPathB)).toBe(true);const lockContentsA = readFileSync(lockPathA, 'utf-8');const lockContentsB = readFileSync(lockPathB, 'utf-8');- expect(lockContentsA).toContain(String(bootedA.port));- expect(lockContentsB).toContain(String(bootedB.port));- expect(lockContentsA).not.toContain(String(bootedB.port));+ expect(JSON.parse(lockContentsA)).toMatchObject({ port: bootedA.port });+ expect(JSON.parse(lockContentsB)).toMatchObject({ port: bootedB.port });const refsA = execFileSync('git',diff --git a/packages/app/tests/stress/_helpers/teardown-fs.ts b/packages/app/tests/stress/_helpers/teardown-fs.tsindex 705672aee..90f43cbc9 100644--- a/packages/app/tests/stress/_helpers/teardown-fs.ts+++ b/packages/app/tests/stress/_helpers/teardown-fs.ts@@ -20,3 +20,29 @@ export function removeAllDuringTeardown(...targets: string[]): void {}if (firstUntolerated !== undefined) throw firstUntolerated;}++export function removeAllStrictDuringTeardown(...targets: string[]): void {+ let firstFailure: unknown;+ for (const target of targets) {+ try {+ rmSync(target, { recursive: true, force: true, maxRetries: REMOVAL_RETRIES });+ } catch (err) {+ firstFailure ??= err;+ }+ }+ if (firstFailure !== undefined) throw firstFailure;+}++export async function runTeardownPhases(+ ...phases: Array<() => void | Promise<void>>+): Promise<void> {+ let firstFailure: unknown;+ for (const phase of phases) {+ try {+ await phase();+ } catch (err) {+ firstFailure ??= err;+ }+ }+ if (firstFailure !== undefined) throw firstFailure;+}diff --git a/packages/desktop/src/main/bug-report-sidecar.test.ts b/packages/desktop/src/main/bug-report-sidecar.test.tsindex 465c3fa4b..88c6d7dcb 100644--- a/packages/desktop/src/main/bug-report-sidecar.test.ts+++ b/packages/desktop/src/main/bug-report-sidecar.test.ts@@ -13,7 +13,8 @@ import { readFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import type { ReportSidecar } from '@inkeep/open-knowledge-core';-import { afterEach, describe, expect, test } from 'vitest';+import * as coreServer from '@inkeep/open-knowledge-core/server';+import { afterEach, describe, expect, test, vi } from 'vitest';import {createBugReportSidecarStore,createInFlightRegistry,@@ -951,11 +952,25 @@ describe('send hooks — a confirmed send is recorded even when the sidecar is uconst store = createBugReportSidecarStore({ dir });expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });+ const markerWriteEntered = Promise.withResolvers<void>();+ const releaseMarkerWrite = Promise.withResolvers<void>();+ const atomicWriteFile = coreServer.atomicWriteFile;+ const write = vi.spyOn(coreServer, 'atomicWriteFile').mockImplementation(async (...args) => {+ if (args[0] === sentMarkerPathForId(dir, id)) {+ markerWriteEntered.resolve();+ await releaseMarkerWrite.promise;+ }+ return atomicWriteFile(...args);+ });const send = store.sendHooks.onSendResult(id, { kind: 'sent', reference: 'REF-RACE' });- const removed = await store.remove(id);- await send;-- expect(removed).toEqual({ ok: false, reason: 'in-flight' });+ try {+ await markerWriteEntered.promise;+ expect(await store.remove(id)).toEqual({ ok: false, reason: 'in-flight' });+ } finally {+ releaseMarkerWrite.resolve();+ await send;+ write.mockRestore();+ }expect(existsSync(sentMarkerPathForId(dir, id))).toBe(true);});diff --git a/packages/desktop/src/main/main-thread-watchdog.test.ts b/packages/desktop/src/main/main-thread-watchdog.test.tsindex b66ca026f..71f3baefd 100644--- a/packages/desktop/src/main/main-thread-watchdog.test.ts+++ b/packages/desktop/src/main/main-thread-watchdog.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { setTimeout as delay } from 'node:timers/promises';@@ -355,11 +355,8 @@ describe('the worker witness', () => {const deadline = Date.now() + 10_000;while (written === null && Date.now() < deadline) {await delay(20);- try {- written = parseWatchdogRecord(readFileSync(path, 'utf8'));- } catch {- written = null;- }+ const observed = watchdog.readPrevious();+ written = observed.kind === 'record' ? observed.record : null;if (written !== null && written.mainTicksObserved < 1) written = null;}@@ -370,8 +367,6 @@ describe('the worker witness', () => {expect(written?.blockedForMs).toBeLessThan(1_000);expect(Number.isFinite(Date.parse(written?.writtenAt ?? ''))).toBe(true);- expect(watchdog.readPrevious()).toEqual({ kind: 'record', record: written });-handle.stop();handle.stop();diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex 2f70f6e82..99260ce42 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -4056,9 +4056,9 @@ describe('agent failures reach the server log', () => {);writeFileSync(dieFile, 'now');await waitUntil(- () => manager.getInfo(info.threadId)?.status === 'exited',+ () => lines.some((line) => line.msg.includes('agent exited unexpectedly')),15_000,- 'the agent to exit',+ 'the agent process exit to be logged',);const exitLine = lines.find((l) => l.msg.includes('agent exited unexpectedly'));diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex 02099111d..3e256ac02 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -320,7 +320,14 @@ describe('createServer() — derived-index branch lifecycle', () => {const coordinator = beginStartup.mock.instances[0] as DerivedDocumentIndex;beginStartup.mockRestore();const settle = vi.spyOn(DerivedDocumentIndex.prototype, 'settleBranchFromDisk');- const emit = vi.spyOn(server.cc1Broadcaster, 'emitBranchSwitched');+ const batchStatesAtBroadcast: boolean[] = [];+ const broadcast = server.cc1Broadcaster.emitBranchSwitched.bind(server.cc1Broadcaster);+ const emit = vi+ .spyOn(server.cc1Broadcaster, 'emitBranchSwitched')+ .mockImplementation((branch) => {+ batchStatesAtBroadcast.push(server.durabilityState.isBatchInProgress());+ broadcast(branch);+ });await git.checkout('feature');await vi.waitFor(() => expect(emit).toHaveBeenCalledWith('feature'), {@@ -330,7 +337,7 @@ describe('createServer() — derived-index branch lifecycle', () => {expect(settle).toHaveBeenCalledTimes(1);expect(settle.mock.invocationCallOrder[0]).toBeLessThan(emit.mock.invocationCallOrder[0] ?? 0);- expect(server.durabilityState.isBatchInProgress()).toBe(false);+ expect(batchStatesAtBroadcast).toEqual([false]);expect(await coordinator.getDocsForTagWithMatches('feature-branch')).toEqual([{ docName: 'feature', matchingTags: ['feature-branch'] },]);@@ -353,7 +360,14 @@ describe('createServer() — derived-index branch lifecycle', () => {new Error('injected branch settlement failure'),);const abort = vi.spyOn(DerivedDocumentIndex.prototype, 'abortBranchSwitch');- const emit = vi.spyOn(server.cc1Broadcaster, 'emitBranchSwitched');+ const batchStatesAtBroadcast: boolean[] = [];+ const broadcast = server.cc1Broadcaster.emitBranchSwitched.bind(server.cc1Broadcaster);+ const emit = vi+ .spyOn(server.cc1Broadcaster, 'emitBranchSwitched')+ .mockImplementation((branch) => {+ batchStatesAtBroadcast.push(server.durabilityState.isBatchInProgress());+ broadcast(branch);+ });await git.checkout('feature');await vi.waitFor(() => expect(emit).toHaveBeenCalledWith('feature'), {@@ -362,7 +376,7 @@ describe('createServer() — derived-index branch lifecycle', () => {});expect(abort).toHaveBeenCalled();- expect(server.durabilityState.isBatchInProgress()).toBe(false);+ expect(batchStatesAtBroadcast).toEqual([false]);await expect(coordinator.getIndexedDocNames()).resolves.toBeInstanceOf(Array);}, 20_000);