diff --git a/src/exe.ts b/src/exe.ts index 1d306d7c..4705a7f4 100644 --- a/src/exe.ts +++ b/src/exe.ts @@ -50,9 +50,24 @@ export function startAgentCommand(agentName: string, connection: ExeConnection, `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`, `prompt=$(printf '%s' ${shellAtom(encodedPrompt)} | base64 -d)`, `${herdrBinary(connection)} agent prompt ${shellAtom(name)} \"$prompt\"`, + `${herdrBinary(connection)} agent get ${shellAtom(name)}`, ].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 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)}`; } + +/** 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 { + 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(" && "); +} + export function agentStatusCommand(connection: ExeConnection, agentName: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent get ${shellAtom(agentName)}`; } diff --git a/src/recovery.ts b/src/recovery.ts new file mode 100644 index 00000000..d33e89e5 --- /dev/null +++ b/src/recovery.ts @@ -0,0 +1,15 @@ +export interface HerdrIdentity { name: string; status: string; kind: string; workspaceId: string; paneId: string; terminalId: string; cwd: string; sessionSource: string; sessionKind: string; sessionValue: string; } +export interface PaneProcess { paneId: string; pid: number; processGroup: number; argv: string[]; executable: string; cwd: string; } +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) }; + return result.name || result.paneId || result.sessionValue ? result : null; +} +export function parseAgent(body: string): HerdrIdentity | null { for (const candidate of [body, ...body.trim().split(/\n/).reverse()]) { try { const parsed = obj(JSON.parse(candidate)); const found = identity(obj(parsed.result).agent ?? parsed.agent ?? parsed.result ?? parsed); if (found) return found; } catch {} } return null; } +export function parseAgentList(body: string): HerdrIdentity[] { try { const parsed = obj(JSON.parse(body)), result = obj(parsed.result); const values = Array.isArray(result.agents) ? result.agents : Array.isArray(parsed.agents) ? parsed.agents : Array.isArray(parsed.result) ? parsed.result : []; return values.map(identity).filter((value): value is HerdrIdentity => value !== null); } catch { return []; } } +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); } +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 af2e05d0..288ebead 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -1,7 +1,8 @@ import { DurableObject } from "cloudflare:workers"; import Mustache from "mustache"; import { decrypt, encrypt } from "./crypto"; -import { agentOutputCommand, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, herdrAgentStatus, herdrCheckCommand, startAgentCommand, stopAgentCommand, type ExeConnection } from "./exe"; +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 { 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"; @@ -89,6 +90,7 @@ export class Tenant extends DurableObject { CREATE TABLE IF NOT EXISTS github_installations (installation_id INTEGER PRIMARY KEY, account_login TEXT NOT NULL, account_type TEXT NOT NULL, state TEXT NOT NULL, updated_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS github_setup_states (nonce TEXT PRIMARY KEY, expires_at INTEGER NOT NULL, used_at TEXT); CREATE TABLE IF NOT EXISTS pending_verifications (id TEXT PRIMARY KEY, flow_id TEXT NOT NULL, delivery_id TEXT NOT NULL, installation_id INTEGER NOT NULL, repository_id INTEGER NOT NULL, repository_owner TEXT NOT NULL, repository_name TEXT NOT NULL, pull_number INTEGER NOT NULL, attempt INTEGER NOT NULL, next_attempt_at INTEGER NOT NULL, payload TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS run_activity (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, action TEXT NOT NULL, detail TEXT NOT NULL, created_at TEXT NOT NULL); `); this.ensureColumn("pipes", "workspace_name", "TEXT NOT NULL DEFAULT ''"); this.ensureColumn("pipes", "agent_kind", "TEXT NOT NULL DEFAULT ''"); @@ -111,6 +113,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_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 { @@ -159,13 +162,13 @@ export class Tenant extends DurableObject { await this.processGitHubVerifications(); // Release completed slots before looking at the queue, so capacity is used // immediately rather than waiting for the next polling alarm. - const running = this.rows("SELECT * FROM runs WHERE state IN ('running','blocked') ORDER BY updated_at LIMIT 40"); + const running = this.rows("SELECT * FROM runs WHERE state IN ('running','blocked','recovering') ORDER BY updated_at LIMIT 40"); for (const run of running) await this.pollRun(run); const queued = this.rows("SELECT * FROM runs WHERE state = 'queued' ORDER BY created_at LIMIT 20"); for (const run of queued) { const pipe = this.one("SELECT * FROM pipes WHERE id = ?", run.pipe_id) as Row | undefined; if (!pipe) continue; - const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id = ? AND state IN ('starting','running','blocked')", pipe.id) as Row; + 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}`; @@ -173,7 +176,7 @@ export class Tenant extends DurableObject { await this.startRun({ ...run, agent_name: name, workspace_name: name }, pipe); } - const pending = this.one("SELECT count(*) AS count FROM runs WHERE state IN ('queued','starting','running','blocked')") as Row; + const pending = this.one("SELECT count(*) AS count FROM runs WHERE state IN ('queued','starting','running','blocked','recovering')") as Row; const verification = this.one("SELECT min(next_attempt_at) AS next_attempt_at FROM pending_verifications") as Row; const nextVerification = Number(verification?.next_attempt_at || 0); if (Number(pending.count) > 0 || nextVerification) await this.ctx.storage.setAlarm(nextVerification ? Math.min(Date.now() + 15_000, nextVerification) : Date.now() + 15_000); @@ -278,7 +281,7 @@ export class Tenant extends DurableObject { const flow = this.one("SELECT id, name, project_id, filter_type, filter_target_id, match_rules, source_kind, source_config, trigger_kind, trigger_config, max_concurrency, workspace_name, agent_kind, exe_connection_id, cwd, COALESCE(NULLIF(context_template, ''), ?) AS context_template, enabled, created_at FROM pipes WHERE id = ?", DEFAULT_CONTEXT_TEMPLATE, flowId); if (!flow) return new Response("Not found", { status: 404 }); const events = this.rows("SELECT id, delivery_id, issue_id, issue_url, event_type, event_action, outcome, detail, provider, received_at FROM flow_events WHERE flow_id = ? ORDER BY received_at DESC LIMIT 100", flowId); - const runs = this.rows("SELECT id, issue_id, issue_url, claim_key, agent_name, workspace_name, agent_kind, state, provider, prompt, result, created_at, updated_at, exec_request, exec_response, exec_status, exec_exit_code FROM runs WHERE pipe_id = ? ORDER BY created_at DESC LIMIT 100", flowId); + const runs = this.rows("SELECT id, issue_id, issue_url, claim_key, agent_name, workspace_name, agent_kind, state, provider, prompt, result, created_at, updated_at, exec_request, exec_response, exec_status, exec_exit_code, recovery_reason, recovery_attempt, recovery_last_action, recovery_started_at FROM runs WHERE pipe_id = ? ORDER BY created_at DESC LIMIT 100", flowId); await Promise.all(runs.map(async (run) => { if (run.state !== "ignored" && typeof run.prompt === "string" && run.prompt) run.prompt = await decrypt(run.prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); if (typeof run.exec_request === "string" && run.exec_request) run.exec_request = await decrypt(run.exec_request, this.env.CREDENTIAL_ENCRYPTION_KEY); @@ -450,7 +453,7 @@ export class Tenant extends DurableObject { catch { this.recordFlowEvent(pipe, deliveryId, workItem.identifier, workItem.url, workItem.event as any, "duplicate", "An active or queued run already owns this work item.", workItem.provider); return; } const prompt = await encrypt(plaintextPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,provider,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, pipe.id, workItem.identifier, workItem.url, workItem.claimKey, `factorize-${runId}`, String(pipe.workspace_name ?? ""), String(pipe.agent_kind ?? ""), "queued", prompt, workItem.provider, now(), now()); - const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id=? AND state IN ('starting','running','blocked')", pipe.id) as Row; + const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id=? AND state IN ('starting','running','blocked','recovering')", pipe.id) as Row; this.recordFlowEvent(pipe, deliveryId, workItem.identifier, workItem.url, workItem.event as any, Number(active.count) < Number(pipe.max_concurrency) ? "accepted" : "queued_capacity", Number(active.count) < Number(pipe.max_concurrency) ? "Handler accepted delivery; agent queued to start." : "Handler accepted delivery; queued for capacity.", workItem.provider); } @@ -540,20 +543,29 @@ export class Tenant extends DurableObject { 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); if (!result.ok || (result.exitCode !== null && result.exitCode !== 0)) return this.finishRun(run, "failed", `Unable to start Herdr agent (exe.dev HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}): ${result.body.slice(0, 800)}`); + this.ctx.storage.sql.exec("UPDATE runs SET prompt_accepted=1,updated_at=? WHERE id=?", now(), run.id); const verification = await exec(connection, agentStatusCommand(connection, String(run.agent_name))); if (!verification.ok || (verification.exitCode !== null && verification.exitCode !== 0) || !herdrAgentStatus(verification.body)) { - return this.finishRun(run, "failed", `Herdr agent start returned successfully, but Factorize could not verify the agent (exe.dev HTTP ${verification.status}, VM exit ${verification.exitCode ?? "not reported"}): ${verification.body.slice(0, 800)}`); + return this.beginRecovery(run, pipe, connection, `agent start succeeded but verification was ambiguous (exe.dev HTTP ${verification.status}, VM exit ${verification.exitCode ?? "not reported"})`); } - this.ctx.storage.sql.exec("UPDATE runs SET state = 'running', updated_at = ? WHERE id = ?", now(), run.id); + const identity = parseAgent(verification.body); + if (!identity) return this.beginRecovery(run, pipe, connection, "agent start succeeded but its structured identity was inconsistent"); + this.persistIdentity(run.id, identity, "running"); + this.ctx.storage.sql.exec("UPDATE runs SET prompt_accepted=1, updated_at=? WHERE id=?", now(), run.id); } private async pollRun(run: Row): Promise { const pipe = this.one("SELECT * FROM pipes WHERE id = ?", run.pipe_id) as Row | undefined; - const connection = pipe ? await this.connectionForPipe(pipe) : null; + if (!pipe) return this.finishRun(run, "failed", "Flow configuration is unavailable."); + const connection = await this.connectionForPipe(pipe); if (!connection) return this.finishRun(run, "failed", "exe.dev connection is unavailable."); + if (String(run.state) === "recovering") return this.recoverRun(run, pipe, connection); const status = await exec(connection, agentStatusCommand(connection, String(run.agent_name))); - if (status.exitCode !== null && status.exitCode !== 0) return this.finishRun(run, "failed", `Unable to query the Herdr agent (VM exit ${status.exitCode}): ${status.body.slice(0, 800)}`); - if (!status.ok) return; // transient VM/API errors are retried by the next alarm + 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)); 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); @@ -564,6 +576,92 @@ export class Tenant extends DurableObject { await this.finishRun(run, "done", output.ok ? output.body : "Agent completed; terminal output could not be read."); } + 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 activity(runId: unknown, action: string, detail: string): void { + this.ctx.storage.sql.exec("INSERT INTO run_activity VALUES (?,?,?,?,?)", id(), runId, action, detail.slice(0, 1000), now()); + } + + private commandActivity(runId: unknown, command: string, result: { ok: boolean; status: number; exitCode: number | null }): void { this.activity(runId, "herdr_command", `${command}: HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}, ${result.ok ? "request succeeded" : "request failed"}`); } + + private async beginRecovery(run: Row, pipe: Row, connection: ExeConnection, reason: string): Promise { + const started = !run.recovery_started_at; + 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 (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); + } + await this.recoverRun({ ...run, state: "recovering", recovery_reason: reason, recovery_started_at: run.recovery_started_at || now() }, pipe, connection); + } + + private async recoverRun(run: Row, pipe: Row, connection: ExeConnection): Promise { + if (Number(run.recovery_next_at || 0) > Date.now()) return; + const attempt = Number(run.recovery_attempt || 0) + 1; + const timeoutMs = Math.max(15_000, Number(this.env.RECOVERY_TIMEOUT_MS) || 5 * 60_000), maxAttempts = Math.max(1, Number(this.env.RECOVERY_MAX_ATTEMPTS) || 8); + if (attempt > maxAttempts || Date.now() - Date.parse(String(run.recovery_started_at)) > timeoutMs) return this.finishRecovery(run, "failed", "Automatic recovery exhausted its bounded retry budget."); + this.ctx.storage.sql.exec("UPDATE runs SET recovery_attempt=?,recovery_last_action='listing Herdr agents',updated_at=? WHERE id=?", attempt, now(), run.id); + const listed = await exec(connection, agentListCommand(connection)); + 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."); + } + 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 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 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) { + const replaced = await exec(connection, replaceForegroundCommand(String(run.agent_name), connection, saved.paneId)); + 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 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))); + 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"); + } + + 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 finishRun(run: Row, state: Extract, result: string): 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); @@ -776,7 +874,7 @@ export class Tenant extends DurableObject { private nextRunSlot(pipe: Row, runId: string): number { const base = String(pipe.workspace_name); - const active = this.rows("SELECT workspace_name FROM runs WHERE pipe_id = ? AND id != ? AND state IN ('starting','running','blocked')", pipe.id, runId); + const active = this.rows("SELECT workspace_name FROM runs WHERE pipe_id = ? AND id != ? AND state IN ('starting','running','blocked','recovering')", pipe.id, runId); const occupied = new Set(active.map((run) => { const match = new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}-(\\d+)$`).exec(String(run.workspace_name)); return match ? Number(match[1]) : 0; diff --git a/src/types.ts b/src/types.ts index 30d02f3f..6e664dc6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,6 +1,6 @@ export type FilterType = "owner" | "creator" | "status" | "label" | "assignee"; export interface MatchRule { type: FilterType; targetId: string; } -export type RunState = "queued" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored"; +export type RunState = "queued" | "starting" | "running" | "recovering" | "done" | "blocked" | "failed" | "ignored"; export interface Env { TENANTS: DurableObjectNamespace; @@ -20,6 +20,8 @@ export interface Env { GITHUB_INTEGRATION_ENABLED?: string; CUSTOM_SOURCES_ENABLED?: string; CUSTOM_HANDLER_LOADER?: WorkerLoader; + RECOVERY_TIMEOUT_MS?: string; + RECOVERY_MAX_ATTEMPTS?: string; OAUTH_KV?: KVNamespace; OAUTH_PROVIDER?: import("@cloudflare/workers-oauth-provider").OAuthHelpers; } diff --git a/src/ui.ts b/src/ui.ts index 58de33e0..ff7076ce 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -139,12 +139,12 @@ const esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d const time=v=>new Date(v).toLocaleString(); const badge=(value,good)=>''+esc(value)+''; const issueLink=(id,url)=>{if(!id)return '—';const trusted=typeof url==='string'&&(url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(url));const href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return ''+esc(id)+' ↗'}; -async function load(){const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='

Could not load this flow.

';return}const data=await response.json(),flow=data.flow,events=data.events||[],runs=data.runs||[];const eventRows=events.map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+badge(event.outcome,event.outcome==='triggered')+''+esc(event.detail)+'').join('')||'No relevant webhooks yet. Update an issue in this flow’s Linear project to see it here.';const runRows=runs.map(run=>''+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+''+esc(run.agent_name)+''+esc(run.workspace_name||flow.workspace_name||'—')+''+badge(run.state,['queued','starting','running','done'].includes(run.state))+''+time(run.updated_at)+'').join('')||'No agent runs yet.';root.innerHTML='

'+esc(flow.name)+'

'+esc(flow.filter_type)+' trigger · '+esc(flow.max_concurrency)+' concurrent agents · '+esc(flow.agent_kind||'Herdr agent')+' · workspace '+esc(flow.workspace_name||'—')+'

Edit Flow

Webhook activity

Relevant Linear webhooks and whether they queued an agent.

'+eventRows+'
ReceivedIssueEventResultDetails

Agent runs

'+runRows+'
IssueHerdr agentWorkspaceStateUpdated
'} +async function load(){const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='

Could not load this flow.

';return}const data=await response.json(),flow=data.flow,events=data.events||[],runs=data.runs||[];const eventRows=events.map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+badge(event.outcome,event.outcome==='triggered')+''+esc(event.detail)+'').join('')||'No relevant webhooks yet. Update an issue in this flow’s Linear project to see it here.';const runRows=runs.map(run=>''+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+''+esc(run.agent_name)+''+esc(run.workspace_name||flow.workspace_name||'—')+''+badge(run.state,['queued','starting','running','recovering','done'].includes(run.state))+''+time(run.updated_at)+'').join('')||'No agent runs yet.';root.innerHTML='

'+esc(flow.name)+'

'+esc(flow.filter_type)+' trigger · '+esc(flow.max_concurrency)+' concurrent agents · '+esc(flow.agent_kind||'Herdr agent')+' · workspace '+esc(flow.workspace_name||'—')+'

Edit Flow

Webhook activity

Relevant Linear webhooks and whether they queued an agent.

'+eventRows+'
ReceivedIssueEventResultDetails

Agent runs

'+runRows+'
IssueHerdr agentWorkspaceStateUpdated
'} const renderActivity=load; load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(!response.ok)return;const data=await response.json(),runs=(data.runs||[]).filter(run=>run.state!=='ignored');if(!runs.length)return;const diagnostics=runs.map(run=>'
'+esc(run.agent_name)+''+(run.exec_status!=null?'HTTP '+esc(String(run.exec_status))+(run.exec_exit_code!=null?' · VM exit '+esc(String(run.exec_exit_code)):'' ):esc(run.state))+'
'+(run.exec_status!=null?'

Exact command submitted to exe.dev

'+esc(run.exec_request)+'

Actual exe.dev response

'+esc(run.exec_response)+'
':'

No exe.dev request or response was recorded for this run. It did not reach the VM-command step.

')+(run.result?'

Herdr agent output

'+esc(run.result)+'
':'')+'
').join('');root.insertAdjacentHTML('beforeend','

Actual exe.dev command results

Only real agent runs appear here. The bearer token is never shown.

'+diagnostics+'
')}; // Keep run details with the run they belong to. The native disclosure control // makes the command and response available without expanding every run. -load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(!response.ok)return;const data=await response.json(),runs=(data.runs||[]).filter(run=>run.state!=='ignored'),runSection=Array.from(root.querySelectorAll('section')).find(section=>section.querySelector('h2')?.textContent==='Agent runs'),webhookSection=Array.from(root.querySelectorAll('section')).find(section=>section.querySelector('h2')?.textContent==='Webhook activity');if(!runSection)return;const panels=runs.map(run=>{const command=run.exec_status!=null?'

Exact command submitted to exe.dev

'+esc(run.exec_request)+'

Actual exe.dev response

'+esc(run.exec_response)+'
':'

No exe.dev request or response was recorded for this run. It did not reach the VM-command step.

';const prompt=run.prompt?'

Prompt sent to agent

'+esc(run.prompt)+'
':'';const output=run.result?'

Full agent output

'+esc(run.result)+'
':'';return '
'+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||data.flow.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+''+badge(run.state,['queued','starting','running','done'].includes(run.state))+''+time(run.updated_at)+'
'+prompt+command+output+'
'}).join('')||'

No agent runs yet.

';runSection.innerHTML='

Agent runs

Open a completed run to inspect its full, scrollable output.

'+panels;if(webhookSection)webhookSection.before(runSection)}; +load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(!response.ok)return;const data=await response.json(),runs=(data.runs||[]).filter(run=>run.state!=='ignored'),runSection=Array.from(root.querySelectorAll('section')).find(section=>section.querySelector('h2')?.textContent==='Agent runs'),webhookSection=Array.from(root.querySelectorAll('section')).find(section=>section.querySelector('h2')?.textContent==='Webhook activity');if(!runSection)return;const panels=runs.map(run=>{const recovery=run.state==='recovering'?'

Recovery attempt '+esc(run.recovery_attempt||0)+' · '+esc(run.recovery_reason||'Herdr state changed')+' · '+esc(run.recovery_last_action||'reconciling')+'

':'';const command=run.exec_status!=null?'

Exact command submitted to exe.dev

'+esc(run.exec_request)+'

Actual exe.dev response

'+esc(run.exec_response)+'
':'

No exe.dev request or response was recorded for this run. It did not reach the VM-command step.

';const prompt=run.prompt?'

Prompt sent to agent

'+esc(run.prompt)+'
':'';const output=run.result?'

Full agent output

'+esc(run.result)+'
':'';return '
'+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||data.flow.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+''+badge(run.state,['queued','starting','running','recovering','done'].includes(run.state))+''+time(run.updated_at)+'
'+recovery+prompt+command+output+'
'}).join('')||'

No agent runs yet.

';runSection.innerHTML='

Agent runs

Open a completed run to inspect its full, scrollable output.

'+panels;if(webhookSection)webhookSection.before(runSection)}; load(); `); diff --git a/test/recovery.test.ts b/test/recovery.test.ts new file mode 100644 index 00000000..bd129931 --- /dev/null +++ b/test/recovery.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { matchesLineage, 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" }; + +describe("Herdr 0.9 recovery identity", () => { + it("parses representative agent get JSON and trailing structured output", () => { + const body = `prompt accepted\n${JSON.stringify({ result: { agent: { name: "flow-1", agent_status: "working", agent_kind: "codex", workspace_id: "ws-1", pane_id: "pane-1", terminal_id: "term-1", cwd: "/repo", session_identity: { source: "codex", kind: "thread", value: "session-7" } } } })}`; + expect(parseAgent(body)).toMatchObject({ name: "flow-1", status: "working", workspaceId: "ws-1", sessionValue: "session-7" }); + }); + + it("finds a moved and renamed agent by stable session before location", () => { + const saved = { sessionKind: "thread", sessionValue: "session-7", paneId: "pane-1", workspaceId: "ws-1" }; + expect(sameStableSession(saved, moved)).toBe(true); + expect(matchesLineage(saved, moved)).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); + expect(agents[0]).toMatchObject({ name: "flow-1", paneId: "pane-1", sessionValue: "abc" }); + }); + + it("adopts only matching cwd/kind/lineage and unclaimed sessions", () => { + const saved = { terminalId: "term-1", kind: "codex", cwd: "/repo" }; + expect(safeToAdopt(saved, moved, new Set())).toBe(true); + expect(safeToAdopt(saved, { ...moved, cwd: "/human" }, new Set())).toBe(false); + expect(safeToAdopt(saved, { ...moved, kind: "claude" }, new Set())).toBe(false); + expect(safeToAdopt(saved, moved, new Set(["session-7"]))).toBe(false); + }); + + it("parses exact foreground identity for stale-PID and cwd validation", () => { + expect(parsePaneProcess(JSON.stringify({ result: { pane_id: "pane-7", foreground: { pid: 401, process_group: 400, argv: ["node", "tool.js"], executable: "/usr/bin/node", cwd: "/repo" } } }))).toEqual({ paneId: "pane-7", pid: 401, processGroup: 400, argv: ["node", "tool.js"], executable: "/usr/bin/node", cwd: "/repo" }); + expect(parsePaneProcess('{"result":{"pid":0,"pgid":0}}')).toBeNull(); + }); +}); diff --git a/test/workspace.test.ts b/test/workspace.test.ts index 5e953df5..573cf47e 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, shellAtom, startAgentCommand } from "../src/exe"; +import { agentStatusCommand, connectionCheckCommand, defaultAgentCommand, herdrAgentStatus, replaceForegroundCommand, shellAtom, startAgentCommand } from "../src/exe"; import { workingDirectoryFor, workspaceNameFor } from "../src/workspace"; describe("flow workspaces", () => { @@ -54,4 +54,14 @@ describe("flow workspaces", () => { expect(herdrAgentStatus('{"result":{"agent":{"agent_status":"working"}}}')).toBe("working"); expect(herdrAgentStatus('{"result":{"agent":{"state":"idle"}}}')).toBe("idle"); }); + + 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).toContain('second_pid" = "$first_pid'); + expect(command).toContain('second_pgid" = "$first_pgid'); + expect(command).toContain('kill -INT -- "-$first_pgid"'); + expect(command).toContain('kill -TERM -- "-$first_pgid"'); + expect(command).not.toContain("pkill"); + }); });