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
feat(roster): share the roster between dev and a packaged build
Vyapak Goyal159e4ce40851
diff --git a/src/main/index.ts b/src/main/index.tsindex 36eac6eb..eba0fbc4 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -33,6 +33,7 @@ import { SlackWebhookServer, SlackReplyServer, postSlackReply, type SlackEventFiimport { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';import { transcribeWithGroq, DEFAULT_GROQ_MODEL } from './freeflow';import { TelemetryCollector } from './telemetry';+import { RosterStore } from './roster';import { ControlRegistry } from './control';import { ClosingTimeController } from './closingTime';import {@@ -1883,7 +1884,11 @@ ipcMain.handle('config:changeHome', async (_evt, payload: unknown) => {if (mode === 'move' && oldHome) {try {- for (const sub of ['hive', 'palace']) {+ // roster.json + its backups ride along with hive/palace: the roster is the+ // renderer's half of the same state, and leaving it behind would move the+ // agents' sessions and memory to the new home while their names, notes and+ // worktree paths stayed at the old one.+ for (const sub of ['hive', 'palace', 'roster.json', 'roster-backups']) {const src = join(oldHome, sub);if (!existsSync(src)) continue;// cpSync copies the whole tree incl. .git and is cross-device safe (unlike@@ -1962,6 +1967,16 @@ ipcMain.handle('git:aheadBehind', (_evt, cwd: unknown) => {return getAheadBehind(cwd);});+// ─── IPC: roster mirror (shared between dev and a packaged build) ───────────+// The renderer's store is built synchronously at module load, before any async+// IPC could resolve, so the read is `ipcMain.on` + `returnValue` — one blocking+// round trip at boot, in exchange for the roster being correct on first paint+// instead of flashing an empty floor and then filling in.+const roster = new RosterStore(() => readConfig().harnessHome);+ipcMain.on('roster:readSync', (evt) => { evt.returnValue = roster.read(); });+ipcMain.handle('roster:read', () => roster.read());+ipcMain.handle('roster:write', (_evt, snap: unknown) => roster.write(snap));+// ─── IPC: hive (multi-agent coordination) ───────────────────────────────────ipcMain.handle('hive:registry', () => hive.registry());ipcMain.handle('hive:board', () => hive.board());@@ -2177,6 +2192,12 @@ ipcMain.handle('app:resetAll', () => {try { rmSync(dir, { recursive: true, force: true }); }catch (e) { console.error('[reset] rm', dir, e); }}+ // The roster is the renderer's half of the same state, so it retires with the+ // hive — archived into roster-backups/ rather than deleted, and cleared as the+ // active file so re-selecting this folder later doesn't resurrect agents whose+ // sessions and memory are gone.+ try { roster.archive(); }+ catch (e) { console.error('[reset] roster.archive:', e); }// Back to first-run defaults, then relaunch clean so all in-memory services// re-bootstrap from scratch and the renderer lands on onboarding.resetConfig();diff --git a/src/main/roster.ts b/src/main/roster.tsnew file mode 100644index 00000000..16b8751d--- /dev/null+++ b/src/main/roster.ts@@ -0,0 +1,193 @@+/**+ * The roster on disk — agents, their notes, worktree paths, archived and+ * restorable entries, and parked message queues, stored as one JSON file beside+ * the hive.+ *+ * WHY THIS EXISTS. All of that used to live only in the renderer's localStorage,+ * and localStorage is partitioned by ORIGIN. A dev run loads the renderer from+ * `http://localhost:5173` and a packaged build loads it from `file://`, so the+ * two never see each other's storage: switching between them showed an empty+ * floor and no notes, even though the hive on disk (sessions, memory, inboxes,+ * tasks) was right there and intact. A file keyed on `harnessHome` is shared by+ * both, because it is addressed by path rather than by page origin.+ *+ * localStorage is still written exactly as before. This file is an ADDITION, not+ * a migration away from it — if anything here fails, the renderer falls back to+ * the storage it has always used and nothing is lost.+ *+ * Durability rules, in order of how much they matter:+ * 1. Never lose a roster. Every write first copies the previous file into+ * `roster-backups/`, which is append-only — nothing in it is ever pruned,+ * overwritten or deleted.+ * 2. Never write a truncated file. Writes go to a temp file and are renamed+ * into place, so a crash mid-write leaves the previous file untouched.+ * 3. Never let an empty renderer erase a full roster. See `write`.+ */+import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++/** What the renderer mirrors to disk. The inner agent shape is deliberately+ * opaque here — the renderer's store owns it, and repeating it would mean+ * editing this file every time an agent gains a field. Main only counts. */+export interface RosterSnapshot {+ version: 1;+ savedAt: string;+ agents: unknown[];+ archived: unknown[];+ restorable: unknown[];+ queues: Record<string, unknown[]>;+ selectedId: string | null;+}++export interface RosterWriteResult {+ ok: boolean;+ /** Set when the write was deliberately declined; the file is unchanged. */+ skipped?: 'empty-first-write';+ error?: string;+}++export function rosterPath(home: string): string {+ return join(home, 'roster.json');+}++export function rosterBackupDir(home: string): string {+ return join(home, 'roster-backups');+}++function isSnapshot(v: unknown): v is RosterSnapshot {+ if (!v || typeof v !== 'object') return false;+ const s = v as Partial<RosterSnapshot>;+ return Array.isArray(s.agents) && Array.isArray(s.archived) && Array.isArray(s.restorable);+}++function entryCount(s: RosterSnapshot): number {+ return s.agents.length + s.archived.length + s.restorable.length;+}++/**+ * Reads and writes one home folder's roster.+ *+ * A class rather than free functions because the empty-guard needs to know+ * whether THIS run has written yet, and a module-level flag would be invisible+ * shared state that no test could reset. One instance per process in `index.ts`;+ * tests make their own.+ */+export class RosterStore {+ /** Set once this store has written successfully. The empty-guard applies only+ * before that: see `write`. */+ private wrote = false;+ /** Disambiguates backups made inside the same millisecond. Two writes in one+ * tick used to produce the same filename, and the second silently replaced+ * the first — a backup folder that quietly loses backups is worse than none. */+ private backupSeq = 0;++ constructor(private readonly getHome: () => string | null) {}++ private home(): string | null {+ try { return this.getHome(); } catch { return null; }+ }++ /** The stored roster, or null when there isn't one (or it can't be parsed).+ * Null means "no opinion" — the renderer then keeps using localStorage, so a+ * corrupt file degrades to the old behaviour instead of to an empty floor. */+ read(): RosterSnapshot | null {+ const home = this.home();+ if (!home) return null;+ try {+ const p = rosterPath(home);+ if (!existsSync(p)) return null;+ const parsed = JSON.parse(readFileSync(p, 'utf8'));+ return isSnapshot(parsed) ? parsed : null;+ } catch {+ return null;+ }+ }++ /**+ * Write the roster, keeping the previous contents as a backup.+ *+ * THE EMPTY-GUARD. The dangerous sequence is: open the packaged build for the+ * first time, its localStorage is empty (different origin), the store boots+ * with zero agents, and the first mirror write flattens a file that holds a+ * real roster. So the first write of a run is refused when it would replace a+ * non-empty roster with an empty one. Later writes go through — by then an+ * empty roster means the user actually removed their agents, and refusing it+ * would make deletion impossible. The previous file is backed up either way,+ * so even a wrong call here is recoverable.+ */+ write(snap: unknown): RosterWriteResult {+ const home = this.home();+ if (!home) return { ok: false, error: 'no harnessHome' };+ if (!isSnapshot(snap)) return { ok: false, error: 'invalid snapshot' };+ const p = rosterPath(home);+ try {+ mkdirSync(home, { recursive: true });+ const existing = this.read();++ if (!this.wrote && existing && entryCount(existing) > 0 && entryCount(snap) === 0) {+ // Back it up anyway: what is on disk right now is exactly what we are+ // protecting, and a copy of it costs nothing.+ this.backup(home, p, 'declined');+ this.wrote = true;+ console.warn('[roster] refused to overwrite a non-empty roster with an empty one');+ return { ok: false, skipped: 'empty-first-write' };+ }++ this.backup(home, p, this.wrote ? 'write' : 'run-start');++ const body: RosterSnapshot = {+ version: 1,+ savedAt: new Date().toISOString(),+ agents: snap.agents,+ archived: snap.archived,+ restorable: snap.restorable,+ queues: snap.queues && typeof snap.queues === 'object' ? snap.queues : {},+ selectedId: typeof snap.selectedId === 'string' ? snap.selectedId : null+ };+ // Temp + rename: `rename` is atomic within a filesystem, so a crash leaves+ // either the old file or the new one, never half of either.+ const tmp = `${p}.tmp`;+ writeFileSync(tmp, JSON.stringify(body, null, 2), 'utf8');+ renameSync(tmp, p);+ this.wrote = true;+ return { ok: true };+ } catch (e) {+ try { rmSync(`${p}.tmp`, { force: true }); } catch { /* noop */ }+ return { ok: false, error: e instanceof Error ? e.message : String(e) };+ }+ }++ /**+ * Retire the active roster during a full reset: copied into `roster-backups/`+ * first, then the live file is removed.+ *+ * Reset wipes the hive, and the roster must not be left behind as the one+ * survivor — pointing the home folder back here afterwards would show a floor+ * full of agents whose sessions, memory and inboxes no longer exist. Archived+ * rather than deleted, because a roster is never destroyed, only superseded.+ */+ archive(): void {+ const home = this.home();+ if (!home) return;+ const p = rosterPath(home);+ try {+ if (!existsSync(p)) return;+ this.backup(home, p, 'reset');+ rmSync(p, { force: true });+ } catch { /* a reset must never fail on this */ }+ }++ /** Copy the current roster into the append-only backup folder. Never prunes:+ * these files are the last line of defence, and a few KB per write is a price+ * worth paying for that. */+ private backup(home: string, p: string, reason: string): void {+ try {+ if (!existsSync(p)) return;+ const dir = rosterBackupDir(home);+ mkdirSync(dir, { recursive: true });+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');+ this.backupSeq += 1;+ copyFileSync(p, join(dir, `roster-${stamp}-${this.backupSeq}-${reason}.json`));+ } catch { /* a failed backup must never block the write */ }+ }+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex ff832f6a..910250c8 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -4,6 +4,20 @@ import type { AgentProvider } from '../shared/agentProvider';// Injected at build time from package.json (see electron.vite.config.ts).declare const __APP_VERSION__: string;+/** The renderer's roster as mirrored to `<harnessHome>/roster.json`. The agent+ * entries stay `unknown` here for the same reason main leaves them opaque: the+ * store owns that shape, and repeating it in the bridge would mean editing two+ * files every time an agent gains a field. */+export interface RosterSnapshot {+ version: 1;+ savedAt: string;+ agents: unknown[];+ archived: unknown[];+ restorable: unknown[];+ queues: Record<string, unknown[]>;+ selectedId: string | null;+}+export interface HiveAgentMeta {id: string;name: string;@@ -785,7 +799,20 @@ const api = {freeflowTranscribe: (arg: {audio: ArrayBuffer | Uint8Array; mimeType?: string; filename?: string; language?: string;}): Promise<{ ok: boolean; text?: string; error?: string }> =>- ipcRenderer.invoke('freeflow:transcribe', arg)+ ipcRenderer.invoke('freeflow:transcribe', arg),++ // ─── Roster mirror (agents + notes + queues, shared dev ↔ packaged) ─────────+ /** Read the roster file beside the hive. SYNCHRONOUS on purpose: the zustand+ * store is created at module load, so an async read would arrive after the+ * first render and the floor would flash empty. One blocking round trip at+ * boot. `null` = no file (or unreadable) — the caller then uses localStorage. */+ rosterReadSync: (): RosterSnapshot | null => {+ try { return ipcRenderer.sendSync('roster:readSync') ?? null; } catch { return null; }+ },+ /** Mirror the roster to disk. Debounced by the caller; main keeps the previous+ * contents as a backup and refuses a first write that would empty a full file. */+ rosterWrite: (snap: RosterSnapshot): Promise<{ ok: boolean; skipped?: string; error?: string }> =>+ ipcRenderer.invoke('roster:write', snap)};contextBridge.exposeInMainWorld('cth', api);diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.tsindex 954054cd..715c9267 100644--- a/src/renderer/src/store/store.ts+++ b/src/renderer/src/store/store.ts@@ -222,15 +222,90 @@ const LS_QUEUES = 'cth.messageQueues';// dead session's context gauge after a restart until the poll caught up.type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason' | 'contextTokens' | 'contextLimit'>;-function persistAgents(agents: Agent[], selectedId: string | null): void {+// ─── The roster mirror ──────────────────────────────────────────────────────+//+// localStorage is partitioned by ORIGIN, and the two ways this app runs do not+// share one: `npm run dev` serves the renderer from http://localhost:5173, a+// packaged build loads it from file://. So the roster — agents, their private+// notes, worktree paths, archived entries, parked queues — was invisible to+// whichever of the two you were not currently in, even though the hive on disk+// (sessions, memory, inboxes, tasks) was shared and intact the whole time.+//+// So we also mirror it to <harnessHome>/roster.json, which both sides reach by+// path. localStorage keeps being written byte-for-byte as before: it is the+// fallback when there is no file yet, and a standing backup afterwards. Main+// keeps every previous version of the file under roster-backups/.+const fileRoster = (() => {+ try { return window.cth?.rosterReadSync?.() ?? null; } catch { return null; }+})();++/** Prefer the shared file, but only when it actually holds a roster. An empty+ * file must never win over a populated localStorage — that is exactly the+ * "opened the build once and my floor went blank" failure this is here to+ * prevent. A genuine delete-all clears both stores, so nothing resurrects. */+const useFileRoster = !!fileRoster+ && fileRoster.agents.length + fileRoster.archived.length + fileRoster.restorable.length > 0;++/** The renderer's running copy of what should be on disk. Kept as a mutable+ * mirror updated slice-by-slice rather than read back out of the store, because+ * every persist* call happens INSIDE a zustand `set()` — `getState()` there+ * still returns the pre-update state, so a snapshot built that way would+ * reliably be one edit stale. */+const rosterMirror: {+ agents: PersistedAgent[];+ archived: PersistedAgent[];+ restorable: PersistedAgent[];+ queues: Record<string, QueuedMessage[]>;+ selectedId: string | null;+} = { agents: [], archived: [], restorable: [], queues: {}, selectedId: null };++let rosterFlush: ReturnType<typeof setTimeout> | null = null;++function flushRosterNow(): void {+ if (rosterFlush) { clearTimeout(rosterFlush); rosterFlush = null; }try {- const slim: PersistedAgent[] = agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {- void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;- return rest;+ void window.cth?.rosterWrite?.({+ version: 1,+ savedAt: new Date().toISOString(),+ agents: rosterMirror.agents,+ archived: rosterMirror.archived,+ restorable: rosterMirror.restorable,+ queues: rosterMirror.queues,+ selectedId: rosterMirror.selectedId});+ } catch { /* the file is a mirror — localStorage already took the write */ }+}++/** Coalesce a burst of persist* calls into one disk write. Agent edits arrive in+ * clusters (spawn writes agents + selection + queues in the same tick). */+function scheduleRosterFlush(): void {+ if (rosterFlush) return;+ rosterFlush = setTimeout(flushRosterNow, 500);+}++// Don't let a quit inside the debounce window drop the last edit. localStorage+// would still have it, but only for THIS origin — and the whole point is that+// the other origin can read it too.+try {+ window.addEventListener('beforeunload', flushRosterNow);+} catch { /* not a browser context (unit tests) */ }++function slimAgents(agents: Agent[]): PersistedAgent[] {+ return agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {+ void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;+ return rest;+ });+}++function persistAgents(agents: Agent[], selectedId: string | null): void {+ const slim = slimAgents(agents);+ try {window.localStorage.setItem(LS_AGENTS, JSON.stringify(slim));window.localStorage.setItem(LS_SELECTED, selectedId ?? '');} catch { /* noop */ }+ rosterMirror.agents = slim;+ rosterMirror.selectedId = selectedId;+ scheduleRosterFlush();}/** Run-state an agent recomputes from its live pty on every reload. A patch made@@ -247,12 +322,27 @@ function touchesDurableAgentField(patch: Partial<Agent>): boolean {return Object.keys(patch).some((k) => !VOLATILE_AGENT_FIELDS.has(k as keyof Agent));}-function loadPersistedAgents(): Agent[] {+/** The persisted list for one slice: the shared file when it has a roster,+ * otherwise this origin's localStorage. Returns [] on anything malformed. */+function persistedSlice(+ key: string,+ fromFile: unknown[] | undefined+): PersistedAgent[] {+ if (useFileRoster) return Array.isArray(fromFile) ? (fromFile as PersistedAgent[]) : [];try {- const raw = window.localStorage.getItem(LS_AGENTS);+ const raw = window.localStorage.getItem(key);if (!raw) return [];- const parsed = JSON.parse(raw) as PersistedAgent[];- if (!Array.isArray(parsed)) return [];+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? (parsed as PersistedAgent[]) : [];+ } catch {+ return [];+ }+}++function loadPersistedAgents(): Agent[] {+ try {+ const parsed = persistedSlice(LS_AGENTS, fileRoster?.agents);+ if (!parsed.length) return [];// Reset volatile run-state; the PTY stream / mock loop will repopulate it.return parsed.map((a) => ({...a,@@ -269,21 +359,18 @@ function loadPersistedAgents(): Agent[] {}function persistArchived(archived: Agent[]): void {+ const slim = slimAgents(archived);try {- const slim: PersistedAgent[] = archived.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {- void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;- return rest;- });window.localStorage.setItem(LS_ARCHIVED, JSON.stringify(slim));} catch { /* noop */ }+ rosterMirror.archived = slim;+ scheduleRosterFlush();}function loadPersistedArchived(): Agent[] {try {- const raw = window.localStorage.getItem(LS_ARCHIVED);- if (!raw) return [];- const parsed = JSON.parse(raw) as PersistedAgent[];- if (!Array.isArray(parsed)) return [];+ const parsed = persistedSlice(LS_ARCHIVED, fileRoster?.archived);+ if (!parsed.length) return [];// Archived agents have no live process — force the flag + clear run-state.return parsed.map((a) => ({...a,@@ -299,21 +386,24 @@ function loadPersistedArchived(): Agent[] {}function persistRestorable(restorable: Agent[]): void {+ // Keeps contextTokens/contextLimit, unlike the other two: a restorable entry+ // is a spawn recipe for a session that has not been re-entered yet, so its+ // last known context size is still meaningful.+ const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {+ void recentAssistantText; void recentTextTs; void blockReason;+ return rest;+ });try {- const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {- void recentAssistantText; void recentTextTs; void blockReason;- return rest;- });window.localStorage.setItem(LS_RESTORABLE, JSON.stringify(slim));} catch { /* noop */ }+ rosterMirror.restorable = slim;+ scheduleRosterFlush();}function loadPersistedRestorable(): Agent[] {try {- const raw = window.localStorage.getItem(LS_RESTORABLE);- if (!raw) return [];- const parsed = JSON.parse(raw) as PersistedAgent[];- if (!Array.isArray(parsed)) return [];+ const parsed = persistedSlice(LS_RESTORABLE, fileRoster?.restorable);+ if (!parsed.length) return [];// No live process — clear run-state; the spawn recipe fields are what matter.return parsed.map((a) => ({...a,@@ -332,14 +422,16 @@ function persistQueues(queues: Record<string, QueuedMessage[]>): void {const slim: Record<string, QueuedMessage[]> = {};for (const [id, q] of Object.entries(queues)) if (q.length) slim[id] = q;window.localStorage.setItem(LS_QUEUES, JSON.stringify(slim));+ rosterMirror.queues = slim;+ scheduleRosterFlush();} catch { /* noop */ }}function loadPersistedQueues(): Record<string, QueuedMessage[]> {try {- const raw = window.localStorage.getItem(LS_QUEUES);- if (!raw) return {};- const parsed = JSON.parse(raw) as Record<string, QueuedMessage[]>;+ const parsed = useFileRoster+ ? (fileRoster?.queues as Record<string, QueuedMessage[]> | undefined)+ : JSON.parse(window.localStorage.getItem(LS_QUEUES) ?? 'null') as Record<string, QueuedMessage[]> | null;if (!parsed || typeof parsed !== 'object') return {};// Defensively keep only well-formed entries.const out: Record<string, QueuedMessage[]> = {};@@ -356,7 +448,7 @@ function loadPersistedQueues(): Record<string, QueuedMessage[]> {function loadPersistedSelectedId(agents: Agent[]): string | null {try {- const id = window.localStorage.getItem(LS_SELECTED);+ const id = useFileRoster ? fileRoster?.selectedId : window.localStorage.getItem(LS_SELECTED);return id && agents.some((a) => a.id === id) ? id : (agents[0]?.id ?? null);} catch {return agents[0]?.id ?? null;@@ -384,6 +476,21 @@ const initialRestorableAgents = loadPersistedRestorable();const initialSelectedId = loadPersistedSelectedId(initialAgents);const initialQueues = loadPersistedQueues();+// Prime the mirror with whatever we just loaded, so a later persist of ONE slice+// writes a complete file rather than blanking the slices it didn't touch.+rosterMirror.agents = slimAgents(initialAgents);+rosterMirror.archived = slimAgents(initialArchivedAgents);+rosterMirror.restorable = slimAgents(initialRestorableAgents);+rosterMirror.queues = initialQueues;+rosterMirror.selectedId = initialSelectedId;++// First run with the file: seed it from this origin's localStorage. Only when+// there is something to seed — writing an empty file here would hand a blank+// roster to the other side, which is precisely the outcome being designed out.+if (!useFileRoster && rosterMirror.agents.length + rosterMirror.archived.length + rosterMirror.restorable.length > 0) {+ scheduleRosterFlush();+}+let queuedSeq = 0;/** Process-unique id for a queued message (timestamp + counter avoids collisions* when several are queued within the same millisecond). */diff --git a/test/roster.test.cjs b/test/roster.test.cjsnew file mode 100644index 00000000..b48a181f--- /dev/null+++ b/test/roster.test.cjs@@ -0,0 +1,171 @@+'use strict';++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 { RosterStore, rosterPath, rosterBackupDir } = loadTs('src/main/roster.ts');++function tmpHome() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'md-roster-'));+}++/** A store bound to `home`. A fresh instance is a fresh RUN — which is what the+ * empty-guard keys off, so "another instance" is how a restart is simulated. */+function storeAt(home) {+ return new RosterStore(() => home);+}++function backupsIn(home) {+ const dir = rosterBackupDir(home);+ return fs.existsSync(dir) ? fs.readdirSync(dir) : [];+}++function snapshot(agents = [], extra = {}) {+ return {+ version: 1,+ savedAt: new Date(0).toISOString(),+ agents,+ archived: [],+ restorable: [],+ queues: {},+ selectedId: null,+ ...extra+ };+}++test('a roster round-trips through the file', () => {+ const home = tmpHome();+ const store = storeAt(home);+ assert.equal(store.read(), null); // nothing written yet++ assert.equal(store.write(snapshot([{ id: 'a', name: 'Dwight', note: 'beets' }])).ok, true);++ const back = store.read();+ assert.equal(back.agents.length, 1);+ assert.equal(back.agents[0].note, 'beets');+ assert.equal(back.version, 1);+});++test('an empty first write cannot wipe a roster that is already on disk', () => {+ // The failure this exists for: opening the packaged build for the first time.+ // Its localStorage is a different origin, so the store boots with zero agents+ // and its first mirror write would otherwise flatten the real roster.+ const home = tmpHome();+ storeAt(home).write(snapshot([{ id: 'a', name: 'Dwight' }]));++ const nextRun = storeAt(home);+ const res = nextRun.write(snapshot([]));+ assert.equal(res.ok, false);+ assert.equal(res.skipped, 'empty-first-write');+ assert.equal(nextRun.read().agents.length, 1, 'the roster on disk survived');+});++test('emptying the roster is allowed once the run has written normally', () => {+ // Deleting every agent is a real thing a user does. Only the FIRST write of a+ // run is suspect; refusing later ones would make deletion impossible.+ const home = tmpHome();+ const store = storeAt(home);+ store.write(snapshot([{ id: 'a', name: 'Dwight' }]));+ assert.equal(store.write(snapshot([])).ok, true);+ assert.equal(store.read().agents.length, 0);+});++test('every previous version is kept, even within the same millisecond', () => {+ // Three writes back-to-back land in one tick, so a timestamp-only filename+ // collides and the later copy silently replaces the earlier one. A backup+ // folder that loses backups is worse than no backup folder.+ const home = tmpHome();+ const store = storeAt(home);+ store.write(snapshot([{ id: 'a' }]));+ store.write(snapshot([{ id: 'a' }, { id: 'b' }]));+ store.write(snapshot([{ id: 'a' }, { id: 'b' }, { id: 'c' }]));++ // Three writes, two of which had a previous file to copy first.+ assert.equal(backupsIn(home).length, 2);+ const sizes = backupsIn(home).map((f) =>+ JSON.parse(fs.readFileSync(path.join(rosterBackupDir(home), f), 'utf8')).agents.length);+ assert.deepEqual(sizes.sort(), [1, 2], 'both prior versions survived, not just the last');+});++test('a refused write still backs up whatever was on disk', () => {+ const home = tmpHome();+ storeAt(home).write(snapshot([{ id: 'a' }]));+ storeAt(home).write(snapshot([])); // declined+ assert.ok(backupsIn(home).some((f) => f.includes('declined')));+});++test('a corrupt file reads as "no opinion" rather than as an empty roster', () => {+ // The renderer treats null as "use localStorage". Returning an empty roster+ // instead would show a blank floor and then mirror that blank back to disk.+ const home = tmpHome();+ fs.writeFileSync(rosterPath(home), '{ this is not json');+ assert.equal(storeAt(home).read(), null);+});++test('a snapshot missing its arrays is rejected, not half-written', () => {+ const home = tmpHome();+ const store = storeAt(home);+ store.write(snapshot([{ id: 'a' }]));+ assert.equal(store.write({ version: 1, agents: 'nope' }).ok, false);+ assert.equal(store.read().agents.length, 1);+ assert.equal(fs.existsSync(`${rosterPath(home)}.tmp`), false, 'no temp file left behind');+});++test('no harnessHome means no file operations at all', () => {+ const store = new RosterStore(() => null);+ assert.equal(store.read(), null);+ assert.equal(store.write(snapshot([{ id: 'a' }])).ok, false);+ store.archive(); // must not throw+});++test('reset archives the roster instead of destroying it', () => {+ const home = tmpHome();+ const store = storeAt(home);+ store.write(snapshot([{ id: 'a', note: 'do not lose me' }]));++ store.archive();+ assert.equal(fs.existsSync(rosterPath(home)), false, 'active roster cleared');+ assert.equal(store.read(), null);++ const saved = backupsIn(home).filter((f) => f.includes('reset'));+ assert.equal(saved.length, 1);+ const body = JSON.parse(fs.readFileSync(path.join(rosterBackupDir(home), saved[0]), 'utf8'));+ assert.equal(body.agents[0].note, 'do not lose me');+});++test('worktree paths and notes survive the round trip verbatim', () => {+ // These two only ever lived in localStorage, so they are the whole reason the+ // file exists.+ const home = tmpHome();+ const agent = {+ id: 'w1',+ name: 'Jim',+ cwd: '/Users/x/HarnessAgents/worktrees/w1',+ worktreePath: '/Users/x/HarnessAgents/worktrees/w1',+ note: '- shipping the queue fix\n- then the roster'+ };+ const store = storeAt(home);+ store.write(snapshot([agent]));+ assert.deepEqual(store.read().agents[0], agent);+});++test('queues and selection round-trip, and a bad queues field degrades to empty', () => {+ const home = tmpHome();+ const store = storeAt(home);+ store.write(snapshot([{ id: 'a' }], {+ queues: { a: [{ id: 'q1', text: 'ship it' }] },+ selectedId: 'a'+ }));+ const back = store.read();+ assert.equal(back.queues.a[0].text, 'ship it');+ assert.equal(back.selectedId, 'a');++ store.write(snapshot([{ id: 'a' }], { queues: null, selectedId: 42 }));+ const coerced = store.read();+ assert.deepEqual(coerced.queues, {});+ assert.equal(coerced.selectedId, null);+});