Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Preserve task-board delivery state and safe history recycling
wytd383877c5f14
diff --git a/src/main/features/group_chat/task_board.ts b/src/main/features/group_chat/task_board.tsindex 5820be89..ff9abb03 100644--- a/src/main/features/group_chat/task_board.ts+++ b/src/main/features/group_chat/task_board.ts@@ -125,6 +125,9 @@ export interface ConversationTask {* log, so a user reply that continues this row gets this copy instead. */assignment_context?: string;source_msg_id?: string;+ /** Send now has persisted the user bubble. Independent of runtime+ * acceptance: the queued item may still await the next steer boundary. */+ message_sent_at?: string;result_msg_id?: string;turn_id?: string;/** A queued user task explicitly folded into an already-running turn.@@ -269,6 +272,7 @@ function normalizeTask(raw: any, cid: string): ConversationTask | null {t.assignment_context = raw.assignment_context;}if (typeof raw.source_msg_id === 'string' && raw.source_msg_id) t.source_msg_id = raw.source_msg_id;+ if (typeof raw.message_sent_at === 'string' && raw.message_sent_at) t.message_sent_at = raw.message_sent_at;if (typeof raw.result_msg_id === 'string' && raw.result_msg_id) t.result_msg_id = raw.result_msg_id;if (typeof raw.turn_id === 'string' && raw.turn_id) t.turn_id = raw.turn_id;if (typeof raw.absorbed_into_turn_id === 'string' && raw.absorbed_into_turn_id) {@@ -404,9 +408,11 @@ function scheduleFlush(b: BoardState): void {});}-/** Wait until every board's pending snapshot is on disk. */-export async function flushBoards(): Promise<void> {- await Promise.all([..._boards.values()].map((b) => {+/** Settle pending snapshots for one conversation, or every board at teardown. */+export async function flushBoards(scope?: { uid: string; cid: string }): Promise<void> {+ const selected = scope ? _boards.get(boardKey(scope.uid, scope.cid)) : undefined;+ const boards = scope ? (selected ? [selected] : []) : [..._boards.values()];+ await Promise.all(boards.map((b) => {const run = b.chain.then(() => flushLocked(b));b.chain = run.catch(() => {});return run;@@ -541,6 +547,18 @@ export function confirmQueued(});}+/** Publish message delivery without claiming execution or absorption. */+export function markMessageSent(+ uid: string, cid: string, taskId: string, sentAt: string,+): Promise<ConversationTask | null> {+ return withBoard(uid, cid, (b) => {+ const task = b.tasks.find((row) => row.task_id === taskId);+ if (!task || task.created_by !== 'user') return null;+ task.message_sent_at ||= sentAt;+ return { ...task };+ });+}+export interface ClaimResult {running: ConversationTask | null;/** Same-assignee waiting_input tasks SUPERSEDED (cancelled) by this claim:diff --git a/src/main/features/task_cleanup.ts b/src/main/features/task_cleanup.tsindex 2e05a92d..274806bc 100644--- a/src/main/features/task_cleanup.ts+++ b/src/main/features/task_cleanup.ts@@ -9,6 +9,7 @@ import * as chats from './chats';import * as recycle from './recycle_bin';import { getProject } from './projects';import { abort, isQuiescent } from './group_chat/bus';+import { flushBoards } from './group_chat/task_board';import { hasPendingAttachmentsForCleanup } from './chat_attachments';import { conversationLayout, conversationMessageReadFile, chatAttachmentDirForConversation } from '../util/project-layout';import { indexedJsonlStamp } from '../util/indexed-jsonl';@@ -209,6 +210,10 @@ export async function remove(uid: string, token: string, cid: string) {// Stop writes current activity timestamps. Keep that boundary for backup// retries, but never accept later execution writes or another live run.cutoff = Date.now() + 1;+ // Stop's task-board terminal is coalesced asynchronously. Settle only+ // this conversation before freezing the file revision; keep the activity+ // cutoff at Stop completion so waiting does not admit later work.+ await flushBoards({ uid, cid });s.stopped.set(cid, { cutoff, revision: await executionRevision(uid, cid, projectId) });}const canDelete = async (candidate: chats.Conversation | null) => {diff --git a/test/e2e/task_cleanup_e2e_history.spec.ts b/test/e2e/task_cleanup_e2e_history.spec.tsindex ae5b3475..4b363d39 100644--- a/test/e2e/task_cleanup_e2e_history.spec.ts+++ b/test/e2e/task_cleanup_e2e_history.spec.ts@@ -239,28 +239,146 @@ test.describe('inline historical task cleanup', () => {await section.locator('[data-cleanup-action="prepare"]').click();await expect(section).toContainText('Running tasks are stopped automatically before cleanup.');await section.screenshot({ path: testInfo.outputPath('cleanup-stop-confirm.png') });- await section.locator('[data-cleanup-action="confirm"]').click();- await expect(section).toContainText('Recycled 1');- expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(false);- // A polling request can overlap the tombstone commit. Absence is the- // required history result until the user explicitly restores this task.- const missing = await app.invoke<any>('conversations.history', { cid });- expect(missing).toMatchObject({ ok: false, error: 'conversation not found' });- await testInfo.attach('deleted-history-receipt', {- body: Buffer.from(JSON.stringify({ expectedAbsent: true, code: missing.code, deletedFileAbsent: true })),- contentType: 'application/json',- });- app.releaseControlledModelChunk(); app.finishControlledModelStream();- const { batches } = await app.invoke<any>('recycle.list');- const batch = batches.find((entry: any) => entry.items.some((item: any) => item.path === `cloud/chats/${cid}.jsonl`));- expect(batch).toBeTruthy();- expect((await app.invoke<any>('recycle.restore', { id: batch.id })).failed).toBe(0);- const history = readFileSync(path.join(root, `${cid}.jsonl`), 'utf8');- expect(history).toContain('Write a short task cleanup fixture.');- const restored = await app.invoke<any>('conversations.history', { cid });- expect(restored.ok).toBe(true);- expect(JSON.stringify(restored.history)).toContain('Write a short task cleanup fixture.');- expect((await app.invoke<any>('groupChat.runtimeStatus', { cid })).processing).toBe(false);+ // Observe only the selected task's original IPC promises; never await a+ // replacement result, inspect metadata, or publish private request data.+ await app.electronApp!.evaluate(({ ipcMain }, selectedCid) => {+ const handlers = (ipcMain as any)._invokeHandlers as Map<string, Function>;+ const original = handlers.get('orkas.invoke')!;+ if (typeof original !== 'function') throw new Error('Cleanup evidence requires the real IPC handler');+ const state = { stage: 'cleanup', rows: [] as any[], overflow: 0, restored: false };+ const missing = (value: any) => value?.ok === false && (+ value.code === 'E_CONVERSATION_NOT_FOUND' || value.code === 'E_NOT_FOUND'+ || value.error === 'conversation not found');+ function observed(this: unknown, event: unknown, request: any) {+ const selected = request?.payload?.cid === selectedCid+ && ['conversations.history', 'groupChat.abort', 'videoStudio.reviewPanel'].includes(request?.channel);+ const returned = original.call(this, event, request);+ if (!selected) return returned;+ if (state.rows.length >= 64) { state.overflow++; return returned; }+ const row: any = { channel: request.channel, startStage: state.stage,+ settled: false, ok: null, knownMissing: false, missingCode: null, rejected: false, reviewEmpty: null };+ state.rows.push(row);+ const observe = (value: any, rejected: boolean) => {+ try {+ Object.assign(row, { endStage: state.stage, settled: true,+ ok: !rejected && value?.ok === true, knownMissing: !rejected && missing(value), rejected,+ missingCode: !rejected && missing(value)+ ? (['E_UNKNOWN', 'E_NOT_FOUND', 'E_CONVERSATION_NOT_FOUND'].includes(value.code) ? value.code : 'other') : null,+ reviewEmpty: request.channel === 'videoStudio.reviewPanel'+ ? Array.isArray(value?.panel?.compositions) && value.panel.compositions.length === 0 : null });+ } catch { /* Observation cannot alter the real response. */ }+ };+ // This non-async wrapper returns the exact original Promise/object.+ // Both side-observer callbacks are bounded and never rethrow.+ if (returned && typeof returned.then === 'function') void returned.then(+ (value: unknown) => observe(value, false), () => observe(null, true));+ else observe(returned, false);+ return returned;+ }+ ipcMain.removeHandler('orkas.invoke'); ipcMain.handle('orkas.invoke', observed as any);+ (globalThis as any).__cleanupLifetimeEvidence = { state, restore() {+ if (handlers.get('orkas.invoke') === observed) {+ ipcMain.removeHandler('orkas.invoke'); ipcMain.handle('orkas.invoke', original as any);+ state.restored = true;+ }+ } };+ }, cid);+ await page.evaluate(selectedCid => {+ const root = window as any, apiFetch = root.apiFetch, video = root.VideoReviewPanel;+ const rows: any[] = []; let overflow = 0;+ const push = (channel: string) => {+ if (rows.length >= 64) { overflow++; return; }+ const stack = String(new Error().stack || '');+ rows.push({ channel, historyLoader: stack.includes('loadConversationHistory'),+ missingRecovery: stack.includes('_recoverMissingConversation'),+ conversationModule: stack.includes('/modules/conversation.js') });+ };+ function observedFetch(this: unknown, url: unknown, ...args: any[]) {+ if (typeof url === 'string') {+ if (url.startsWith('/api/conversations/' + encodeURIComponent(selectedCid) + '/history?')) push('conversations.history');+ else if (url === '/api/conversations/' + selectedCid + '/abort') push('groupChat.abort');+ }+ return apiFetch.call(this, url, ...args);+ }+ const originals = { probe: video?.probe, notifyTurnEnd: video?.notifyTurnEnd };+ const wrappers: Record<string, Function> = {};+ for (const method of ['probe', 'notifyTurnEnd'] as const) if (typeof originals[method] === 'function') {+ wrappers[method] = function (this: unknown, owner: unknown, ...args: any[]) {+ if (owner === selectedCid) push('VideoReviewPanel.' + method);+ return originals[method].call(this, owner, ...args);+ };+ video[method] = wrappers[method];+ }+ root.apiFetch = observedFetch;+ root.__cleanupLifetimeEvidence = { rows, get overflow() { return overflow; }, restore() {+ if (root.apiFetch === observedFetch) root.apiFetch = apiFetch;+ for (const method of ['probe', 'notifyTurnEnd']) if (video?.[method] === wrappers[method]) video[method] = originals[method as keyof typeof originals];+ } };+ }, cid);+ const markStage = (stage: 'cleanup' | 'absence-check' | 'restore' | 'recovered') =>+ app.electronApp!.evaluate((_electron, stage) => { (globalThis as any).__cleanupLifetimeEvidence.state.stage = stage; }, stage);+ let evidence: any;+ try {+ await section.locator('[data-cleanup-action="confirm"]').click();+ await expect(section).toContainText('Recycled 1');+ await markStage('absence-check');+ expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(false);+ // A polling request can overlap the tombstone commit. Absence is the+ // required history result until the user explicitly restores this task.+ const missing = await app.invoke<any>('conversations.history', { cid });+ expect(missing).toMatchObject({ ok: false, error: 'conversation not found' });+ await testInfo.attach('deleted-history-receipt', {+ body: Buffer.from(JSON.stringify({ expectedAbsent: true, code: missing.code, deletedFileAbsent: true })),+ contentType: 'application/json',+ });+ app.releaseControlledModelChunk(); app.finishControlledModelStream();+ const { batches } = await app.invoke<any>('recycle.list');+ const batch = batches.find((entry: any) => entry.items.some((item: any) => item.path === `cloud/chats/${cid}.jsonl`));+ expect(batch).toBeTruthy();+ await markStage('restore');+ // Independent existing file-absence oracle at the actual restore boundary.+ // This one additional assertion read is separate from the zero-I/O observer.+ expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(false);+ expect((await app.invoke<any>('recycle.restore', { id: batch.id })).failed).toBe(0);+ await markStage('recovered');+ const history = readFileSync(path.join(root, `${cid}.jsonl`), 'utf8');+ expect(history).toContain('Write a short task cleanup fixture.');+ const restored = await app.invoke<any>('conversations.history', { cid });+ expect(restored.ok).toBe(true);+ expect(JSON.stringify(restored.history)).toContain('Write a short task cleanup fixture.');+ expect((await app.invoke<any>('groupChat.runtimeStatus', { cid })).processing).toBe(false);+ await expect.poll(() => app.electronApp!.evaluate(() =>+ (globalThis as any).__cleanupLifetimeEvidence.state.rows.every((row: any) => row.settled),+ )).toBe(true);+ } finally {+ const main = await app.electronApp!.evaluate(() => {+ const owner = (globalThis as any).__cleanupLifetimeEvidence;+ owner.restore();+ return owner.state;+ });+ const renderer = await page.evaluate(() => {+ const owner = (window as any).__cleanupLifetimeEvidence;+ owner.restore();+ return { rows: owner.rows, overflow: owner.overflow };+ });+ evidence = { main, renderer };+ await testInfo.attach('cleanup-lifetime-requests', {+ body: Buffer.from(JSON.stringify(evidence)), contentType: 'application/json',+ });+ }+ expect(evidence.main.restored).toBe(true);+ expect(evidence.main.overflow).toBe(0);+ expect(evidence.renderer.overflow).toBe(0);+ const reviewCalls = evidence.main.rows.filter((row: any) => row.channel === 'videoStudio.reviewPanel');+ expect(reviewCalls.every((row: any) => row.settled && row.ok && row.reviewEmpty)).toBe(true);+ const historyCalls = evidence.main.rows.filter((row: any) => row.channel === 'conversations.history');+ const failures = historyCalls.filter((row: any) => row.settled && !row.ok);+ expect(failures.every((row: any) => row.knownMissing && !row.rejected)).toBe(true);+ expect(failures.every((row: any) => row.startStage !== 'recovered')).toBe(true);+ const absenceCalls = historyCalls.filter((row: any) => row.startStage === 'absence-check');+ expect(absenceCalls.length).toBeGreaterThan(0);+ expect(absenceCalls.every((row: any) => row.settled && !row.ok && row.knownMissing)).toBe(true);+ expect(historyCalls.some((row: any) => row.startStage === 'recovered' && row.settled && row.ok)).toBe(true);});for (const inProject of [false, true]) test(`previews, cancels, excludes, cleans and restores ${inProject ? 'project' : 'personal'} history using real IPC and storage`, async ({ orkas }, testInfo) => {const projectId = inProject ? (await orkas.invoke<any>('projects.create', { name: 'Cleanup project' })).project.project_id : '';diff --git a/test/main/features/group_chat/task-board.test.ts b/test/main/features/group_chat/task-board.test.tsindex c8c46bbe..c4ee2029 100644--- a/test/main/features/group_chat/task-board.test.ts+++ b/test/main/features/group_chat/task-board.test.ts@@ -83,6 +83,21 @@ describe('task_board › planned split note (D29)', () => {});describe('task_board › lifecycle', () => {+ it('persists sent-message state without claiming execution and retains it on reload', async () => {+ const tb = await board();+ const task = await tb.createTask(TEST_UID, TEST_CID, {+ assignee: 'commander', instruction: 'Correction', createdBy: 'user', sourceMsgId: 'm1',+ });+ const at = '2026-10-21T12:00:00Z';+ expect(await tb.markMessageSent(TEST_UID, TEST_CID, task.task_id, at)).toMatchObject({+ status: 'queued', message_sent_at: at,+ });+ expect((await readSnapshot())[0]).toMatchObject({ status: 'queued', message_sent_at: at });+ tb._resetForTest();+ const restored = (await tb.listTasks(TEST_UID, TEST_CID))[0];+ expect(restored.message_sent_at).toBe(at);+ expect(restored.absorbed_into_turn_id).toBeUndefined();+ });it('reports listener failure privately and still persists the task and notifies other listeners', async () => {const tb = await board();const next = vi.fn();diff --git a/test/main/features/task-cleanup-board-persistence.test.ts b/test/main/features/task-cleanup-board-persistence.test.tsnew file mode 100644index 00000000..99f89202--- /dev/null+++ b/test/main/features/task-cleanup-board-persistence.test.ts@@ -0,0 +1,262 @@+/** Real cleanup, task-board scheduling/storage, archive/delete/restore.+ * The bus boundary settles a synthetic live execution without a model request.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import { syncBuiltinESMExports } from 'node:module';+import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';++const bus = vi.hoisted(() => ({ quiet: false, abort: vi.fn() }));+const logs = vi.hoisted(() => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }));+vi.mock('../../../src/main/features/group_chat/bus', () => ({+ abort: (...args: any[]) => bus.abort(...args),+ isQuiescent: () => bus.quiet,+ dropConv: vi.fn(async () => {}),+ // The real archive/restore dependencies import the facade's event exports;+ // no event admission is part of this filesystem persistence scenario.+ subscribe: vi.fn(() => { throw new Error('Unexpected bus subscription'); }),+ submitCliAsyncInput: vi.fn(() => { throw new Error('Unexpected CLI input'); }),+ subscribeTaskTerminals: vi.fn(() => { throw new Error('Unexpected task subscription'); }),+}));+vi.mock('../../../src/main/logger', () => ({ createLogger: () => logs }));++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>(done => { resolve = done; });+ return { promise, resolve };+}+const uid = 'cleanup-board-user';+const cid = 'selected-history';+const old = '2020-01-01T00:00:00Z';+let root: string;+let previousRoot: string | undefined;+let releaseAll: Array<() => void> = [];+let pendingRemovals: Promise<unknown>[] = [];+function tracked<T>(pending: Promise<T>): Promise<T> { pendingRemovals.push(pending); return pending; }++beforeEach(async () => {+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;+ root = '';+ releaseAll = []; pendingRemovals = [];+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-cleanup-board-'));+ process.env.ORKAS_WORKSPACE_ROOT = root;+ vi.resetModules(); vi.clearAllMocks(); bus.quiet = false; releaseAll = []; pendingRemovals = [];+ const users = await import('../../../src/main/features/users');+ users.activateUser(uid);+ (await import('../../../src/main/features/group_chat/task_board'))._resetForTest();+});+afterEach(async () => {+ const failures: unknown[] = [];+ const attempt = async (operation: () => unknown | Promise<unknown>) => {+ try { await operation(); } catch (error) { failures.push(error); }+ };+ try {+ // Release every controlled writer first, including a failed/unrelated+ // branch. A failing test must never leave cleanup waiting on its gate.+ for (const release of releaseAll) await attempt(release);+ await attempt(() => Promise.allSettled(pendingRemovals));+ await attempt(async () => {+ const board = await import('../../../src/main/features/group_chat/task_board');+ try { await board.flushBoards(); }+ finally { board._resetForTest(); }+ });+ } finally {+ // Failure to flush or import an owner cannot skip resource/environment+ // restoration. Keep all failures, including independent log failures.+ await attempt(() => vi.restoreAllMocks());+ await attempt(() => syncBuiltinESMExports());+ try {+ await attempt(() => drainMainRuntimeForTest());+ } finally {+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;+ if (root) await attempt(() => fs.promises.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));+ }+ }+ // There are no expected WARN/ERROR events in these scenarios. The synthetic+ // bus owns no provider stream, so the original E2E's abort warnings do not+ // apply here. Inspect all captured messages if either independent gate fails.+ await attempt(() => expect(logs.error.mock.calls, 'Unexpected captured main-process errors').toEqual([]));+ await attempt(() => expect(logs.warn.mock.calls, 'Unreviewed captured main-process warnings').toEqual([]));+ if (failures.length) throw new AggregateError(failures, 'Cleanup persistence case teardown or captured logs failed');+});++async function seed() {+ const chats = await import('../../../src/main/features/chats');+ const board = await import('../../../src/main/features/group_chat/task_board');+ const { conversationLayout } = await import('../../../src/main/util/project-layout');+ const created = await chats.createConversation(uid, { conversationId: cid, title: 'History to recycle' });+ expect(created).toMatchObject({ conversation_id: cid, kind: 'normal' });+ const layout = conversationLayout(uid, cid);+ const tasksFile = path.join(layout.groupDir, 'tasks.json');+ const task = await board.createTask(uid, cid, {+ assignee: 'commander', createdBy: 'user', running: true,+ instruction: 'Keep this stopped history recoverable', sourceMsgId: 'original-input',+ });+ await board.flushBoards();+ fs.writeFileSync(layout.stateFile, JSON.stringify({ status: 'running', in_flight: ['commander'], last_active_at: old }));+ fs.writeFileSync(layout.messageFile, JSON.stringify({+ id: 'original-input', from: 'user', to: ['commander'], text: 'Keep this stopped history recoverable', ts: old,+ }) + '\n');+ // Match the live E2E fixture: age persisted data while the real in-memory+ // task stays live. No model response or expected terminal is injected.+ for (const file of [path.join(path.dirname(layout.groupDir), '_index.json'), path.join(layout.groupDir, 'meta.json'), tasksFile]) {+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));+ for (const row of Array.isArray(data) ? data : [data]) {+ if (row.conversation_id && row.conversation_id !== cid) continue;+ for (const key of ['created_at', 'updated_at', 'last_active_at', 'started_at', 'ended_at']) if (row[key]) row[key] = old;+ }+ fs.writeFileSync(file, JSON.stringify(data));+ }+ chats.invalidateConversationCaches(uid);+ return { chats, board, layout, tasksFile, task };+}++/** Hold a real atomic writer after its tmp bytes exist but before publication.+ * This is the same existing filesystem seam used by task-board.test.ts.+ * No scheduler/board mutation is replaced.+ */+async function arrangeDeferredStop(unrelated = false) {+ const seeded = await seed();+ const { board, layout, tasksFile, task } = seeded;+ const state = await import('../../../src/main/features/group_chat/state');+ const cleanup = await import('../../../src/main/features/task_cleanup');+ const recycle = await import('../../../src/main/features/recycle_bin');+ const { isAtomicWriteTempPath } = await import('../../../src/main/storage');+ const preview = await cleanup.preview(uid, { days: 30 });+ expect(preview.rows).toEqual([expect.objectContaining({ cid, selectable: true, blocked: 'busy' })]);+ const targetWritten = deferred(), targetRelease = deferred();+ const unrelatedWritten = deferred(), unrelatedRelease = deferred();+ const broadFlush = deferred();+ releaseAll.push(targetRelease.resolve, unrelatedRelease.resolve);+ const trace: string[] = [];+ let armed = false, stopReturned = false, targetPublished = false, otherPublished = false;+ const otherFile = path.join(path.dirname(layout.groupDir), 'unrelated-history', 'tasks.json');+ const writeFile = fs.promises.writeFile.bind(fs.promises);+ vi.spyOn(fs.promises, 'writeFile').mockImplementation(async (...args) => {+ await writeFile(...args);+ const file = String(args[0]);+ if (armed && file.startsWith(tasksFile + '.') && isAtomicWriteTempPath(file)) {+ trace.push('selected terminal tmp bytes ready'); targetWritten.resolve();+ await targetRelease.promise;+ }+ if (unrelated && file.startsWith(otherFile + '.') && isAtomicWriteTempPath(file)) {+ unrelatedWritten.resolve(); await unrelatedRelease.promise;+ }+ });+ const renameSync = fs.renameSync.bind(fs);+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ renameSync(from, to);+ if (armed && String(to) === tasksFile && isAtomicWriteTempPath(String(from))) { targetPublished = true; trace.push('selected terminal snapshot published'); }+ if (String(to) === otherFile && isAtomicWriteTempPath(String(from))) otherPublished = true;+ });+ const flush = board.flushBoards.bind(board);+ // Release the controlled writer if the cleanup requests its existing owner+ // barrier. This hook only controls I/O completion, never supplies a result.+ // The proposed optional selector must preserve default all-board behavior.+ vi.spyOn(board, 'flushBoards').mockImplementation(async (...args: any[]) => {+ if (stopReturned) {+ targetRelease.resolve();+ const scope = args[0];+ if (unrelated && (!scope || scope.uid !== uid || scope.cid !== cid)) broadFlush.resolve();+ }+ await (flush as any)(...args);+ });+ const stat = fs.promises.stat.bind(fs.promises);+ vi.spyOn(fs.promises, 'stat').mockImplementation((async (...args: any[]) => {+ const captured = await (stat as any)(...args);+ if (armed && stopReturned && String(args[0]) === tasksFile && !targetPublished) {+ // Valid concurrent schedule: the first receipt has already read old+ // metadata when the actual end-of-tick terminal write is published.+ trace.push('receipt sampled unpublished selected snapshot ' + JSON.stringify({ size: captured.size, mtimeMs: captured.mtimeMs, ctimeMs: captured.ctimeMs }));+ if (unrelated) broadFlush.resolve();+ targetRelease.resolve();+ await (flush as any)({ uid, cid });+ const published = await (stat as any)(...args);+ trace.push('published selected snapshot ' + JSON.stringify({ size: published.size, mtimeMs: published.mtimeMs, ctimeMs: published.ctimeMs }));+ return captured;+ }+ return captured;+ }) as any);+ syncBuiltinESMExports();+ if (unrelated) {+ await board.createTask(uid, 'unrelated-history', {+ assignee: 'agent-other', createdBy: 'user', running: true, instruction: 'Unrelated live work',+ });+ // The unrelated writer is deliberately still blocked when cleanup ends.+ await unrelatedWritten.promise;+ }+ bus.abort.mockImplementation(async () => {+ await state.setStatus(uid, cid, 'aborted');+ armed = true;+ await board.finishTask(uid, cid, task.task_id, 'cancelled');+ // Real scheduleFlush has started its writer, but it is not durable yet.+ await targetWritten.promise;+ bus.quiet = true; stopReturned = true; trace.push('Stop returned with terminal write pending');+ });+ const originalText = fs.readFileSync(layout.messageFile, 'utf8');+ return { ...seeded, cleanup, recycle, preview, originalText, trace, broadFlush,+ targetPublished: () => targetPublished, otherPublished: () => otherPublished };+}++describe('historical cleanup after deferred task-board persistence', () => {+ it('recycles only after its stopped task is durable and restores the original history and cancelled run', async () => {+ const s = await arrangeDeferredStop();+ // Baseline should fail here with skipped: its own Stop write changes the+ // revision between initial receipt and canDelete. Preserve that failure.+ expect(await tracked(s.cleanup.remove(uid, s.preview.token, cid)), JSON.stringify(s.trace)).toEqual({ status: 'deleted' });+ expect(s.targetPublished()).toBe(true);+ expect(fs.existsSync(s.layout.messageFile)).toBe(false);+ expect(await s.chats.getConversationMetadata(uid, cid)).toBeNull();+ const [batch] = await s.recycle.listRecycleBatches(uid);+ expect(batch.items.map(item => item.path)).toContain(`cloud/chats/${cid}/tasks.json`);+ const restored = await s.recycle.restoreRecycleBatch(uid, batch.id);+ expect(restored.batch?.id).toBe(batch.id);+ expect(restored.failed_paths).toEqual([]);+ expect(restored.restored_paths).toContain(`cloud/chats/${cid}.jsonl`);+ expect(fs.readFileSync(s.layout.messageFile, 'utf8')).toBe(s.originalText);+ expect(JSON.parse(fs.readFileSync(s.tasksFile, 'utf8'))).toEqual([+ expect.objectContaining({ task_id: s.task.task_id, status: 'cancelled', source_msg_id: 'original-input' }),+ ]);+ s.chats.invalidateConversationCaches(uid);+ expect(await s.chats.getConversationMetadata(uid, cid)).toMatchObject({ conversation_id: cid, title: 'History to recycle' });+ expect(bus.quiet).toBe(true);+ });++ it('preserves history and discards its backup if another task snapshot is written after the completed Stop', async () => {+ const s = await arrangeDeferredStop();+ const archive = s.recycle.createAppRecycleBatchForConversation.bind(s.recycle);+ vi.spyOn(s.recycle, 'createAppRecycleBatchForConversation').mockImplementation(async (...args) => {+ const receipt = await archive(...args);+ const rows = JSON.parse(fs.readFileSync(s.tasksFile, 'utf8'));+ rows[0].instruction = 'External change after Stop and during backup';+ fs.writeFileSync(s.tasksFile, JSON.stringify(rows));+ return receipt;+ });+ expect(await tracked(s.cleanup.remove(uid, s.preview.token, cid))).toEqual({ status: 'skipped' });+ // The archive must have really occurred before this external-change guard+ // can pass; otherwise the baseline's earlier false skip could mask it.+ expect(s.recycle.createAppRecycleBatchForConversation).toHaveBeenCalledOnce();+ expect(fs.readFileSync(s.layout.messageFile, 'utf8')).toBe(s.originalText);+ expect(JSON.parse(fs.readFileSync(s.tasksFile, 'utf8'))[0].instruction).toBe('External change after Stop and during backup');+ expect(await s.chats.getConversationMetadata(uid, cid)).not.toBeNull();+ expect(await s.recycle.listRecycleBatches(uid)).toEqual([]);+ });++ it('recycles the selected conversation without waiting for an unrelated blocked board writer', async () => {+ const s = await arrangeDeferredStop(true);+ const pending = tracked(s.cleanup.remove(uid, s.preview.token, cid));+ const result = await Promise.race([+ pending,+ s.broadFlush.promise.then(() => { throw new Error('Cleanup selected an unrelated blocked task-board writer'); }),+ ]);+ expect(result, JSON.stringify(s.trace)).toEqual({ status: 'deleted' });+ expect(s.targetPublished()).toBe(true);+ expect(s.otherPublished()).toBe(false);+ expect(fs.existsSync(s.layout.messageFile)).toBe(false);+ const [batch] = await s.recycle.listRecycleBatches(uid);+ expect(batch.items.some(item => item.path.includes('unrelated-history'))).toBe(false);+ });+});