Skip to content

Commit 10628ad

Browse files
Merge pull request #179 from GenerationSoftware/gen-2120-harness-diagnostics
GEN-2120: Persist harness stderr and exit diagnostics
2 parents 8c0c716 + 9e13b15 commit 10628ad

15 files changed

Lines changed: 454 additions & 40 deletions
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- Terminal execution evidence is independent of artifact and cleanup errors.
2+
ALTER TABLE app.runs ADD COLUMN execution_diagnostics jsonb;

‎packages/app/src/exe-vm-backend.ts‎

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, Laun
22
import { base64 } from "./crypto";
33
import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe";
44

5+
import { HARNESS_LOG_LIMIT, safeDiagnosticText } from "./harness-diagnostics";
6+
57
const API = "https://exe.dev/exec";
68
const capabilities = ["output", "recovery", "stop"] as const;
79

@@ -101,31 +103,51 @@ export class ExeVmBackend implements ExecutionBackend {
101103
"mkdir -p /home/exedev/workspace",
102104
"cd /home/exedev/workspace",
103105
`printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`,
104-
`if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:${output} ${harnessCommand(request.harness)}; fi`,
106+
`if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`,
105107
"echo started",
106108
].join("; ");
107109
let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`);
108110
const accepted = (result: BackendCommandResult) => result.ok && result.body.trim() === "started";
109111
for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`);
110112
if (!accepted(started)) {
111-
const cleanup = await this.deleteVm(vm);
112-
const detail = `VM provisioning failed (${started.status}): ${started.body.slice(0, 500)}${cleanup.ok ? "" : `; cleanup also failed: ${cleanup.body.slice(0, 200)}`}`;
113+
const detail = `VM provisioning failed (${started.status}): ${safeDiagnosticText(started.body, 500)}`;
113114
return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail, command: started }, command: started };
114115
}
115116
return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "running", command: started }, command: started };
116117
}
117118

118119
async inspect(handle: RunHandle): Promise<ExecutionObservation> {
119120
const vm = this.vm(handle);
120-
const inspect = `unit=${shellAtom(vm)}; load=$(sudo systemctl show "$unit" --property=LoadState --value 2>/dev/null || true); active=$(sudo systemctl show "$unit" --property=ActiveState --value 2>/dev/null || true); sub=$(sudo systemctl show "$unit" --property=SubState --value 2>/dev/null || true); result=$(sudo systemctl show "$unit" --property=Result --value 2>/dev/null || true); code=$(sudo systemctl show "$unit" --property=ExecMainStatus --value 2>/dev/null || true); if [ "$load" != loaded ]; then printf missing; elif [ "$sub" = running ] || [ "$sub" = start ] || [ "$active" = activating ] || [ "$active" = deactivating ]; then printf running; elif [ "$result" = success ] && [ "$code" = 0 ]; then printf succeeded; else printf failed; fi`;
121-
const result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`);
122-
if (!result.ok) return result.status >= 500
123-
? { state: "running", detail: `VM inspection is temporarily unavailable (${result.status})`, command: result }
124-
: { state: "failed", detail: `The run-owned VM is unavailable (${result.status}): ${result.body.slice(0, 300)}`, command: result };
125-
const state = result.body.trim();
126-
if (state === "succeeded") return { state: "succeeded", command: result };
127-
if (state === "running") return { state: "running", command: result };
128-
return { state: "failed", detail: state === "missing" ? "The run supervisor disappeared before recording a result." : "The supervised agent process exited unsuccessfully.", command: result };
121+
const inspect = `sudo systemctl show ${shellAtom(vm)} --property=LoadState,ActiveState,SubState,Result,ExecMainCode,ExecMainStatus`;
122+
let response: BackendCommandResult;
123+
try { response = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`); }
124+
catch { return { state: "running", detail: "VM inspection is temporarily unavailable" }; }
125+
// systemctl can return nonzero for a missing unit, but still emits LoadState.
126+
if (!response.ok && !response.body.includes("LoadState=not-found")) return ![404, 410].includes(response.status)
127+
? { state: "running", detail: `VM inspection is temporarily unavailable (${response.status})` }
128+
: { state: "failed", detail: `The run-owned VM is unavailable (${response.status})` };
129+
const properties = Object.fromEntries(response.body.split("\n").filter(line => /^[A-Za-z]+=/.test(line)).map(line => { const index = line.indexOf("="); return [line.slice(0, index), line.slice(index + 1).trim()]; }));
130+
const label = (name: string) => /^[a-z-]{1,64}$/.test(properties[name] ?? "") ? properties[name] : "";
131+
const number = (name: string) => /^\d{1,10}$/.test(properties[name] ?? "") ? Number(properties[name]) : null;
132+
const systemd = { loadState: label("LoadState"), activeState: label("ActiveState"), subState: label("SubState"), result: label("Result"), execMainCode: number("ExecMainCode"), execMainStatus: number("ExecMainStatus") };
133+
if (!systemd.loadState) return { state: "running", detail: "VM inspection returned incomplete supervisor metadata" };
134+
if (systemd.loadState !== "loaded") return { state: "failed", systemd, detail: "The run supervisor disappeared before recording a result." };
135+
if (["running", "start"].includes(systemd.subState) || ["activating", "deactivating"].includes(systemd.activeState)) return { state: "running", systemd };
136+
if (!systemd.activeState || !systemd.subState || !systemd.result || systemd.execMainStatus === null || systemd.execMainCode === null) return { state: "running", detail: "VM inspection returned incomplete supervisor metadata" };
137+
if (systemd.result === "success" && systemd.execMainStatus === 0) return { state: "succeeded", systemd };
138+
return { state: "failed", systemd, detail: `The supervised agent process exited unsuccessfully (Result=${systemd.result}, ExecMainCode=${systemd.execMainCode}, ExecMainStatus=${systemd.execMainStatus}).` };
139+
}
140+
141+
async readHarnessLog(handle: RunHandle): Promise<string> {
142+
// Read the first bounded bytes: starting in the middle of a credential could evade redaction.
143+
// Old VMs have only the combined log.
144+
const remote = `if [ -f /tmp/factorize.stderr ]; then head -c ${HARNESS_LOG_LIMIT} /tmp/factorize.stderr; else head -c ${HARNESS_LOG_LIMIT} /tmp/factorize.log; fi`;
145+
const response = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`);
146+
if (!response.ok) throw new Error(`Harness log collection failed (${response.status})`);
147+
// Drop a possibly cut final line before redaction. Never retain a partial credential.
148+
const text = new TextEncoder().encode(response.body).length >= HARNESS_LOG_LIMIT
149+
? response.body.slice(0, response.body.lastIndexOf("\n") + 1) + "\n[Harness log truncated]\n" : response.body;
150+
return safeDiagnosticText(text, HARNESS_LOG_LIMIT);
129151
}
130152

131153
async readOutput(handle: RunHandle): Promise<string | null> {

‎packages/app/src/execution.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export interface LaunchRequest {
2020
export interface RunHandle { backendKind: string; id: string; }
2121

2222
export interface ExecutionObservation {
23+
systemd?: import("./harness-diagnostics").ExecutionDiagnostics["systemd"];
2324
state: ExecutionState;
2425
detail?: string;
2526
command?: BackendCommandResult;

‎packages/app/src/flow-service.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,9 @@ export class ApiService {
8686
async listTailIntegrations() { await this.authorize("flows:read"); return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails(); }
8787
async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query); }
8888
async search(query: string) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query); }
89-
async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); return run; }
89+
async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); run.execution_diagnostics ??= null; run.harness_log = (await new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId)).find(item => item.kind === "terminal_log") ?? null; return run; }
9090
async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); }
91-
async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; }
91+
async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, execution: run.execution_diagnostics, harnessLog: run.harness_log, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; }
9292
async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; }
9393
killRun(runId: string) { return this.stopRun(runId); }
9494
async listJobs() { await this.authorize("flows:read"); return Promise.all((await this.jobs().list()).map(job => this.presentJob(job))); }
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import type { ExecutionObservation } from "./execution";
2+
import { scrubSession } from "./session-scrubber";
3+
4+
export const HARNESS_LOG_LIMIT = 64 * 1024;
5+
export interface ExecutionDiagnostics {
6+
state: "succeeded" | "failed" | "stopped";
7+
detail: string | null;
8+
systemd: { loadState: string; activeState: string; subState: string; result: string; execMainCode: number | null; execMainStatus: number | null } | null;
9+
}
10+
11+
/** Redact before truncation so a cut cannot expose part of a recognized credential. */
12+
export function safeDiagnosticText(value: string, limit = 2048): string {
13+
const withoutAssignments = value.replace(/^.*["']?(?:[\w-]*(?:token|secret|password|passwd|api[_-]?key|authorization|cookie))["']?\s*[:=].*$/gim, "[REDACTED]");
14+
const safe = scrubSession(withoutAssignments)
15+
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*/gi, "[REDACTED]")
16+
.replace(/\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD)\s*=\s*[^\r\n]+/g, "[REDACTED]")
17+
.replace(/([?&](?:token|key|signature|credential|password|secret|x-amz-[\w-]+)=)[^&#\s]+/gi, "$1[REDACTED]");
18+
return new TextDecoder().decode(new TextEncoder().encode(safe).slice(0, limit)).replace(/\uFFFD$/, "");
19+
}
20+
21+
export function terminalDiagnostics(observation: ExecutionObservation): ExecutionDiagnostics {
22+
return {
23+
state: observation.state === "succeeded" ? "succeeded" : observation.state === "stopped" ? "stopped" : "failed",
24+
detail: observation.detail ? safeDiagnosticText(observation.detail) : null,
25+
systemd: observation.systemd ?? null,
26+
};
27+
}

‎packages/app/src/postgres/artifact-repository.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export class ArtifactRepository {
1111
await client.query(`INSERT INTO app.run_artifacts(tenant_id,run_id,id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state)
1212
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
1313
ON CONFLICT (tenant_id,object_key) DO UPDATE SET byte_size=excluded.byte_size,sha256=excluded.sha256,state=excluded.state`, [this.tenantId, input.runId, id, input.kind, input.objectKey, input.provider, input.format, input.formatVersion ?? null, input.cliVersion ?? null, input.nativeSessionId ?? null, input.byteSize, input.sha256, input.state ?? "stored"]);
14-
await client.query("UPDATE app.runs SET artifact_state='stored',artifact_error=NULL,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]);
14+
await client.query("UPDATE app.runs SET artifact_state='stored',updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]);
1515
});
1616
}
1717
async list(runId: string) { return (await this.database.pool.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; }

0 commit comments

Comments
 (0)