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(codex): expose hive sessions to usage scanners
fangweijing5196c79afaa0
diff --git a/src/main/hive.ts b/src/main/hive.tsindex ce5cd937..15cecca5 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -19,9 +19,10 @@*/import {existsSync, mkdirSync, readFileSync, writeFileSync, renameSync,- readdirSync, statSync, rmSync, appendFileSync, symlinkSync, copyFileSync, chmodSync+ readdirSync, statSync, lstatSync, realpathSync, rmSync, appendFileSync,+ symlinkSync, unlinkSync, copyFileSync, cpSync, chmodSync} from 'node:fs';-import { join, dirname, isAbsolute } from 'node:path';+import { join, dirname, basename, isAbsolute, relative } from 'node:path';import { homedir } from 'node:os';import { spawnSync, spawn, type ChildProcess } from 'node:child_process';import { randomBytes, createHash } from 'node:crypto';@@ -476,6 +477,13 @@ export class HiveManager {if (!existsSync(registry)) {this.writeJson(registry, { godId: null, agents: {} } as Registry);}+ const userCodexHome = join(homedir(), '.codex');+ for (const [id, agent] of Object.entries(this.registry().agents)) {+ const codexHome = join(root, 'agents', id, '.codex');+ if (agent.provider === 'codex' && existsSync(codexHome)) {+ this.exposeCodexDataDirs(codexHome, userCodexHome, id);+ }+ }const board = join(root, 'board.md');if (!existsSync(board)) {writeFileSync(board, '# Hive board\n\n_Shared plans live here. The god agent is the scribe._\n', 'utf8');@@ -663,8 +671,8 @@ export class HiveManager {// preset's `hookBridge`. agy needs a translating shim (its hook stdin/stdout// shape differs from Claude's); codex reuses the Claude `cth-hook` shim// verbatim (its hook payload + response contract are already Claude-shaped)- // and is isolated to a per-agent CODEX_HOME so the user's global ~/.codex is- // never mutated. Both share the HIVE_SOCK wiring below.+ // and is isolated to a per-agent CODEX_HOME so the user's global Codex+ // configuration is never mutated. Both share the HIVE_SOCK wiring below.const preArgs: string[] = [];// Dispatch on the structured bridge descriptor (the foundation's `bridgeOf`// derives {kind:'hooks'} from the legacy `hookBridge` for agy/codex, and@@ -681,7 +689,7 @@ export class HiveManager {if (desc.kind === 'hooks') {if (desc.shim === 'agy') this.installAgyHooks();else if (desc.shim === 'codex') {- env.CODEX_HOME = this.installCodexHooks(dir);+ env.CODEX_HOME = this.installCodexHooks(dir, meta.id);// Codex refuses to run hooks from a config dir without persisted// "hook trust" (normally an interactive gate). Our hooks.json is// hive-authored inside an isolated CODEX_HOME, so we bypass that gate@@ -1581,14 +1589,16 @@ export class HiveManager {* reuse the Claude `cth-hook` shim VERBATIM (no translator, unlike agy) and let* HookServer handle everything unchanged.*- * ISOLATION: rather than mutate the user's global ~/.codex (which also holds- * their login), we point this worker at a PER-AGENT CODEX_HOME (`<dir>/.codex`,- * alongside Claude's settings.json) holding our own config.toml with `[hooks]`- * tables — so the hooks fire ONLY for hive workers and a personal `codex` run is- * untouched. The user's ~/.codex/auth.json is linked in and their config.toml is- * copied + extended (login + model/provider/trust settings still apply).+ * ISOLATION: rather than mutate the user's global Codex configuration (which+ * also holds their login), we point this worker at a PER-AGENT CODEX_HOME+ * (`<dir>/.codex`, alongside Claude's settings.json) holding our own config.toml+ * with `[hooks]` tables — so the hooks fire ONLY for hive workers and a personal+ * `codex` run is untouched. Rollout directories are linked into that isolated+ * home from namespaced paths under the standard global scan roots. The user's+ * ~/.codex/auth.json is linked in and their config.toml is copied + extended+ * (login + model/provider/trust settings still apply).* Returns the CODEX_HOME path for the caller to put in the worker's env. */- private installCodexHooks(dir: string): string {+ private installCodexHooks(dir: string, agentId: string): string {const home = join(dir, '.codex');try {mkdirSync(home, { recursive: true });@@ -1651,10 +1661,122 @@ export class HiveManager {}}writeFileSync(join(home, 'config.toml'), config, 'utf8');++ // Keep each worker's CODEX_HOME isolated while putting its rollout data+ // below Codex's standard scan roots. External usage tools can then discover+ // the sessions without understanding the hive's private directory layout.+ this.exposeCodexDataDirs(home, userHome, agentId);} catch (e) { console.error('[hive] installCodexHooks failed:', e); }return home;}+ private exposeCodexDataDirs(home: string, userHome: string, agentId: string): void {+ for (const kind of ['sessions', 'archived_sessions'] as const) {+ try { this.exposeCodexDataDir(home, userHome, agentId, kind); }+ catch (e) { console.error(`[hive] exposeCodexDataDir(${kind}) failed:`, e); }+ }+ }++ private moveCodexDataDir(from: string, to: string): void {+ try {+ renameSync(from, to);+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'EXDEV') throw e;+ cpSync(from, to, { recursive: true, force: false, errorOnExist: true });+ rmSync(from, { recursive: true, force: true });+ }+ }++ private exposeCodexDataDir(+ home: string,+ userHome: string,+ agentId: string,+ kind: 'sessions' | 'archived_sessions'+ ): void {+ const root = this.root();+ if (!root) return;+ if (!agentId || basename(agentId) !== agentId || agentId === '.' || agentId === '..') {+ throw new Error(`invalid agent id: ${agentId}`);+ }+ const source = join(home, kind);+ const scanRoot = join(userHome, kind, 'munder-difflin');+ const hiveId = createHash('sha1').update(root).digest('hex').slice(0, 12);+ const target = join(scanRoot, hiveId, agentId);++ let sourceStat: ReturnType<typeof lstatSync> | null = null;+ try { sourceStat = lstatSync(source); }+ catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; }++ if (sourceStat?.isSymbolicLink()) {+ let current: string | null = null;+ try { current = realpathSync(source); }+ catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;+ unlinkSync(source);+ sourceStat = null;+ }+ if (current) {+ const rel = relative(realpathSync(scanRoot), current);+ const scope = dirname(rel);+ if (rel && !rel.startsWith('..') && !isAbsolute(rel)+ && dirname(scope) === '.' && basename(rel) === agentId) return;+ throw new Error(`${source} points outside ${scanRoot}`);+ }+ }+ if (sourceStat && !sourceStat.isDirectory()) throw new Error(`${source} is not a directory`);++ mkdirSync(dirname(target), { recursive: true });+ if (sourceStat) {+ if (existsSync(target)) {+ if (readdirSync(target).length > 0) throw new Error(`${source} and ${target} both contain data`);+ rmSync(target, { recursive: true, force: true });+ }+ this.moveCodexDataDir(source, target);+ } else if (!existsSync(target)) {+ mkdirSync(target, { recursive: true });+ }++ try {+ symlinkSync(target, source, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (e) {+ if (!existsSync(source) && existsSync(target)) {+ try { this.moveCodexDataDir(target, source); } catch { /* data remains at target */ }+ }+ throw e;+ }+ }++ /** Remove rollout directories moved under the user's standard Codex scan+ * roots before a full hive reset removes the isolated CODEX_HOME links. */+ removeExposedCodexData(): void {+ const root = this.root();+ if (!root) return;+ const agents = join(root, 'agents');+ if (!existsSync(agents)) return;+ const userHome = join(homedir(), '.codex');++ for (const entry of readdirSync(agents, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ for (const kind of ['sessions', 'archived_sessions'] as const) {+ const source = join(agents, entry.name, '.codex', kind);+ try {+ if (!lstatSync(source).isSymbolicLink()) continue;+ const target = realpathSync(source);+ const scanRoot = realpathSync(join(userHome, kind, 'munder-difflin'));+ const rel = relative(scanRoot, target);+ const scope = dirname(rel);+ if (!rel || rel.startsWith('..') || isAbsolute(rel)+ || dirname(scope) !== '.' || basename(rel) !== entry.name) continue;+ rmSync(target, { recursive: true, force: true });+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {+ console.error('[hive] removeExposedCodexData failed:', e);+ }+ }+ }+ }+ }+/** Pi (earendil-works) bridge. Pi has a rich `pi.on(event, …)` lifecycle but no* Claude-shaped hook file; instead we drop a bundled EXTENSION into a PER-AGENT* PI_CODING_AGENT_DIR (so the user's global ~/.pi is never mutated) that, when Pidiff --git a/src/main/index.ts b/src/main/index.tsindex 45d288e4..db91712a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3480,6 +3480,7 @@ ipcMain.handle('app:resetAll', () => {try { reflector.stop(); } catch (e) { console.error('[reset] reflector.stop:', e); }try { persist.close(); } catch (e) { console.error('[reset] persist.close:', e); }try { ptyManager.killAll(); } catch (e) { console.error('[reset] killAll:', e); }+ try { hive.removeExposedCodexData(); } catch (e) { console.error('[reset] removeExposedCodexData:', e); }// Erase the hive (Michael's + every agent's memory, inboxes, tasks, board,// git history) and the semantic-memory palace. Only these harness-created// subdirs are removed — never the user's whole harnessHome folder.diff --git a/test/hive-hook-node.test.cjs b/test/hive-hook-node.test.cjsindex 25af0213..3e7a9963 100644--- a/test/hive-hook-node.test.cjs+++ b/test/hive-hook-node.test.cjs@@ -32,6 +32,24 @@ function tmpHome() {return fs.mkdtempSync(path.join(os.tmpdir(), 'md-hive-node-'));}+function isolatedHomes(t) {+ const base = tmpHome();+ const home = path.join(base, 'user');+ const harness = path.join(base, 'harness');+ t.after(() => fs.rmSync(base, { recursive: true, force: true }));++ 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');+ return { home, harness };+}+const launcherIn = (home) =>path.join(home, 'hive', 'bin', POSIX ? 'hive-node' : 'hive-node.cmd');@@ -124,7 +142,7 @@ test('every hook installer routes through the launcher — none left on bare nodhive.installAgyHooks();hive.installGrokHooks();- hive.installCodexHooks(path.join(home, 'hive/agents/a1'));+ hive.installCodexHooks(path.join(home, 'hive/agents/a1'), 'a1');const launcher = launcherIn(home);const commands = hookCommandsUnder(home);@@ -138,6 +156,120 @@ test('every hook installer routes through the launcher — none left on bare nod}});+test('Codex rollouts remain isolated and are visible under the standard scan roots', (t) => {+ const { home, harness } = isolatedHomes(t);+ const hive = new HiveManager(() => harness);+ hive.ensureHive();+ const agentDir = path.join(harness, 'hive', 'agents', 'a1');+ const codexHome = path.join(agentDir, '.codex');+ const files = {+ sessions: path.join('2026', '08', '21', 'rollout-live.jsonl'),+ archived_sessions: 'rollout-archived.jsonl'+ };+ for (const [kind, relative] of Object.entries(files)) {+ const file = path.join(codexHome, kind, relative);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, `${kind}\n`, 'utf8');+ }++ hive.installCodexHooks(agentDir, 'a1');++ const targets = {};+ for (const [kind, relative] of Object.entries(files)) {+ const isolated = path.join(codexHome, kind);+ assert.equal(fs.lstatSync(isolated).isSymbolicLink(), true,+ `${kind} must stay reachable from the isolated CODEX_HOME`);+ targets[kind] = fs.realpathSync(isolated);+ assert.equal(targets[kind].startsWith(+ path.join(fs.realpathSync(home), '.codex', kind, 'munder-difflin') + path.sep+ ), true, `${targets[kind]} is outside the standard Codex scan root under ${home}`);+ assert.equal(fs.readFileSync(path.join(isolated, relative), 'utf8'), `${kind}\n`,+ `existing ${kind} data was lost during exposure`);+ }++ hive.installCodexHooks(agentDir, 'a1');+ for (const kind of Object.keys(files)) {+ assert.equal(fs.realpathSync(path.join(codexHome, kind)), targets[kind],+ `reinstalling hooks moved ${kind} again`);+ }+});++test('bootstrap exposes archived Codex agents without respawning them', (t) => {+ const { home, harness } = isolatedHomes(t);+ const root = path.join(harness, 'hive');+ const agentDir = path.join(root, 'agents', 'a1');+ const sessions = path.join(agentDir, '.codex', 'sessions');+ fs.mkdirSync(sessions, { recursive: true });+ fs.writeFileSync(path.join(sessions, 'rollout-old.jsonl'), 'old\n', 'utf8');+ fs.writeFileSync(path.join(root, 'registry.json'), JSON.stringify({+ godId: null,+ agents: { a1: { id: 'a1', name: 'A', provider: 'codex', cwd: harness, archived: true } }+ }), 'utf8');++ new HiveManager(() => harness).ensureHive();++ assert.equal(fs.lstatSync(sessions).isSymbolicLink(), true,+ 'an archived agent is never respawned, so bootstrap must expose its rollouts');+ assert.equal(fs.realpathSync(sessions).startsWith(+ path.join(fs.realpathSync(home), '.codex', 'sessions', 'munder-difflin') + path.sep+ ), true);+ assert.equal(fs.readFileSync(path.join(sessions, 'rollout-old.jsonl'), 'utf8'), 'old\n');+});++test('a missing exposed directory is repaired on the next spawn', (t) => {+ const { home, harness } = isolatedHomes(t);+ const hive = new HiveManager(() => harness);+ hive.ensureHive();+ const agentDir = path.join(harness, 'hive', 'agents', 'a1');+ const sessions = path.join(agentDir, '.codex', 'sessions');+ const staleTarget = path.join(home, '.codex', 'sessions', 'munder-difflin', 'stale', 'a1');+ fs.mkdirSync(staleTarget, { recursive: true });+ fs.mkdirSync(path.dirname(sessions), { recursive: true });+ fs.symlinkSync(staleTarget, sessions, process.platform === 'win32' ? 'junction' : 'dir');+ fs.rmSync(staleTarget, { recursive: true, force: true });++ hive.installCodexHooks(agentDir, 'a1');++ assert.equal(fs.lstatSync(sessions).isSymbolicLink(), true);+ assert.equal(fs.statSync(sessions).isDirectory(), true, 'the stale link still has no writable target');+});++test('an unsafe agent id cannot escape the Munder scan namespace', (t) => {+ const { home, harness } = isolatedHomes(t);+ const hive = new HiveManager(() => harness);+ hive.ensureHive();+ const codexHome = path.join(harness, 'hive', 'agents', 'safe', '.codex');+ const sessions = path.join(codexHome, 'sessions');+ fs.mkdirSync(sessions, { recursive: true });+ fs.writeFileSync(path.join(sessions, 'rollout.jsonl'), 'safe\n', 'utf8');++ assert.throws(() => hive.exposeCodexDataDir(+ codexHome, path.join(home, '.codex'), '../outside', 'sessions'+ ), /invalid agent id/);+ assert.equal(fs.readFileSync(path.join(sessions, 'rollout.jsonl'), 'utf8'), 'safe\n');+ assert.equal(fs.existsSync(path.join(home, '.codex', 'sessions', 'munder-difflin', 'outside')), false);+});++test('reset cleanup removes only exposed Munder rollouts', (t) => {+ const { home, harness } = isolatedHomes(t);+ const hive = new HiveManager(() => harness);+ hive.ensureHive();+ const agentDir = path.join(harness, 'hive', 'agents', 'a1');+ const isolated = path.join(agentDir, '.codex', 'sessions');+ fs.mkdirSync(isolated, { recursive: true });+ fs.writeFileSync(path.join(isolated, 'rollout-munder.jsonl'), 'munder\n', 'utf8');+ const personal = path.join(home, '.codex', 'sessions', '2026', '08', '21', 'rollout-personal.jsonl');+ fs.mkdirSync(path.dirname(personal), { recursive: true });+ fs.writeFileSync(personal, 'personal\n', 'utf8');+ hive.installCodexHooks(agentDir, 'a1');+ const exposed = fs.realpathSync(isolated);++ hive.removeExposedCodexData();++ assert.equal(fs.existsSync(exposed), false, 'reset left Munder rollout data behind');+ assert.equal(fs.readFileSync(personal, 'utf8'), 'personal\n', 'reset touched a personal Codex session');+});+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 }));