From 144947b38b6f65ae5edc7ea3985f7d5664703082 Mon Sep 17 00:00:00 2001 From: Brendan Date: Mon, 14 Sep 2026 15:04:21 +0000 Subject: [PATCH 1/2] Prevent recovery from proliferating Herdr panes --- src/exe.ts | 19 +++++++++---------- src/flow-schemas.ts | 2 +- src/recovery.ts | 9 +++++---- src/tenant.ts | 21 +++++++++++++-------- test/recovery.test.ts | 9 +++++++-- test/workspace.test.ts | 11 ++++++----- 6 files changed, 41 insertions(+), 30 deletions(-) diff --git a/src/exe.ts b/src/exe.ts index 429ba1a4..d3adbeea 100644 --- a/src/exe.ts +++ b/src/exe.ts @@ -35,7 +35,7 @@ export function shellAtom(value: string): string { return `'${value.replaceAll("'", `'"'"'`)}'`; } -export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName: string, worktreePath: string, lease: string): string { +export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName: string, runPath: string, lease: string): string { const encodedPrompt = base64(prompt); const name = agentName; const herdr = herdrBinary(connection); @@ -43,14 +43,13 @@ export function startAgentCommand(agentName: string, connection: ExeConnection, return [ herdrPrefix(connection), `cd ${shellAtom(connection.cwd)}`, - `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"`, + `mkdir -p ${shellAtom(`${connection.cwd.replace(/\/$/, "")}/.factorize-runs`)}`, + `test ! -e ${shellAtom(runPath)} && mkdir ${shellAtom(runPath)}`, + `printf '%s' ${shellAtom(lease)} > ${shellAtom(`${runPath}/.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)`, + `created=$(${herdr} pane split "$anchor" --direction down --cwd ${shellAtom(runPath)} --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)`, @@ -62,7 +61,7 @@ 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 validateWorktreeLeaseCommand(connection: ExeConnection, runPath: string, lease: string): string { return `${herdrPrefix(connection)} && test -d ${shellAtom(runPath)} && test "$(cat ${shellAtom(`${runPath}/.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, 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)}`; } @@ -92,10 +91,10 @@ 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 { +/** Revalidate terminal, run directory, and lease immediately before closing a pane. */ +export function garbageCollectPaneCommand(connection: ExeConnection, paneId: string, terminalId: string, runPath: 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(" && "); + 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 -d ${shellAtom(runPath)}`, `test "$(cat ${shellAtom(`${runPath}/.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 { diff --git a/src/flow-schemas.ts b/src/flow-schemas.ts index ce10d5eb..eaf9020b 100644 --- a/src/flow-schemas.ts +++ b/src/flow-schemas.ts @@ -1,7 +1,7 @@ import { z } from "zod"; export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]); -export const runStateSchema = z.enum(["queued", "starting", "running", "done", "blocked", "failed", "ignored"]); +export const runStateSchema = z.enum(["queued", "starting", "running", "recovering", "done", "blocked", "failed", "ignored"]); export const matchRuleSchema = z.object({ type: z.enum(["owner", "creator", "status", "label", "assignee"]), targetId: z.string().min(1), diff --git a/src/recovery.ts b/src/recovery.ts index e419b0a5..757c3949 100644 --- a/src/recovery.ts +++ b/src/recovery.ts @@ -3,8 +3,8 @@ export interface PaneProcess { paneId: string; pid: number; processGroup: number const obj = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; const str = (...values: unknown[]) => String(values.find((value) => typeof value === "string" || typeof value === "number") ?? ""); function identity(value: unknown): HerdrIdentity | null { - const wrapper = obj(value), agent = obj(wrapper.agent ?? wrapper), session = obj(agent.session_identity ?? agent.agent_session ?? agent.session), source = obj(session.source); - const result = { name: str(agent.name, agent.agent_name), status: str(agent.agent_status, agent.status, agent.state).toLowerCase(), kind: str(agent.agent_kind, agent.kind), workspaceId: str(agent.workspace_id, obj(agent.workspace).id), paneId: str(agent.pane_id, obj(agent.pane).id), terminalId: str(agent.terminal_id, obj(agent.terminal).id), cwd: str(agent.cwd), sessionSource: typeof session.source === "string" ? session.source : str(agent.session_source), sessionKind: str(session.kind, source.kind, agent.session_kind), sessionValue: str(session.value, session.id, source.value, agent.session_id, agent.session_value) }; + const wrapper = obj(value), agent = wrapper.agent && typeof wrapper.agent === "object" ? obj(wrapper.agent) : wrapper, session = obj(agent.session_identity ?? agent.agent_session ?? agent.session), source = obj(session.source); + const result = { name: str(agent.name, agent.agent_name), status: str(agent.agent_status, agent.status, agent.state).toLowerCase(), kind: str(agent.agent_kind, agent.kind, agent.agent), workspaceId: str(agent.workspace_id, obj(agent.workspace).id), paneId: str(agent.pane_id, obj(agent.pane).id), terminalId: str(agent.terminal_id, obj(agent.terminal).id), cwd: str(agent.cwd), sessionSource: typeof session.source === "string" ? session.source : str(agent.session_source), sessionKind: str(session.kind, source.kind, agent.session_kind), sessionValue: str(session.value, session.id, source.value, agent.session_id, agent.session_value) }; return result.name || result.paneId || result.sessionValue ? result : null; } function jsonObjects(body: string): Record[] { @@ -36,7 +36,8 @@ export function safeToAdopt(saved: Partial, live: HerdrIdentity, 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 findOwnedAgent(saved: Partial, agents: HerdrIdentity[], worktreePath: string, expectedName: string, expectedKind: string): HerdrIdentity | undefined { - return agents.find((agent) => ownsPane(saved, agent, worktreePath)) ?? agents.find((agent) => agent.name === expectedName && agent.cwd === worktreePath && (!expectedKind || agent.kind === expectedKind)); +export function findOwnedAgent(saved: Partial, agents: HerdrIdentity[], worktreePath: string, expectedName: string, expectedKind: string, runId: string): HerdrIdentity | undefined { + const runPath = (cwd: string) => cwd.includes(`/.factorize-runs/${runId}`) || cwd.includes(`/.factorize-worktrees/${runId}`); + return agents.find((agent) => ownsPane(saved, agent, worktreePath)) ?? agents.find((agent) => agent.name === expectedName && (!expectedKind || agent.kind === expectedKind) && (agent.cwd === worktreePath || runPath(agent.cwd))); } 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 c70ffcf5..61279fc5 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -117,7 +117,7 @@ export class Tenant extends DurableObject { 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); + 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", recovery_replacement_attempted: "INTEGER NOT NULL DEFAULT 0" })) this.ensureColumn("runs", column, definition); } async fetch(request: Request): Promise { @@ -399,8 +399,8 @@ export class Tenant extends DurableObject { private async stopRun(runId: string): Promise { const run = this.one("SELECT * FROM runs WHERE id = ?", runId); if (!run) return new Response("Not found", { status: 404 }); - if (!["starting", "running"].includes(String(run.state))) return Response.json({ error: "Run is not starting or running" }, { status: 409 }); - if (["starting", "running"].includes(String(run.state))) { + if (!["starting", "running", "recovering"].includes(String(run.state))) return Response.json({ error: "Run is not active" }, { status: 409 }); + if (["starting", "running", "recovering"].includes(String(run.state))) { const pipe = this.one("SELECT * FROM pipes WHERE id = ?", run.pipe_id) as Row | undefined; if (pipe) { const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); @@ -624,7 +624,7 @@ export class Tenant extends DurableObject { 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)}`; + const worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-runs/${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); @@ -724,7 +724,7 @@ 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 owned = findOwnedAgent(saved, agents, String(run.worktree_path || ""), String(run.agent_name || ""), connection.agentKind); + const owned = findOwnedAgent(saved, agents, String(run.worktree_path || ""), String(run.agent_name || ""), connection.agentKind, String(run.id)); if (owned) { const rotated = String(run.agent_session_value || "") !== owned.sessionValue; this.persistIdentity(run.id, owned, "running", rotated); @@ -765,8 +765,13 @@ export class Tenant extends DurableObject { } 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 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); + if (Number(run.recovery_replacement_attempted) || attempt > 1) { + if (!Number(run.recovery_replacement_attempted)) this.ctx.storage.sql.exec("UPDATE runs SET recovery_replacement_attempted=1 WHERE id=?", run.id); + this.scheduleRecovery(run.id, attempt, "waiting for the single previously requested replacement; no additional pane was created"); + return; + } + const lease = crypto.randomUUID(), worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-runs/${String(run.id)}-recovery-${attempt}`; + this.ctx.storage.sql.exec("UPDATE runs SET worktree_path=?,ownership_lease=?,ownership_generation=ownership_generation+1,recovery_replacement_attempted=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)); this.commandActivity(run.id, "replacement agent start", replacement); if (replacement.ok && (replacement.exitCode === null || replacement.exitCode === 0)) this.ctx.storage.sql.exec("UPDATE runs SET prompt_accepted=1 WHERE id=?", run.id); @@ -777,7 +782,7 @@ 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_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 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,recovery_replacement_attempted=0,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, outputCaptured = false): Promise { const encryptedResult = await encrypt(result, this.env.CREDENTIAL_ENCRYPTION_KEY); diff --git a/test/recovery.test.ts b/test/recovery.test.ts index 4775f810..0e59803e 100644 --- a/test/recovery.test.ts +++ b/test/recovery.test.ts @@ -37,8 +37,13 @@ describe("Herdr 0.9 recovery identity", () => { it("recovers pre-persistence agents by exact alias, kind, and unique worktree", () => { const expected = { ...moved, name: "run-agent", cwd: "/repo/.factorize-worktrees/run-1" }; const wrongCwd = { ...expected, cwd: "/repo/human" }; - expect(findOwnedAgent({}, [wrongCwd, expected], expected.cwd, "run-agent", "codex")).toBe(expected); - expect(findOwnedAgent({}, [wrongCwd], expected.cwd, "run-agent", "codex")).toBeUndefined(); + expect(findOwnedAgent({}, [wrongCwd, expected], "/stale/recovery-path", "run-agent", "codex", "run-1")).toBe(expected); + expect(findOwnedAgent({}, [wrongCwd], expected.cwd, "run-agent", "codex", "run-1")).toBeUndefined(); + }); + + it("accepts the current Herdr agent field as the agent kind", () => { + const agents = parseAgentList(JSON.stringify({ result: { agents: [{ name: "run-agent", agent: "codex", agent_status: "idle", cwd: "/repo/.factorize-runs/run-1", pane_id: "pane-1" }] } })); + expect(agents[0]).toMatchObject({ kind: "codex", status: "idle" }); }); it("adopts only matching cwd/kind/lineage and unclaimed sessions", () => { diff --git a/test/workspace.test.ts b/test/workspace.test.ts index 0ed486ce..55b8b03f 100644 --- a/test/workspace.test.ts +++ b/test/workspace.test.ts @@ -18,9 +18,10 @@ describe("flow workspaces", () => { }); it("passes the saved flow workspace to Herdr", () => { - 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"); + const command = startAgentCommand("bug-fixes-a1b2c3d4", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "fix it", "bug-fixes", "/repo/.factorize-runs/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("mkdir '/repo/.factorize-runs/run-1'"); + expect(command).not.toContain("git worktree"); expect(command).toContain("pane split"); expect(command).toContain("--no-focus"); expect(command).not.toContain("__FACTORIZE_EXIT_CODE__"); @@ -38,12 +39,12 @@ 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", "factorize", "/repo/.factorize-worktrees/run", "lease"); + const command = startAgentCommand("factorize-1", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo", agentCommand: "--model 'gpt 5'" }, "fix it", "factorize", "/repo/.factorize-runs/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"); + it("garbage collects only after terminal, run directory, and lease revalidation", () => { + const command = garbageCollectPaneCommand({ vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "w1:p2", "term-7", "/repo/.factorize-runs/run", "lease-7"); expect(command).toContain(".terminal_id == $terminal"); expect(command).toContain("factorize-lease"); expect(command).toContain("agent stop 'w1:p2'"); From ece43bd5a5612542c048fa8926bb3a2b12a2668c Mon Sep 17 00:00:00 2001 From: Brendan Date: Mon, 14 Sep 2026 15:21:58 +0000 Subject: [PATCH 2/2] Make Herdr run tabs idempotent --- src/exe.ts | 39 +++++++++++++++++++++------------------ src/tenant.ts | 17 ++++++----------- test/exe.test.ts | 27 +++++++++++++++++++++++---- test/workspace.test.ts | 9 ++++++--- 4 files changed, 56 insertions(+), 36 deletions(-) diff --git a/src/exe.ts b/src/exe.ts index d3adbeea..0d40b541 100644 --- a/src/exe.ts +++ b/src/exe.ts @@ -19,15 +19,21 @@ export interface ExeResponse { /** Calls exe.dev's documented HTTPS SSH-command API. */ export async function exec(connection: ExeConnection, remoteCommand: string): Promise { - const requestBody = `ssh ${shellAtom(connection.vmName)} ${shellAtom(remoteCommand)}`; + const marker = `__factorize_exit_${crypto.randomUUID().replaceAll("-", "")}__`; + const wrappedCommand = `( ${remoteCommand} ); factorize_exit=$?; printf '\\n${marker}:%s\\n' "$factorize_exit"; exit "$factorize_exit"`; + const requestBody = `ssh ${shellAtom(connection.vmName)} ${shellAtom(wrappedCommand)}`; const response = await fetch("https://exe.dev/exec", { method: "POST", headers: { Authorization: `Bearer ${connection.apiToken}`, "Content-Type": "text/plain" }, body: requestBody, }); - const body = await response.text(); - const exit = response.headers.get("X-Exe-Exit"); - return { ok: response.ok, status: response.status, exitCode: exit && /^\d+$/.test(exit) ? Number(exit) : null, body, requestBody }; + const rawBody = await response.text(); + const sentinel = new RegExp(`(?:\\r?\\n)?${marker}:(\\d+)(?:\\r?\\n)?$`); + const captured = rawBody.match(sentinel); + const headerExit = response.headers.get("X-Exe-Exit"); + const exitCode = captured ? Number(captured[1]) : headerExit && /^\d+$/.test(headerExit) ? Number(headerExit) : null; + const body = captured ? rawBody.replace(sentinel, "") : rawBody; + return { ok: response.ok && exitCode === 0, status: response.status, exitCode, body, requestBody }; } /** Single shell atom; prevents ticket content from becoming syntax in either SSH parser. */ @@ -39,28 +45,24 @@ export function startAgentCommand(agentName: string, connection: ExeConnection, const encodedPrompt = base64(prompt); const name = agentName; 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)}`, `mkdir -p ${shellAtom(`${connection.cwd.replace(/\/$/, "")}/.factorize-runs`)}`, - `test ! -e ${shellAtom(runPath)} && mkdir ${shellAtom(runPath)}`, - `printf '%s' ${shellAtom(lease)} > ${shellAtom(`${runPath}/.factorize-lease`)}`, + `if [ ! -e ${shellAtom(runPath)} ]; then mkdir ${shellAtom(runPath)}; fi`, + `test -d ${shellAtom(runPath)}`, + `if [ -e ${shellAtom(`${runPath}/.factorize-lease`)} ]; then test "$(cat ${shellAtom(`${runPath}/.factorize-lease`)})" = ${shellAtom(lease)}; else printf '%s' ${shellAtom(lease)} > ${shellAtom(`${runPath}/.factorize-lease`)}; fi`, `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(runPath)} --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)}`, + `if [ -z "$workspace_id" ]; then created=$(${herdr} workspace create --cwd ${shellAtom(runPath)} --label ${shellAtom(workspaceName)} --no-focus) && workspace_id=$(printf '%s' "$created" | jq -er '.result.workspace.workspace_id') && tab_id=$(printf '%s' "$created" | jq -er '.result.tab.tab_id') && pane=$(printf '%s' "$created" | jq -er '.result.root_pane.pane_id') && ${herdr} tab rename "$tab_id" ${shellAtom(name)} >/dev/null; else tabs=$(${herdr} tab list --workspace "$workspace_id") && tab_id=$(printf '%s' "$tabs" | jq -r --arg label ${shellAtom(name)} '.result.tabs[]? | select(.label == $label) | .tab_id' | head -n1); if [ -z "$tab_id" ]; then created=$(${herdr} tab create --workspace "$workspace_id" --cwd ${shellAtom(runPath)} --label ${shellAtom(name)} --no-focus) && tab_id=$(printf '%s' "$created" | jq -er '.result.tab.tab_id') && pane=$(printf '%s' "$created" | jq -er '.result.root_pane.pane_id'); else panes=$(${herdr} pane list --workspace "$workspace_id") && pane=$(printf '%s' "$panes" | jq -r --arg tab "$tab_id" '.result.panes[]? | select(.tab_id == $tab) | .pane_id' | head -n1); test -n "$pane"; extras=$(printf '%s' "$panes" | jq -r --arg tab "$tab_id" --arg keep "$pane" '.result.panes[]? | select(.tab_id == $tab and .pane_id != $keep) | .pane_id'); for extra in $extras; do ${herdr} pane close "$extra" >/dev/null; done; fi; fi`, + `existing=$(${herdr} agent get ${shellAtom(name)} 2>/dev/null || true)`, + `if [ -n "$existing" ]; then printf '%s\\n' "$existing"; else ${herdr} agent start ${shellAtom(name)} --kind ${shellAtom(connection.agentKind)} --pane "$pane"${agentCommand(connection)} && prompt=$(printf '%s' ${shellAtom(encodedPrompt)} | base64 -d) && ${herdr} agent prompt ${shellAtom(name)} "$prompt" && ${herdr} agent get ${shellAtom(name)}; fi`, ].join(" && "); } 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 paneProcessInfoCommand(connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} pane process-info --pane ${shellAtom(paneId)}`; } export function validateWorktreeLeaseCommand(connection: ExeConnection, runPath: string, lease: string): string { return `${herdrPrefix(connection)} && test -d ${shellAtom(runPath)} && test "$(cat ${shellAtom(`${runPath}/.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, 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)}`; } @@ -70,7 +72,7 @@ export function startAgentInPaneCommand(agentName: string, connection: ExeConnec 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(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(" && "); + return [herdrPrefix(connection), `first=$(${herdr} pane process-info --pane ${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 ${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 { @@ -88,13 +90,14 @@ export function agentOutputCommand(connection: ExeConnection, agentName: string) } export function stopAgentCommand(connection: ExeConnection, agentName: string): string { - return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent stop ${shellAtom(agentName)}`; + const herdr = herdrBinary(connection); + return `${herdrPrefix(connection)} && agent=$(${herdr} agent get ${shellAtom(agentName)}) && pane=$(printf '%s' "$agent" | jq -er '.result.agent.pane_id') && ${herdr} pane close "$pane"`; } /** Revalidate terminal, run directory, and lease immediately before closing a pane. */ export function garbageCollectPaneCommand(connection: ExeConnection, paneId: string, terminalId: string, runPath: 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 -d ${shellAtom(runPath)}`, `test "$(cat ${shellAtom(`${runPath}/.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(" && "); + 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 -d ${shellAtom(runPath)}`, `test "$(cat ${shellAtom(`${runPath}/.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`, `${herdr} pane close ${pane}`].join(" && "); } export function herdrCheckCommand(connection: ExeConnection): string { diff --git a/src/tenant.ts b/src/tenant.ts index 61279fc5..5e457bcf 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -117,7 +117,7 @@ export class Tenant extends DurableObject { 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", recovery_replacement_attempted: "INTEGER NOT NULL DEFAULT 0" })) 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); } async fetch(request: Request): Promise { @@ -765,24 +765,19 @@ export class Tenant extends DurableObject { } 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")}.`; - if (Number(run.recovery_replacement_attempted) || attempt > 1) { - if (!Number(run.recovery_replacement_attempted)) this.ctx.storage.sql.exec("UPDATE runs SET recovery_replacement_attempted=1 WHERE id=?", run.id); - this.scheduleRecovery(run.id, attempt, "waiting for the single previously requested replacement; no additional pane was created"); - return; - } - const lease = crypto.randomUUID(), worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-runs/${String(run.id)}-recovery-${attempt}`; - this.ctx.storage.sql.exec("UPDATE runs SET worktree_path=?,ownership_lease=?,ownership_generation=ownership_generation+1,recovery_replacement_attempted=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)); + const runPath = String(run.worktree_path || ""), lease = String(run.ownership_lease || ""); + if (!runPath || !lease) return this.finishRecovery(run, "failed", "Recovery cannot prove the run directory lease."); + const replacement = await exec(connection, startAgentCommand(String(run.agent_name), connection, recoveryPrompt, String(run.workspace_name), runPath, lease)); this.commandActivity(run.id, "replacement agent start", replacement); 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); - this.scheduleRecovery(run.id, attempt, "replacement workspace/harness was not yet verifiable"); + this.scheduleRecovery(run.id, attempt, "idempotent run-tab reconciliation was not yet verifiable"); } 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_attempt=0,recovery_reason=NULL,recovery_started_at=NULL,recovery_last_action=?,recovery_next_at=NULL,recovery_comment_finished=1,recovery_replacement_attempted=0,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 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, outputCaptured = false): Promise { const encryptedResult = await encrypt(result, this.env.CREDENTIAL_ENCRYPTION_KEY); diff --git a/test/exe.test.ts b/test/exe.test.ts index 6641fff9..4f2cbd90 100644 --- a/test/exe.test.ts +++ b/test/exe.test.ts @@ -1,5 +1,7 @@ -import { describe, expect, it } from "vitest"; -import { agentOutputCommand, stopAgentCommand } from "../src/exe"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { agentOutputCommand, exec, stopAgentCommand } from "../src/exe"; + +afterEach(() => vi.unstubAllGlobals()); describe("agent output command", () => { it("requests the complete available transcript without a line limit", () => { @@ -16,8 +18,25 @@ describe("agent output command", () => { }); describe("agent stop command", () => { - it("uses the fixed Herdr agent stop command and quotes the agent name", () => { + it("resolves the agent pane and closes it", () => { const command = stopAgentCommand({ vmName: "vm", apiToken: "secret", agentKind: "codex", cwd: "/workspace" }, "agent; unsafe"); - expect(command).toContain("agent stop 'agent; unsafe'"); + expect(command).toContain("agent get 'agent; unsafe'"); + expect(command).toContain("pane close \"$pane\""); + expect(command).not.toContain("agent stop"); + }); +}); + +describe("exe command exit status", () => { + it("uses the command sentinel when the proxy omits X-Exe-Exit", async () => { + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + const marker = String(init.body).match(/__factorize_exit_[a-f0-9]+__/)?.[0]; + expect(marker).toBeTruthy(); + return new Response(`usage\n${marker}:2\n`, { status: 200 }); + })); + + const result = await exec({ vmName: "vm", apiToken: "secret", agentKind: "codex", cwd: "/workspace" }, "false"); + expect(result.ok).toBe(false); + expect(result.exitCode).toBe(2); + expect(result.body).toBe("usage"); }); }); diff --git a/test/workspace.test.ts b/test/workspace.test.ts index 55b8b03f..1b2ce402 100644 --- a/test/workspace.test.ts +++ b/test/workspace.test.ts @@ -22,7 +22,10 @@ describe("flow workspaces", () => { expect(command).toContain("--label 'bug-fixes'"); expect(command).toContain("mkdir '/repo/.factorize-runs/run-1'"); expect(command).not.toContain("git worktree"); - expect(command).toContain("pane split"); + expect(command).toContain("tab list --workspace"); + expect(command).toContain("tab create --workspace"); + expect(command).toContain("tab rename \"$tab_id\" 'bug-fixes-a1b2c3d4'"); + expect(command).not.toContain("pane split"); expect(command).toContain("--no-focus"); expect(command).not.toContain("__FACTORIZE_EXIT_CODE__"); expect(command).toContain('export PATH="$HOME/.local/bin:$PATH"'); @@ -47,7 +50,7 @@ describe("flow workspaces", () => { const command = garbageCollectPaneCommand({ vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "w1:p2", "term-7", "/repo/.factorize-runs/run", "lease-7"); expect(command).toContain(".terminal_id == $terminal"); expect(command).toContain("factorize-lease"); - expect(command).toContain("agent stop 'w1:p2'"); + expect(command).not.toContain("agent stop"); expect(command).toContain("pane close 'w1:p2'"); }); @@ -69,7 +72,7 @@ describe("flow workspaces", () => { it("revalidates exact pane and process identities before bounded escalation", () => { const command = replaceForegroundCommand("flow-1", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "pane-7"); - expect(command.match(/pane process-info 'pane-7'/g)).toHaveLength(2); + expect(command.match(/pane process-info --pane 'pane-7'/g)).toHaveLength(2); expect(command).toContain('second_pid" = "$first_pid'); expect(command).toContain('second_pgid" = "$first_pgid'); expect(command).toContain('kill -INT -- "-$first_pgid"');