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(hive): per-agent env metadata — cwdValid guard + agent-env query tool
Chaitanya Giri86928ab19259
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 6d86cfae..51190fbd 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -21,7 +21,7 @@ import {existsSync, mkdirSync, readFileSync, writeFileSync, renameSync,readdirSync, statSync, rmSync, appendFileSync, symlinkSync, copyFileSync} from 'node:fs';-import { join, dirname } from 'node:path';+import { join, dirname, isAbsolute } from 'node:path';import { homedir } from 'node:os';import { spawnSync, spawn, type ChildProcess } from 'node:child_process';import { randomBytes, createHash } from 'node:crypto';@@ -123,6 +123,12 @@ export interface RegistryAgent extends AgentMeta {* resume after a crash/restart) AND the cost accounting/dedup key on every* AgentUsageSample / cost-ledger row. */sessionId?: string;+ /** Whether `cwd` is actually usable for a (re)spawn — i.e. an ABSOLUTE path+ * that exists as a directory. Computed + persisted at spawn so the roster+ * reliably exposes each worker's environment validity. A non-absolute fragment+ * (e.g. "ClaudeTerminalHarness") spawns into a nonexistent dir and fails; this+ * flag makes that visible instead of letting it slip through silently. */+ cwdValid?: boolean;}export interface Registry {@@ -297,6 +303,22 @@ export class HiveManager {}}+ /** Validate an agent's cwd the way a spawn does — it must be an ABSOLUTE path+ * that exists as a directory. Surfaced as `cwdValid` on the registry entry so+ * the roster reliably exposes whether a worker's working directory is usable.+ * Best-effort; never throws (a stat error degrades to invalid). */+ private cwdValidity(cwd: string | undefined): { valid: boolean; issue: string | null } {+ if (!cwd || typeof cwd !== 'string') return { valid: false, issue: 'missing' };+ if (!isAbsolute(cwd)) return { valid: false, issue: 'not-absolute' };+ try {+ return statSync(cwd).isDirectory()+ ? { valid: true, issue: null }+ : { valid: false, issue: 'not-a-directory' };+ } catch {+ return { valid: false, issue: 'missing-dir' };+ }+ }+/*** Ensure an agent's workspace + registry entry, returning the spawn injection* (provider-specific args + env) that makes the process hive-aware.@@ -348,12 +370,16 @@ export class HiveManager {// `--resume` is never attached — i.e. every restart starts a fresh thread.const reg = this.registry();const prev = reg.agents[meta.id];+ // Validate the working directory at the source so a bad value is visible on+ // the roster (cwdValid) rather than silently spawning into a nonexistent dir.+ const cwd = this.cwdValidity(meta.cwd);reg.agents[meta.id] = {...prev,...meta,capabilities: meta.capabilities ?? [],role: meta.role ?? (meta.isGod ? 'orchestrator' : 'agent'),status: 'idle',+ cwdValid: cwd.valid,// A (re)spawn always means a live terminal — clear any prior archived flag.archived: false,lastSeen: Date.now()@@ -362,6 +388,10 @@ export class HiveManager {this.writeJson(join(root, 'registry.json'), reg);this.appendLog({ kind: 'spawn', agentId: meta.id, name: meta.name, isGod: !!meta.isGod });+ // Only logs on an invalid cwd (rare) — not a per-spawn line, so no log spam.+ if (!cwd.valid) {+ this.appendLog({ kind: 'cwd_invalid', agentId: meta.id, cwd: meta.cwd, issue: cwd.issue });+ }this.commit(`hive: register ${meta.id}`);const env: Record<string, string> = {diff --git a/tools/AGENT-ENV.md b/tools/AGENT-ENV.mdnew file mode 100644index 00000000..ad9973ca--- /dev/null+++ b/tools/AGENT-ENV.md@@ -0,0 +1,67 @@+# Per-agent environment metadata++A documented, non-sensitive way for the **orchestrator** to query each hive+agent's working directory and basic terminal/session details — and a spawn-time+guard so a bad working directory can't silently slip through.++## The problem++The roster surfaces tokens / cost / breaker / status, but not a *reliable*,+validated view of **where** each agent runs. Respawning a worker next to a peer+needs a known-good **absolute** cwd; a non-absolute fragment like+`"ClaudeTerminalHarness"` spawns into a nonexistent directory and the spawn+fails. The data existed in `registry.json`/`fleet.json` but nothing validated it+or exposed it cleanly.++## Two parts++### 1. Spawn-time instrumentation — `cwdValid` (`src/main/hive.ts`)++`ensureAgent()` now validates `meta.cwd` at registration (absolute **and** exists+as a directory) and persists the result as **`cwdValid`** on the registry entry,+so the roster reliably exposes each worker's environment validity. When a cwd is+invalid it appends a single `cwd_invalid` activity-log event (only on the rare bad+case — no per-spawn line, so no log spam). The check is best-effort and never+throws; spawn behaviour is unchanged.++### 2. Query helper — `tools/agent-env.cjs`++A dependency-free Node CLI that reads the canonical hive state and emits a clean,+non-sensitive record per agent:++```sh+node tools/agent-env.cjs # table of live (non-archived) agents+node tools/agent-env.cjs --all # include archived agents+node tools/agent-env.cjs <agent-id> # one agent, pretty JSON+node tools/agent-env.cjs --json [--all] # JSON array to stdout+node tools/agent-env.cjs --snapshot # also write <hive>/shared/agent-env.json+node tools/agent-env.cjs --hive <dir> # override the hive root+```++Locates the hive via `$HIVE_ROOT` (or `--hive`). Prefers the harness-persisted+`cwdValid`; falls back to a live path check for older registries. Exit code `2`+for an unknown agent / no hive; never throws on a corrupt registry/fleet.++**Fields:** `cwd`, `cwdValid`, `cwdIssue` (`not-absolute` / `missing-dir` / …),+`provider` (the CLI/terminal engine), `sessionId` (non-secret `claude --resume`+key), `status`, `archived`, `lastSeen`, plus live telemetry (`breaker`,+`lastTool`, `lastActiveSecAgo`, `inboxBacklog`).++**Respawn recipe** — copy a peer's *valid* cwd into a new spawn:++```sh+node tools/agent-env.cjs <peer-id> | grep cwd # -> the known-good directory+```++## Where it's stored++Reads `registry.json` + `fleet.json` (already on disk, no new hot-path writes).+`--snapshot` writes a static, regenerable artifact at `<hive>/shared/agent-env.json`+the orchestrator can read directly.++## Security++Reads **only** `registry.json` + `fleet.json`; touches no secret store, process+env, or key material, and never prints file contents / credentials / API keys.+Output is directory paths + non-secret session metadata. `sessionId` is a resume+UUID, not a credential.diff --git a/tools/agent-env.cjs b/tools/agent-env.cjsnew file mode 100644index 00000000..c35f52df--- /dev/null+++ b/tools/agent-env.cjs@@ -0,0 +1,150 @@+#!/usr/bin/env node+'use strict';+/**+ * agent-env.cjs — query per-agent environment / session metadata for the orchestrator.+ *+ * WHY: the roster surfaces tokens / cost / breaker / status, but not a reliable,+ * validated view of WHERE each agent runs (its cwd) or its session identity. To+ * respawn a worker next to a peer (e.g. put a new agent in the same checkout as+ * Oscar) the orchestrator needs a known-good ABSOLUTE cwd; a bad relative path+ * like "ClaudeTerminalHarness" spawns into a nonexistent dir and fails. This reads+ * the canonical hive state and emits a clean, NON-SENSITIVE record per agent,+ * flagging whether each cwd is actually usable (absolute + exists on disk).+ *+ * The harness now also persists `cwdValid` onto each registry entry at spawn+ * (src/main/hive.ts); this tool prefers that stored flag and otherwise validates+ * the path live, so it is correct against both new and pre-existing registries.+ *+ * DATA SOURCES (read-only, no instrumentation, no log spam):+ * - registry.json -> canonical roster: cwd, cwdValid, sessionId, provider, role, status+ * - fleet.json -> live telemetry: breaker, lastTool, lastActiveSecAgo, inboxBacklog+ *+ * SECURITY: reads ONLY registry.json + fleet.json (no secret stores, no process+ * env, no key material). Emits directory PATHS + non-secret session metadata; it+ * never reads or prints file contents, credentials, or API keys. `sessionId` is a+ * non-secret `claude --resume` UUID, already stored plaintext in registry.json.+ *+ * USAGE (run from anywhere; $HIVE_ROOT or --hive locates the hive):+ * node tools/agent-env.cjs # table of live (non-archived) agents+ * node tools/agent-env.cjs --all # include archived agents+ * node tools/agent-env.cjs <agent-id> # one agent, pretty JSON+ * node tools/agent-env.cjs --json [--all] # JSON array to stdout+ * node tools/agent-env.cjs --snapshot # also write <hive>/shared/agent-env.json+ * node tools/agent-env.cjs --hive <dir> # override the hive root+ *+ * Exit code 2 if a named agent is not found / no hive located; else 0. Never+ * throws on bad/missing input (a corrupt registry/fleet degrades to empty).+ */+const fs = require('fs');+const path = require('path');++function resolveHiveRoot(argv) {+ const i = argv.indexOf('--hive');+ if (i >= 0 && argv[i + 1]) return path.resolve(argv[i + 1]);+ if (process.env.HIVE_ROOT) return process.env.HIVE_ROOT;+ return null;+}++function readJson(p, fallback) {+ try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return fallback; }+}++/** Validate a cwd the way a spawn would: absolute path that exists as a directory. */+function cwdState(cwd) {+ if (cwd == null || typeof cwd !== 'string' || cwd === '') return { valid: false, issue: 'missing' };+ if (!path.isAbsolute(cwd)) return { valid: false, issue: 'not-absolute' };+ try {+ if (fs.statSync(cwd).isDirectory()) return { valid: true, issue: null };+ return { valid: false, issue: 'not-a-directory' };+ } catch {+ return { valid: false, issue: 'missing-dir' };+ }+}++function buildRecords(hiveRoot) {+ const reg = readJson(path.join(hiveRoot, 'registry.json'), { agents: {} });+ const fleet = readJson(path.join(hiveRoot, 'fleet.json'), { agents: [] });+ const live = new Map();+ for (const a of (fleet.agents || [])) live.set(a.id, a);++ const records = [];+ for (const [id, a] of Object.entries(reg.agents || {})) {+ const f = live.get(id) || {};+ const cwd = a.cwd ?? null;+ const cs = cwdState(cwd);+ // Prefer the harness-persisted cwdValid; fall back to a live check (older registries).+ const valid = typeof a.cwdValid === 'boolean' ? a.cwdValid : cs.valid;+ records.push({+ id,+ name: a.name ?? null,+ provider: a.provider ?? null, // terminal/CLI engine: claude / codex / crush / ...+ role: a.role ?? null,+ isGod: !!a.isGod,+ archived: !!a.archived,+ // --- environment ---+ cwd,+ cwdValid: valid,+ cwdIssue: valid ? null : cs.issue,+ // --- session ---+ sessionId: a.sessionId ?? null, // non-secret `claude --resume` key (null = never started)+ status: a.status ?? null,+ lastSeen: a.lastSeen ?? null,+ // --- live telemetry (fleet.json; absent for never-run agents) ---+ breaker: f.breaker ?? null,+ lastTool: f.lastTool ?? null,+ lastActiveSecAgo: f.lastActiveSecAgo ?? null,+ inboxBacklog: f.inboxBacklog ?? null,+ });+ }+ return records;+}++function pad(s, n) { s = String(s ?? ''); return s.length >= n ? s : s + ' '.repeat(n - s.length); }++function printTable(records) {+ const cols = [['ID', 22], ['NAME', 10], ['PROV', 7], ['STATUS', 8], ['CWD?', 13]];+ console.log(cols.map(([h, w]) => pad(h, w)).join(' ') + ' CWD');+ console.log(cols.map(([, w]) => '-'.repeat(w)).join(' ') + ' ' + '-'.repeat(40));+ for (const r of records) {+ const ok = r.cwdValid ? 'ok' : (r.cwdIssue || 'bad');+ console.log(+ pad(r.id, 22) + ' ' + pad(r.name, 10) + ' ' + pad(r.provider, 7) + ' ' ++ pad(r.status, 8) + ' ' + pad(ok, 13) + ' ' + (r.cwd ?? '(none)')+ );+ }+}++function main() {+ const argv = process.argv.slice(2);+ const hiveRoot = resolveHiveRoot(argv);+ if (!hiveRoot) {+ console.error('agent-env: no hive root — set $HIVE_ROOT or pass --hive <dir>');+ process.exit(2);+ }+ const flags = new Set(argv.filter(a => a.startsWith('--')));+ const id = argv.find((a, idx) => !a.startsWith('--') && argv[idx - 1] !== '--hive');+ const includeArchived = flags.has('--all');++ let records = buildRecords(hiveRoot);+ if (!includeArchived && !id) records = records.filter(r => !r.archived);++ if (flags.has('--snapshot')) {+ const snap = { generatedBy: 'tools/agent-env.cjs', ts: Date.now(), agents: records };+ const out = path.join(hiveRoot, 'shared', 'agent-env.json');+ fs.mkdirSync(path.dirname(out), { recursive: true });+ fs.writeFileSync(out, JSON.stringify(snap, null, 2) + '\n', 'utf8');+ console.error(`wrote ${path.relative(hiveRoot, out)} (${records.length} agents)`);+ }++ if (id) {+ const rec = records.find(r => r.id === id) || buildRecords(hiveRoot).find(r => r.id === id);+ if (!rec) { console.error(`agent-env: no agent with id "${id}"`); process.exit(2); }+ console.log(JSON.stringify(rec, null, 2));+ return;+ }++ if (flags.has('--json')) { console.log(JSON.stringify(records, null, 2)); return; }+ if (!flags.has('--snapshot')) printTable(records);+}++main();