Skip to content

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

fix(hive): stop a single task edit from wiping every card on the board

Ed Chan75d1c0e41eca
diff --git a/package.json b/package.json
index 8dc851de..7e01c131 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-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/task-ledger.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.ts
index 16f5235c..4890c9bb 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -36,6 +36,7 @@ import {
type AgentProvider
} from '../shared/agentProvider';
import { MCP_CATALOG } from '../shared/mcpCatalog';
+import { mergeTaskLedger } from '../shared/taskLedger';
import { expandTilde } from './fs';
/** The subset of HarnessConfig the hive consumes for the default-MCP merge.
@@ -1315,14 +1316,28 @@ export class HiveManager {
}
/** Persist the task ledger to hive/tasks.json and commit it. Mirrors the
- * board/message persist pattern: write JSON, log the change, single-commit. */
+ * board/message persist pattern: write JSON, log the change, single-commit.
+ *
+ * MERGES by card id instead of clobbering. Callers hold PARTIAL models of a
+ * card — the renderer's kanban parser knows nine fields, the god writes as
+ * many as the work needs (`result`, the verbatim Slack reply posted back to
+ * the user; `repo`; `scope`; `origin`; `commit`; …). A wholesale write meant
+ * one small edit through the UI deleted every unmodelled field on EVERY card
+ * on the board. Now an unmentioned field keeps its on-disk value.
+ *
+ * Deleting a card still works: the incoming list IS the membership, so a card
+ * dropped from it (TasksKanban dismiss, the voice delete_task action) is
+ * gone. Merging protects fields, never card membership. */
writeTasks(tasks: HiveTask[]): void {
const root = this.root();
if (!root) return;
this.ensureHive();
- this.writeJson(join(root, 'tasks.json'), { tasks });
- this.appendLog({ kind: 'tasks', count: tasks.length });
- this.commit(`hive: tasks (${tasks.length})`);
+ const path = join(root, 'tasks.json');
+ const current = this.readJson<{ tasks?: unknown }>(path, { tasks: [] });
+ const merged = mergeTaskLedger(current?.tasks, tasks);
+ this.writeJson(path, { tasks: merged });
+ this.appendLog({ kind: 'tasks', count: merged.length });
+ this.commit(`hive: tasks (${merged.length})`);
}
memory(id: string): string {
const p = join(this.agentDir(id), 'memory.md');
diff --git a/src/renderer/src/components/AskMeTab.tsx b/src/renderer/src/components/AskMeTab.tsx
index 958f9f3e..e3b737bd 100644
--- a/src/renderer/src/components/AskMeTab.tsx
+++ b/src/renderer/src/components/AskMeTab.tsx
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { PixelButton } from './PixelButton';
import { PixelBadge } from './PixelBadge';
import { useStore } from '@/store/store';
-import { type HiveTask, openQuestion, waitsOnHuman } from './TasksKanban';
+import { type HiveTask, type HumanQA, openQuestion, waitsOnHuman } from './TasksKanban';
+import { patchTaskInLedger } from '../../../shared/taskLedger';
/**
* ASK ME — first-class human feedback through the task system.
@@ -66,6 +67,34 @@ export function AskMeTab() {
const waiting = tasks.filter(waitsOnHuman);
+ /**
+ * Apply `patch` to the OPEN humanQA entry of one card, on the RAW ledger.
+ * Returns whether it landed.
+ *
+ * Re-reads tasks.json first rather than writing this view's 5s-old snapshot,
+ * because `hive:writeTasks` treats the incoming array as the card MEMBERSHIP:
+ * writing our snapshot back would delete any card the god added since the last
+ * poll. Re-locating the open question by its text also means an answer can
+ * never land on a different question the god swapped in underneath us — in
+ * that case nothing is written and the draft is kept.
+ */
+ const patchOpenQuestion = async (
+ taskId: string,
+ question: string,
+ patch: Partial<HumanQA>
+ ): Promise<boolean> => {
+ const raw = (await window.cth.hiveTasks()) as { tasks?: unknown };
+ const list: unknown[] = Array.isArray(raw?.tasks) ? raw.tasks : [];
+ const card = list.find(
+ (t): t is HiveTask => !!t && typeof t === 'object' && (t as HiveTask).id === taskId
+ );
+ const open = card ? openQuestion(card) : undefined;
+ if (!card || !open || open.q !== question) return false;
+ const humanQA = (card.humanQA ?? []).map((e) => (e === open ? { ...e, ...patch } : e));
+ await window.cth.hiveWriteTasks(patchTaskInLedger(list, taskId, { humanQA }) as HiveTask[]);
+ return true;
+ };
+
const sendAnswer = async (task: HiveTask) => {
const text = (drafts[task.id] ?? '').trim();
const open = openQuestion(task);
@@ -73,17 +102,12 @@ export function AskMeTab() {
setSending(task.id);
try {
// 1) Document the answer ON the card.
- const next = tasks.map((t) => {
- if (t.id !== task.id) return t;
- const qa = (t.humanQA ?? []).map((e) =>
- e === open || (e.q === open.q && !e.a)
- ? { ...e, a: text, answeredAt: new Date().toISOString() }
- : e
- );
- return { ...t, humanQA: qa };
- });
- await window.cth.hiveWriteTasks(next);
- setTasks(next);
+ if (!(await patchOpenQuestion(task.id, open.q, { a: text, answeredAt: new Date().toISOString() }))) {
+ setSending(null);
+ await refresh(); // the ask moved on — show what the card says now
+ return;
+ }
+ await refresh();
// 2) Tell the god, so the card gets unblocked and work continues.
await window.cth.hiveSend({
to: 'god',
@@ -110,7 +134,8 @@ export function AskMeTab() {
const dismiss = async (task: HiveTask) => {
const open = openQuestion(task);
if (!open || sending === task.id) return;
- const next = tasks.map((t) => {
+ // Optimistic — the card disappears immediately.
+ setTasks((prev) => prev.map((t) => {
if (t.id !== task.id) return t;
const qa = (t.humanQA ?? []).map((e) =>
e === open || (e.q === open.q && !e.a && !e.dismissedAt)
@@ -118,13 +143,11 @@ export function AskMeTab() {
: e
);
return { ...t, humanQA: qa };
- });
- setTasks(next); // optimistic — the card disappears immediately
+ }));
try {
- await window.cth.hiveWriteTasks(next);
- } catch {
- setTasks(tasks); // restore on failure so the user can retry
- }
+ await patchOpenQuestion(task.id, open.q, { dismissedAt: new Date().toISOString() });
+ } catch { /* the refresh below restores whatever the ledger actually says */ }
+ await refresh();
};
return (
diff --git a/src/renderer/src/components/TaskDetailOverlay.tsx b/src/renderer/src/components/TaskDetailOverlay.tsx
index a0e562ac..2eee1cc6 100644
--- a/src/renderer/src/components/TaskDetailOverlay.tsx
+++ b/src/renderer/src/components/TaskDetailOverlay.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useStore } from '@/store/store';
import { TaskDetail, parseTasks, type HiveTask } from './TasksKanban';
+import { patchTaskInLedger } from '../../../shared/taskLedger';
/**
* App-wide host for the task detail: whoever calls store.openTaskDetail(id) —
@@ -40,10 +41,20 @@ export function TaskDetailOverlay() {
const nameFor = (id?: string): string | undefined =>
id ? (agents.find((a) => a.id === id)?.name ?? restorable.find((a) => a.id === id)?.name ?? id) : undefined;
+ // Moving a card writes ONE field. Operate on the RAW ledger (the same pattern
+ // as TasksKanban.dismissTask), never on the display-parsed state: parseTasks
+ // NORMALIZES, so re-serializing it turns a hand-written `priority: "high"`
+ // into the number 3 and grafts `dependsOn: []` onto a card that spells the key
+ // `deps`. Those are real values, so they survive the merge in hive.writeTasks
+ // and land on disk — a status change quietly rewriting the god's cards.
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(); }
+ setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, status } : t))); // optimistic
+ try {
+ const raw = (await window.cth.hiveTasks()) as { tasks?: unknown };
+ await window.cth.hiveWriteTasks(
+ patchTaskInLedger(raw?.tasks, task.id, { status }) as HiveTask[]
+ );
+ } catch { void refresh(); }
};
const assign = () => {
diff --git a/src/shared/taskLedger.ts b/src/shared/taskLedger.ts
new file mode 100644
index 00000000..978b8d0f
--- /dev/null
+++ b/src/shared/taskLedger.ts
@@ -0,0 +1,87 @@
+/**
+ * Non-destructive edits to the task ledger (`hive/tasks.json`).
+ *
+ * The ledger is a HAND-WRITTEN file: the god appends whatever fields a card
+ * needs — `result` (the verbatim Slack reply posted back to the user), `repo`,
+ * `scope`, `origin`, `deliverable`, `commit`, `blockedOn`, `notes` — none of
+ * which the renderer's display model knows about. Several UI surfaces write the
+ * ledger back after a small edit (answer a question, move a card, dismiss one),
+ * and `hive:writeTasks` replaces the file wholesale. So any writer holding a
+ * partial model of a card silently DELETED every field it didn't know about,
+ * on EVERY card on the board, the moment the user touched one of them.
+ *
+ * Two rules fix that, and both live here so main and the renderer share them:
+ *
+ * - `mergeTaskLedger` — the persistence-side backstop. A card the writer
+ * didn't fully describe keeps the fields it already had on disk.
+ * - `patchTaskInLedger` — the caller-side rule. Edit the RAW ledger entry
+ * rather than re-serializing a display model, so a normalizing parser can't
+ * overwrite a field it coerced (a string `priority` re-emitted as a number).
+ *
+ * Deletion deliberately still works: a card absent from the incoming list is
+ * gone. Merging protects fields, never card membership.
+ */
+
+/** One raw ledger entry as it sits on disk — an object of unknown fields. */
+type RawTask = Record<string, unknown>;
+
+function isRawTask(value: unknown): value is RawTask {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function idOf(value: unknown): string | null {
+ if (!isRawTask(value)) return null;
+ return typeof value.id === 'string' && value.id ? value.id : null;
+}
+
+/**
+ * Fold `incoming` over `existing`, matching cards by `id`.
+ *
+ * The result is `incoming` — its order, and its membership, so removing a card
+ * from the list still deletes it. What survives the fold are the fields on the
+ * matching on-disk card that `incoming` does not mention.
+ *
+ * A field the caller DOES send wins, including an explicit `null` — that's the
+ * way to clear one. A shallow merge cannot express "delete this key", and it
+ * shouldn't: writers here are partial models, so a missing key means "I don't
+ * know about this", never "remove it".
+ *
+ * Entries without a string `id` (a malformed card the god hand-wrote) pass
+ * through untouched — there is no key to merge them on, and dropping them would
+ * lose data the same way this function exists to prevent.
+ */
+export function mergeTaskLedger(existing: unknown, incoming: unknown): unknown[] {
+ const incomingList = Array.isArray(incoming) ? incoming : [];
+ const existingList = Array.isArray(existing) ? existing : [];
+ const byId = new Map<string, RawTask>();
+ for (const entry of existingList) {
+ const id = idOf(entry);
+ if (id && !byId.has(id)) byId.set(id, entry as RawTask);
+ }
+ return incomingList.map((entry) => {
+ const id = idOf(entry);
+ if (!id) return entry;
+ const prior = byId.get(id);
+ return prior ? { ...prior, ...(entry as RawTask) } : entry;
+ });
+}
+
+/**
+ * Apply `patch` to one card in a RAW ledger array, leaving every other card —
+ * and every other field of the patched card — byte-identical.
+ *
+ * This is what a UI edit should write. Re-serializing the display model instead
+ * feeds the ledger a normalized card: `parseTasks` coerces a hand-written
+ * `priority: "high"` to the number `3` and re-emits `dependsOn: []` for a card
+ * that spells the key `deps`, and those coercions are real values, so they beat
+ * `mergeTaskLedger` and land on disk. Patching the raw entry never produces
+ * them in the first place.
+ */
+export function patchTaskInLedger(
+ rawTasks: unknown,
+ id: string,
+ patch: Record<string, unknown>
+): unknown[] {
+ const list = Array.isArray(rawTasks) ? rawTasks : [];
+ return list.map((entry) => (idOf(entry) === id ? { ...(entry as RawTask), ...patch } : entry));
+}
diff --git a/test/task-ledger.test.cjs b/test/task-ledger.test.cjs
new file mode 100644
index 00000000..1718efa1
--- /dev/null
+++ b/test/task-ledger.test.cjs
@@ -0,0 +1,172 @@
+'use strict';
+
+/**
+ * Data-loss guarantee for hive/tasks.json.
+ *
+ * The ledger is hand-written by the god and carries whatever fields a card
+ * needs — `result` (the verbatim Slack reply posted back to the user), `repo`,
+ * `origin`, `commit`, string priorities, a `deps` key instead of `dependsOn`.
+ * Every UI surface that writes the ledger back holds only a PARTIAL model of a
+ * card, and `hive:writeTasks` replaced the file wholesale, so one edit through
+ * the UI stripped every unmodelled field from EVERY card on the board.
+ *
+ * Two legs, and both are needed — the merge alone does not fix a normalized
+ * write, because a coerced value is a real value and wins the merge:
+ * - mergeTaskLedger : a field the writer never mentioned keeps its disk value
+ * - patchTaskInLedger: the writer never emits a coerced value in the first place
+ */
+
+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 { mergeTaskLedger, patchTaskInLedger } = loadTs('src/shared/taskLedger.ts');
+const { HiveManager } = loadTs('src/main/hive.ts');
+
+/** A card as the god actually writes one — most of it outside any UI model. */
+const richCard = () => ({
+ id: 'vxr-onboarding-review',
+ title: 'Review the onboarding doc',
+ status: 'blocked',
+ deps: ['vxr-intake'],
+ priority: 'high',
+ createdAt: '2026-08-14T09:00:00.000Z',
+ repo: 'vxretail-migration',
+ origin: 'slack',
+ scope: 'docs/onboarding/**',
+ deliverable: 'a reviewed doc + summary',
+ commit: 'a1b2c3d',
+ result: 'Reviewed. Three gaps found — posted verbatim to the Slack thread.',
+ humanQA: [{ q: 'Which branch should I read?', askedAt: '2026-08-14T09:05:00.000Z' }]
+});
+
+// ── mergeTaskLedger ──────────────────────────────────────────────────────────
+
+test('a field the writer never mentioned survives the write', () => {
+ const disk = [richCard()];
+ // What the ASK ME view sends: the same card with its question answered.
+ const incoming = [{
+ id: 'vxr-onboarding-review',
+ title: 'Review the onboarding doc',
+ status: 'blocked',
+ humanQA: [{ q: 'Which branch should I read?', a: 'main', answeredAt: '2026-08-16T10:00:00.000Z' }]
+ }];
+
+ const [merged] = mergeTaskLedger(disk, incoming);
+
+ assert.equal(merged.result, 'Reviewed. Three gaps found — posted verbatim to the Slack thread.');
+ assert.equal(merged.repo, 'vxretail-migration');
+ assert.equal(merged.origin, 'slack');
+ assert.equal(merged.scope, 'docs/onboarding/**');
+ assert.equal(merged.deliverable, 'a reviewed doc + summary');
+ assert.equal(merged.commit, 'a1b2c3d');
+ assert.deepEqual(merged.deps, ['vxr-intake']);
+ assert.equal(merged.humanQA[0].a, 'main', 'the field the writer DID send must win');
+});
+
+test('deleting a card still deletes it — merging protects fields, not membership', () => {
+ const disk = [richCard(), { id: 'other', title: 'Other', status: 'todo' }];
+
+ assert.deepEqual(
+ mergeTaskLedger(disk, [{ id: 'other', title: 'Other', status: 'todo' }]).map((t) => t.id),
+ ['other'],
+ 'a card dropped from the incoming list is gone'
+ );
+ assert.deepEqual(mergeTaskLedger(disk, []), [], 'clearing the board still clears it');
+});
+
+test('an explicit null clears a field — a missing key never does', () => {
+ const disk = [{ id: 'a', title: 'A', status: 'blocked', blockedOn: 'the human' }];
+
+ assert.equal(mergeTaskLedger(disk, [{ id: 'a', blockedOn: null }])[0].blockedOn, null);
+ assert.equal(mergeTaskLedger(disk, [{ id: 'a', status: 'doing' }])[0].blockedOn, 'the human',
+ 'not mentioning a field means "I do not model it", never "remove it"');
+});
+
+test('a card the god wrote without an id passes through instead of being dropped', () => {
+ const incoming = [{ title: 'no id here', status: 'todo' }];
+ assert.deepEqual(mergeTaskLedger([], incoming), incoming);
+});
+
+test('a brand new card is added untouched', () => {
+ const fresh = { id: 'new', title: 'New', status: 'todo', slack: { channel: 'C1', thread_ts: '1.2' } };
+ const out = mergeTaskLedger([richCard()], [richCard(), fresh]);
+ assert.equal(out.length, 2);
+ assert.deepEqual(out[1], fresh);
+});
+
+// ── patchTaskInLedger ────────────────────────────────────────────────────────
+
+test('moving a card does not normalize the rest of it', () => {
+ // The corruption the merge CANNOT catch: parseTasks coerces `priority: "high"`
+ // to the number 3 and emits `dependsOn: []` for a card that spells it `deps`.
+ // Those are real values, so they beat the merge. Patching the raw entry is
+ // what stops them from ever being produced.
+ const [moved] = patchTaskInLedger([richCard()], 'vxr-onboarding-review', { status: 'done' });
+
+ assert.equal(moved.status, 'done');
+ assert.equal(moved.priority, 'high', 'a string priority must not be coerced to a number');
+ assert.deepEqual(moved.deps, ['vxr-intake']);
+ assert.equal(moved.dependsOn, undefined, 'no phantom dependsOn grafted on');
+ assert.equal(moved.result, 'Reviewed. Three gaps found — posted verbatim to the Slack thread.');
+});
+
+test('patching one card leaves its neighbours byte-identical', () => {
+ const neighbour = richCard();
+ neighbour.id = 'neighbour';
+ const out = patchTaskInLedger([richCard(), neighbour], 'vxr-onboarding-review', { status: 'done' });
+ assert.deepEqual(out[1], neighbour);
+});
+
+// ── end to end through the real persistence path ─────────────────────────────
+
+test('answering a question through hive.writeTasks preserves the whole board', (t) => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'md-task-ledger-'));
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ const ledger = () => JSON.parse(fs.readFileSync(path.join(home, 'hive', 'tasks.json'), 'utf8')).tasks;
+
+ const second = richCard();
+ second.id = 'hive-delivery-pump-down';
+ second.result = 'Root-caused and fixed; replied in thread.';
+ hive.writeTasks([richCard(), second]);
+
+ // The ASK ME view answers the question on the first card, sending the partial
+ // model it holds. The second card is sent as the view last read it.
+ hive.writeTasks([
+ {
+ id: 'vxr-onboarding-review',
+ title: 'Review the onboarding doc',
+ status: 'blocked',
+ humanQA: [{ q: 'Which branch should I read?', a: 'main', answeredAt: '2026-08-16T10:00:00.000Z' }]
+ },
+ { id: 'hive-delivery-pump-down', title: second.title, status: 'blocked' }
+ ]);
+
+ const [answered, untouched] = ledger();
+ assert.equal(answered.humanQA[0].a, 'main', 'the answer is recorded');
+ assert.equal(answered.result, 'Reviewed. Three gaps found — posted verbatim to the Slack thread.',
+ 'the Slack reply text must survive an answer — this is what was destroyed live');
+ assert.equal(answered.commit, 'a1b2c3d');
+ assert.equal(answered.priority, 'high');
+ assert.equal(untouched.result, 'Root-caused and fixed; replied in thread.',
+ 'a card nobody edited must not be collateral damage');
+ assert.deepEqual(untouched.deps, ['vxr-intake']);
+});
+
+test('hive.writeTasks can still empty the ledger', (t) => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'md-task-ledger-del-'));
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ const ledger = () => JSON.parse(fs.readFileSync(path.join(home, 'hive', 'tasks.json'), 'utf8')).tasks;
+
+ hive.writeTasks([richCard(), { id: 'other', title: 'Other', status: 'todo' }]);
+ hive.writeTasks([{ id: 'other', title: 'Other', status: 'todo' }]);
+ assert.deepEqual(ledger().map((t) => t.id), ['other']);
+
+ hive.writeTasks([]);
+ assert.deepEqual(ledger(), []);
+});