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(worker): teardown-safety gate — never auto-discard a worker's unintegrated work
Chaitanya Giri13c5435788b4
diff --git a/src/main/git.ts b/src/main/git.tsindex 8dd229e5..44d9f186 100644--- a/src/main/git.ts+++ b/src/main/git.ts@@ -173,3 +173,32 @@ export async function removeWorktree(if (res.ok) return { ok: true };return { ok: false, error: res.error };}++/** Does this worktree hold work that must NOT be auto-discarded? `keep` is true if+ * the working tree is dirty (uncommitted/untracked changes) OR the branch has+ * commits the base branch doesn't (un-integrated / would-be-PR commits). Ephemeral+ * workers never push, so "commits ahead of base" is the local proxy for "un-pushed+ * / open PR" work. Fails SAFE: any git query we can't run is treated as "there+ * might be work" → keep, so an uncertain state never triggers an auto-remove. */+export async function worktreeHasUnintegratedWork(+ wtPath: string, baseBranch: string+): Promise<{ keep: boolean; detail: string; branch: string; dirty: boolean; ahead: number }> {+ const br = await getBranch(wtPath);+ const branch = 'current' in br && br.current ? br.current : '(detached)';+ // Uncommitted or untracked changes?+ const status = await runGit(wtPath, ['status', '--porcelain']);+ const dirty = status.ok ? status.stdout.trim().length > 0 : true; // unknown → assume dirty+ // Commits on HEAD not reachable from the base branch?+ let ahead = 0;+ let aheadKnown = true;+ const rl = await runGit(wtPath, ['rev-list', '--count', `${baseBranch}..HEAD`]);+ if (rl.ok) {+ const n = parseInt(rl.stdout.trim(), 10);+ ahead = Number.isFinite(n) ? n : 0;+ } else {+ aheadKnown = false; // unknown → assume there is work+ }+ const keep = dirty || ahead > 0 || !aheadKnown;+ const detail = `dirty=${dirty}, commitsAheadOf(${baseBranch})=${aheadKnown ? ahead : 'unknown'}`;+ return { keep, detail, branch, dirty, ahead };+}diff --git a/src/main/index.ts b/src/main/index.tsindex 80e98479..d0d43f8f 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+ addWorktree, removeWorktree, worktreeHasUnintegratedWork} from './git';import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';import { HookServer } from './hooks';@@ -157,6 +157,19 @@ const worktreePaths = new Map<string, string>();* `git worktree remove` from the parent tree, not the worktree itself). */const worktreeOrigins = new Map<string, string>();+/** A live god-triggered ephemeral worker, tracked from spawn to teardown. */+interface WorkerRec {+ workerId: string; // == the PTY id == hive agent id (`worker-<reqId>`)+ reqId: string; // the spawn-request id+ slack?: { channel: string; thread_ts: string };+ baseBranch: string; // the branch its worktree was cut from (for ahead-of-base)+ spawnedAt: number; // epoch ms+}+/** 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>();+/*** 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@@ -191,12 +204,65 @@ function teardownPty(id: string): void {const origCwd = worktreeOrigins.get(id) ?? wtPath;worktreePaths.delete(id);worktreeOrigins.delete(id);- void removeWorktree(origCwd, wtPath)- .then(r => { if (!r.ok) console.error('[worktree] removeWorktree failed:', r.error); })- .catch(e => console.error('[worktree] removeWorktree threw:', e));+ // Ephemeral workers get a SAFETY-GATED teardown: never auto-remove a worktree+ // that holds unintegrated work. This sits INSIDE teardownPty so it covers ALL+ // teardown routes — a worker that finished (controller kill), crashed, or was+ // idle-reaped all land here. Normal agents keep the immediate force-remove.+ const worker = liveWorkers.get(id);+ if (worker) {+ liveWorkers.delete(id);+ void finalizeWorkerWorktree(wtPath, origCwd, worker);+ } else {+ void removeWorktree(origCwd, wtPath)+ .then(r => { if (!r.ok) console.error('[worktree] removeWorktree failed:', r.error); })+ .catch(e => console.error('[worktree] removeWorktree threw:', e));+ }}+ // A worker whose isolation failed (non-repo cwd) has no worktree to gate above —+ // still clear its tracking entry so the controller stops watching a dead PTY.+ if (liveWorkers.has(id)) liveWorkers.delete(id);syncKeepAwake();}++/** Send an inform to the god agent (the human's proxy). The ephemeral-worker+ * controller uses this to surface every terminal failure AND to carry the Slack+ * {channel,thread_ts} so god can post a 'couldn't complete' reply — closing the+ * Slack loop (the success path is the worker replying in-thread itself). */+function informGod(subject: string, body: string, slack?: { channel: string; thread_ts: string }): void {+ try {+ const slackLine = slack+ ? `\n\n[SLACK] Close the loop — post a reply to channel ${slack.channel} thread ${slack.thread_ts} via:\n node "${slackReplyScriptPath()}" --channel ${slack.channel} --thread ${slack.thread_ts} --text "<your message>"`+ : '';+ hive.send({ to: 'god', act: 'inform', subject, body: body + slackLine }, 'ephemeral-worker');+ } catch (e) {+ console.error('[worker] informGod failed:', e);+ }+}++/** Gated worktree teardown for an ephemeral worker: remove it ONLY when it holds no+ * unintegrated work; otherwise leave it (and its branch) in place and ping god, the+ * sole integrator. Async + best-effort; on any uncertainty it KEEPS the worktree+ * (fail-safe — never auto-discard possibly-valuable work). */+async function finalizeWorkerWorktree(wtPath: string, origCwd: string, worker: WorkerRec): Promise<void> {+ try {+ const work = await worktreeHasUnintegratedWork(wtPath, worker.baseBranch);+ if (work.keep) {+ console.warn(`[worker] PRESERVING worktree with unintegrated work: ${wtPath} (${work.detail})`);+ 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}"`,+ worker.slack+ );+ return;+ }+ const r = await removeWorktree(origCwd, wtPath);+ if (!r.ok) console.error('[worker] removeWorktree failed:', r.error);+ } catch (e) {+ console.error('[worker] finalizeWorkerWorktree threw (worktree left in place):', e);+ }+}// A natural PTY exit must run the same teardown as an explicit kill.ptyManager.setExitHandler(teardownPty);