an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
fix: make renderer task mutations atomic
baziyerb622f0ac56ad
diff --git a/package.json b/package.jsonindex 8dc851de..c974da3b 100644--- a/package.json+++ b/package.json@@ -19,7 +19,7 @@"typecheck:node": "tsc --noEmit -p tsconfig.node.json","typecheck:web": "tsc --noEmit -p tsconfig.web.json","typecheck": "npm run typecheck:node && npm run typecheck:web",- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs",+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs","check:links": "node tools/check-release-links.cjs","dist": "npm run build && electron-builder","dist:mac": "npm run build && electron-builder --mac",diff --git a/src/main/hive.ts b/src/main/hive.tsindex 16f5235c..62f62b69 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -94,6 +94,7 @@ export interface HumanQA {a?: string;askedAt?: string;answeredAt?: string;+ dismissedAt?: string;}export interface HiveTask {@@ -1324,6 +1325,40 @@ export class HiveManager {this.appendLog({ kind: 'tasks', count: tasks.length });this.commit(`hive: tasks (${tasks.length})`);}++ /** Append one card against the latest on-disk ledger. Renderer callers must+ * use this instead of re-writing a collection they read before another+ * source (webhook, Slack, god, voice) added work. Idempotent by task id. */+ addTask(task: HiveTask): boolean {+ const ledger = this.tasks() as { tasks?: HiveTask[] };+ const tasks = Array.isArray(ledger?.tasks) ? ledger.tasks : [];+ if (tasks.some((current) => current?.id === task.id)) return false;+ this.writeTasks([...tasks, task]);+ return true;+ }++ /** Patch one card against the latest on-disk ledger, preserving unrelated+ * cards and fields (notably webhook.tokenHash and Slack thread metadata). */+ patchTask(id: string, patch: Partial<Omit<HiveTask, 'id'>>): boolean {+ const ledger = this.tasks() as { tasks?: HiveTask[] };+ const tasks = Array.isArray(ledger?.tasks) ? ledger.tasks : [];+ const index = tasks.findIndex((task) => task?.id === id);+ if (index < 0) return false;+ const next = tasks.slice();+ next[index] = { ...tasks[index], ...patch, id };+ this.writeTasks(next);+ return true;+ }++ /** Delete only the named card from the latest on-disk ledger. */+ deleteTask(id: string): boolean {+ const ledger = this.tasks() as { tasks?: HiveTask[] };+ const tasks = Array.isArray(ledger?.tasks) ? ledger.tasks : [];+ const next = tasks.filter((task) => task?.id !== id);+ if (next.length === tasks.length) return false;+ this.writeTasks(next);+ return true;+ }memory(id: string): string {const p = join(this.agentDir(id), 'memory.md');return existsSync(p) ? readFileSync(p, 'utf8') : '';diff --git a/src/main/index.ts b/src/main/index.tsindex cb30da18..7504c84b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3076,11 +3076,25 @@ ipcMain.handle('hive:send', (_evt, partial: Partial<HiveMessage>, from: unknown)const msg = hive.send(partial ?? {}, typeof from === 'string' ? from : 'system');return { ok: true, message: msg };});-ipcMain.handle('hive:writeTasks', (_evt, tasks: unknown) => {- if (!Array.isArray(tasks)) return { ok: false, error: 'invalid tasks' };+ipcMain.handle('hive:addTask', (_evt, task: unknown) => {+ if (!task || typeof task !== 'object' || Array.isArray(task)+ || typeof (task as { id?: unknown }).id !== 'string') {+ return { ok: false, error: 'invalid task' };+ }if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };- hive.writeTasks(tasks as HiveTask[]);- return { ok: true };+ return { ok: hive.addTask(task as HiveTask) };+});+ipcMain.handle('hive:patchTask', (_evt, id: unknown, patch: unknown) => {+ if (typeof id !== 'string' || !id || !patch || typeof patch !== 'object' || Array.isArray(patch)) {+ return { ok: false, error: 'invalid task patch' };+ }+ if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };+ return { ok: hive.patchTask(id, patch as Partial<Omit<HiveTask, 'id'>>) };+});+ipcMain.handle('hive:deleteTask', (_evt, id: unknown) => {+ if (typeof id !== 'string' || !id) return { ok: false, error: 'invalid task id' };+ if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };+ return { ok: hive.deleteTask(id) };});ipcMain.handle('hive:setArchived', (_evt, id: unknown, archived: unknown) => {if (typeof id !== 'string') return { ok: false, error: 'invalid id' };diff --git a/src/preload/index.ts b/src/preload/index.tsindex a04efc67..a59cafe9 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -137,6 +137,7 @@ export interface HumanQA {a?: string;askedAt?: string;answeredAt?: string;+ dismissedAt?: string;}/** A card on the task kanban, persisted to hive/tasks.json. */@@ -962,9 +963,17 @@ const api = {},// ─── Task kanban (hive/tasks.json) ───────────────────────────────────────- /** Overwrite the hive task ledger with the full task list and commit it. */- hiveWriteTasks: (tasks: HiveTask[]): Promise<{ ok: boolean; error?: string }> =>- ipcRenderer.invoke('hive:writeTasks', tasks),+ /** Atomically append one card against the latest main-process ledger. */+ hiveAddTask: (task: HiveTask): Promise<{ ok: boolean; error?: string }> =>+ ipcRenderer.invoke('hive:addTask', task),+ /** Atomically patch one named card without replacing unrelated cards/fields. */+ hivePatchTask: (+ id: string,+ patch: Partial<Omit<HiveTask, 'id'>>+ ): Promise<{ ok: boolean; error?: string }> => ipcRenderer.invoke('hive:patchTask', id, patch),+ /** Atomically remove one named card from the latest main-process ledger. */+ hiveDeleteTask: (id: string): Promise<{ ok: boolean; error?: string }> =>+ ipcRenderer.invoke('hive:deleteTask', id),// ─── Scheduled missions (recurring auto-dispatch) ──────────────────────────listMissions: (): Promise<ScheduledMission[]> => ipcRenderer.invoke('missions:list'),diff --git a/src/renderer/src/components/AskMeTab.tsx b/src/renderer/src/components/AskMeTab.tsxindex 958f9f3e..2b64304f 100644--- a/src/renderer/src/components/AskMeTab.tsx+++ b/src/renderer/src/components/AskMeTab.tsx@@ -15,7 +15,7 @@ import { type HiveTask, openQuestion, waitsOnHuman } from './TasksKanban';* tasks stuck waiting on this one — so "why isn't X done?" reads as "ah,* because I still owe something here."*- * Sending an answer does two things atomically-ish:+ * Sending an answer does two things:* 1. writes it into the card's humanQA entry in hive/tasks.json (the* decision is documented ON the task, forever), and* 2. mails the god so it picks the answer up, unblocks the card, and the@@ -82,7 +82,11 @@ export function AskMeTab() {);return { ...t, humanQA: qa };});- await window.cth.hiveWriteTasks(next);+ const updated = next.find((candidate) => candidate.id === task.id);+ const result = updated+ ? await window.cth.hivePatchTask(task.id, { humanQA: updated.humanQA })+ : { ok: false };+ if (!result.ok) throw new Error('task changed before answer could be saved');setTasks(next);// 2) Tell the god, so the card gets unblocked and work continues.await window.cth.hiveSend({@@ -106,7 +110,6 @@ export function AskMeTab() {// stops returning it and the card leaves this view — the question itself stays// on the card, so the Q&A history is never dropped (protocol). The task stays// blocked on the kanban; the god can re-ask by appending a fresh humanQA entry.- // Reuses hiveWriteTasks (same path as the answer flow) — no new IPC.const dismiss = async (task: HiveTask) => {const open = openQuestion(task);if (!open || sending === task.id) return;@@ -121,7 +124,11 @@ export function AskMeTab() {});setTasks(next); // optimistic — the card disappears immediatelytry {- await window.cth.hiveWriteTasks(next);+ const updated = next.find((candidate) => candidate.id === task.id);+ const result = updated+ ? await window.cth.hivePatchTask(task.id, { humanQA: updated.humanQA })+ : { ok: false };+ if (!result.ok) throw new Error('task changed before ask could be dismissed');} catch {setTasks(tasks); // restore on failure so the user can retry}diff --git a/src/renderer/src/components/TaskDetailOverlay.tsx b/src/renderer/src/components/TaskDetailOverlay.tsxindex a0e562ac..0697df8a 100644--- a/src/renderer/src/components/TaskDetailOverlay.tsx+++ b/src/renderer/src/components/TaskDetailOverlay.tsx@@ -43,7 +43,10 @@ export function TaskDetailOverlay() {const move = async (status: HiveTask['status']) => {const next = tasks.map((t) => (t.id === task.id ? { ...t, status } : t));setTasks(next); // optimistic- try { await window.cth.hiveWriteTasks(next); } catch { void refresh(); }+ try {+ const result = await window.cth.hivePatchTask(task.id, { status });+ if (!result.ok) void refresh();+ } catch { void refresh(); }};const assign = () => {diff --git a/src/renderer/src/components/TasksKanban.tsx b/src/renderer/src/components/TasksKanban.tsxindex ad61f078..f2b7aea6 100644--- a/src/renderer/src/components/TasksKanban.tsx+++ b/src/renderer/src/components/TasksKanban.tsx@@ -7,8 +7,7 @@ import { useStore } from '@/store/store';/** A card on the task kanban. Mirrors HiveTask in the main/preload process —* re-declared locally so the renderer doesn't reach into the preload package- * (same convention as store/config.ts). Structurally compatible with- * window.cth.hiveWriteTasks. */+ * (same convention as store/config.ts). */export interface HumanQA {q: string;a?: string;@@ -131,17 +130,15 @@ export function TasksKanban() {// Dismiss a card off the board (human-initiated). The kanban is otherwise the// god's to write, but a person can clear a card they no longer want tracked.- // Operates on the RAW ledger (not the display-parsed state, which drops fields- // like notes/conversation) so dismissing one card never strips the others.+ // Main removes the named id from its latest on-disk ledger, so a webhook or+ // god card added since this renderer's last poll cannot be lost.const dismissTask = useCallback(async (id: string) => {setTasks((prev) => prev.filter((t) => t.id !== id)); // optimistictry {- const raw = (await window.cth.hiveTasks()) as { tasks?: unknown[] };- const arr = Array.isArray(raw?.tasks) ? raw.tasks : [];- const next = arr.filter((t) => !(t && typeof t === 'object' && (t as { id?: unknown }).id === id));- await window.cth.hiveWriteTasks(next as HiveTask[]);+ const result = await window.cth.hiveDeleteTask(id);+ if (!result.ok) void refresh();} catch { /* keep last good; the next poll re-syncs from disk */ }- }, []);+ }, [refresh]);useEffect(() => {refresh();diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex c7b10fd3..7883d2f7 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -763,7 +763,7 @@ export function useHive(config: HarnessConfig | null): void {// reply in-thread once the card later reaches 'done'. ADDITIVE + idempotent +// best-effort: a failure here never affects the dispatch that already happened,// and only dispatched work items land here (slash commands/acks never do).- type SlackTaskCard = Parameters<typeof window.cth.hiveWriteTasks>[0][number];+ type SlackTaskCard = Parameters<typeof window.cth.hiveAddTask>[0];const ensureSlackCard = async (m: QueuedMessage): Promise<void> => {const slack = m.slack;if (!slack) return;@@ -786,7 +786,7 @@ export function useHive(config: HarnessConfig | null): void {createdAt: new Date().toISOString(),slack};- await window.cth.hiveWriteTasks([...existing, card]);+ await window.cth.hiveAddTask(card);} catch { /* best-effort: card promotion must never sink dispatch */ }};diff --git a/test/hive-task-mutation.test.cjs b/test/hive-task-mutation.test.cjsnew file mode 100644index 00000000..3c94ce07--- /dev/null+++ b/test/hive-task-mutation.test.cjs@@ -0,0 +1,110 @@+'use strict';++/**+ * Regression for the 2026-08-15 webhook-card loss: ASK ME had read an eight-card+ * ledger, the webhook appended card nine, then ASK ME overwrote tasks.json with+ * its stale eight-card snapshot while recording an answer. Renderer actions must+ * mutate one card against the latest main-process ledger instead of replacing the+ * whole collection they happened to read earlier.+ */++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const loadTs = require('./load-ts.cjs');++const { HiveManager } = loadTs('src/main/hive.ts');++function floor(t) {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'md-task-mutate-'));+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));+ return new HiveManager(() => home);+}++function card(id, extra = {}) {+ return {+ id,+ title: id,+ status: 'todo',+ dependsOn: [],+ priority: 3,+ createdAt: '2026-08-15T08:00:00.000Z',+ ...extra+ };+}++function tasks(hive) {+ return hive.tasks().tasks;+}++test('patching a stale UI card preserves a concurrently appended webhook card', (t) => {+ const hive = floor(t);+ const question = card('needs-human', {+ status: 'blocked',+ humanQA: [{ q: 'Which option?', askedAt: '2026-08-15T08:00:00.000Z' }]+ });+ hive.writeTasks([question]);++ // The renderer still holds this one-card snapshot when the webhook arrives.+ const staleQuestion = structuredClone(tasks(hive)[0]);+ const webhook = card('webhook-1', {+ webhook: { tokenHash: 'a'.repeat(64) }+ });+ assert.equal(hive.addTask(webhook), true);++ staleQuestion.humanQA[0].a = 'Option B';+ staleQuestion.humanQA[0].answeredAt = '2026-08-15T08:00:01.000Z';+ assert.equal(hive.patchTask(staleQuestion.id, { humanQA: staleQuestion.humanQA }), true);++ assert.deepEqual(tasks(hive).map((task) => task.id), ['needs-human', 'webhook-1']);+ assert.equal(tasks(hive)[0].humanQA[0].a, 'Option B');+ assert.equal(tasks(hive)[1].webhook.tokenHash, 'a'.repeat(64));+});++test('atomic add is idempotent and delete removes only the named card', (t) => {+ const hive = floor(t);+ hive.writeTasks([card('existing')]);++ assert.equal(hive.addTask(card('new')), true);+ assert.equal(hive.addTask(card('new', { title: 'duplicate' })), false);+ assert.equal(hive.deleteTask('existing'), true);+ assert.equal(hive.deleteTask('missing'), false);++ assert.deepEqual(tasks(hive).map((task) => task.id), ['new']);+ assert.equal(tasks(hive)[0].title, 'new');+});++test('patch refuses an unknown card without rewriting the ledger', (t) => {+ const hive = floor(t);+ hive.writeTasks([card('existing')]);++ assert.equal(hive.patchTask('missing', { status: 'done' }), false);+ assert.deepEqual(tasks(hive), [card('existing')]);+});++test('renderer task actions never send a whole stale ledger back to main', () => {+ const root = path.resolve(__dirname, '..');+ const preload = fs.readFileSync(path.join(root, 'src/preload/index.ts'), 'utf8');+ const main = fs.readFileSync(path.join(root, 'src/main/index.ts'), 'utf8');+ const sources = [+ 'src/renderer/src/components/AskMeTab.tsx',+ 'src/renderer/src/components/TaskDetailOverlay.tsx',+ 'src/renderer/src/components/TasksKanban.tsx',+ 'src/renderer/src/hooks/useHive.ts'+ ].map((file) => fs.readFileSync(path.join(root, file), 'utf8'));++ for (const source of sources) {+ assert.doesNotMatch(source, /hiveWriteTasks\s*\(/,+ 'renderer code must use atomic task IPC rather than overwrite tasks.json');+ }+ assert.doesNotMatch(preload, /hiveWriteTasks\s*:/,+ 'the renderer bridge must not expose the unsafe whole-ledger write primitive');+ assert.doesNotMatch(main, /ipcMain\.handle\('hive:writeTasks'/,+ 'main must not accept whole-ledger writes from a stale renderer');+ assert.match(sources[0], /hivePatchTask\s*\(/);+ assert.match(sources[1], /hivePatchTask\s*\(/);+ assert.match(sources[2], /hiveDeleteTask\s*\(/);+ assert.match(sources[3], /hiveAddTask\s*\(/);+});