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

feat(worker): P4 lifecycle hardening — worktree GC + token-cap wiring + Workers tab

Chaitanya Girid6708569c1a0
diff --git a/scripts/verify-worker-gc.mjs b/scripts/verify-worker-gc.mjs
new file mode 100644
index 00000000..fd362742
--- /dev/null
+++ b/scripts/verify-worker-gc.mjs
@@ -0,0 +1,102 @@
+#!/usr/bin/env node
+/**
+ * Acceptance verify for the P4 ephemeral-worker GC gate (worktreeIsGcSafe in
+ * src/main/git.ts). The repo has no test runner and git.ts can't be imported
+ * standalone, so this mirrors the EXACT three git commands the helper runs
+ * against real throwaway repos + worktrees and asserts the GC decision:
+ *
+ * clean = `git status --porcelain` is empty
+ * if !clean -> KEEP
+ * ahead = `git rev-list --count <base>..HEAD`
+ * if ahead === 0 -> GC (HEAD reachable from base: FF / plain merge)
+ * if `git diff --quiet <base> HEAD` exits 0 -> GC (tree identical: SQUASH merge)
+ * else -> KEEP
+ *
+ * Proves the fail-safe gate keeps un-integrated work AND correctly reclaims both
+ * fast-forward AND squash-merged worktrees (the case the ahead-count alone misses).
+ * Run: node scripts/verify-worker-gc.mjs (exit 0 = all pass)
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let failures = 0;
+const tmp = mkdtempSync(join(tmpdir(), 'wgc-'));
+const git = (cwd, ...args) => {
+ try { return { ok: true, out: execFileSync('git', args, { cwd, encoding: 'utf8' }).trim() }; }
+ catch (e) { return { ok: false, out: (e.stderr || e.stdout || String(e)).toString().trim() }; }
+};
+const gitOkExit = (cwd, ...args) => {
+ // returns true when git exits 0 (used for `diff --quiet`)
+ try { execFileSync('git', args, { cwd, stdio: 'ignore' }); return true; }
+ catch { return false; }
+};
+
+/** The decision under test — a faithful mirror of worktreeIsGcSafe. */
+function gcSafe(wtPath, base) {
+ const status = git(wtPath, 'status', '--porcelain');
+ if (!status.ok) return { gc: false, detail: 'status failed' };
+ if (status.out.length > 0) return { gc: false, detail: 'dirty' };
+ const rl = git(wtPath, 'rev-list', '--count', `${base}..HEAD`);
+ if (rl.ok && parseInt(rl.out, 10) === 0) return { gc: true, detail: 'ahead==0' };
+ if (gitOkExit(wtPath, 'diff', '--quiet', base, 'HEAD')) return { gc: true, detail: 'tree==base (squash)' };
+ return { gc: false, detail: 'unintegrated' };
+}
+
+function check(label, got, want) {
+ const ok = got === want;
+ if (!ok) failures++;
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${label} (gc=${got}, expected ${want})`);
+}
+
+// ── Build a base repo ──────────────────────────────────────────────────────
+const repo = join(tmp, 'repo');
+execFileSync('git', ['init', '-q', '-b', 'main', repo]);
+git(repo, 'config', 'user.email', 'v@x'); git(repo, 'config', 'user.name', 'v');
+writeFileSync(join(repo, 'a.txt'), 'base\n');
+git(repo, 'add', '-A'); git(repo, 'commit', '-qm', 'base');
+
+const wt = (name) => join(tmp, name);
+
+// ── Scenario A: un-integrated commit → KEEP ─────────────────────────────────
+git(repo, 'worktree', 'add', '-q', '-b', 'wA', wt('wA'), 'main');
+writeFileSync(join(wt('wA'), 'a.txt'), 'base\nwork-A\n');
+git(wt('wA'), 'add', '-A'); git(wt('wA'), 'commit', '-qm', 'A work');
+check('A un-integrated commit', gcSafe(wt('wA'), 'main').gc, false);
+
+// ── Scenario B: same branch fast-forward-merged into main → GC (ahead==0) ───
+git(repo, 'merge', '-q', '--ff-only', 'wA'); // main now contains wA
+check('B fast-forward integrated', gcSafe(wt('wA'), 'main').gc, true);
+
+// ── Scenario C: squash merge — work in main as a NEW commit, original commits
+// stay unreachable (ahead>0) but the TREE is identical → GC via diff --quiet ─
+git(repo, 'worktree', 'add', '-q', '-b', 'wC', wt('wC'), 'main');
+writeFileSync(join(wt('wC'), 'b.txt'), 'feature-C\n');
+git(wt('wC'), 'add', '-A'); git(wt('wC'), 'commit', '-qm', 'C1');
+writeFileSync(join(wt('wC'), 'b.txt'), 'feature-C\nmore\n');
+git(wt('wC'), 'add', '-A'); git(wt('wC'), 'commit', '-qm', 'C2');
+// squash-merge wC's content into main as one new commit
+git(repo, 'merge', '-q', '--squash', 'wC');
+git(repo, 'commit', '-qm', 'squash C');
+const cAhead = parseInt(git(wt('wC'), 'rev-list', '--count', 'main..HEAD').out, 10);
+check('C squash-merged (content in base)', gcSafe(wt('wC'), 'main').gc, true);
+console.log(` (sanity: wC is ${cAhead} commits ahead of main yet tree-identical — ahead-count alone would never GC this)`);
+
+// ── Scenario D: dirty working tree → KEEP ───────────────────────────────────
+git(repo, 'worktree', 'add', '-q', '-b', 'wD', wt('wD'), 'main');
+writeFileSync(join(wt('wD'), 'a.txt'), 'uncommitted edit\n');
+check('D dirty working tree', gcSafe(wt('wD'), 'main').gc, false);
+
+// ── Scenario E: clean worktree identical to base, no commits → GC ───────────
+git(repo, 'worktree', 'add', '-q', '-b', 'wE', wt('wE'), 'main');
+check('E clean + identical to base', gcSafe(wt('wE'), 'main').gc, true);
+
+// ── Scenario F: untracked file only (still dirty) → KEEP ────────────────────
+git(repo, 'worktree', 'add', '-q', '-b', 'wF', wt('wF'), 'main');
+writeFileSync(join(wt('wF'), 'scratch.tmp'), 'junk\n');
+check('F untracked file present', gcSafe(wt('wF'), 'main').gc, false);
+
+rmSync(tmp, { recursive: true, force: true });
+console.log(failures === 0 ? '\nALL CHECKS PASS' : `\n${failures} CHECK(S) FAILED`);
+process.exit(failures === 0 ? 0 : 1);
diff --git a/src/main/config.ts b/src/main/config.ts
index 2fa933f9..c02738d3 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -170,6 +170,14 @@ export interface HarnessConfig {
* — idle-based, never wall-clock, so an actively-working worker is never reaped.
* Default 20. */
workerIdleTimeoutMinutes?: number;
+ /** Default per-worker TOTAL-token cap (input+output+cache) applied to every
+ * god-triggered ephemeral worker; a worker's own spawn-request `tokenCap`
+ * overrides it. When the effective cap is exceeded the worker is reaped (its
+ * committed work preserved) and god is informed. This is PLUMBING for a later
+ * budget feature: per the human directive there is NO per-worker cap today, so
+ * the default is 0 = UNLIMITED — the mechanism is wired but never throttles
+ * unless someone explicitly sets a positive cap (per request or here). */
+ defaultWorkerTokenCap?: number;
/** Circuit-breaker thresholds (Lane A #6.6b). Unset = conservative defaults. */
circuitBreaker?: CircuitBreakerConfig;
/** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */
@@ -265,6 +273,7 @@ const DEFAULTS: HarnessConfig = {
mcpDefaults: defaultMcpDefaults(),
maxConcurrentWorkers: 4,
workerIdleTimeoutMinutes: 20,
+ defaultWorkerTokenCap: 0, // 0 = unlimited (human directive: NO per-worker cap)
semanticMemory: true,
embeddingModel: 'minilm',
missions: [OPS_STANDUP_MISSION],
diff --git a/src/main/git.ts b/src/main/git.ts
index 44d9f186..6a3d5a3d 100644
--- a/src/main/git.ts
+++ b/src/main/git.ts
@@ -202,3 +202,42 @@ export async function worktreeHasUnintegratedWork(
const detail = `dirty=${dirty}, commitsAheadOf(${baseBranch})=${aheadKnown ? ahead : 'unknown'}`;
return { keep, detail, branch, dirty, ahead };
}
+
+/** Is this preserved worker worktree SAFE to garbage-collect — i.e. is its work
+ * fully integrated (or empty) with nothing uncommitted to lose? Used by the
+ * ephemeral-worker GC sweep, which must NEVER discard un-integrated work.
+ *
+ * Returns `gc: true` ONLY when BOTH:
+ * (1) the working tree is clean (no uncommitted/untracked changes), AND
+ * (2) the worker's content is already in `baseBranch` — proven by EITHER
+ * commitsAheadOf(base) === 0 (HEAD reachable from base: fast-forward /
+ * plain merge, robust even after base advances) OR `git diff base HEAD`
+ * being empty (base's tree equals HEAD's tree: catches a SQUASH merge,
+ * which leaves the original commits unreachable so the ahead-count alone
+ * would never clear).
+ *
+ * Fails SAFE in every other case: a dirty tree, un-integrated commits, OR any
+ * git query we can't run all yield `gc: false` (keep the worktree). This is the
+ * stronger sibling of `worktreeHasUnintegratedWork` — that gate decides whether
+ * to PRESERVE at teardown; this one decides whether a preserved worktree may now
+ * be reclaimed. */
+export async function worktreeIsGcSafe(
+ wtPath: string, baseBranch: string
+): Promise<{ gc: boolean; detail: string }> {
+ // (1) Clean tree?
+ const status = await runGit(wtPath, ['status', '--porcelain']);
+ if (!status.ok) return { gc: false, detail: 'status query failed' };
+ if (status.stdout.trim().length > 0) return { gc: false, detail: 'working tree dirty' };
+ // (2a) HEAD fully reachable from base (ahead == 0)?
+ const rl = await runGit(wtPath, ['rev-list', '--count', `${baseBranch}..HEAD`]);
+ if (rl.ok) {
+ const n = parseInt(rl.stdout.trim(), 10);
+ if (Number.isFinite(n) && n === 0) return { gc: true, detail: `clean + 0 commits ahead of ${baseBranch}` };
+ }
+ // (2b) base tree identical to HEAD tree (squash-merge / equivalent content)?
+ // `git diff --quiet <base> HEAD` → exit 0 (ok) means NO differences.
+ const diff = await runGit(wtPath, ['diff', '--quiet', baseBranch, 'HEAD']);
+ if (diff.ok) return { gc: true, detail: `clean + tree identical to ${baseBranch} (integrated/squashed)` };
+ // Either there are real un-integrated commits, or a query failed → keep.
+ return { gc: false, detail: `clean but content not yet in ${baseBranch}` };
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 5b582131..b4f452b2 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -12,7 +12,7 @@ import {
import { listDir, readFileText, writeFileText } from './fs';
import {
getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo,
- addWorktree, removeWorktree, worktreeHasUnintegratedWork
+ addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe
} from './git';
import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';
import { HookServer } from './hooks';
@@ -161,16 +161,37 @@ const worktreeOrigins = new Map<string, string>();
interface WorkerRec {
workerId: string; // == the PTY id == hive agent id (`worker-<reqId>`)
reqId: string; // the spawn-request id
+ name?: string; // display name (for the worker tab)
slack?: { channel: string; thread_ts: string };
baseBranch: string; // the branch its worktree was cut from (for ahead-of-base)
spawnedAt: number; // epoch ms
releasing?: boolean; // kill issued; awaiting teardownPty (skip re-processing)
+ /** Per-worker TOTAL-token cap from the spawn-request (overrides the config
+ * default). 0/undefined = no per-request cap. P4 plumbing — unlimited today. */
+ tokenCap?: number;
}
/** Live ephemeral workers by id. Populated by the spawn-request watcher; consulted
* by teardownPty so a finished/crashed/reaped worker's worktree is PRESERVED (not
* force-removed) when it holds unintegrated work — god is the sole integrator. */
const liveWorkers = new Map<string, WorkerRec>();
+/** A worker worktree that teardown PRESERVED because it held unintegrated work.
+ * Tracked so the GC sweep can reclaim it (+ its scratch dir) once the work lands
+ * in base or the worktree is removed by hand — see gcPreservedWorktrees(). */
+interface PreservedWorktree {
+ workerId: string;
+ wtPath: string;
+ origCwd: string; // the parent repo to run `git worktree remove` from
+ baseBranch: string; // re-checked against this for "integrated yet?"
+ scratchDir: string | null; // HIVE_ROOT/agents/<workerId> — removed alongside the worktree
+ slack?: { channel: string; thread_ts: string };
+ preservedAt: number; // epoch ms
+}
+/** Preserved worker worktrees awaiting integration, keyed by worktree path. The GC
+ * sweep drains this: an entry is removed (worktree + scratch GC'd) only when the
+ * work is provably integrated, or when the worktree is already gone from disk. */
+const preservedWorktrees = new Map<string, PreservedWorktree>();
+
/**
* Tear down everything tied to a PTY id: archive its hive agent, remove its
* isolated git worktree, and drop the bookkeeping-map entries. Runs on BOTH an
@@ -249,21 +270,60 @@ async function finalizeWorkerWorktree(wtPath: string, origCwd: string, worker: W
const work = await worktreeHasUnintegratedWork(wtPath, worker.baseBranch);
if (work.keep) {
console.warn(`[worker] PRESERVING worktree with unintegrated work: ${wtPath} (${work.detail})`);
+ // Track it so the GC sweep can reclaim it (+ scratch dir) once integrated —
+ // the worker is gone from liveWorkers by now, so its identity lives here.
+ preservedWorktrees.set(wtPath, {
+ workerId: worker.workerId, wtPath, origCwd, baseBranch: worker.baseBranch,
+ scratchDir: workerScratchDir(worker.workerId), slack: worker.slack, preservedAt: Date.now()
+ });
informGod(
`[worker worktree preserved] ${worker.workerId}`,
`Ephemeral worker ${worker.workerId} ended but its worktree holds unintegrated work, so it was NOT auto-removed (you are the sole integrator).\n`
+ `Worktree: ${wtPath}\nBranch: ${work.branch}\nState: ${work.detail}\n`
- + `Review/merge it, then remove the worktree with: git -C "${origCwd}" worktree remove "${wtPath}"`,
+ + `Review/merge it — it will be auto-reclaimed once its work lands in ${worker.baseBranch}, or remove it now with: git -C "${origCwd}" worktree remove "${wtPath}"`,
worker.slack
);
return;
}
const r = await removeWorktree(origCwd, wtPath);
- if (!r.ok) console.error('[worker] removeWorktree failed:', r.error);
+ if (!r.ok) { console.error('[worker] removeWorktree failed:', r.error); return; }
+ // Worktree is gone (clean/integrated at teardown), but DEFER its scratch-dir
+ // cleanup to the throttled GC sweep rather than deleting it synchronously here:
+ // HIVE_ROOT/agents/<id> holds the worker's memory.md and the MemPalace miner
+ // ingests it asynchronously, so an immediate delete can beat the miner and
+ // permanently lose the worker's durable notes from the shared palace. Register
+ // it (its worktree path is now absent) so the sweep's path-gone branch reclaims
+ // the scratch after a window — same throttled path the preserved case uses.
+ preservedWorktrees.set(wtPath, {
+ workerId: worker.workerId, wtPath, origCwd, baseBranch: worker.baseBranch,
+ scratchDir: workerScratchDir(worker.workerId), slack: worker.slack, preservedAt: Date.now()
+ });
} catch (e) {
console.error('[worker] finalizeWorkerWorktree threw (worktree left in place):', e);
}
}
+
+/** The hive scratch dir for a worker (its inbox/outbox/memory): HIVE_ROOT/agents/<id>.
+ * Null when there's no hive root. */
+function workerScratchDir(workerId: string): string | null {
+ const root = hive.root();
+ return root ? join(root, 'agents', workerId) : null;
+}
+
+/** Best-effort removal of a worker's scratch (hive agent) dir. Guarded to ONLY ever
+ * delete a path that resolves to exactly HIVE_ROOT/agents/<workerId> and never a
+ * still-live worker — so a crafted/mismatched id can't escape the agents root. */
+function removeWorkerScratch(workerId: string): void {
+ if (liveWorkers.has(workerId)) return; // never wipe a live worker's mailbox
+ const dir = workerScratchDir(workerId);
+ const root = hive.root();
+ if (!dir || !root) return;
+ const agentsRoot = join(root, 'agents');
+ // Path-safety: the resolved dir must sit directly under agents/ with basename == id.
+ if (resolve(dir) !== join(resolve(agentsRoot), basename(dir)) || basename(dir) !== workerId) return;
+ try { rmSync(dir, { recursive: true, force: true }); }
+ catch (e) { console.error('[worker] removeWorkerScratch failed:', e); }
+}
// A natural PTY exit must run the same teardown as an explicit kill.
ptyManager.setExitHandler(teardownPty);
@@ -2659,8 +2719,11 @@ async function processSpawnRequest(filePath: string): Promise<void> {
}
if (!res.ok) { fail(`spawn failed — ${res.error ?? 'unknown error'}`); return; }
- // Register for done-scan / idle-reap / safe teardown (pty id == workerId).
- liveWorkers.set(workerId, { workerId, reqId, slack, baseBranch, spawnedAt: Date.now() });
+ // Register for done-scan / idle-reap / token-cap / safe teardown (pty id == workerId).
+ // tokenCap is optional plumbing (default unlimited) — only a positive finite cap is kept.
+ const tokenCap = typeof raw.tokenCap === 'number' && Number.isFinite(raw.tokenCap) && raw.tokenCap > 0
+ ? raw.tokenCap : undefined;
+ liveWorkers.set(workerId, { workerId, reqId, name: meta.name, slack, baseBranch, spawnedAt: Date.now(), tokenCap });
// Dispatch the objective via the standard inbox path (zero new transport),
// reusing the autonomous-request preamble so the worker gets the exact Slack
@@ -2680,6 +2743,62 @@ async function processSpawnRequest(filePath: string): Promise<void> {
archiveRequest(filePath, '.done');
}
+/** Total tokens (input+output+cache) a worker has burned so far, from the usage
+ * provider — 0 when unknown. Mirrors the breaker's `tokensOf`. Used only by the
+ * (default-off) per-worker token cap. */
+function workerTokensUsed(workerId: string): number {
+ const s = usageProvider.getAgentUsage(workerId);
+ return s ? s.input + s.output + s.cacheRead + s.cacheCreation : 0;
+}
+
+/** Throttle for the GC sweep — git checks are cheap but pointless every 1.5s tick. */
+const GC_SWEEP_MS = 60_000;
+let lastGcSweepAt = 0;
+let gcSweepRunning = false;
+
+/** Reclaim preserved worker worktrees (+ their scratch dirs) whose work is now
+ * integrated, or whose worktree was already removed by hand. Fail-safe: a worktree
+ * is removed ONLY when `worktreeIsGcSafe` proves it clean AND integrated; any doubt
+ * KEEPS it (never discards un-integrated work — god is the sole integrator). Runs
+ * inside the worker tick, throttled to GC_SWEEP_MS, and is a no-op when nothing is
+ * preserved (the common case → zero cost). */
+async function gcPreservedWorktrees(): Promise<void> {
+ if (gcSweepRunning || preservedWorktrees.size === 0) return;
+ gcSweepRunning = true;
+ try {
+ for (const [key, e] of [...preservedWorktrees]) {
+ // A worker id that is live again (reqId reuse) → never GC its worktree or
+ // scratch out from under the new run; leave the stale entry for a later sweep.
+ if (liveWorkers.has(e.workerId)) continue;
+ // (a) Worktree already gone (removed at clean teardown, or god removed it by
+ // hand per the preserve note) → just reclaim the scratch dir + drop tracking.
+ if (!existsSync(e.wtPath)) {
+ removeWorkerScratch(e.workerId);
+ preservedWorktrees.delete(key);
+ console.log(`[worker gc] ${e.workerId}: worktree already gone — reclaimed scratch`);
+ continue;
+ }
+ // (b) Still on disk → reclaim ONLY when provably integrated + clean.
+ let safe: { gc: boolean; detail: string };
+ try { safe = await worktreeIsGcSafe(e.wtPath, e.baseBranch); }
+ catch (err) { console.error('[worker gc] gc-safe check threw (keeping):', err); continue; }
+ if (!safe.gc) continue; // keep — fail-safe
+ const r = await removeWorktree(e.origCwd, e.wtPath);
+ if (!r.ok) { console.error(`[worker gc] removeWorktree failed (keeping ${e.workerId}):`, r.error); continue; }
+ removeWorkerScratch(e.workerId);
+ preservedWorktrees.delete(key);
+ console.log(`[worker gc] reclaimed ${e.workerId} (${safe.detail})`);
+ informGod(
+ `[worker worktree reclaimed] ${e.workerId}`,
+ `The preserved worktree for ${e.workerId} is now integrated (${safe.detail}), so it and its scratch dir were garbage-collected.\nWorktree: ${e.wtPath}`,
+ e.slack
+ );
+ }
+ } finally {
+ gcSweepRunning = false;
+ }
+}
+
/** One controller tick: (1) finish/reap live workers (frees slots), then (2) pull
* new requests up to the concurrency cap. Order matters so a freed slot is reused
* the same tick. */
@@ -2690,6 +2809,10 @@ async function ephemeralWorkerTick(): Promise<void> {
const cfg = readConfig();
const maxWorkers = Math.max(1, cfg.maxConcurrentWorkers ?? 4);
const idleTimeoutMs = Math.max(1, cfg.workerIdleTimeoutMinutes ?? 20) * 60_000;
+ // Per-worker token cap. 0 = UNLIMITED (the default — wired but never throttles
+ // unless a positive cap is set per-request or via defaultWorkerTokenCap).
+ const defaultTokenCap = typeof cfg.defaultWorkerTokenCap === 'number' && cfg.defaultWorkerTokenCap > 0
+ ? cfg.defaultWorkerTokenCap : 0;
// (1) Finish or reap. ptyManager.kill → teardownPty → gated worktree + archive
// + liveWorkers.delete. `releasing` guards the gap before onExit fires.
@@ -2702,6 +2825,23 @@ async function ephemeralWorkerTick(): Promise<void> {
ptyManager.kill(workerId);
continue;
}
+ // Token-cap reap (default-off plumbing). An effective cap > 0 → reap when the
+ // worker's cumulative token use exceeds it; its committed work is preserved.
+ const tokenCap = (rec.tokenCap && rec.tokenCap > 0) ? rec.tokenCap : defaultTokenCap;
+ if (tokenCap > 0) {
+ const used = workerTokensUsed(workerId);
+ if (used > tokenCap) {
+ rec.releasing = true;
+ console.warn(`[worker] reaping ${workerId} — token cap (${used.toLocaleString()} > ${tokenCap.toLocaleString()})`);
+ informGod(
+ `[worker reaped — token cap] ${workerId}`,
+ `Worker ${workerId} used ${used.toLocaleString()} tokens (> its cap of ${tokenCap.toLocaleString()}) and was reaped. Any committed work on its branch is preserved for you.`,
+ rec.slack
+ );
+ ptyManager.kill(workerId);
+ continue;
+ }
+ }
const idleMs = ptyManager.idleFor(workerId);
if (idleMs === undefined) continue; // PTY already gone; teardownPty cleans up
if (idleMs > idleTimeoutMs) {
@@ -2727,6 +2867,14 @@ async function ephemeralWorkerTick(): Promise<void> {
await processSpawnRequest(join(dir, f));
}
}
+
+ // (3) GC preserved worktrees whose work has since integrated. Throttled to
+ // GC_SWEEP_MS and a no-op when nothing is preserved (the common case).
+ const now = Date.now();
+ if (preservedWorktrees.size > 0 && now - lastGcSweepAt >= GC_SWEEP_MS) {
+ lastGcSweepAt = now;
+ await gcPreservedWorktrees();
+ }
} catch (e) {
console.error('[worker] tick error:', e);
} finally {
@@ -2745,6 +2893,73 @@ function stopEphemeralWorkerWatcher(): void {
if (workerWatchTimer) { clearInterval(workerWatchTimer); workerWatchTimer = null; }
}
+/** Snapshot of one live ephemeral worker for the renderer Workers tab. */
+interface WorkerSnapshot {
+ workerId: string;
+ reqId: string;
+ name: string;
+ baseBranch: string;
+ spawnedAt: number;
+ ageMs: number;
+ idleMs: number | null; // null = PTY already gone
+ tokensUsed: number;
+ tokenCap: number | null; // effective cap (per-request or config default); null = unlimited
+ hasSlack: boolean;
+ releasing: boolean;
+ status: 'releasing' | 'working';
+}
+/** Snapshot of a preserved-but-not-yet-GC'd worktree for the tab. */
+interface PreservedSnapshot {
+ workerId: string;
+ wtPath: string;
+ baseBranch: string;
+ preservedAt: number;
+}
+
+/** List live ephemeral workers (+ preserved worktrees awaiting GC) for the tab. */
+ipcMain.handle('workers:list', (): { live: WorkerSnapshot[]; preserved: PreservedSnapshot[]; maxWorkers: number } => {
+ const cfg = readConfig();
+ const defaultCap = typeof cfg.defaultWorkerTokenCap === 'number' && cfg.defaultWorkerTokenCap > 0
+ ? cfg.defaultWorkerTokenCap : 0;
+ const now = Date.now();
+ const live: WorkerSnapshot[] = [...liveWorkers.values()].map((rec) => {
+ const idle = ptyManager.idleFor(rec.workerId);
+ const effCap = (rec.tokenCap && rec.tokenCap > 0) ? rec.tokenCap : (defaultCap > 0 ? defaultCap : 0);
+ return {
+ workerId: rec.workerId,
+ reqId: rec.reqId,
+ name: rec.name ?? rec.workerId,
+ baseBranch: rec.baseBranch,
+ spawnedAt: rec.spawnedAt,
+ ageMs: Math.max(0, now - rec.spawnedAt),
+ idleMs: idle === undefined ? null : idle,
+ tokensUsed: workerTokensUsed(rec.workerId),
+ tokenCap: effCap > 0 ? effCap : null,
+ hasSlack: !!rec.slack,
+ releasing: !!rec.releasing,
+ status: rec.releasing ? 'releasing' : 'working'
+ };
+ });
+ const preserved: PreservedSnapshot[] = [...preservedWorktrees.values()].map((e) => ({
+ workerId: e.workerId, wtPath: e.wtPath, baseBranch: e.baseBranch, preservedAt: e.preservedAt
+ }));
+ return { live, preserved, maxWorkers: Math.max(1, cfg.maxConcurrentWorkers ?? 4) };
+});
+
+/** Manually stop a live ephemeral worker. Mirrors the done-release path: mark
+ * releasing, then kill → teardownPty runs the SAFETY-GATED worktree teardown
+ * (committed work is preserved, never force-discarded). Idempotent. */
+ipcMain.handle('workers:stop', (_evt, workerId: string): { ok: boolean; error?: string } => {
+ if (typeof workerId !== 'string' || !workerId) return { ok: false, error: 'invalid worker id' };
+ const rec = liveWorkers.get(workerId);
+ if (!rec) return { ok: false, error: 'no such live worker' };
+ if (rec.releasing) return { ok: true }; // already stopping
+ rec.releasing = true;
+ console.log(`[worker] manual stop requested for ${workerId}`);
+ try { ptyManager.kill(workerId); } catch (e) { return { ok: false, error: String(e) }; }
+ return { ok: true };
+});
+
/** Start every hive-bound background service against the current harnessHome.
* Called on boot, and again to recover in place if a folder-change copy fails
* (config:changeHome tears these down before copying). No-op without a home. */
diff --git a/src/preload/index.ts b/src/preload/index.ts
index f3ced960..d7120975 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -385,6 +385,29 @@ export interface CIRun {
url: string;
}
+/** One live god-triggered ephemeral worker, as shown in the Workers tab. */
+export interface WorkerSnapshot {
+ workerId: string;
+ reqId: string;
+ name: string;
+ baseBranch: string;
+ spawnedAt: number;
+ ageMs: number;
+ idleMs: number | null; // null = PTY already gone
+ tokensUsed: number;
+ tokenCap: number | null; // effective cap; null = unlimited (the default)
+ hasSlack: boolean;
+ releasing: boolean;
+ status: 'releasing' | 'working';
+}
+/** A worker worktree preserved at teardown, awaiting integration + GC. */
+export interface PreservedWorktreeSnapshot {
+ workerId: string;
+ wtPath: string;
+ baseBranch: string;
+ preservedAt: number;
+}
+
const api = {
version: __APP_VERSION__,
@@ -477,6 +500,14 @@ const api = {
hiveMemory: (id: string): Promise<string> => ipcRenderer.invoke('hive:memory', id),
hiveInbox: (id: string): Promise<HiveMessage[]> => ipcRenderer.invoke('hive:inbox', id),
+ // ─── Ephemeral workers (P4 — Slack-triggered isolated workers) ───────────
+ /** Live ephemeral workers + worktrees preserved awaiting integration/GC. */
+ listWorkers: (): Promise<{ live: WorkerSnapshot[]; preserved: PreservedWorktreeSnapshot[]; maxWorkers: number }> =>
+ ipcRenderer.invoke('workers:list'),
+ /** Manually stop a live ephemeral worker (safety-gated teardown; work preserved). */
+ stopWorker: (workerId: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('workers:stop', workerId),
+
// ─── Semantic memory (MemPalace CLI) ─────────────────────────────────────
memoryStatus: (): Promise<MemoryStatus> => ipcRenderer.invoke('hive:memoryStatus'),
searchMemory: (query: string, wing?: string): Promise<{ ok: boolean; output: string; error?: string }> =>
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index 5424203e..846b4465 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -8,6 +8,7 @@ import { MessageQueueComposer } from './MessageQueueComposer';
import { TasksKanban } from './TasksKanban';
import { AskMeTab } from './AskMeTab';
import { SchedulesTab } from './SchedulesTab';
+import { WorkersTab } from './WorkersTab';
import { acquireTerminal, resetTerminal } from './terminalPool';
import { Icon } from './Icon';
import { MemoryGraphPanel } from './MemoryGraphPanel';
@@ -25,7 +26,7 @@ import { canReceiveInbox } from '@shared/agentProvider';
// Both the AskMe (#human) tab and the Schedules (#50) tab live here. The inline
// SCHEDULES section + its ScheduledMission/relTime helpers moved into SchedulesTab.
-type CCTab = 'terminal' | 'floor' | 'tasks' | 'human' | 'schedules' | 'memory' | 'graph' | 'activity' | 'handbook';
+type CCTab = 'terminal' | 'floor' | 'tasks' | 'human' | 'schedules' | 'memory' | 'graph' | 'activity' | 'handbook' | 'workers';
/** Fallback denominator for the per-agent token meter when no floor token budget
* is configured — so the bar reads as a budget estimate (filled + remaining)
@@ -51,7 +52,8 @@ const TABS: { key: CCTab; label: string; icon: Parameters<typeof Icon>[0]['name'
{ key: 'memory', label: 'memory', icon: 'sparkle' },
{ key: 'graph', label: 'graph', icon: 'web' },
{ key: 'activity', label: 'activity', icon: 'bell' },
- { key: 'handbook', label: 'commands', icon: 'code' }
+ { key: 'handbook', label: 'commands', icon: 'code' },
+ { key: 'workers', label: 'workers', icon: 'gear' }
];
export function CommandCenterPanel({ agent }: { agent: Agent }) {
@@ -188,6 +190,7 @@ export function CommandCenterPanel({ agent }: { agent: Agent }) {
)}
{tab === 'activity' && <ActivityTab />}
{tab === 'handbook' && <HandbookTab />}
+ {tab === 'workers' && <WorkersTab />}
</div>
</PixelPanel>
);
diff --git a/src/renderer/src/components/WorkersTab.tsx b/src/renderer/src/components/WorkersTab.tsx
new file mode 100644
index 00000000..f2dbd157
--- /dev/null
+++ b/src/renderer/src/components/WorkersTab.tsx
@@ -0,0 +1,172 @@
+import { useEffect, useState, useCallback } from 'react';
+import { PixelButton } from './PixelButton';
+
+/**
+ * WORKERS — live god-triggered ephemeral Slack workers (the Phase-1 spawn loop):
+ * fresh isolated worktree → does a job → replies in-thread → safe teardown. This
+ * tab reads main's `liveWorkers` map (via workers:list) so a human can SEE what's
+ * running and stop one by hand; it also surfaces worktrees PRESERVED at teardown
+ * (held until their work integrates, then auto-GC'd) so nothing silently piles up.
+ */
+
+// Types flow from main's `workers:list` handler via the typed `window.cth` global
+// (declared in preload/index.d.ts) — derived here so there's no cross-package import.
+type WorkersData = Awaited<ReturnType<typeof window.cth.listWorkers>>;
+type WorkerSnapshot = WorkersData['live'][number];
+type PreservedWorktreeSnapshot = WorkersData['preserved'][number];
+
+const POLL_MS = 2000;
+
+function relAge(ms: number): string {
+ if (ms < 1000) return '0s';
+ const s = Math.round(ms / 1000);
+ if (s < 90) return `${s}s`;
+ const m = Math.round(s / 60);
+ if (m < 90) return `${m}m`;
+ const h = Math.round(m / 60);
+ return h < 48 ? `${h}h` : `${Math.round(h / 24)}d`;
+}
+
+function fmtTokens(n: number): string {
+ if (n < 1000) return String(n);
+ if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`;
+ return `${(n / 1_000_000).toFixed(2)}M`;
+}
+
+const card: React.CSSProperties = {
+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 6
+};
+const metaRow: React.CSSProperties = {
+ display: 'flex', flexWrap: 'wrap', gap: '4px 14px', fontFamily: 'var(--cth-font-mono)',
+ fontSize: 11, color: 'var(--cth-ink-700)'
+};
+const sectionHead: React.CSSProperties = {
+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase',
+ letterSpacing: 0.5, color: 'var(--cth-ink-900)', margin: '2px 0'
+};
+
+function StatusBadge({ w }: { w: WorkerSnapshot }) {
+ const releasing = w.status === 'releasing';
+ return (
+ <span style={{
+ fontFamily: 'var(--cth-font-mono)', fontSize: 10, padding: '1px 6px',
+ textTransform: 'uppercase', letterSpacing: 0.5,
+ color: releasing ? 'var(--cth-paper-100)' : 'var(--cth-ink-900)',
+ background: releasing ? 'var(--cth-ink-700)' : 'var(--cth-green, #2f8f4e)',
+ boxShadow: releasing ? 'none' : 'inset 0 0 0 1px var(--cth-ink-700)'
+ }}>
+ {releasing ? 'stopping' : 'working'}
+ </span>
+ );
+}
+
+export function WorkersTab() {
+ const [data, setData] = useState<WorkersData | null>(null);
+ const [stopping, setStopping] = useState<Record<string, boolean>>({});
+
+ const refresh = useCallback(() => {
+ window.cth.listWorkers().then(setData).catch(() => { /* main not ready */ });
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ const t = setInterval(refresh, POLL_MS);
+ return () => clearInterval(t);
+ }, [refresh]);
+
+ const stop = useCallback((workerId: string) => {
+ setStopping((s) => ({ ...s, [workerId]: true }));
+ window.cth.stopWorker(workerId)
+ .catch(() => { /* surfaced by the row vanishing or not */ })
+ .finally(() => { refresh(); });
+ }, [refresh]);
+
+ const live = data?.live ?? [];
+ const preserved = data?.preserved ?? [];
+ const max = data?.maxWorkers ?? 4;
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '4px 2px', overflow: 'auto' }}>
+ <div>
+ <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
+ <span style={sectionHead}>Live workers</span>
+ <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-700)' }}>
+ {live.length} / {max}
+ </span>
+ </div>
+ <p style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-700)', margin: '2px 0 8px' }}>
+ Isolated workers Michael spins up to handle Slack messages — they run to completion, reply in-thread, then tear down.
+ </p>
+
+ {live.length === 0 ? (
+ <div style={{ ...card, color: 'var(--cth-ink-700)', fontFamily: 'var(--cth-font-ui)', fontSize: 12 }}>
+ No workers running right now.
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+ {live.map((w) => (
+ <div key={w.workerId} style={card}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'space-between' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
+ <StatusBadge w={w} />
+ <span style={{
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13, fontWeight: 600, color: 'var(--cth-ink-900)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
+ }}>{w.name}</span>
+ {w.hasSlack && (
+ <span title="replies to a Slack thread" style={{
+ fontFamily: 'var(--cth-font-mono)', fontSize: 10, color: 'var(--cth-ink-700)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)', padding: '0 5px'
+ }}>slack</span>
+ )}
+ </div>
+ <PixelButton
+ onClick={() => stop(w.workerId)}
+ disabled={w.releasing || !!stopping[w.workerId]}
+ >
+ {w.releasing || stopping[w.workerId] ? 'stopping…' : 'stop'}
+ </PixelButton>
+ </div>
+ <div style={metaRow}>
+ <span title="worker / PTY id">{w.workerId}</span>
+ <span title="base branch the worktree was cut from">base: {w.baseBranch}</span>
+ <span title="time since spawn">up {relAge(w.ageMs)}</span>
+ <span title="time since last terminal output">
+ {w.idleMs === null ? 'pty gone' : `idle ${relAge(w.idleMs)}`}
+ </span>
+ <span title="cumulative tokens (input+output+cache)">
+ tokens {fmtTokens(w.tokensUsed)}{w.tokenCap !== null ? ` / ${fmtTokens(w.tokenCap)}` : ' · uncapped'}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {preserved.length > 0 && (
+ <div>
+ <span style={sectionHead}>Preserved worktrees ({preserved.length})</span>
+ <p style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-700)', margin: '2px 0 8px' }}>
+ Finished workers whose worktree held un-integrated work — kept (never auto-discarded) and auto-reclaimed once the work lands in its base branch.
+ </p>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+ {preserved.map((p) => (
+ <div key={p.wtPath} style={card}>
+ <div style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 12, fontWeight: 600, color: 'var(--cth-ink-900)' }}>
+ {p.workerId}
+ </div>
+ <div style={metaRow}>
+ <span style={{ wordBreak: 'break-all' }}>{p.wtPath}</span>
+ <span>base: {p.baseBranch}</span>
+ <span>kept {relAge(Math.max(0, Date.now() - p.preservedAt))} ago</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}