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

test(hive): lock in the cwd/tilde, bundled-node hook and roster-injection fixes

Chaitanya Giri85946c28f0d5
diff --git a/package.json b/package.json
index 2ce3431b..37b0dd56 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: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",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
"dist:win": "npm run build && electron-builder --win",
diff --git a/test/expand-tilde.test.cjs b/test/expand-tilde.test.cjs
new file mode 100644
index 00000000..75194c74
--- /dev/null
+++ b/test/expand-tilde.test.cjs
@@ -0,0 +1,51 @@
+'use strict';
+
+/**
+ * `~` is a SHELL convention — Node's fs/child_process treat it as a literal
+ * directory name. Adding a project with `~/dev/foo` therefore died on
+ * "cwd does not exist". expandTilde is the single shared expander that fixes it.
+ */
+
+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 { expandTilde } = loadTs('src/main/fs.ts');
+
+const HOME = os.homedir();
+
+test('expands the tilde-home forms', () => {
+ assert.equal(expandTilde('~/dev/proj'), path.join(HOME, 'dev/proj'));
+ assert.equal(expandTilde('~'), HOME, 'a bare ~ is a valid cwd too');
+ assert.equal(expandTilde('~/'), HOME);
+ assert.equal(expandTilde(' ~/dev/proj '), path.join(HOME, 'dev/proj'), 'pasted paths carry whitespace');
+});
+
+test('leaves absolute paths alone (beyond normalizing)', () => {
+ assert.equal(expandTilde('/a/b/c'), '/a/b/c');
+ assert.equal(expandTilde('/a/b/c/'), '/a/b/c');
+ assert.equal(expandTilde('/a/b/../c'), '/a/c');
+});
+
+test('does not touch anything that is not a tilde-home path', () => {
+ assert.equal(expandTilde(''), '');
+ assert.equal(expandTilde('~notauser/x'), '~notauser/x', '~user is not a form we expand');
+ assert.equal(expandTilde('C:\\Users\\me\\proj'), 'C:\\Users\\me\\proj', 'windows paths must survive');
+});
+
+test('a still-relative path is returned untouched, NOT resolved', () => {
+ // Deliberate: resolving here would silently anchor the path to the Electron
+ // process cwd. Callers keep their own "not absolute" error instead.
+ assert.equal(expandTilde('relative/path'), 'relative/path');
+ assert.equal(expandTilde('./rel'), './rel');
+});
+
+test('the expanded path is what fs can actually stat — the original bug', () => {
+ assert.equal(fs.existsSync('~'), false, 'the literal "~" never exists on disk');
+ const expanded = expandTilde('~');
+ assert.equal(path.isAbsolute(expanded), true);
+ assert.equal(fs.existsSync(expanded), true);
+});
diff --git a/test/hive-cwd.test.cjs b/test/hive-cwd.test.cjs
new file mode 100644
index 00000000..b1ae4006
--- /dev/null
+++ b/test/hive-cwd.test.cjs
@@ -0,0 +1,63 @@
+'use strict';
+
+/**
+ * Ingestion guarantee: whatever the user types, the hive registry stores an
+ * ABSOLUTE cwd. A `~/…` entry used to land verbatim and then read
+ * "not absolute" / cwdValid:false forever, so the agent could never spawn.
+ */
+
+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 tmpHome() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'md-hive-cwd-'));
+}
+
+function registryOf(home) {
+ return JSON.parse(fs.readFileSync(path.join(home, 'hive', 'registry.json'), 'utf8'));
+}
+
+test('a "~/…" cwd is expanded before it reaches the registry', async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: '~' });
+
+ const agent = registryOf(home).agents.a1;
+ assert.equal(agent.cwd, os.homedir(), 'the registry must hold the resolved path');
+ assert.equal(path.isAbsolute(agent.cwd), true);
+ assert.equal(agent.cwdValid, true, 'the raw "~" is what made this false');
+});
+
+test('an absolute cwd is unchanged', async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: home });
+
+ const agent = registryOf(home).agents.a1;
+ assert.equal(agent.cwd, home);
+ assert.equal(agent.cwdValid, true);
+});
+
+test('cwdValidity repairs a "~" left in an older registry', async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+
+ // Entries written before the fix are still on disk; reading one must not
+ // report it as permanently invalid.
+ assert.equal(hive.cwdValidity('~').valid, true);
+ assert.equal(hive.cwdValidity(path.join('~', 'definitely-not-here-xyz')).valid, false,
+ 'expansion must not paper over a genuinely missing directory');
+ assert.equal(hive.cwdValidity('relative/path').valid, false,
+ 'a relative path is still an error, not silently resolved');
+});
diff --git a/test/hive-hook-node.test.cjs b/test/hive-hook-node.test.cjs
new file mode 100644
index 00000000..25af0213
--- /dev/null
+++ b/test/hive-hook-node.test.cjs
@@ -0,0 +1,186 @@
+'use strict';
+
+/**
+ * Hooks run under `/bin/sh` with a bare PATH (`/usr/bin:/bin:…`). A hook command
+ * of `node "<shim>"` therefore exits 127 — "node: command not found" — on every
+ * machine where node lives in a shell-managed prefix (nvm, volta, Homebrew).
+ *
+ * The fix is `<hive>/bin/hive-node`: a one-line wrapper around Electron's OWN
+ * bundled node (`ELECTRON_RUN_AS_NODE=1 exec "<execPath>"`). Every hook installer
+ * must route through it.
+ *
+ * A wrapper SCRIPT rather than an inline `ELECTRON_RUN_AS_NODE=1 "<exe>" …`
+ * prefix, because that prefix is POSIX-sh syntax and a hard error under cmd.exe —
+ * which is what runs hook commands on Windows.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const net = require('node:net');
+const os = require('node:os');
+const path = require('node:path');
+const { spawn } = require('node:child_process');
+const loadTs = require('./load-ts.cjs');
+
+const { HiveManager } = loadTs('src/main/hive.ts');
+
+const POSIX = process.platform !== 'win32';
+const STRIPPED_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';
+
+function tmpHome() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'md-hive-node-'));
+}
+
+const launcherIn = (home) =>
+ path.join(home, 'hive', 'bin', POSIX ? 'hive-node' : 'hive-node.cmd');
+
+/** Every file under `dir`. */
+function walk(dir, out = []) {
+ for (const e of fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }) : []) {
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) walk(p, out);
+ else out.push(p);
+ }
+ return out;
+}
+
+/** Sweep every config an installer wrote for commands that invoke one of our
+ * shims. Path-agnostic on purpose, so a new installer cannot be missed. */
+function hookCommandsUnder(home) {
+ const shim = /(cth-hook\.cjs|agy-hook\.cjs|grok-hook\.cjs)/;
+ const found = [];
+ for (const file of walk(home)) {
+ let text;
+ try { text = fs.readFileSync(file, 'utf8'); } catch { continue; }
+ if (!shim.test(text)) continue;
+ // JSON hook configs: "command": "<…>" TOML (codex): command = '<…>'
+ for (const m of text.matchAll(/"command"\s*:\s*"((?:[^"\\]|\\.)*)"/g)) found.push(JSON.parse(`"${m[1]}"`));
+ for (const m of text.matchAll(/command = '([^']+)'/g)) found.push(m[1]);
+ }
+ return found.filter((c) => shim.test(c));
+}
+
+const usesLauncher = (cmd, launcher) => cmd.startsWith(launcher) || cmd.startsWith(`"${launcher}"`);
+
+async function run(cmd, env) {
+ return new Promise((resolve) => {
+ const child = spawn('/bin/sh', ['-c', cmd], { env, stdio: ['pipe', 'pipe', 'pipe'] });
+ let stderr = '';
+ child.stderr.on('data', (d) => { stderr += d; });
+ child.stdin.end(JSON.stringify({ hook_event_name: 'Stop', session_id: 's1' }));
+ child.on('close', (code) => resolve({ code, stderr }));
+ });
+}
+
+test('ensureHive writes an executable bundled-node launcher', async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: home });
+
+ const launcher = launcherIn(home);
+ assert.equal(fs.existsSync(launcher), true);
+ const body = fs.readFileSync(launcher, 'utf8');
+ assert.match(body, /ELECTRON_RUN_AS_NODE=1/, 'without this the binary opens a second app window');
+ assert.ok(body.includes(process.execPath), 'execPath is re-baked each bootstrap so an app move/update heals');
+ if (POSIX) assert.ok(fs.statSync(launcher).mode & 0o111, 'must be executable');
+});
+
+test('the claude hook + statusLine commands run through the launcher', async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: home });
+
+ const launcher = launcherIn(home);
+ const settings = JSON.parse(fs.readFileSync(path.join(home, 'hive/agents/a1/settings.json'), 'utf8'));
+ const commands = [
+ ...Object.values(settings.hooks).flatMap((matchers) => matchers.flatMap((m) => m.hooks.map((h) => h.command))),
+ settings.statusLine.command
+ ];
+
+ assert.ok(commands.length > 0);
+ for (const cmd of commands) assert.equal(usesLauncher(cmd, launcher), true, cmd);
+});
+
+test('every hook installer routes through the launcher — none left on bare node', async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: home });
+
+ // agy and grok install into the USER's home. Redirect it, and refuse to run
+ // rather than write into the developer's real ~/.gemini / ~/.grok.
+ const realHome = process.env.HOME;
+ const realProfile = process.env.USERPROFILE;
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ t.after(() => {
+ if (realHome === undefined) delete process.env.HOME; else process.env.HOME = realHome;
+ if (realProfile === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = realProfile;
+ });
+ assert.equal(os.homedir(), home, 'home redirect failed — aborting before touching the real home');
+
+ hive.installAgyHooks();
+ hive.installGrokHooks();
+ hive.installCodexHooks(path.join(home, 'hive/agents/a1'));
+
+ const launcher = launcherIn(home);
+ const commands = hookCommandsUnder(home);
+ // claude (Stop/statusLine/…) + agy + grok + codex.
+ assert.ok(commands.length >= 4, `expected commands from all installers, got ${commands.length}`);
+ const bare = commands.filter((c) => !usesLauncher(c, launcher));
+ assert.deepEqual(bare, [], 'these hook commands would exit 127 wherever node is not on the bare PATH');
+
+ for (const shim of ['agy-hook.cjs', 'grok-hook.cjs']) {
+ assert.ok(commands.some((c) => c.includes(shim)), `${shim} installer produced no command`);
+ }
+});
+
+test('a hook fires with NO node on PATH, and its payload reaches HIVE_SOCK', { skip: !POSIX }, async (t) => {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: home });
+
+ const sock = path.join(home, 'hive', 'hooks.sock');
+ try { fs.unlinkSync(sock); } catch { /* not there */ }
+
+ const received = [];
+ const server = net.createServer((conn) => {
+ let buf = '';
+ conn.on('error', () => { /* the shim may hang up first */ });
+ conn.on('data', (d) => { buf += d; });
+ // The shim writes its payload and waits for OUR end() — it never half-closes,
+ // so the payload is only complete on 'close', not 'end'.
+ conn.on('close', () => { if (buf) received.push(buf); });
+ conn.write(JSON.stringify({ ok: true }) + '\n', () => conn.end());
+ });
+ server.on('error', () => { /* keep a socket error out of the test process */ });
+ await new Promise((resolve) => server.listen(sock, resolve));
+ t.after(() => server.close());
+
+ const env = { PATH: STRIPPED_PATH, HIVE_SOCK: sock, AGENT_ID: 'a1', HOME: home };
+ const shim = path.join(home, 'hive/bin/cth-hook.cjs');
+
+ // Control: the command shape used before the fix. Only meaningful if node is
+ // genuinely absent from the stripped PATH (it is on a dev machine using nvm,
+ // volta or Homebrew; it is not on an image with /usr/bin/node).
+ const probe = await run('command -v node', env);
+ if (probe.code !== 0) {
+ const before = await run(`node "${shim}"`, env);
+ assert.equal(before.code, 127, 'the bug: bare `node` is not resolvable from a hook');
+ }
+
+ // NOTE: async spawn, not spawnSync — the shim connects back to a socket THIS
+ // process is serving, so a sync call would block our own event loop and
+ // deadlock the handshake.
+ const settings = JSON.parse(fs.readFileSync(path.join(home, 'hive/agents/a1/settings.json'), 'utf8'));
+ const after = await run(settings.hooks.Stop[0].hooks[0].command, env);
+ assert.equal(after.code, 0, `hook failed under a stripped PATH: ${after.stderr}`);
+
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ assert.ok(received.length > 0, 'nothing arrived at HIVE_SOCK');
+ assert.match(received[0], /"hook_event_name"\s*:\s*"Stop"/);
+});
diff --git a/test/hive-roster-injection.test.cjs b/test/hive-roster-injection.test.cjs
new file mode 100644
index 00000000..06fe2548
--- /dev/null
+++ b/test/hive-roster-injection.test.cjs
@@ -0,0 +1,119 @@
+'use strict';
+
+/**
+ * God has to know the LIVE floor across its own restarts — a roster it read once
+ * goes stale, and it then messages agents that were archived or killed. So the
+ * roster is PUSHED into god's context (SessionStart + every prompt) rather than
+ * pulled.
+ *
+ * Only one `additionalContext` may be returned per hook, so the roster and the
+ * operator-steer path must MERGE — otherwise they silently displace each other.
+ */
+
+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');
+
+// hooks.ts pulls Notification from electron; outside Electron that resolve gives
+// a path string, so seed the cache with the surface the server actually touches.
+const electron = require.resolve('electron');
+require.cache[electron] = {
+ id: electron,
+ filename: electron,
+ loaded: true,
+ exports: { Notification: class { show() {} static isSupported() { return false; } } }
+};
+
+const { HiveManager } = loadTs('src/main/hive.ts');
+const { HookServer } = loadTs('src/main/hooks.ts');
+
+const CONFIG = { notifications: false };
+
+function tmpHome() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'md-roster-inj-'));
+}
+
+async function floor(t, { steer } = {}) {
+ const home = tmpHome();
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ await hive.ensureAgent({ id: 'god-1', name: 'Michael', provider: 'claude', cwd: home, isGod: true });
+ await hive.ensureAgent({ id: 'jim-1', name: 'Jim', provider: 'claude', cwd: home });
+
+ const control = steer
+ ? { takeSteer: (id) => (id === 'god-1' ? steer : null), shouldHalt: () => false, toolDecision: () => ({ deny: false }) }
+ : undefined;
+ const server = new HookServer(hive, () => null, () => CONFIG, control, undefined);
+ const fire = (agent_id, hook_event_name) => server.handle({ agent_id, hook_event_name, session_id: 's1' });
+ return { home, hive, server, fire };
+}
+
+function snapshot(hive) {
+ hive.writeFleetSnapshot({
+ ts: Date.now() - 4000,
+ agents: [
+ { id: 'god-1', name: 'Michael', role: 'orchestrator', isGod: true, breaker: 'ok', tokens: 812_400, usd: 4.2199, lastActiveSecAgo: 6, inboxBacklog: 2 },
+ { id: 'jim-1', name: 'Jim', role: 'agent', breaker: 'warn', tokens: 120_401, usd: 1.0231, lastActiveSecAgo: 240, inboxBacklog: 0 },
+ { id: 'pam-1', name: 'Pam', role: 'agent', breaker: 'ok', tokens: 0, usd: 0, lastActiveSecAgo: null, inboxBacklog: 0 }
+ ]
+ });
+}
+
+const context = (res) => res?.hookSpecificOutput?.additionalContext ?? '';
+
+test('the roster line carries the whole floor and its state', async (t) => {
+ const { hive } = await floor(t);
+ assert.equal(hive.rosterContext(), null, 'no snapshot yet — inject nothing rather than noise');
+
+ snapshot(hive);
+ const line = hive.rosterContext();
+
+ assert.ok(!line.includes('\n'), 'must stay a single compact line');
+ for (const id of ['god-1', 'jim-1', 'pam-1']) assert.ok(line.includes(id), `missing ${id}`);
+ assert.match(line, /812k tok/);
+ assert.match(line, /\$4\.22/);
+ assert.match(line, /inbox 2/);
+ assert.match(line, /breaker warn/);
+ assert.match(line, /god-1[^;]*you/, 'god has to be able to spot itself');
+ assert.match(line, /no activity yet/, 'an agent that never ran must not read as "active never"');
+ assert.match(line, /SUPERSEDES/, 'the point is to override what god remembers');
+ assert.ok(line.length < 1200, `too long for a 3-agent floor: ${line.length} chars`);
+});
+
+test('god gets the roster on SessionStart and on every prompt — nobody else does', async (t) => {
+ const { hive, fire } = await floor(t);
+ snapshot(hive);
+
+ const start = await fire('god-1', 'SessionStart');
+ assert.match(context(start), /LIVE ROSTER/);
+ assert.equal(start.hookSpecificOutput.hookEventName, 'SessionStart');
+ assert.match(context(await fire('god-1', 'UserPromptSubmit')), /LIVE ROSTER/);
+
+ assert.doesNotMatch(context(await fire('jim-1', 'SessionStart')), /LIVE ROSTER/);
+ assert.doesNotMatch(context(await fire('jim-1', 'UserPromptSubmit')), /LIVE ROSTER/);
+ assert.doesNotMatch(context(await fire('god-1', 'PostToolUse')), /LIVE ROSTER/,
+ 'prompt boundaries only — not once per tool call');
+});
+
+test('a queued operator steer is not swallowed by the roster', async (t) => {
+ const steer = 'OPERATOR: stop and summarize.';
+ const { hive, fire } = await floor(t, { steer });
+ snapshot(hive);
+
+ const ctx = context(await fire('god-1', 'UserPromptSubmit'));
+ assert.match(ctx, /LIVE ROSTER/);
+ assert.ok(ctx.includes(steer), 'only one additionalContext exists — the two must merge, not race');
+});
+
+test('a corrupt fleet.json degrades to no injection instead of throwing into a hook', async (t) => {
+ const { home, hive, fire } = await floor(t);
+ snapshot(hive);
+ fs.writeFileSync(path.join(home, 'hive', 'fleet.json'), '{ not json');
+
+ assert.equal(hive.rosterContext(), null);
+ const res = await fire('god-1', 'SessionStart');
+ assert.doesNotMatch(context(res), /LIVE ROSTER/);
+});