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(resume): restore agent sessions across restart + Add Agent resume-session field
Vyapak Goyal44d73cb4ac7d
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 4c0724bb..17917e7a 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -295,9 +295,15 @@ export class HiveManager {const cursor = join(dir, 'cursor.json');if (!existsSync(cursor)) this.writeJson(cursor, { lastProcessed: null });- // upsert registry+ // upsert registry — spread the PRIOR entry first so a respawn preserves+ // fields the spawn `meta` doesn't carry, above all `sessionId`. Without this,+ // ensureAgent (which runs before the resume lookup in the pty:spawn handler)+ // would wipe the recorded session id, so `lastSession()` returns undefined and+ // `--resume` is never attached — i.e. every restart starts a fresh thread.const reg = this.registry();+ const prev = reg.agents[meta.id];reg.agents[meta.id] = {+ ...prev,...meta,capabilities: meta.capabilities ?? [],role: meta.role ?? (meta.isGod ? 'orchestrator' : 'agent'),diff --git a/src/main/index.ts b/src/main/index.tsindex 23de3bdd..0a0d1282 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -21,7 +21,7 @@ import type { UsageProvider } from './usage';import { MemoryManager } from './memory';import { MemoryReflector, type ReflectSettings } from './reflect';import { PersistStore } from './db';-import { readAgentUsage, readContextTokens } from './transcript';+import { readAgentUsage, readContextTokens, seedSessionTranscript, resolveSessionCwd } from './transcript';import { listIssues, listCIRuns } from './github';import { SlackWebhookServer, SlackReplyServer, postSlackReply, type SlackEventFile } from './slack';import { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';@@ -1197,7 +1197,7 @@ function createWindow(): void {}// ─── IPC: pty lifecycle ─────────────────────────────────────────────────────-ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; provider?: AgentProvider }) => {+ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; resumeSessionId?: string; provider?: AgentProvider }) => {if (!opts || typeof opts.id !== 'string' || typeof opts.cwd !== 'string' || typeof opts.command !== 'string') {return { ok: false, error: 'invalid SpawnOptions' };}@@ -1213,6 +1213,11 @@ ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMeta// its own worktree on an `agent/<id>` branch so it can't clobber other agents'// (or the user's) working tree. Best-effort — a failure falls back to the// shared cwd rather than blocking the spawn.+ // NOTE (tracked, not yet hardened): the restore flow passes isolate:false and+ // re-enters the existing worktree by cwd, so it never reaches here. But a stale+ // `isolate:true` recipe spawned against an already-existing worktree path would+ // make addWorktree below conflict (path/branch exists) and fall back to the base+ // cwd — reuse-existing-worktree handling here is the follow-up.if (opts.isolate === true && await isRepo(opts.cwd)) {try {const origCwd = opts.cwd;@@ -1260,6 +1265,12 @@ ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMeta}// Long-run guardrails + tiering (Lane A #6.4/#6.6). All additive to the args// already assembled (incl. the hive injection); an explicit choice always wins.+ // Set when an explicit Add Agent "resume session" id couldn't be located and we+ // silently fell back to a fresh session — returned so the dialog can surface it.+ let resumeNotFound = false;+ // Set when `--resume` was actually attached (explicit id or restore-on-restart),+ // so the renderer can skip re-orienting a god/assistant that resumed its thread.+ let didResume = false;// Claude-only — these are Claude Code flags; other CLIs carry their own flags// in the command string the renderer already built.if (opts.hive && claudeProvider) {@@ -1275,6 +1286,28 @@ ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMetaif (typeof cfg.maxTurns === 'number' && cfg.maxTurns > 0 && !args.includes('--max-turns')) {args.push('--max-turns', String(cfg.maxTurns));}+ // Resume: an explicit session id (Add Agent "resume session" field, #2) wins,+ // else this agent's last recorded session (#1 restore-on-restart / #6.6a).+ // Seed the transcript into the target cwd's Claude project dir first — Claude+ // keys sessions by cwd, so a session started elsewhere is invisible until its+ // `.jsonl` is copied across. Only attach `--resume` if the transcript is+ // actually present (already or after the copy); otherwise fall back to a fresh+ // session rather than launching a `--resume` against a missing id.+ const explicitSid = typeof opts.resumeSessionId === 'string' ? opts.resumeSessionId.trim() : '';+ const sid = explicitSid || (opts.resume === true ? hive.lastSession(opts.hive.id) : undefined);+ if (sid && !args.includes('--resume')) {+ if (seedSessionTranscript(opts.cwd, sid)) {+ args.push('--resume', sid);+ didResume = true;+ } else if (explicitSid) {+ // The user typed a session id in the Add Agent dialog but it isn't in any+ // Claude project dir — we fall back to a FRESH session rather than a broken+ // `--resume`. Make that non-silent: warn on the floor and flag it back to+ // the renderer so the dialog can tell the user 'started fresh'.+ console.warn(`[resume] session "${explicitSid}" not found in any Claude project dir — starting a fresh session`);+ resumeNotFound = true;+ }+ }opts.args = args;}// Idempotent session resume on respawn (#6.6a) — provider-aware: Claude@@ -1282,7 +1315,10 @@ ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMeta// comes from hook payloads (agy's conversationId flows through the bridge), so// a restored worker continues its prior CLI session. Only when requested AND a// prior id exists for this agent.- if (opts.hive && opts.resume === true) {+ // Claude resume — incl. transcript seeding + only-attach-when-present — is+ // handled in the Claude-only block above; this generic flag path covers the+ // other CLIs (it must not blindly attach `--resume` when the seed failed).+ if (opts.hive && opts.resume === true && !claudeProvider) {const rf = providerPreset(provider).resumeFlag;const sid = hive.lastSession(opts.hive.id);if (rf && sid) {@@ -1309,7 +1345,12 @@ ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMeta}const res = ptyManager.spawn(opts);syncKeepAwake(); // arm the power-save blocker while ≥1 agent PTY is alive (#18)- return res;+ // Hand the resolved worktree path back to the renderer so it can persist it on+ // the agent (only set when isolation actually provisioned a worktree above).+ // The restore flow re-enters this exact worktree (cwd = worktreePath) so a+ // restored isolated agent resumes in the CORRECT checkout, not the base repo.+ const worktreePath = worktreePaths.get(opts.id);+ return { ...res, ...(worktreePath ? { worktreePath } : {}), ...(resumeNotFound ? { resumeNotFound: true } : {}), ...(didResume ? { resumed: true } : {}) };});ipcMain.handle('pty:write', (_evt, id: string, data: string) => {if (typeof id !== 'string' || typeof data !== 'string') return { ok: false, error: 'invalid args' };@@ -1330,6 +1371,12 @@ ipcMain.handle('pty:kill', (_evt, id: string) => {});ipcMain.handle('pty:list', () => ptyManager.list());+// Resolve a pasted Claude session id to the cwd it originally ran in, so the Add+// Agent dialog can auto-fill the folder for a resume (#2 zero-step resume). Reads+// the cwd from a transcript record; null when the id is invalid/unknown.+ipcMain.handle('session:resolveCwd', (_evt, sessionId: unknown) =>+ (typeof sessionId === 'string' ? resolveSessionCwd(sessionId) : null));+// ─── IPC: clipboard ─────────────────────────────────────────────────────────ipcMain.handle('app:copyToClipboard', (_evt, text: unknown) => {if (typeof text !== 'string') return { ok: false, error: 'invalid text' };diff --git a/src/main/transcript.ts b/src/main/transcript.tsindex 06630850..02f56b45 100644--- a/src/main/transcript.ts+++ b/src/main/transcript.ts@@ -1,4 +1,4 @@-import { closeSync, existsSync, fstatSync, openSync, readSync, readdirSync, readFileSync } from 'node:fs';+import { closeSync, cpSync, existsSync, fstatSync, mkdirSync, openSync, readSync, readdirSync, readFileSync, statSync } from 'node:fs';import os from 'node:os';import path from 'node:path';import { estimateCostUsd, normalizeModel } from './pricing';@@ -16,6 +16,80 @@ export function projectDir(cwd: string): string {return path.join(os.homedir(), '.claude/projects', key);}+/** Ensure session `<sessionId>.jsonl` exists in `cwd`'s Claude project dir so a+ * `claude --resume <sessionId>` spawn in that cwd can find it. Claude keys+ * transcripts by cwd, so a session started elsewhere is invisible until its+ * `.jsonl` is seeded across.+ *+ * - Already present in the target project dir → no-op, returns true.+ * - Found under a DIFFERENT project dir (resumed from another cwd — the Add+ * Agent "resume session" flow, #2) → copied across, returns true.+ * - Not found anywhere → returns false, so the caller can fall back to a fresh+ * session instead of launching a broken `--resume`.+ *+ * Best-effort: any fs error yields false rather than throwing into the spawn. */+/** A Claude session id is a UUID. Renderer-supplied ids flow into `path.join`, so+ * reject anything outside this charset before using one as a path component (a+ * crafted id like `../../x` would otherwise traverse out of the project dirs). */+const VALID_SESSION_ID = /^[A-Za-z0-9_-]+$/;++export function seedSessionTranscript(cwd: string, sessionId: string): boolean {+ try {+ if (!sessionId || !VALID_SESSION_ID.test(sessionId)) return false;+ const target = path.join(projectDir(cwd), `${sessionId}.jsonl`);+ if (existsSync(target)) return true;+ const projectsRoot = path.join(os.homedir(), '.claude/projects');+ if (!existsSync(projectsRoot)) return false;+ for (const dir of readdirSync(projectsRoot)) {+ const candidate = path.join(projectsRoot, dir, `${sessionId}.jsonl`);+ if (existsSync(candidate)) {+ mkdirSync(path.dirname(target), { recursive: true });+ cpSync(candidate, target);+ return true;+ }+ }+ return false;+ } catch {+ return false;+ }+}++/** Resolve a session id to the ORIGINAL working directory it ran in, for the Add+ * Agent "resume session" auto-fill. The cwd is read from a transcript RECORD+ * (every line carries a `cwd` field) — deliberately NOT by un-dashing the+ * project-dir name, which is lossy when the path itself contains dashes. Searches+ * every `~/.claude/projects/<dir>/<sessionId>.jsonl`; if more than one matches+ * (shouldn't — session ids are unique UUIDs) the most-recently-modified wins.+ * Returns the cwd string, or null if not found / unreadable / no cwd record. */+export function resolveSessionCwd(sessionId: string): string | null {+ try {+ if (!sessionId || !VALID_SESSION_ID.test(sessionId)) return null;+ const projectsRoot = path.join(os.homedir(), '.claude/projects');+ if (!existsSync(projectsRoot)) return null;+ let best: { file: string; mtime: number } | null = null;+ for (const dir of readdirSync(projectsRoot)) {+ const candidate = path.join(projectsRoot, dir, `${sessionId}.jsonl`);+ try {+ const st = statSync(candidate);+ if (!best || st.mtimeMs > best.mtime) best = { file: candidate, mtime: st.mtimeMs };+ } catch { /* not present in this project dir */ }+ }+ if (!best) return null;+ const text = readFileSync(best.file, 'utf8');+ for (const line of text.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ const rec = JSON.parse(trimmed) as { cwd?: unknown };+ if (typeof rec.cwd === 'string' && rec.cwd) return rec.cwd;+ } catch { /* skip a malformed line */ }+ }+ return null;+ } catch {+ return null;+ }+}+export interface AgentUsage {inputTokens: number;outputTokens: number;diff --git a/src/preload/index.ts b/src/preload/index.tsindex df3c33c2..4f422007 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -110,8 +110,14 @@ export interface SpawnPtyOptions {/** When true (and cwd is a git repo), spawn the agent in its own git worktree. */isolate?: boolean;/** When true, continue the agent's prior CLI session if one was recorded- * (provider-aware: Claude `--resume`, Antigravity `--conversation`). */+ * (provider-aware: Claude `--resume`, Antigravity `--conversation`). For+ * Claude the main process looks up the session id from the hive registry and+ * seeds its transcript into the cwd's project dir (#1 — restore on restart). */resume?: boolean;+ /** Explicit Claude session id to resume (#2 — Add Agent "resume session"). The+ * main process seeds that session's `.jsonl` into the target cwd's project dir+ * (copying it from wherever it lives) and launches `claude --resume <id>`. */+ resumeSessionId?: string;}export interface PtyExit { exitCode: number; signal?: number | undefined }@@ -306,7 +312,7 @@ const api = {version: __APP_VERSION__,// ─── PTY ─────────────────────────────────────────────────────────────────- spawnPty: (opts: SpawnPtyOptions): Promise<{ ok: boolean; error?: string }> =>+ spawnPty: (opts: SpawnPtyOptions): Promise<{ ok: boolean; error?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean }> =>ipcRenderer.invoke('pty:spawn', opts),writePty: (id: string, data: string): Promise<{ ok: boolean; error?: string }> =>ipcRenderer.invoke('pty:write', id, data),@@ -316,6 +322,10 @@ const api = {ipcRenderer.invoke('pty:kill', id),listPtys: (): Promise<Array<{ id: string; cwd: string; command: string; pid: number }>> =>ipcRenderer.invoke('pty:list'),+ /** Resolve a Claude session id to the cwd it originally ran in (Add Agent+ * resume auto-fill), or null if the id is invalid/unknown. */+ resolveSessionCwd: (sessionId: string): Promise<string | null> =>+ ipcRenderer.invoke('session:resolveCwd', sessionId),onPtyData: (id: string, cb: (data: string) => void): (() => void) => {const channel = `pty:data:${id}`;const listener = (_e: IpcRendererEvent, data: string) => cb(data);diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsxindex 8ab67e64..401f650c 100644--- a/src/renderer/src/components/AddAgentModal.tsx+++ b/src/renderer/src/components/AddAgentModal.tsx@@ -73,9 +73,27 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {const preset = providerPreset(provider);const [goal, setGoal] = useState('');const [isolate, setIsolate] = useState(false);+ // #2 — optional Claude session id to continue. When set, the spawn seeds that+ // session's transcript into the cwd's project dir and launches `--resume`.+ const [resumeSessionId, setResumeSessionId] = useState('');+ const resuming = resumeSessionId.trim().length > 0;+ // Note shown when the folder was auto-filled from the pasted session id.+ const [folderNote, setFolderNote] = useState<string | undefined>();const [error, setError] = useState<string | undefined>();const [busy, setBusy] = useState(false);+ // Zero-step resume: when a session id is entered, look up the cwd it originally+ // ran in (from the transcript) and pre-fill the Folder so the user doesn't have+ // to find the worktree. They can still override the folder afterwards. Runs on+ // blur so we don't hit the resolver on every keystroke.+ const resolveFolderFromSession = async () => {+ const sid = resumeSessionId.trim();+ if (!sid) { setFolderNote(undefined); return; }+ const resolved = await window.cth.resolveSessionCwd(sid);+ if (resolved) { setCwd(resolved); setFolderNote(`folder set from session: ${resolved}`); }+ else setFolderNote(undefined);+ };+const pickFolder = async () => {setError(undefined);const res = await window.cth.chooseFolder();@@ -105,7 +123,11 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {cols: 100,rows: 30,// When set, the main process spawns this agent in its own git worktree.- isolate,+ // Forced OFF when resuming a session — `--resume` needs the real cwd's+ // transcript, not a fresh worktree with a different (empty) project dir.+ isolate: resuming ? false : isolate,+ // #2 — continue an existing Claude session in this agent's cwd.+ resumeSessionId: resuming ? resumeSessionId.trim() : undefined,// Provision this agent in the hive (memory + mailbox + identity/protocol).hive: {id,@@ -120,6 +142,11 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {setError(spawnRes.error ?? 'spawn failed');return;}+ // #2 — the requested resume session id wasn't found anywhere; main fell back+ // to a fresh session. Don't block the spawn, but make it visible.+ if (resuming && spawnRes.resumeNotFound) {+ console.warn(`[add-agent] resume session "${resumeSessionId.trim()}" not found — started a fresh session`);+ }const agent: Agent = {id,@@ -132,13 +159,16 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {cwd,goal: goal.trim() || undefined,status: 'idle',- action: 'starting up',+ action: resuming && spawnRes.resumeNotFound ? 'session not found — fresh start' : 'starting up',progress: 0,currentStation: 'desk',ptyId,command: command.trim(),provider,model,+ // Persist the resolved worktree path (set only when isolation provisioned+ // one) so a restart can re-enter this exact worktree — see restoreTeam.+ worktreePath: spawnRes.worktreePath,recentTextTs: Date.now()};addAgent(agent);@@ -309,12 +339,33 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {/></Row>- <label style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer' }}>+ <Row label="Resume session ID (optional)">+ <input+ value={resumeSessionId}+ onChange={(e) => { setResumeSessionId(e.target.value); setFolderNote(undefined); }}+ onBlur={resolveFolderFromSession}+ placeholder="paste a Claude session id to continue its conversation"+ style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)', fontSize: 14 }}+ />+ {folderNote && (+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-mint, var(--cth-ink-700))' }}>+ {folderNote}+ </span>+ )}+ {resuming && (+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-700)' }}>+ Will resume this session in the chosen folder (git isolation disabled).+ </span>+ )}+ </Row>++ <label style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: resuming ? 'not-allowed' : 'pointer', opacity: resuming ? 0.5 : 1 }}><inputtype="checkbox"- checked={isolate}+ checked={resuming ? false : isolate}+ disabled={resuming}onChange={(e) => setIsolate(e.target.checked)}- style={{ width: 16, height: 16, cursor: 'pointer' }}+ style={{ width: 16, height: 16, cursor: resuming ? 'not-allowed' : 'pointer' }}/><span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 14, color: 'var(--cth-ink-900)' }}>Git isolation (own worktree)diff --git a/src/renderer/src/components/AgentStrip.tsx b/src/renderer/src/components/AgentStrip.tsxindex eff7a457..94825b90 100644--- a/src/renderer/src/components/AgentStrip.tsx+++ b/src/renderer/src/components/AgentStrip.tsx@@ -56,22 +56,44 @@ export function AgentStrip({ config }: AgentStripProps) {if (!command || !a.cwd) { useStore.getState().removeRestorableAgent(a.id); continue; }const [exe, ...args] = tokenizeCommand(command);const ptyId = a.ptyId ?? `pty-${a.id}`;+ // An isolated agent's worktree SURVIVES an app restart on disk (it's only+ // torn down on per-tab close / mid-session exit, not on quit). So re-enter+ // that exact worktree as the cwd rather than re-isolating — `git worktree+ // add` would conflict with the existing path/branch, and re-isolating would+ // also lose the worktree's uncommitted work. cwd = the worktree means+ // resume + seedSessionTranscript land in the CORRECT checkout.+ // But the user may have manually pruned/deleted the worktree between runs —+ // gitIsRepo (git rev-parse) returns false for a missing/invalid dir, so+ // fall back to the base repo cwd rather than spawning into a dead path.+ let cwd = a.cwd;+ let worktreeGone = false;+ if (a.worktreePath) {+ if (await window.cth.gitIsRepo(a.worktreePath)) {+ cwd = a.worktreePath;+ } else {+ worktreeGone = true;+ console.warn(`[restore] worktree gone for ${a.id} (${a.worktreePath}); falling back to base repo ${a.cwd}`);+ }+ }const res = await window.cth.spawnPty({id: ptyId,- cwd: a.cwd,+ cwd,command: exe,provider,args,cols: 100,rows: 30,+ // Worktree (if any) already exists on disk — cd into it, don't create a+ // new one (re-isolating would conflict on the existing path/branch and+ // lose its uncommitted work).+ isolate: false,// Continue the worker's prior CLI session if one was recorded — the// main process picks the provider's resume flag (Claude --resume,- // agy --conversation). No-op when there's no recorded session id.+ // agy --conversation) and for Claude reattaches the transcript. The+ // agent id is preserved across restart, so its registry entry,+ // memory.md and inbox reattach by id. No-op without a recorded session.resume: true,- // Re-request isolation if the agent ran in its own worktree before —- // the old worktree was torn down on exit, so a fresh one is created.- isolate: !!a.worktreePath,- hive: { id: a.id, name: a.name, provider, cwd: a.cwd, role: a.description }+ hive: { id: a.id, name: a.name, provider, cwd, role: a.description }});if (res.ok) {useStore.getState().addAgent({@@ -80,7 +102,12 @@ export function AgentStrip({ config }: AgentStripProps) {ptyId,archived: false,status: 'idle',- action: 'starting up',+ // Surface the worktree fallback on the floor card; otherwise normal.+ action: worktreeGone ? 'worktree gone — using base repo' : 'starting up',+ // The worktree is no longer on disk — drop it so this agent is treated+ // as a plain base-cwd agent going forward (a future restore won't keep+ // re-probing a dead path).+ worktreePath: worktreeGone ? undefined : a.worktreePath,carrying: undefined,currentStation: 'desk',recentTextTs: Date.now()diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex 80c7dc39..325bb057 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -212,6 +212,12 @@ export function useHive(config: HarnessConfig | null): void {args,cols: 100,rows: 30,+ // Restore Michael's prior conversation across an app restart. His session+ // id lives in the hive registry (recorded from his hooks), so the main+ // process attaches `--resume <id>`; a missing transcript falls back to a+ // fresh session. Without this the most important context on the floor —+ // the orchestrator's — was lost on every restart.+ resume: true,hive: { id: GOD_ID, name: 'Michael', provider: 'claude', cwd: config.harnessHome!, isGod: true, role: 'orchestrator (god)' }});if (cancelled) { godSpawning.current = false; return; }@@ -239,21 +245,25 @@ export function useHive(config: HarnessConfig | null): void {useStore.getState().addAgent(god);useStore.getState().setGodStatus('ready');- // Fresh spawn → kick Michael off once his TUI is up. First enable remote- // control so the human can approve permission prompts from their phone- // (best-effort — a failed/unknown slash command just prints to his terminal- // and is harmless), PAUSE so it lands on its own line, then hand him the- // orientation prompt. Both go through the per-pty submit chain, so they're- // strictly sequential and can't jam together; the boot-grace window keeps- // the inbox-wake/drain loops off Michael until he's oriented. Restored- // sessions (the live-PTY branch above) skip this.+ // Kick Michael off once his TUI is up. Always re-enable remote control so+ // the human can approve permission prompts from their phone (best-effort — a+ // failed/unknown slash command just prints to his terminal and is harmless).+ // Then, ONLY on a genuinely fresh spawn, hand him the orientation prompt —+ // a RESUMED Michael already has his full context and must not be re-oriented+ // mid-thread (that would reset the floor's situational awareness). Both go+ // through the per-pty submit chain, so they're strictly sequential and can't+ // jam together; the boot-grace window keeps the inbox-wake/drain loops off+ // Michael until he's settled. The live-PTY branch above skips this entirely.+ const resumedGod = res.resumed === true;bootGraceUntil.current[GOD_ID] = Date.now() + BOOT_GRACE_MS;timers.push(setTimeout(() => {if (cancelled) return;// settleMs pauses the chain ~1.5s after /remote-control before the- // orientation prompt is submitted next.+ // orientation prompt (fresh spawns only) is submitted next.submitToPty(GOD_PTY, '/remote-control', REMOTE_CONTROL_SETTLE_MS).catch(() => { /* best-effort */ });- submitToPty(GOD_PTY, INITIAL_GOD_PROMPT).catch(() => { /* pty may have died */ });+ if (!resumedGod) {+ submitToPty(GOD_PTY, INITIAL_GOD_PROMPT).catch(() => { /* pty may have died */ });+ }}, GOD_BOOT_MS));}, 1200);return () => { cancelled = true; clearTimeout(t); timers.forEach(clearTimeout); };