diff --git a/src/exe.ts b/src/exe.ts index 4705a7f4..1def1948 100644 --- a/src/exe.ts +++ b/src/exe.ts @@ -35,19 +35,24 @@ export function shellAtom(value: string): string { return `'${value.replaceAll("'", `'"'"'`)}'`; } -export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName = agentName): string { +export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName: string, worktreePath: string, lease: string): string { const encodedPrompt = base64(prompt); const name = agentName; - const resetPrompt = newContextPrompt(connection.agentKind); + const herdr = herdrBinary(connection); // Herdr commands are deliberately kept to a fixed allowlist. The sole dynamic payload is base64. return [ herdrPrefix(connection), `cd ${shellAtom(connection.cwd)}`, - // A named agent stays live after completing a turn. Reuse an idle/done - // slot instead of trying to start another agent with the same name. - `existing=$(${herdrBinary(connection)} agent get ${shellAtom(name)} 2>/dev/null || true)`, - "existing_status=$(printf '%s' \"$existing\" | jq -r '.result.agent.agent_status // .result.agent.state // empty' 2>/dev/null | tr '[:upper:]' '[:lower:]')", - `if [ -n \"$existing_status\" ]; then case \"$existing_status\" in idle|done) ${herdrBinary(connection)} agent prompt ${shellAtom(name)} ${shellAtom(resetPrompt)} ;; *) echo \"Factorize cannot reuse active Herdr agent ${name} (status: $existing_status)\" >&2; exit 1 ;; esac; else workspace=$(${herdrBinary(connection)} workspace create --cwd ${shellAtom(connection.cwd)} --label ${shellAtom(workspaceName)} --no-focus) && pane=$(printf '%s' \"$workspace\" | jq -r '.result.root_pane.pane_id // .pane_id // .paneId') && ${herdrBinary(connection)} agent start ${shellAtom(name)} --kind ${shellAtom(connection.agentKind)} --pane \"$pane\"${agentCommand(connection)}; fi`, + `mkdir -p ${shellAtom(`${connection.cwd.replace(/\/$/, "")}/.factorize-worktrees`)}`, + `test ! -e ${shellAtom(worktreePath)} && git worktree add --detach ${shellAtom(worktreePath)} HEAD`, + `gitdir=$(git -C ${shellAtom(worktreePath)} rev-parse --git-dir)`, + `printf '%s' ${shellAtom(lease)} > "$gitdir/factorize-lease"`, + `workspaces=$(${herdr} workspace list)`, + `workspace_id=$(printf '%s' "$workspaces" | jq -r --arg label ${shellAtom(workspaceName)} '.result.workspaces[]? | select(.label == $label) | .workspace_id' | head -n1)`, + `if [ -z "$workspace_id" ]; then workspace=$(${herdr} workspace create --cwd ${shellAtom(connection.cwd)} --label ${shellAtom(workspaceName)} --no-focus) && workspace_id=$(printf '%s' "$workspace" | jq -er '.result.workspace.workspace_id') && anchor=$(printf '%s' "$workspace" | jq -er '.result.root_pane.pane_id'); else anchor=$(${herdr} pane list --workspace "$workspace_id" | jq -er '.result.panes[0].pane_id'); fi`, + `created=$(${herdr} pane split "$anchor" --direction down --cwd ${shellAtom(worktreePath)} --no-focus)`, + `pane=$(printf '%s' "$created" | jq -er '.result.pane.pane_id')`, + `${herdr} agent start ${shellAtom(name)} --kind ${shellAtom(connection.agentKind)} --pane "$pane"${agentCommand(connection)}`, `prompt=$(printf '%s' ${shellAtom(encodedPrompt)} | base64 -d)`, `${herdrBinary(connection)} agent prompt ${shellAtom(name)} \"$prompt\"`, `${herdrBinary(connection)} agent get ${shellAtom(name)}`, @@ -57,15 +62,16 @@ export function startAgentCommand(agentName: string, connection: ExeConnection, export function agentListCommand(connection: ExeConnection): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent list`; } export function paneGetCommand(connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} pane get ${shellAtom(paneId)}`; } export function paneProcessInfoCommand(connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} pane process-info ${shellAtom(paneId)}`; } +export function validateWorktreeLeaseCommand(connection: ExeConnection, worktreePath: string, lease: string): string { return `${herdrPrefix(connection)} && test "$(git -C ${shellAtom(worktreePath)} rev-parse --show-toplevel)" = ${shellAtom(worktreePath)} && gitdir=$(git -C ${shellAtom(worktreePath)} rev-parse --git-dir) && test "$(cat "$gitdir/factorize-lease")" = ${shellAtom(lease)}`; } export function renameAgentCommand(connection: ExeConnection, currentName: string, expectedName: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent rename ${shellAtom(currentName)} ${shellAtom(expectedName)} && ${herdrBinary(connection)} agent get ${shellAtom(expectedName)}`; } -export function startAgentInPaneCommand(agentName: string, connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && cd ${shellAtom(connection.cwd)} && ${herdrBinary(connection)} agent start ${shellAtom(agentName)} --kind ${shellAtom(connection.agentKind)} --pane ${shellAtom(paneId)}${agentCommand(connection)} && ${herdrBinary(connection)} agent get ${shellAtom(agentName)}`; } +export function startAgentInPaneCommand(agentName: string, connection: ExeConnection, paneId: string, cwd = connection.cwd): string { return `${herdrPrefix(connection)} && cd ${shellAtom(cwd)} && ${herdrBinary(connection)} agent start ${shellAtom(agentName)} --kind ${shellAtom(connection.agentKind)} --pane ${shellAtom(paneId)}${agentCommand(connection)} && ${herdrBinary(connection)} agent get ${shellAtom(agentName)}`; } /** Stop only the foreground process group observed in the exact persisted pane. * Every signal is preceded by a fresh identity read, preventing stale-PID races. */ -export function replaceForegroundCommand(agentName: string, connection: ExeConnection, paneId: string): string { +export function replaceForegroundCommand(agentName: string, connection: ExeConnection, paneId: string, cwd = connection.cwd): string { const herdr = herdrBinary(connection), pane = shellAtom(paneId); - const fields = `jq -er --arg pane ${pane} --arg cwd ${shellAtom(connection.cwd)} '[.result.pane_id // .pane_id // .result.pane.pane_id, .result.foreground.pid // .result.pid // .pid, .result.foreground.process_group // .result.foreground.pgid // .result.process_group // .result.pgid // .pgid, .result.foreground.cwd // .result.cwd // .cwd] | select(.[0] == $pane and .[1] > 1 and .[2] > 1 and .[3] == $cwd) | @tsv'`; - return [herdrPrefix(connection), `first=$(${herdr} pane process-info ${pane} | ${fields})`, `first_pid=$(printf '%s' "$first" | cut -f2)`, `first_pgid=$(printf '%s' "$first" | cut -f3)`, `kill -INT -- "-$first_pgid"`, `i=0; while [ "$i" -lt 10 ] && kill -0 -- "-$first_pgid" 2>/dev/null; do i=$((i+1)); sleep 1; done`, `if kill -0 -- "-$first_pgid" 2>/dev/null; then second=$(${herdr} pane process-info ${pane} | ${fields}) && second_pid=$(printf '%s' "$second" | cut -f2) && second_pgid=$(printf '%s' "$second" | cut -f3) && [ "$second_pid" = "$first_pid" ] && [ "$second_pgid" = "$first_pgid" ] && kill -TERM -- "-$first_pgid"; fi`, `i=0; while [ "$i" -lt 10 ] && kill -0 -- "-$first_pgid" 2>/dev/null; do i=$((i+1)); sleep 1; done`, `! kill -0 -- "-$first_pgid" 2>/dev/null`, `cd ${shellAtom(connection.cwd)}`, `${herdr} agent start ${shellAtom(agentName)} --kind ${shellAtom(connection.agentKind)} --pane ${pane}${agentCommand(connection)}`, `${herdr} agent get ${shellAtom(agentName)}`].join(" && "); + const fields = `jq -er --arg pane ${pane} --arg cwd ${shellAtom(cwd)} '[.result.pane_id // .pane_id // .result.pane.pane_id, .result.foreground.pid // .result.pid // .pid, .result.foreground.process_group // .result.foreground.pgid // .result.process_group // .result.pgid // .pgid, .result.foreground.cwd // .result.cwd // .cwd] | select(.[0] == $pane and .[1] > 1 and .[2] > 1 and .[3] == $cwd) | @tsv'`; + return [herdrPrefix(connection), `first=$(${herdr} pane process-info ${pane} | ${fields})`, `first_pid=$(printf '%s' "$first" | cut -f2)`, `first_pgid=$(printf '%s' "$first" | cut -f3)`, `kill -INT -- "-$first_pgid"`, `i=0; while [ "$i" -lt 10 ] && kill -0 -- "-$first_pgid" 2>/dev/null; do i=$((i+1)); sleep 1; done`, `if kill -0 -- "-$first_pgid" 2>/dev/null; then second=$(${herdr} pane process-info ${pane} | ${fields}) && second_pid=$(printf '%s' "$second" | cut -f2) && second_pgid=$(printf '%s' "$second" | cut -f3) && [ "$second_pid" = "$first_pid" ] && [ "$second_pgid" = "$first_pgid" ] && kill -TERM -- "-$first_pgid"; fi`, `i=0; while [ "$i" -lt 10 ] && kill -0 -- "-$first_pgid" 2>/dev/null; do i=$((i+1)); sleep 1; done`, `! kill -0 -- "-$first_pgid" 2>/dev/null`, `cd ${shellAtom(cwd)}`, `${herdr} agent start ${shellAtom(agentName)} --kind ${shellAtom(connection.agentKind)} --pane ${pane}${agentCommand(connection)}`, `${herdr} agent get ${shellAtom(agentName)}`].join(" && "); } export function agentStatusCommand(connection: ExeConnection, agentName: string): string { @@ -86,6 +92,12 @@ export function stopAgentCommand(connection: ExeConnection, agentName: string): return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent stop ${shellAtom(agentName)}`; } +/** Revalidate terminal, worktree, and lease immediately before closing a pane. */ +export function garbageCollectPaneCommand(connection: ExeConnection, paneId: string, terminalId: string, worktreePath: string, lease: string): string { + const herdr = herdrBinary(connection), pane = shellAtom(paneId); + return [herdrPrefix(connection), `pane_json=$(${herdr} pane get ${pane})`, `printf '%s' "$pane_json" | jq -e --arg pane ${pane} --arg terminal ${shellAtom(terminalId)} '(.result.pane // .result) | .pane_id == $pane and .terminal_id == $terminal' >/dev/null`, `test "$(git -C ${shellAtom(worktreePath)} rev-parse --show-toplevel)" = ${shellAtom(worktreePath)}`, `gitdir=$(git -C ${shellAtom(worktreePath)} rev-parse --git-dir)`, `test "$(cat "$gitdir/factorize-lease")" = ${shellAtom(lease)}`, `agent=$(${herdr} agent get ${pane} 2>/dev/null || true)`, `status=$(printf '%s' "$agent" | jq -r '.result.agent.agent_status // .result.agent.state // empty' | tr '[:upper:]' '[:lower:]')`, `case "$status" in ''|idle|done) ;; *) exit 1 ;; esac`, `[ -z "$status" ] || ${herdr} agent stop ${pane}`, `test -z "$(${herdr} agent get ${pane} 2>/dev/null || true)"`, `process=$(${herdr} pane process-info ${pane})`, `printf '%s' "$process" | jq -e '(.result.foreground.executable // .result.process.executable // "") | test("(^|/)(ba|z|fi)?sh$")' >/dev/null`, `${herdr} pane close ${pane}`].join(" && "); +} + export function herdrCheckCommand(connection: ExeConnection): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} --version && ${herdrBinary(connection)} workspace list`; } @@ -104,10 +116,6 @@ function herdrBinary(connection: ExeConnection): string { return connection.herdrCommand?.trim() || "herdr"; } -function newContextPrompt(agentKind: string): string { - return agentKind === "claude" ? "/clear" : "/new"; -} - /** Herdr owns the executable; it forwards these arguments after `--` to it. */ function agentCommand(connection: ExeConnection): string { const command = connection.agentCommand?.trim() || defaultAgentCommand(connection.agentKind); diff --git a/src/recovery.ts b/src/recovery.ts index d33e89e5..0d41b6b9 100644 --- a/src/recovery.ts +++ b/src/recovery.ts @@ -12,4 +12,8 @@ export function parseAgentList(body: string): HerdrIdentity[] { try { const pars export function sameStableSession(saved: Partial, live: HerdrIdentity): boolean { return Boolean(saved.sessionValue && live.sessionValue && saved.sessionValue === live.sessionValue && (!saved.sessionKind || !live.sessionKind || saved.sessionKind === live.sessionKind)); } export function matchesLineage(saved: Partial, live: HerdrIdentity): boolean { return Boolean((saved.terminalId && saved.terminalId === live.terminalId) || (saved.paneId && saved.paneId === live.paneId && (!saved.workspaceId || !live.workspaceId || saved.workspaceId === live.workspaceId))); } export function safeToAdopt(saved: Partial, live: HerdrIdentity, claimedSessions: Set): boolean { return matchesLineage(saved, live) && (!saved.kind || saved.kind === live.kind) && (!saved.cwd || saved.cwd === live.cwd) && !claimedSessions.has(live.sessionValue); } +/** Native sessions and aliases may rotate; terminal + worktree own the pane. */ +export function ownsPane(saved: Partial, live: HerdrIdentity, worktreePath: string): boolean { + return Boolean(saved.terminalId && saved.terminalId === live.terminalId && worktreePath && live.cwd === worktreePath && (!saved.paneId || saved.paneId === live.paneId)); +} export function parsePaneProcess(body: string): PaneProcess | null { try { const parsed = obj(JSON.parse(body)), result = obj(parsed.result), foreground = obj(result.foreground ?? result.process ?? parsed.foreground ?? parsed); const pane = obj(result.pane); const pid = Number(foreground.pid ?? result.pid), processGroup = Number(foreground.process_group ?? foreground.pgid ?? result.process_group ?? result.pgid); if (!Number.isSafeInteger(pid) || pid <= 1 || !Number.isSafeInteger(processGroup) || processGroup <= 1) return null; return { paneId: str(result.pane_id, pane.pane_id, pane.id, parsed.pane_id), pid, processGroup, argv: Array.isArray(foreground.argv) ? foreground.argv.map(String) : [], executable: str(foreground.executable, foreground.exe), cwd: str(foreground.cwd, result.cwd) }; } catch { return null; } } diff --git a/src/tenant.ts b/src/tenant.ts index 78886385..74973808 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -1,8 +1,8 @@ import { DurableObject } from "cloudflare:workers"; import Mustache from "mustache"; import { decrypt, encrypt } from "./crypto"; -import { agentListCommand, agentOutputCommand, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, herdrAgentStatus, herdrCheckCommand, paneGetCommand, paneProcessInfoCommand, renameAgentCommand, replaceForegroundCommand, startAgentCommand, startAgentInPaneCommand, stopAgentCommand, type ExeConnection } from "./exe"; -import { parseAgent, parseAgentList, parsePaneProcess, safeToAdopt, sameStableSession, type HerdrIdentity } from "./recovery"; +import { agentListCommand, agentOutputCommand, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, garbageCollectPaneCommand, herdrAgentStatus, herdrCheckCommand, paneGetCommand, paneProcessInfoCommand, replaceForegroundCommand, startAgentCommand, startAgentInPaneCommand, stopAgentCommand, validateWorktreeLeaseCommand, type ExeConnection } from "./exe"; +import { ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY } from "./linear"; import { matchingIssue } from "./matcher"; import type { Env, ExeConnectionInput, FilterType, MatchRule, PipeInput, RunState } from "./types"; @@ -116,6 +116,7 @@ export class Tenant extends DurableObject { this.ensureColumn("flow_events", "provider", "TEXT NOT NULL DEFAULT 'linear'"); this.ensureColumn("runs", "provider", "TEXT NOT NULL DEFAULT 'linear'"); this.ensureColumn("runs", "claim_key", "TEXT"); + for (const [column, definition] of Object.entries({ herdr_server_namespace: "TEXT NOT NULL DEFAULT 'default'", worktree_path: "TEXT", ownership_lease: "TEXT", ownership_generation: "INTEGER NOT NULL DEFAULT 0", agent_session_generation: "INTEGER NOT NULL DEFAULT 0", output_captured: "INTEGER NOT NULL DEFAULT 0", claim_released: "INTEGER NOT NULL DEFAULT 0", pane_collected: "INTEGER NOT NULL DEFAULT 0", worktree_disposition: "TEXT" })) this.ensureColumn("runs", column, definition); for (const [column, definition] of Object.entries({ herdr_workspace_id: "TEXT", herdr_pane_id: "TEXT", herdr_terminal_id: "TEXT", agent_session_source: "TEXT", agent_session_kind: "TEXT", agent_session_value: "TEXT", herdr_cwd: "TEXT", last_agent_status: "TEXT", recovery_attempt: "INTEGER NOT NULL DEFAULT 0", recovery_reason: "TEXT", recovery_started_at: "TEXT", recovery_last_action: "TEXT", recovery_next_at: "INTEGER", recovery_comment_started: "INTEGER NOT NULL DEFAULT 0", recovery_comment_finished: "INTEGER NOT NULL DEFAULT 0", prompt_accepted: "INTEGER NOT NULL DEFAULT 0", recovery_prompt_attempted: "INTEGER NOT NULL DEFAULT 0", recovery_prompt_accepted: "INTEGER NOT NULL DEFAULT 0" })) this.ensureColumn("runs", column, definition); } @@ -181,10 +182,9 @@ export class Tenant extends DurableObject { if (!pipe) continue; const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id = ? AND state IN ('starting','running','blocked','recovering')", pipe.id) as Row; if (Number(active.count) >= Number(pipe.max_concurrency)) continue; - const slot = this.nextRunSlot(pipe, String(run.id)); - const name = `${String(pipe.workspace_name)}-${slot}`; - this.ctx.storage.sql.exec("UPDATE runs SET state = 'starting', agent_name = ?, workspace_name = ?, updated_at = ? WHERE id = ? AND state = 'queued'", name, name, now(), run.id); - await this.startRun({ ...run, agent_name: name, workspace_name: name }, pipe); + const name = `${String(pipe.workspace_name).slice(0, 20)}-${String(run.id).replaceAll("-", "").slice(0, 8)}`; + this.ctx.storage.sql.exec("UPDATE runs SET state = 'starting', agent_name = ?, workspace_name = ?, updated_at = ? WHERE id = ? AND state = 'queued'", name, pipe.workspace_name, now(), run.id); + await this.startRun({ ...run, agent_name: name, workspace_name: pipe.workspace_name }, pipe); } const pending = this.one("SELECT count(*) AS count FROM runs WHERE state IN ('queued','starting','running','blocked','recovering')") as Row; @@ -599,9 +599,12 @@ export class Tenant extends DurableObject { const connection = await this.connectionForPipe(pipe); if (!connection) return this.finishRun(run, "failed", "No exe.dev VM is connected."); const workspaceName = String(run.workspace_name || pipe.workspace_name || workspaceNameFor(String(pipe.name))); + const lease = crypto.randomUUID(); + const worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-worktrees/${String(run.id)}`; + this.ctx.storage.sql.exec("UPDATE runs SET herdr_server_namespace='default',worktree_path=?,ownership_lease=?,ownership_generation=ownership_generation+1,agent_session_generation=1,updated_at=? WHERE id=?", worktreePath, lease, now(), run.id); if (String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `Factorize started **${connection.agentKind}** on ${connection.vmName} in Herdr workspace \`${workspaceName}\` for this issue.`); const prompt = await decrypt(String(run.prompt), this.env.CREDENTIAL_ENCRYPTION_KEY); - const result = await exec(connection, startAgentCommand(String(run.agent_name), connection, prompt, workspaceName)); + const result = await exec(connection, startAgentCommand(String(run.agent_name), connection, prompt, workspaceName, worktreePath, lease)); const execRequest = await encrypt(result.requestBody, this.env.CREDENTIAL_ENCRYPTION_KEY); const execResponse = await encrypt(result.body, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET exec_request = ?, exec_response = ?, exec_status = ?, exec_exit_code = ?, updated_at = ? WHERE id = ?", execRequest, execResponse, result.status, result.exitCode, now(), run.id); @@ -627,8 +630,15 @@ export class Tenant extends DurableObject { if (!status.ok && (status.exitCode === null || status.exitCode === 0)) return; // transient exe.dev/API failure if (!status.ok || (status.exitCode !== null && status.exitCode !== 0)) return this.beginRecovery(run, pipe, connection, `expected Herdr agent is no longer resolvable (VM exit ${status.exitCode ?? "unknown"})`); const live = parseAgent(status.body); - if (!live || (run.agent_session_value && !sameStableSession(this.savedIdentity(run), live))) return this.beginRecovery(run, pipe, connection, "Herdr returned an inconsistent agent identity"); - this.persistIdentity(run.id, live, String(run.state)); + if (!live) return this.beginRecovery(run, pipe, connection, "Herdr returned an inconsistent agent identity"); + const terminalOwned = Boolean(run.herdr_terminal_id && ownsPane(this.savedIdentity(run), live, String(run.worktree_path || ""))); + if (terminalOwned) { + const rotated = String(run.agent_session_value || "") !== live.sessionValue; + this.persistIdentity(run.id, live, String(run.state), rotated); + this.ctx.storage.sql.exec("UPDATE runs SET recovery_attempt=0,recovery_started_at=NULL,recovery_next_at=NULL,recovery_reason=NULL WHERE id=?", run.id); + } + if (run.herdr_terminal_id && !terminalOwned) return this.beginRecovery(run, pipe, connection, "Herdr alias resolved to a different terminal owner"); + if (!terminalOwned) this.persistIdentity(run.id, live, String(run.state)); const agentStatus = herdrAgentStatus(status.body); if (agentStatus === "blocked") { this.ctx.storage.sql.exec("UPDATE runs SET state = 'blocked', updated_at = ? WHERE id = ?", now(), run.id); @@ -636,13 +646,13 @@ export class Tenant extends DurableObject { } if (agentStatus !== "done" && agentStatus !== "idle") return; const output = await exec(connection, agentOutputCommand(connection, String(run.agent_name))); - await this.finishRun(run, "done", output.ok ? output.body : "Agent completed; terminal output could not be read."); + await this.finishRun(run, "done", output.ok ? output.body : "Agent completed; terminal output could not be read.", output.ok); } private savedIdentity(run: Row): Partial { return { name: String(run.agent_name || ""), kind: String(run.agent_kind || ""), workspaceId: String(run.herdr_workspace_id || ""), paneId: String(run.herdr_pane_id || ""), terminalId: String(run.herdr_terminal_id || ""), cwd: String(run.herdr_cwd || ""), sessionSource: String(run.agent_session_source || ""), sessionKind: String(run.agent_session_kind || ""), sessionValue: String(run.agent_session_value || "") }; } - private persistIdentity(runId: unknown, live: HerdrIdentity, state = "running"): void { - this.ctx.storage.sql.exec("UPDATE runs SET state=?,herdr_workspace_id=?,herdr_pane_id=?,herdr_terminal_id=?,agent_session_source=?,agent_session_kind=?,agent_session_value=?,herdr_cwd=?,last_agent_status=?,updated_at=? WHERE id=?", state, live.workspaceId, live.paneId, live.terminalId, live.sessionSource, live.sessionKind, live.sessionValue, live.cwd, live.status, now(), runId); + private persistIdentity(runId: unknown, live: HerdrIdentity, state = "running", sessionRotated = false): void { + this.ctx.storage.sql.exec("UPDATE runs SET state=?,herdr_workspace_id=?,herdr_pane_id=?,herdr_terminal_id=?,agent_session_source=?,agent_session_kind=?,agent_session_value=?,agent_session_generation=agent_session_generation+?,herdr_cwd=?,last_agent_status=?,updated_at=? WHERE id=?", state, live.workspaceId, live.paneId, live.terminalId, live.sessionSource, live.sessionKind, live.sessionValue, sessionRotated ? 1 : 0, live.cwd, live.status, now(), runId); } private activity(runId: unknown, action: string, detail: string): void { @@ -656,7 +666,7 @@ export class Tenant extends DurableObject { this.ctx.storage.sql.exec("UPDATE runs SET state='recovering',recovery_reason=?,recovery_started_at=COALESCE(recovery_started_at,?),recovery_next_at=?,recovery_last_action='inspecting Herdr state',updated_at=? WHERE id=?", reason, now(), Date.now(), now(), run.id); this.activity(run.id, "recovery_started", reason); const captured = await exec(connection, agentOutputCommand(connection, String(run.agent_name))); - if (captured.ok && captured.body.trim()) { const encrypted = await encrypt(captured.body, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET result=? WHERE id=?", encrypted, run.id); this.activity(run.id, "transcript_captured", "Captured recent output before reconciliation."); } + if (captured.ok && captured.body.trim()) { const encrypted = await encrypt(captured.body, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET result=?,output_captured=1 WHERE id=?", encrypted, run.id); this.activity(run.id, "transcript_captured", "Captured recent output before reconciliation."); } if (started && !Number(run.recovery_comment_started) && String(run.provider || "linear") === "linear") { await this.safeLinearComment(String(run.issue_id), `Factorize detected a Herdr change and started automatic recovery for run \`${run.id}\`. The concurrency slot remains reserved.`); this.ctx.storage.sql.exec("UPDATE runs SET recovery_comment_started=1 WHERE id=?", run.id); @@ -674,47 +684,50 @@ export class Tenant extends DurableObject { this.commandActivity(run.id, "agent list", listed); if (!listed.ok || (listed.exitCode !== null && listed.exitCode !== 0)) { this.scheduleRecovery(run.id, attempt, "transient Herdr agent-list failure"); return; } const agents = parseAgentList(listed.body), saved = this.savedIdentity(run); - const stable = agents.find((agent) => sameStableSession(saved, agent)); - if (stable) { - let live = stable; - if (stable.name !== String(run.agent_name)) { const renamed = await exec(connection, renameAgentCommand(connection, stable.name, String(run.agent_name))); this.commandActivity(run.id, "agent rename", renamed); if (!renamed.ok || (renamed.exitCode !== null && renamed.exitCode !== 0)) { this.scheduleRecovery(run.id, attempt, "stable session found but expected name could not be reclaimed"); return; } live = parseAgent(renamed.body) ?? { ...stable, name: String(run.agent_name) }; } - return this.finishRecovery(run, "running", "Recovered the original stable agent session after its pane/name moved.", live); - } - const claimed = new Set(this.rows("SELECT agent_session_value FROM runs WHERE id != ? AND state IN ('starting','running','blocked','recovering') AND agent_session_value IS NOT NULL", run.id).map((row) => String(row.agent_session_value))); - const lineage = agents.find((agent) => safeToAdopt(saved, agent, claimed)); - if (lineage) { - let live = lineage; - if (lineage.name !== String(run.agent_name)) { const renamed = await exec(connection, renameAgentCommand(connection, lineage.name, String(run.agent_name))); if (!renamed.ok) { this.scheduleRecovery(run.id, attempt, "matching restarted harness could not be renamed"); return; } live = parseAgent(renamed.body) ?? { ...lineage, name: String(run.agent_name) }; } - return this.resumeRecoveredHarness(run, connection, live, "Adopted a matching restarted harness in the owned pane."); + const owned = agents.find((agent) => ownsPane(saved, agent, String(run.worktree_path || ""))); + if (owned) { + const rotated = String(run.agent_session_value || "") !== owned.sessionValue; + this.persistIdentity(run.id, owned, "running", rotated); + return this.finishRecovery({ ...run, recovery_attempt: attempt }, "running", "Reconciled the owned terminal and worktree; refreshed native session continuity metadata.", owned); } if (saved.paneId) { const pane = await exec(connection, paneGetCommand(connection, saved.paneId)); this.commandActivity(run.id, "pane get", pane); if (pane.ok && (pane.exitCode === null || pane.exitCode === 0)) { + const lease = await exec(connection, validateWorktreeLeaseCommand(connection, String(run.worktree_path || ""), String(run.ownership_lease || ""))); + this.commandActivity(run.id, "worktree lease validation", lease); + if (!lease.ok || (lease.exitCode !== null && lease.exitCode !== 0)) { this.scheduleRecovery(run.id, attempt, "owned pane remained but its worktree lease did not validate"); return; } const process = await exec(connection, paneProcessInfoCommand(connection, saved.paneId)); this.commandActivity(run.id, "pane process-info", process); const processIdentity = process.ok ? parsePaneProcess(process.body) : null; const processCommand = [processIdentity?.executable, ...(processIdentity?.argv ?? [])].join(" ").toLowerCase(); if (processIdentity && processIdentity.paneId === saved.paneId && processIdentity.cwd === saved.cwd && processCommand.includes(connection.agentKind.toLowerCase())) { - const adopted = await exec(connection, startAgentInPaneCommand(String(run.agent_name), connection, saved.paneId)); + const adopted = await exec(connection, startAgentInPaneCommand(String(run.agent_name), connection, saved.paneId, String(run.worktree_path))); const live = adopted.ok ? parseAgent(adopted.body) : null; if (live) return this.finishRecovery(run, "running", "Returned the matching harness in the owned pane to Herdr control.", live); } + if (processIdentity && processIdentity.paneId === saved.paneId && processIdentity.cwd === saved.cwd && /(^|\/)(ba|z|fi)?sh(?:\s|$)/.test(processCommand)) { + const restarted = await exec(connection, startAgentInPaneCommand(String(run.agent_name), connection, saved.paneId, String(run.worktree_path))); + const live = restarted.ok ? parseAgent(restarted.body) : null; + if (live) return this.resumeRecoveredHarness(run, connection, live, "Started a deliberate replacement after the owned pane's agent exited."); + } if (processIdentity && processIdentity.paneId === saved.paneId && processIdentity.cwd === saved.cwd) { - const replaced = await exec(connection, replaceForegroundCommand(String(run.agent_name), connection, saved.paneId)); + const replaced = await exec(connection, replaceForegroundCommand(String(run.agent_name), connection, saved.paneId, String(run.worktree_path))); const live = replaced.ok ? parseAgent(replaced.body) : null; if (live) return this.resumeRecoveredHarness(run, connection, live, "Gracefully stopped the exact validated foreground process and restarted the configured harness."); this.scheduleRecovery(run.id, attempt, "foreground process identity changed during validated interruption"); return; } - const restarted = await exec(connection, startAgentInPaneCommand(String(run.agent_name), connection, saved.paneId)); + const restarted = await exec(connection, startAgentInPaneCommand(String(run.agent_name), connection, saved.paneId, String(run.worktree_path))); const live = restarted.ok ? parseAgent(restarted.body) : null; if (live) return this.resumeRecoveredHarness(run, connection, live, "Restarted the configured harness in the recovered pane."); } } const prompt = await decrypt(String(run.prompt), this.env.CREDENTIAL_ENCRYPTION_KEY); const recoveryPrompt = `${prompt}\n\nRecovery context: inspect the existing repository state and continue completed work rather than repeating it. Last status: ${String(run.last_agent_status || "unknown")}.`; - const replacement = await exec(connection, startAgentCommand(String(run.agent_name), connection, recoveryPrompt, String(run.workspace_name))); + const lease = crypto.randomUUID(), worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-worktrees/${String(run.id)}-recovery-${attempt}`; + this.ctx.storage.sql.exec("UPDATE runs SET worktree_path=?,ownership_lease=?,ownership_generation=ownership_generation+1 WHERE id=?", worktreePath, lease, run.id); + const replacement = await exec(connection, startAgentCommand(String(run.agent_name), connection, recoveryPrompt, String(run.workspace_name), worktreePath, lease)); if (replacement.ok && (replacement.exitCode === null || replacement.exitCode === 0)) this.ctx.storage.sql.exec("UPDATE runs SET prompt_accepted=1 WHERE id=?", run.id); const live = replacement.ok ? parseAgent(replacement.body) : null; if (live) return this.finishRecovery(run, "running", "Recreated the deleted pane/workspace and started a replacement harness.", live); @@ -723,16 +736,28 @@ export class Tenant extends DurableObject { private scheduleRecovery(runId: unknown, attempt: number, action: string): void { const delay = Math.min(60_000, 2_000 * 2 ** Math.min(attempt - 1, 5)); this.ctx.storage.sql.exec("UPDATE runs SET recovery_next_at=?,recovery_last_action=?,updated_at=? WHERE id=?", Date.now() + delay, action, now(), runId); this.activity(runId, "recovery_retry", action); } private async resumeRecoveredHarness(run: Row, connection: ExeConnection, live: HerdrIdentity, action: string): Promise { if (Number(run.recovery_prompt_attempted)) return this.finishRecovery(run, "running", `${action} Recovery prompt delivery was previously attempted and was not repeated.`, live); const prompt = await decrypt(String(run.prompt), this.env.CREDENTIAL_ENCRYPTION_KEY); const output = run.result ? await decrypt(String(run.result), this.env.CREDENTIAL_ENCRYPTION_KEY) : ""; const recoveryPrompt = `${prompt}\n\nRecovery context: inspect existing repository state and continue rather than repeating completed work. Last captured output/status:\n${output.slice(-4000)}\n${String(run.last_agent_status || "unknown")}`; this.ctx.storage.sql.exec("UPDATE runs SET recovery_prompt_attempted=1 WHERE id=?", run.id); const sent = await exec(connection, `${agentStatusCommand(connection, live.name)} && ${connection.herdrCommand?.trim() || "herdr"} agent prompt '${live.name.replaceAll("'", `'\"'\"'`)}' '${recoveryPrompt.replaceAll("'", `'\"'\"'`)}'`); if (!sent.ok || (sent.exitCode !== null && sent.exitCode !== 0)) return this.finishRecovery(run, "running", `${action} Recovery prompt acknowledgement was ambiguous, so it will not be submitted twice.`, live); this.ctx.storage.sql.exec("UPDATE runs SET recovery_prompt_accepted=1 WHERE id=?", run.id); await this.finishRecovery(run, "running", action, live); } - private async finishRecovery(run: Row, state: "running" | "failed", action: string, live?: HerdrIdentity): Promise { this.activity(run.id, state === "running" ? "recovery_succeeded" : "recovery_failed", action); if (live) this.persistIdentity(run.id, live, state); this.ctx.storage.sql.exec("UPDATE runs SET state=?,recovery_last_action=?,recovery_next_at=NULL,recovery_comment_finished=1,updated_at=? WHERE id=?", state, action, now(), run.id); if (!Number(run.recovery_comment_finished) && String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `Factorize automatic recovery ${state === "running" ? "succeeded" : "permanently failed"} for run \`${run.id}\`: ${action}`); if (state === "failed") { const encrypted = await encrypt(action, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET result=? WHERE id=?", encrypted, run.id); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id=? AND issue_id=?", run.pipe_id, run.claim_key || run.issue_id); } } + private async finishRecovery(run: Row, state: "running" | "failed", action: string, live?: HerdrIdentity): Promise { this.activity(run.id, state === "running" ? "recovery_succeeded" : "recovery_failed", action); if (live) this.persistIdentity(run.id, live, state); this.ctx.storage.sql.exec("UPDATE runs SET state=?,recovery_attempt=0,recovery_reason=NULL,recovery_started_at=NULL,recovery_last_action=?,recovery_next_at=NULL,recovery_comment_finished=1,updated_at=? WHERE id=?", state, action, now(), run.id); if (!Number(run.recovery_comment_finished) && String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `Factorize automatic recovery ${state === "running" ? "succeeded" : "permanently failed"} for run \`${run.id}\`: ${action}`); if (state === "failed") { const encrypted = await encrypt(action, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET result=? WHERE id=?", encrypted, run.id); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id=? AND issue_id=?", run.pipe_id, run.claim_key || run.issue_id); this.ctx.storage.sql.exec("UPDATE runs SET claim_released=1 WHERE id=?", run.id); } } - private async finishRun(run: Row, state: Extract, result: string): Promise { + private async finishRun(run: Row, state: Extract, result: string, outputCaptured = false): Promise { const encryptedResult = await encrypt(result, this.env.CREDENTIAL_ENCRYPTION_KEY); - this.ctx.storage.sql.exec("UPDATE runs SET state = ?, result = ?, updated_at = ? WHERE id = ?", state, encryptedResult, now(), run.id); + this.ctx.storage.sql.exec("UPDATE runs SET state = ?, result = ?, output_captured=?, updated_at = ? WHERE id = ?", state, encryptedResult, outputCaptured ? 1 : Number(run.output_captured || 0), now(), run.id); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id = ? AND issue_id = ?", run.pipe_id, run.claim_key || run.issue_id); + this.ctx.storage.sql.exec("UPDATE runs SET claim_released=1 WHERE id=?", run.id); + await this.collectRunPane({ ...run, state, output_captured: outputCaptured ? 1 : Number(run.output_captured || 0), claim_released: 1 }); const heading = state === "done" ? "Factorize completed the agent run." : "Factorize could not complete the agent run."; if (String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `${heading}\n\nRun ID: \`${run.id}\`. Review the Herdr session on the configured VM for details.`); } + private async collectRunPane(run: Row): Promise { + if (!['done', 'failed', 'cancelled'].includes(String(run.state)) || !Number(run.output_captured) || !Number(run.claim_released) || !run.herdr_pane_id || !run.herdr_terminal_id || !run.worktree_path || !run.ownership_lease) return; + const pipe = this.one("SELECT * FROM pipes WHERE id=?", run.pipe_id) as Row | undefined; + const connection = pipe ? await this.connectionForPipe(pipe) : null; + if (!connection) return; + const collected = await exec(connection, garbageCollectPaneCommand(connection, String(run.herdr_pane_id), String(run.herdr_terminal_id), String(run.worktree_path), String(run.ownership_lease))); + this.commandActivity(run.id, "pane garbage collection", collected); + if (collected.ok && (collected.exitCode === null || collected.exitCode === 0)) this.ctx.storage.sql.exec("UPDATE runs SET pane_collected=1,worktree_disposition='retained',updated_at=? WHERE id=?", now(), run.id); + } + private async safeLinearComment(issueId: string, body: string): Promise { try { await this.postLinearComment(issueId, body); } catch (error) { console.warn(JSON.stringify({ event: "linear_notification_failed", issueId, message: error instanceof Error ? error.message : "unknown" })); } } private async postLinearComment(issueId: string, body: string): Promise { diff --git a/test/recovery.test.ts b/test/recovery.test.ts index bd129931..b073493a 100644 --- a/test/recovery.test.ts +++ b/test/recovery.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { matchesLineage, parseAgent, parseAgentList, parsePaneProcess, safeToAdopt, sameStableSession } from "../src/recovery"; +import { matchesLineage, ownsPane, parseAgent, parseAgentList, parsePaneProcess, safeToAdopt, sameStableSession } from "../src/recovery"; const moved = { name: "renamed", status: "working", kind: "codex", workspaceId: "ws-2", paneId: "pane-2", terminalId: "term-1", cwd: "/repo", sessionSource: "codex", sessionKind: "thread", sessionValue: "session-7" }; @@ -15,6 +15,11 @@ describe("Herdr 0.9 recovery identity", () => { expect(matchesLineage(saved, moved)).toBe(false); }); + it("keeps pane ownership when the native session generation rotates", () => { + expect(ownsPane({ terminalId: "term-1", paneId: "pane-2", sessionValue: "old" }, { ...moved, sessionValue: "new" }, "/repo")).toBe(true); + expect(ownsPane({ terminalId: "term-other", paneId: "pane-2" }, moved, "/repo")).toBe(false); + }); + it("parses agent list arrays", () => { const agents = parseAgentList(JSON.stringify({ result: { agents: [{ name: "flow-1", kind: "codex", pane_id: "pane-1", session: { id: "abc" } }] } })); expect(agents).toHaveLength(1); diff --git a/test/workspace.test.ts b/test/workspace.test.ts index 573cf47e..3b4118b9 100644 --- a/test/workspace.test.ts +++ b/test/workspace.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { agentStatusCommand, connectionCheckCommand, defaultAgentCommand, herdrAgentStatus, replaceForegroundCommand, shellAtom, startAgentCommand } from "../src/exe"; +import { agentStatusCommand, connectionCheckCommand, defaultAgentCommand, garbageCollectPaneCommand, herdrAgentStatus, replaceForegroundCommand, shellAtom, startAgentCommand } from "../src/exe"; import { workingDirectoryFor, workspaceNameFor } from "../src/workspace"; describe("flow workspaces", () => { @@ -18,15 +18,16 @@ describe("flow workspaces", () => { }); it("passes the saved flow workspace to Herdr", () => { - const command = startAgentCommand("bug-fixes-1", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "fix it", "bug-fixes-1"); - expect(command).toContain("--label 'bug-fixes-1'"); + const command = startAgentCommand("bug-fixes-a1b2c3d4", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "fix it", "bug-fixes", "/repo/.factorize-worktrees/run-1", "lease-1"); + expect(command).toContain("--label 'bug-fixes'"); + expect(command).toContain("git worktree add --detach '/repo/.factorize-worktrees/run-1'"); + expect(command).toContain("pane split"); expect(command).toContain("--no-focus"); expect(command).not.toContain("__FACTORIZE_EXIT_CODE__"); expect(command).toContain('export PATH="$HOME/.local/bin:$PATH"'); expect(command).not.toContain("-- 'codex'"); - expect(command).toContain("agent get 'bug-fixes-1'"); - expect(command).toContain('idle|done'); - expect(command).toContain("agent prompt 'bug-fixes-1' '/new'"); + expect(command).toContain("agent get 'bug-fixes-a1b2c3d4'"); + expect(command).not.toContain("/new"); expect(command).toContain("-- '--dangerously-bypass-approvals-and-sandbox'"); }); @@ -37,10 +38,18 @@ describe("flow workspaces", () => { }); it("passes a configured agent command as safely quoted arguments", () => { - const command = startAgentCommand("factorize-1", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo", agentCommand: "--model 'gpt 5'" }, "fix it"); + const command = startAgentCommand("factorize-1", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo", agentCommand: "--model 'gpt 5'" }, "fix it", "factorize", "/repo/.factorize-worktrees/run", "lease"); expect(command).toContain("-- '--model' 'gpt 5'"); }); + it("garbage collects only after terminal, worktree, and lease revalidation", () => { + const command = garbageCollectPaneCommand({ vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "w1:p2", "term-7", "/repo/.factorize-worktrees/run", "lease-7"); + expect(command).toContain(".terminal_id == $terminal"); + expect(command).toContain("factorize-lease"); + expect(command).toContain("agent stop 'w1:p2'"); + expect(command).toContain("pane close 'w1:p2'"); + }); + it("quotes the complete exe.dev SSH request body", () => { const command = "cd '/repo' && herdr status --json"; expect(`ssh ${shellAtom("exedev@vm")} ${shellAtom(command)}`).toContain("ssh 'exedev@vm'");