From b1051f0ab48012464a6ac26e8e5ef4181b2f09c2 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 5 Nov 2026 18:57:46 +0000 Subject: [PATCH] Require structured results for agent runs --- packages/api-client/src/schema.d.ts | 199 +++++-- .../0026_structured_job_results.sql | 6 + packages/api/src/agent-driver.ts | 3 +- packages/api/src/api-contract.ts | 7 +- packages/api/src/artifact-upload.ts | 21 +- packages/api/src/artifacts.ts | 2 +- packages/api/src/exe-vm-backend.ts | 40 +- packages/api/src/execution.ts | 1 + packages/api/src/flow-service.ts | 12 +- packages/api/src/job-result.ts | 24 + .../api/src/postgres/automation-scheduler.ts | 3 +- packages/api/src/postgres/job-repository.ts | 4 +- packages/api/src/postgres/run-repository.ts | 15 +- packages/api/src/postgres/run-scheduler.ts | 35 +- packages/api/src/postgres/schema.ts | 2 +- packages/api/src/protected-api.ts | 3 +- packages/api/src/run-read-contracts.ts | 2 + packages/api/test/api-boundary.test.ts | 3 +- packages/api/test/api-contract.test.ts | 6 +- packages/api/test/artifact-upload.test.ts | 5 + packages/api/test/job-result.test.ts | 17 + packages/api/test/run-finalization.test.ts | 33 ++ .../app/src/features/runs/expanded-detail.tsx | 7 +- packages/docs/llms-full.txt | 2 + packages/docs/openapi.yaml | 538 +++++++++++++++--- packages/docs/work/results.mdx | 2 + 26 files changed, 846 insertions(+), 146 deletions(-) create mode 100644 packages/api/migrations/0026_structured_job_results.sql create mode 100644 packages/api/src/job-result.ts create mode 100644 packages/api/test/job-result.test.ts diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 5f7cd2c7..95b3b0fd 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1496,6 +1496,28 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/runs/{runId}/artifacts/{artifactId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Download a retained run artifact + * @description Requires the runs:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_runs_runId_artifacts_artifactId"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/runs/{runId}/trace-pages": { parameters: { query?: never; @@ -1918,21 +1940,85 @@ export interface components { }; RunDetail: { id: string; - state: string; - /** @description Live file generation; clients reset trace pagination when it changes. */ - trace_generation?: string | null; - trace_projection?: components["schemas"]["TraceProjection"]; - trace_sources?: components["schemas"]["TraceSources"]; - execution_diagnostics: components["schemas"]["ExecutionDiagnostics"]; - harness_log: components["schemas"]["HarnessLog"]; - /** @description Secondary artifact or cleanup error; does not replace execution_diagnostics */ - artifact_error?: string | null; - /** @description Current job name, included so run content does not require a separate job request. */ + job_id: string; + project_id?: string; + project_name?: string; job_name: string; + issue_id: string; + issue_url: string | null; + issue_title: string; + run_name: string; + agent_name: string; + workspace_name: string; + agent_kind: string; + /** @enum {string} */ + state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; + provider: string; + backend_kind: string; + capabilities: string[]; + destination_url: string | null; + /** @enum {string} */ + artifact_state: "pending" | "collecting" | "stored" | "partial" | "failed"; + artifact_error: string | null; + created_at: string; + updated_at: string; + started_at: string | null; + failure_source: ("system" | "agent") | null; + agent_error: { + reason: string; + reported_at: string; + reporter: { + user_id: string; + /** @enum {string} */ + kind: "api_key" | "oauth" | "session"; + id: string; + }; + } | null; + elapsed_time?: ({ + duration: number; + } | { + low: number; + high: number; + }) | null; + job_result: { + /** @enum {string} */ + status: "succeeded" | "failed"; + summary?: string; + reason?: string; + outputs?: { + [key: string]: unknown; + }; + } | null; + run_artifacts: { + id: string; + kind: string; + provider: string; + format: string; + byte_size: number; + sha256: string; + state: string; + media_type: string | null; + created_at: string; + }[]; + tenant_id: string; + invocation_id: string; + execution_handle: { + backendKind: string; + id: string; + } | null; + execution_backend_kind: string; + execution_capabilities: string[]; + claim_released: boolean; + vm_cleanup_attempt: number; + cleanup_next_at: string | null; + vm_cleanup_complete: boolean; prompt: string; context: { [key: string]: unknown; }; + occurrence: { + [key: string]: unknown; + } | null; invocation: { id: string; source: string; @@ -1946,33 +2032,54 @@ export interface components { } | null; created_at: string; }; + invocation_source: string; + invocation_claim_key: string; + invocation_trigger_id: string | null; + invocation_created_at: string; activity: { action: string; detail: string; created_at: string; }[]; - tenant_id?: string; - invocation_id?: string; - execution_handle?: { - backendKind: string; - id: string; + execution_diagnostics: { + [key: string]: unknown; } | null; - execution_backend_kind?: string; - execution_capabilities?: string[]; - claim_released?: boolean; - vm_cleanup_attempt?: number; - vm_cleanup_complete?: boolean; - /** Format: date-time */ - cleanup_next_at?: string | null; - occurrence?: { + trace_sources: { + primary: { + /** @enum {string} */ + kind: "execution_stream" | "native_session"; + path: string; + /** @constant */ + mediaType: "application/x-ndjson"; + /** @enum {string} */ + provider: "codex" | "claude" | "pi"; + formatVersion?: string; + cliVersion?: string; + harnessVersion?: string; + discoverCommand?: string; + }; + nativeSession?: { + /** @enum {string} */ + kind: "execution_stream" | "native_session"; + path: string; + /** @constant */ + mediaType: "application/x-ndjson"; + /** @enum {string} */ + provider: "codex" | "claude" | "pi"; + formatVersion?: string; + cliVersion?: string; + harnessVersion?: string; + discoverCommand?: string; + }; + } | null; + trace_projection: { [key: string]: unknown; } | null; - invocation_source?: string; - invocation_claim_key?: string; - invocation_trigger_id?: string | null; - /** Format: date-time */ - invocation_created_at?: string; - } & WithRequired; + trace_generation: string | null; + harness_log: { + [key: string]: unknown; + } | null; + }; RunDiagnostics: { runId: string; jobId: string; @@ -6276,6 +6383,37 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_runs_runId_artifacts_artifactId: { + parameters: { + query?: never; + header?: never; + path: { + runId: string; + artifactId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Authorized artifact bytes */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/octet-stream": string; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_runs_runId_trace_pages: { parameters: { query?: { @@ -6618,6 +6756,3 @@ export interface operations { }; }; } -type WithRequired = T & { - [P in K]-?: T[P]; -}; diff --git a/packages/api/migrations/0026_structured_job_results.sql b/packages/api/migrations/0026_structured_job_results.sql new file mode 100644 index 00000000..39276539 --- /dev/null +++ b/packages/api/migrations/0026_structured_job_results.sql @@ -0,0 +1,6 @@ +ALTER TABLE app.runs ADD COLUMN result_protocol_version integer NOT NULL DEFAULT 0; +ALTER TABLE app.runs ADD COLUMN job_result jsonb; +ALTER TABLE app.runs ADD CONSTRAINT runs_result_protocol_version_check CHECK (result_protocol_version IN (0,1)); +ALTER TABLE app.run_artifacts DROP CONSTRAINT IF EXISTS run_artifacts_kind_check; +ALTER TABLE app.run_artifacts ADD CONSTRAINT run_artifacts_kind_check CHECK (kind IN ('execution_stream','native_session','related_session','terminal_log','manifest','job_file')); +INSERT INTO app.schema_migrations(version) VALUES ('0026_structured_job_results') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/agent-driver.ts b/packages/api/src/agent-driver.ts index 241584c6..5bc873df 100644 --- a/packages/api/src/agent-driver.ts +++ b/packages/api/src/agent-driver.ts @@ -1,6 +1,7 @@ import { CLAUDE_STREAM_HARNESS } from "./claude-stream"; import { PI_CLI_VERSION, PI_SESSION_VERSION } from "./pi-trace"; import type { TraceSources } from "./trace-source"; +import { JOB_RESULT_PATH } from "./job-result"; export type AgentKind = "codex" | "claude" | "pi"; export interface AgentConfiguration { model?: string; effort?: string; } @@ -70,7 +71,7 @@ class PiDriver implements AgentDriver { const drivers: Record = { codex: new CodexDriver(), claude: new ClaudeDriver(), pi: new PiDriver() }; export function agentDriver(kind: AgentKind): AgentDriver { const driver = drivers[kind]; - return { kind, launch(runId, config) { const spec = driver.launch(runId, config); return { ...spec, traceSources: driverTraceSources(kind, spec) }; } }; + return { kind, launch(runId, config) { const spec = driver.launch(runId, config); return { ...spec, env: { ...spec.env, FACTORIZE_RESULT_PATH: JOB_RESULT_PATH }, traceSources: driverTraceSources(kind, spec) }; } }; } /** Compatibility for drivers and historical runs that only declare native sessions. */ diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 2581278b..89028036 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -3,7 +3,7 @@ import { searchResponse } from "./search-contracts"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; import { exeConnection, integrationStatus, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; import { triggerAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; -import { runSummaryResponse, runPageResponse, runStatusResponse, revisionTracePage, revisionTraceQuery } from "./run-read-contracts"; +import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery } from "./run-read-contracts"; import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts"; import { projectInput, projectListQuery, projectResponse } from "./project-contracts"; import { z } from "zod"; @@ -867,6 +867,10 @@ export const API_ROUTES: RouteContract[] = [ description: "No prompt decryption, invocation context, artifacts, activity or diagnostics assembly. Continue polling terminal runs while finalizing is true. trace_revision changes on generation transition or canonical projection/replay; live appends retain the revision. Full detail remains available at GET /runs/{runId}.", responses: { "200": { description: "Status", content: { "application/json": { schema: jsonSchema(runStatusResponse, "output") } } } }, }, (service, { params }) => service.getRunStatus(params.runId), { parameters: z.object({ runId: z.guid() }) }), + route("GET", "/api/v1/runs/{runId}/artifacts/{artifactId}", "runs:read", { + summary: "Download a retained run artifact", + responses: { "200": { description: "Authorized artifact bytes", content: { "application/octet-stream": { schema: { type: "string", format: "binary" } } } } }, + }, (service, { params }) => service.downloadRunArtifact(params.runId, params.artifactId), { parameters: z.object({ runId: z.guid(), artifactId: z.guid() }) }), route("GET", "/api/v1/runs/{runId}/trace-pages", "runs:read", { summary: "Get revision-bound trace page", description: "First request omits revision and uses after=0. Subsequent requests supply the returned revision. A changed generation or canonical projection returns reset=true and events from zero in the new revision, from one database snapshot. Discard all cached old pages before merging the response. nextCursor=null means caught up, not finalized; poll after the last sequence while active/finalizing. Legacy GET /trace remains unchanged.", @@ -1099,6 +1103,7 @@ export function generateOpenApi() { ...document.components.schemas, Run: { ...jsonSchema(runSummaryResponse, "output"), additionalProperties: true }, RunPage: jsonSchema(runPageResponse, "output"), + RunDetail: jsonSchema(fullRunResponse, "output"), ...Object.fromEntries( Object.entries(namedBodies).map(([name, schema]) => [ name, diff --git a/packages/api/src/artifact-upload.ts b/packages/api/src/artifact-upload.ts index 50749f8f..aa4fdacb 100644 --- a/packages/api/src/artifact-upload.ts +++ b/packages/api/src/artifact-upload.ts @@ -12,7 +12,8 @@ export interface ArtifactUploadGrant { path: string; contentType: string; provider: "codex" | "claude" | "pi"; - format: "jsonl"; + format: "jsonl" | "file"; + artifactType?: "job_file"; nativeSessionId?: string; sourceKind?: "execution_stream" | "native_session"; sourcePath?: string; @@ -47,6 +48,7 @@ export async function readArtifactUploadGrant(token: string, secret: string, now const value = JSON.parse(fromB64url(payload)) as ArtifactUploadGrant; if (!value.tenantId || !value.runId || !value.path || !value.contentType || !Number.isSafeInteger(value.expiresAt) || value.expiresAt < now) return null; if (value.sourceKind && !["execution_stream", "native_session"].includes(value.sourceKind)) return null; + if (value.artifactType === "job_file" && (!value.path || value.path.startsWith("/") || value.path.split("/").some(part => !part || part === "." || part === "..") || /[\\\\\r\n\0]/.test(value.path))) return null; artifactKey(value.tenantId, value.runId, value.path); return value; } catch { return null; } @@ -62,20 +64,25 @@ export async function artifactUpload(request: Request, env: Env, token: string): const sha256 = request.headers.get("X-Artifact-SHA256")?.toLowerCase() ?? "", size = Number(request.headers.get("Content-Length") ?? NaN); if (!/^[0-9a-f]{64}$/.test(sha256) || !Number.isSafeInteger(size) || size < 0) return new Response("Artifact checksum and size are required", { status: 400 }); if (!request.body && size !== 0) return new Response("Artifact body is required", { status: 400 }); - if (size > 256 * 1024 * 1024) return new Response("Artifact exceeds the 256 MiB limit", { status: 413 }); + if (grant.artifactType === "job_file" ? size > 10 * 1024 * 1024 : size > 256 * 1024 * 1024) return new Response(grant.artifactType === "job_file" ? "Job file exceeds the 10 MiB limit" : "Artifact exceeds the 256 MiB limit", { status: 413 }); const suppliedType = request.headers.get("Content-Type")?.split(";", 1)[0]?.trim().toLowerCase(); if (suppliedType !== grant.contentType.toLowerCase()) return new Response("Artifact content type does not match the grant", { status: 400 }); if ((grant.sourceKind === "execution_stream" || grant.primary === true) && grant.traceGeneration === undefined) return new Response("Terminal trace generation is required", { status: 400 }); // Content-addressed stream keys preserve the exact terminal snapshot across retries. - const key = artifactKey(grant.tenantId, grant.runId, grant.sourceKind === "execution_stream" ? `trace/${sha256}.jsonl` : `native/${sha256}.jsonl`); + const key = artifactKey(grant.tenantId, grant.runId, grant.artifactType === "job_file" ? `job/${grant.path}` : grant.sourceKind === "execution_stream" ? `trace/${sha256}.jsonl` : `native/${sha256}.jsonl`); const repository = new ArtifactRepository(databaseFor(env), grant.tenantId); const existing = await repository.list(grant.runId); + if (grant.artifactType === "job_file") { + const total = existing.filter(item => item.kind === "job_file" && item.state === "stored").reduce((sum, item) => sum + Number(item.byte_size), 0); + const prior = existing.find(item => item.kind === "job_file" && item.source_path === grant.path); + if (total - Number(prior?.byte_size ?? 0) + size > 50 * 1024 * 1024) return new Response("Job output directory exceeds the 50 MiB total limit", { status: 413 }); + } const terminal = existing.find(item => item.kind === "execution_stream" && item.state === "stored"); if (grant.sourceKind === "execution_stream" && terminal && terminal.sha256 !== sha256) return new Response("Terminal trace stream is immutable", { status: 409 }); const retainedStream = grant.sourceKind === "execution_stream" && terminal; if (retainedStream) await request.body?.cancel(); const object = retainedStream ? null : await env.RUN_ARTIFACTS.put(key, request.body ?? new Uint8Array(), { httpMetadata: { contentType: grant.contentType }, customMetadata: { tenantId: grant.tenantId, runId: grant.runId, generation: grant.traceGeneration ?? "", sourcePath: grant.sourcePath ?? "" }, sha256 }); - const record = (client: DatabaseClient) => repository.record({ runId: grant.runId, kind: grant.sourceKind ?? "native_session", sourceGeneration: grant.traceGeneration, sourcePath: grant.sourcePath, mediaType: grant.contentType, harnessVersion: grant.harnessVersion, formatVersion: grant.formatVersion, cliVersion: grant.cliVersion, objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }, client); + const record = (client: DatabaseClient) => repository.record({ runId: grant.runId, kind: grant.artifactType ?? grant.sourceKind ?? "native_session", sourceGeneration: grant.traceGeneration, sourcePath: grant.artifactType === "job_file" ? grant.path : grant.sourcePath, mediaType: grant.contentType, harnessVersion: grant.harnessVersion, formatVersion: grant.formatVersion, cliVersion: grant.cliVersion, objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }, client); const stored = await env.RUN_ARTIFACTS.get(key); if (!stored) return new Response("Artifact disappeared after upload", { status: 502 }); if (stored.size !== size) { await stored.body.cancel(); return new Response("Retained artifact size does not match upload receipt", { status: 422 }); } @@ -84,7 +91,7 @@ export async function artifactUpload(request: Request, env: Env, token: string): // Shares the lock with incremental ingestion: terminal projection wins atomically. const run = (await client.query("SELECT id,trace_sources FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [grant.tenantId, grant.runId])).rows[0]; if (!run) return "Run not found"; - if (grant.sourceKind === "execution_stream" || grant.primary === true) { + if (grant.artifactType !== "job_file" && (grant.sourceKind === "execution_stream" || grant.primary === true)) { const primary = run.trace_sources?.primary; if (primary && (primary.kind !== (grant.sourceKind ?? "native_session") || (primary.provider && primary.provider !== grant.provider) || (primary.path && primary.path !== grant.sourcePath))) return "Terminal trace source mismatch"; const cursor = (await client.query("SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [grant.tenantId, grant.runId])).rows[0]; @@ -94,8 +101,8 @@ export async function artifactUpload(request: Request, env: Env, token: string): const terminal = artifacts.find(item => item.kind === "execution_stream" && item.state === "stored"); if (grant.sourceKind === "execution_stream" && terminal && terminal.sha256 !== sha256) return "Terminal trace stream is immutable"; const native = artifacts.find(item => item.kind === "native_session" && item.state === "stored"); - if (grant.sourceKind !== "execution_stream" && native && native.sha256 !== sha256) return "Terminal native session is immutable"; - const primary = grant.sourceKind === "execution_stream" || (grant.primary !== false && !terminal && run?.trace_sources?.primary?.kind !== "execution_stream"); + if (grant.artifactType !== "job_file" && grant.sourceKind !== "execution_stream" && native && native.sha256 !== sha256) return "Terminal native session is immutable"; + const primary = grant.artifactType !== "job_file" && (grant.sourceKind === "execution_stream" || (grant.primary !== false && !terminal && run?.trace_sources?.primary?.kind !== "execution_stream")); const projection = (await client.query("SELECT source_kind,artifact_sha256,parser_version FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [grant.tenantId, grant.runId])).rows[0]; await record(client); // Keep the immutable receipt even when projection fails. A retry projects diff --git a/packages/api/src/artifacts.ts b/packages/api/src/artifacts.ts index ab26bfd9..00f5873f 100644 --- a/packages/api/src/artifacts.ts +++ b/packages/api/src/artifacts.ts @@ -1,4 +1,4 @@ -export type ArtifactKind = "execution_stream" | "native_session" | "related_session" | "terminal_log" | "manifest"; +export type ArtifactKind = "execution_stream" | "native_session" | "related_session" | "terminal_log" | "manifest" | "job_file"; export type ArtifactState = "pending" | "collecting" | "stored" | "partial" | "failed"; export interface RunArtifact { diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index 6b1c32fa..82c8bf8a 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -1,5 +1,5 @@ import { sourceCommand, validateTraceSources } from "./trace-source"; -import type { ArtifactCollectionRequest, TraceChunkCollectionRequest } from "./execution"; +import type { ArtifactCollectionRequest, JobFileCollectionRequest, TraceChunkCollectionRequest } from "./execution"; import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; import { base64 } from "./crypto"; import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; @@ -166,6 +166,7 @@ export class ExeVmBackend implements ExecutionBackend { "cd /home/exedev/workspace", ...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []), `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, + "sudo install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job", `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=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`, "echo started", ].join("; "); @@ -229,6 +230,43 @@ export class ExeVmBackend implements ExecutionBackend { return result.ok ? result.body : null; } + /** null means the protocol file is confirmed absent; command errors remain retryable. */ + async readJobResult(handle: RunHandle): Promise { + const remote = "if [ -f /home/exedev/.factorize-job/results.json ]; then size=$(wc -c < /home/exedev/.factorize-job/results.json); if [ \"$size\" -gt 65536 ]; then printf OVERSIZE; else base64 -w0 /home/exedev/.factorize-job/results.json; fi; else printf MISSING; fi"; + const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); + if (!result.ok) throw new Error(`Structured job result collection failed (${result.status})`); + if (result.body.trim() === "MISSING") return null; + if (result.body.trim() === "OVERSIZE") return "OVERSIZE"; + const encoded = result.body.trim(); + if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) throw new Error("Structured job result transport returned invalid base64"); + try { return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(atob(encoded), c => c.charCodeAt(0))); } + catch { throw new Error("Structured job result transport returned invalid UTF-8"); } + } + + async listJobFiles(handle: RunHandle): Promise { + const remote = "find /home/exedev/.factorize-job -mindepth 1 -type f ! -name results.json -printf '%P\\t%s\\n'"; + const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); + if (!result.ok) throw new Error(`Job output directory collection failed (${result.status})`); + const paths: string[] = []; let total = 0; + for (const line of result.body.split("\n").filter(Boolean)) { + const match = /^([^\t\r\0]+)\t(\d+)$/.exec(line); + if (!match || match[1].startsWith("/") || match[1].split("/").some(part => !part || part === "." || part === "..") || /[\\\\\r\n]/.test(match[1])) throw new Error("Job output directory contains an unsafe path"); + const size = Number(match[2]); + if (!Number.isSafeInteger(size) || size > 10 * 1024 * 1024) throw new Error("A job output file exceeds the 10 MiB per-file limit"); + total += size; if (total > 50 * 1024 * 1024) throw new Error("Job output directory exceeds the 50 MiB total limit"); + paths.push(match[1]); + } + if (paths.length > 100) throw new Error("Job output directory exceeds the 100 file limit"); + return paths; + } + + async collectJobFile(handle: RunHandle, request: JobFileCollectionRequest) { + const file = `/home/exedev/.factorize-job/${request.path}`; + const remote = `set -eu; file=${shellAtom(file)}; test -f "$file"; test ! -L "$file"; real=$(realpath -- "$file"); case "$real" in /home/exedev/.factorize-job/*) ;; *) exit 41;; esac; size=$(wc -c < "$file" | tr -d ' '); test "$size" -le 10485760; sha=$(sha256sum "$file" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H 'Content-Type: application/octet-stream' -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$file" ${shellAtom(request.uploadUrl)}`; + const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); + return { ok: result.ok, detail: result.ok ? undefined : `Job file upload failed (${result.status})`, command: result }; + } + async collectArtifact(handle: RunHandle, request: ArtifactCollectionRequest) { const remote = `set -eu; file=$(${request.source ? sourceCommand(request.source) : request.discoverCommand}); test -n "$file"; test -f "$file"; snapshot=$(mktemp); trap 'rm -f "$snapshot"' EXIT; cp "$file" "$snapshot"; size=$(wc -c < "$snapshot" | tr -d ' '); sha=$(sha256sum "$snapshot" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$snapshot" ${shellAtom(request.uploadUrl)}`; const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 11e791d9..2bf49631 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -41,6 +41,7 @@ export interface PromptDeliveryReceipt { command?: BackendCommandResult; } export interface ArtifactCollectionRequest { uploadUrl: string; contentType: string; source?: TraceSource; discoverCommand?: string; } +export interface JobFileCollectionRequest { path: string; uploadUrl: string; } export interface TraceChunkCollectionRequest { uploadUrl: string; source?: TraceSource; discoverCommand?: string; generation: string | null; offset: number; previousHash: string; } export interface ArtifactCollectionReceipt { ok: boolean; detail?: string; command?: BackendCommandResult; } diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 4755a337..322830ba 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -211,9 +211,19 @@ export class ApiService { job_name: run.job_name, prompt: run.prompt, context: run.context, occurrence: run.occurrence, invocation: run.invocation, invocation_source: run.invocation_source, invocation_claim_key: run.invocation_claim_key, invocation_trigger_id: run.invocation_trigger_id, invocation_created_at: run.invocation_created_at, activity: run.activity, execution_diagnostics: run.execution_diagnostics, trace_sources: run.trace_sources, - trace_projection: run.trace_projection, trace_generation: run.trace_generation, harness_log: run.harness_log }))); + trace_projection: run.trace_projection, trace_generation: run.trace_generation, harness_log: run.harness_log, + job_result: run.job_result ?? null, + run_artifacts: artifacts.filter(item => !["execution_stream", "native_session"].includes(item.kind)).map(item => ({ id: item.id, kind: item.kind, provider: String(item.provider ?? ""), format: String(item.format ?? ""), byte_size: Number(item.byte_size), sha256: String(item.sha256 ?? ""), state: String(item.state ?? ""), media_type: item.media_type ?? null, created_at: item.created_at instanceof Date ? item.created_at.toISOString() : String(item.created_at ?? "") })), }))); } 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); } + async downloadRunArtifact(runId: string, artifactId: string): Promise { + await this.authorize("runs:read"); + const row = (await databaseFor(this.env).pool.query<{ object_key: string; format: string; id: string }>("SELECT a.object_key,a.format,a.id FROM app.run_artifacts a JOIN app.runs r ON r.tenant_id=a.tenant_id AND r.id=a.run_id WHERE a.tenant_id=$1 AND a.run_id=$2 AND a.id=$3 AND a.state='stored'", [this.auth.tenantId, runId, artifactId])).rows[0]; + if (!row) throw new ServiceError(404, "not_found", "Artifact not found"); + const object = await this.env.RUN_ARTIFACTS?.get(row.object_key); + if (!object) throw new ServiceError(404, "not_found", "Artifact bytes are unavailable"); + return new Response(object.body, { headers: { "Content-Type": "application/octet-stream", "Content-Disposition": `attachment; filename="run-artifact-${row.id}"`, "Cache-Control": "private, no-store" } }); + } async getRunDiagnostics(runId: string) { const run = await this.getRun(runId), database = databaseFor(this.env); const [evidence, artifacts] = await Promise.all([ diff --git a/packages/api/src/job-result.ts b/packages/api/src/job-result.ts new file mode 100644 index 00000000..3e0157fb --- /dev/null +++ b/packages/api/src/job-result.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; + +/** Maximum UTF-8 bytes accepted from the execution VM. */ +export const JOB_RESULT_LIMIT = 64 * 1024; +export const JOB_RESULT_PATH = "/home/exedev/.factorize-job/results.json"; + +export const jobResultEnvelope = z.object({ + status: z.enum(["succeeded", "failed"]), + summary: z.string().max(10_000).optional(), + outputs: z.record(z.string(), z.unknown()).optional(), + reason: z.string().min(1).max(10_000).optional(), +}).strict().superRefine((value, context) => { + if (value.status === "failed" && !value.reason?.trim()) context.addIssue({ code: "custom", path: ["reason"], message: "A failed result requires a reason" }); +}); + +export type JobResult = z.infer; +export function parseJobResult(input: string): JobResult { + if (new TextEncoder().encode(input).byteLength > JOB_RESULT_LIMIT) throw new Error("Job result exceeds the 64 KiB limit"); + let value: unknown; + try { value = JSON.parse(input); } catch { throw new Error("Job result is not valid JSON"); } + return jobResultEnvelope.parse(value); +} + +export const JOB_RESULT_INSTRUCTIONS = `\n\n## Required run result\nWrite one JSON object to the absolute path in FACTORIZE_RESULT_PATH before exiting. Use {"status":"succeeded"} when the task is complete, or {"status":"failed","reason":"..."} when it is not. You may include a concise summary and an outputs JSON object. Keep the file at most 64 KiB. Put additional files for this run in ~/.factorize-job/; regular files there are retained as run artifacts.`; diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index efafda71..b0ce2cfb 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -58,6 +58,7 @@ export class AutomationScheduler { // scheduler passes cannot cross this ordering boundary. for (;;) { const rows = await this.database.pool.query(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,t.config,r.id source_run_id,r.job_id source_job_id,r.state,r.updated_at + ,r.job_result FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id JOIN app.runs r ON r.tenant_id=t.tenant_id @@ -69,7 +70,7 @@ export class AutomationScheduler { AND d.source_run_id IS NULL ORDER BY r.updated_at LIMIT 100`); if (!rows.rows.length) break; for (const row of rows.rows) { - const context = { sourceRunId: row.source_run_id, sourceJobId: row.source_job_id, state: row.state, completedAt: row.updated_at.toISOString() }, occurrence = { occurredAt: context.completedAt, externalId: `${row.source_run_id}:${row.state}`, metadata: context }; + const context = { sourceRunId: row.source_run_id, sourceJobId: row.source_job_id, state: row.state, completedAt: row.updated_at.toISOString(), outputs: row.job_result?.outputs ?? null }, occurrence = { occurredAt: context.completedAt, externalId: `${row.source_run_id}:${row.state}`, metadata: context }; // Acknowledge after invocation so transient failures remain retryable. // Queue-full is an intentional terminal outcome: no run is queued, so // acknowledging it permits idle triggers to proceed. diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index e27c1cdf..70fd7778 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -154,11 +154,11 @@ export class PostgresJobRepository implements JobRepository { if (!inserted.rowCount) return false; await reserveExecutionSlot(client, this.tenantId, invocation.jobId, run, concurrencyLimit); await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,encrypted_skill_snapshot,run_name,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, run.encryptedSkillSnapshot ?? null, run.runName ?? "", run.createdAt, run.updatedAt]); - await client.query(`INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,run_name,agent_name,workspace_name,agent_kind,state,execution_backend_kind,execution_config,execution_capabilities,created_at,updated_at) + await client.query(`INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,run_name,agent_name,workspace_name,agent_kind,state,execution_backend_kind,execution_config,execution_capabilities,result_protocol_version,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$8,'',j.slug,j.execution_config->>'agentKind',$7, CASE WHEN j.execution_config->>'agentKind'='Amp' THEN 'amp' ELSE 'exe-vm' END, j.execution_config || jsonb_build_object('model',j.model,'effort',j.effort,'tags',j.tags), - CASE WHEN j.execution_config->>'agentKind'='Amp' THEN '["stop"]'::jsonb ELSE '["recovery","stop"]'::jsonb END,$9,$10 + CASE WHEN j.execution_config->>'agentKind'='Amp' THEN '["stop"]'::jsonb ELSE '["recovery","stop"]'::jsonb END,1,$9,$10 FROM app.jobs j WHERE j.tenant_id=$1 AND j.id=$3`, [this.tenantId, run.id, run.jobId, run.invocationId, invocation.source, invocation.claimKey, run.state, run.runName ?? "", run.createdAt, run.updatedAt]); await client.query("INSERT INTO app.wake_hints(key,not_before) VALUES ('global',now()) ON CONFLICT (key) DO UPDATE SET not_before=least(app.wake_hints.not_before,excluded.not_before),updated_at=now()"); diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index c795281e..185a7ed8 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -3,21 +3,22 @@ import { terminalDiagnostics, safeDiagnosticText, type ExecutionDiagnostics } fr import type { ExecutionObservation } from "../execution"; import type { ExecutionState, RunHandle } from "../execution"; import type { Database, DatabaseClient } from "./database"; +import type { JobResult } from "../job-result"; export interface PersistedRun { tenantId: string; id: string; jobId: string; invocationId: string; state: ExecutionState; encryptedPrompt: string; executionConfig: Record; executionHandle: RunHandle | null; traceSources?: TraceSources | null; executionDiagnostics?: ExecutionDiagnostics | null; finalizationAttempt?: number; - backendKind: string; capabilities: string[]; artifactState: string; createdAt: string; updatedAt: string; + backendKind: string; capabilities: string[]; artifactState: string; resultProtocolVersion: number; createdAt: string; updatedAt: string; } interface RunRow { tenant_id: string; id: string; job_id: string; invocation_id: string; state: ExecutionState; encrypted_prompt: string; execution_config: Record; execution_handle: RunHandle | null; execution_backend_kind: string; trace_sources: TraceSources | null; execution_diagnostics: ExecutionDiagnostics | null; vm_cleanup_attempt: number; - execution_capabilities: string[]; artifact_state: string; created_at: Date; updated_at: Date; + execution_capabilities: string[]; artifact_state: string; result_protocol_version: number; created_at: Date; updated_at: Date; } -const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: row.id, jobId: row.job_id, invocationId: row.invocation_id, state: row.state, encryptedPrompt: row.encrypted_prompt, executionConfig: row.execution_config, traceSources: row.trace_sources, executionHandle: row.execution_handle, executionDiagnostics: row.execution_diagnostics, finalizationAttempt: row.vm_cleanup_attempt, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); +const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: row.id, jobId: row.job_id, invocationId: row.invocation_id, state: row.state, encryptedPrompt: row.encrypted_prompt, executionConfig: row.execution_config, traceSources: row.trace_sources, executionHandle: row.execution_handle, executionDiagnostics: row.execution_diagnostics, finalizationAttempt: row.vm_cleanup_attempt, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, resultProtocolVersion: row.result_protocol_version, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); export class RunRepository { constructor(private database: Database) {} @@ -35,7 +36,7 @@ export class RunRepository { ), claimed AS ( UPDATE app.job_runs r SET state='starting',launch_lease_expires_at=now()+interval '5 minutes',updated_at=now() FROM candidate c WHERE r.tenant_id=c.tenant_id AND r.id=c.id RETURNING r.* - ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,c.created_at,c.updated_at + ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,c.created_at,c.updated_at FROM claimed c JOIN app.jobs j ON j.tenant_id=c.tenant_id AND j.id=c.job_id JOIN app.runs x ON x.tenant_id=c.tenant_id AND x.id=c.id`, []); const row = result.rows[0]; if (!row) return null; @@ -45,7 +46,7 @@ export class RunRepository { } async dueForPoll(limit = 40): Promise { - const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,r.created_at,r.updated_at + const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,r.created_at,r.updated_at FROM app.job_runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.runs x ON x.tenant_id=r.tenant_id AND x.id=r.id WHERE r.state IN ('running','blocked','stopping') AND (r.next_poll_at IS NULL OR r.next_poll_at<=now()) ORDER BY r.next_poll_at NULLS FIRST,r.updated_at LIMIT $1`, [limit]); return result.rows.map(mapped); @@ -76,6 +77,10 @@ export class RunRepository { return result.rows[0].execution_diagnostics; } + async recordJobResult(run: PersistedRun, result: JobResult): Promise { + await this.database.pool.query("UPDATE app.runs SET job_result=COALESCE(job_result,$3::jsonb),updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, JSON.stringify(result)]); + } + async recordStopAttempt(run: PersistedRun): Promise { await this.database.pool.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) VALUES ($1,$2,$3,'stop_attempt','Scheduler attempted agent termination')", [run.tenantId, crypto.randomUUID(), run.id]); } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 46dbb3fa..2e564006 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -17,6 +17,7 @@ import { traceMetric } from "../trace-observability"; import { rolloutTraceSources } from "../trace-source"; import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./trace-projection-repository"; import { LiveTraceRepository } from "./live-trace-repository"; +import { JOB_RESULT_INSTRUCTIONS, parseJobResult } from "../job-result"; export class RunScheduler { private runs: RunRepository; @@ -38,10 +39,12 @@ export class RunScheduler { } private async launch(run: PersistedRun) { + if (run.executionConfig.agentKind === "Amp") throw new Error("Amp execution is unavailable for new runs because it cannot deliver the required structured result file. Choose an exe.dev agent integration."); const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); validateTraceSources(sources); - const launched = await backend.launch({ runId: run.id, prompt: await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY), traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } }); + const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); + const launched = await backend.launch({ runId: run.id, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}`, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } @@ -64,6 +67,22 @@ export class RunScheduler { run.executionDiagnostics = diagnostics; let artifactState: "stored" | "partial" | "failed" = "stored"; const errors: string[] = []; + let finalState = diagnostics.state; + let resultFailure: string | undefined; + if (run.resultProtocolVersion === 1 && diagnostics.state !== "failed" && diagnostics.state !== "stopped") { + if (!(backend instanceof ExeVmBackend)) throw new Error("This execution backend cannot collect structured job results"); + let raw: string | null; + try { raw = await backend.readJobResult(run.executionHandle!); } + catch (error) { throw error; } // Collection errors are transient and retried by finalization. + if (raw === null) { finalState = "failed"; resultFailure = "Required structured job result is missing"; } + else { + try { + const result = parseJobResult(raw); + await this.runs.recordJobResult(run, result); + if (result.status === "failed") { finalState = "failed"; resultFailure = result.reason; } + } catch (error) { finalState = "failed"; resultFailure = `Invalid structured job result: ${error instanceof Error ? error.message : "validation failed"}`; } + } + } if (backend instanceof ExeVmBackend) { const artifacts = new ArtifactRepository(this.database, run.tenantId); const stored = await artifacts.list(run.id); @@ -89,6 +108,18 @@ export class RunScheduler { try { errors.push(...await this.finalizePrimary(run, sources.primary)); } catch { errors.push("Retained primary trace projection failed"); } } + if (run.resultProtocolVersion === 1) { + try { + const current = await artifacts.list(run.id); + const retained = new Set(current.filter(item => item.kind === "job_file" && item.state === "stored").map(item => item.source_path)); + for (const path of await backend.listJobFiles(run.executionHandle!)) { + if (retained.has(path)) continue; + const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path, artifactType: "job_file", contentType: "application/octet-stream", provider: run.executionConfig.agentKind, format: "file", expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); + const uploaded = await backend.collectJobFile(run.executionHandle!, { path, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` }); + if (!uploaded.ok) throw new Error(uploaded.detail ?? "Job file upload failed"); + } + } catch { errors.push("Job output file collection or storage failed"); } + } // Retry collection, but do not keep a VM forever for an absent session/log. if (errors.length && (run.finalizationAttempt ?? 0) < 2) { await this.runs.retryFinalization(run, "partial", errors.join("; ")); @@ -103,7 +134,7 @@ export class RunScheduler { return; } } - await this.runs.terminal(run, diagnostics.state, artifactState, errors.join("; ") || undefined, true); + await this.runs.terminal(run, finalState, artifactState, [resultFailure, ...errors].filter(Boolean).join("; ") || undefined, true); } /** Retry projection from retained bytes, without relying on a surviving VM. */ diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 30698e59..22fb9c19 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -71,7 +71,7 @@ export const jobRuns = app.table("job_runs", { export const runs = app.table("runs", { executionConfig: jsonb("execution_config").$type().notNull(), - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]); export const runArtifacts = app.table("run_artifacts", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), id: uuid("id").notNull(), kind: text("kind").$type().notNull(), objectKey: text("object_key").notNull(), provider: text("provider").notNull(), format: text("format").notNull(), formatVersion: text("format_version"), cliVersion: text("cli_version"), nativeSessionId: text("native_session_id"), sourceGeneration: text("source_generation"), sourcePath: text("source_path"), mediaType: text("media_type"), harnessVersion: text("harness_version"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type().notNull(), createdAt: createdAt(), diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 2df05a1b..7678e8a5 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -93,7 +93,8 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (route.authOperation) return timed(await executeAuth(route.authOperation, request, env, body as Record)); service = new ApiService(env, auth!, ctx); const query = route.query?.parse(queryInput(url)); - return timed(Response.json(await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url }), { status: route.status })); + const result = await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url }); + return timed(result instanceof Response ? result : Response.json(result, { status: route.status })); } catch (error) { return timed(errorResponse(error)); } } diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index 0e2a4d25..e12ae53d 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -31,6 +31,8 @@ export const runPageResponse = z.object({ items: z.array(runSummaryResponse), ne const record = z.record(z.string(), z.unknown()); const traceSource = z.object({ kind: z.enum(["execution_stream", "native_session"]), path: z.string(), mediaType: z.literal("application/x-ndjson"), provider: z.enum(["codex", "claude", "pi"]), formatVersion: z.string().optional(), cliVersion: z.string().optional(), harnessVersion: z.string().optional(), discoverCommand: z.string().optional() }); export const fullRunResponse = runSummaryResponse.extend({ + job_result: z.object({ status: z.enum(["succeeded", "failed"]), summary: z.string().optional(), reason: z.string().optional(), outputs: z.record(z.string(), z.unknown()).optional() }).nullable(), + run_artifacts: z.array(z.object({ id: z.string(), kind: z.string(), provider: z.string(), format: z.string(), byte_size: z.number(), sha256: z.string(), state: z.string(), media_type: z.string().nullable(), created_at: z.string() })), tenant_id: z.string(), invocation_id: z.string(), execution_handle: z.object({ backendKind: z.string(), id: z.string() }).nullable(), execution_backend_kind: z.string(), execution_capabilities: z.array(z.string()), diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index 73fe70c2..7cd7909b 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -172,10 +172,11 @@ describe("Worker OpenAPI request/response boundaries", () => { "/api/v1/jobs/{jobId}", 400, ); + await assertResponse(await request("GET", "/api/v1/runs/00000000-0000-4000-8000-000000000001/artifacts/00000000-0000-4000-8000-000000000002", undefined, { auth: { ...auth, scopes: [] } }), "GET", "/api/v1/runs/{runId}/artifacts/{artifactId}", 403); }); it("documents the job name in run detail for clients with only runs:read", async () => { - vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); + vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, job_result: null, run_artifacts: [], prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); const result = await assertResponse(await request("GET", "/api/v1/runs/run-1", undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", "/api/v1/runs/{runId}", 200); expect(result.job_name).toBe("Job name"); }); diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index 13c59116..169b4c5a 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -120,12 +120,14 @@ describe("versioned API contract", () => { const resolved = response.$ref ? openapi.components.responses[response.$ref.split("/").at(-1)] : response; - expect(resolved.content["application/json"].schema).toBeDefined(); + if (!resolved.content) { expect(Number(status)).toBe(204); continue; } + const mediaType = resolved.content["application/json"] ? "application/json" : "application/octet-stream"; + expect(resolved.content[mediaType].schema).toBeDefined(); // Resolve every local reference, including nested references in trace diagnostics. ajv.compile({ $id: `https://factorize.test/contract/${operation.operationId}/${status}`, components: openapi.components, - ...resolved.content["application/json"].schema, + ...resolved.content[mediaType].schema, }); } } diff --git a/packages/api/test/artifact-upload.test.ts b/packages/api/test/artifact-upload.test.ts index b6cc1e92..d936c06d 100644 --- a/packages/api/test/artifact-upload.test.ts +++ b/packages/api/test/artifact-upload.test.ts @@ -12,6 +12,11 @@ describe("artifact upload grants", () => { await expect(readArtifactUploadGrant(`${token}x`, secret)).resolves.toBeNull(); }); + it("rejects traversal paths in job-file grants", async () => { + const token = await issueArtifactUploadGrant({ ...grant, path: "../outside", artifactType: "job_file", format: "file" }, secret); + await expect(readArtifactUploadGrant(token, secret)).resolves.toBeNull(); + }); + it("streams the request into its deterministic object key", async () => { const put = vi.fn(async (_key, body) => ({ httpEtag: "etag", size: 7, body })); const token = await issueArtifactUploadGrant(grant, secret); diff --git a/packages/api/test/job-result.test.ts b/packages/api/test/job-result.test.ts new file mode 100644 index 00000000..25f56dbf --- /dev/null +++ b/packages/api/test/job-result.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { JOB_RESULT_LIMIT, parseJobResult } from "../src/job-result"; + +describe("structured job result protocol", () => { + it("accepts succeeded results with arbitrary JSON outputs", () => { + expect(parseJobResult('{"status":"succeeded","summary":"done","outputs":{"count":2,"nested":{"ok":true}}}')) + .toEqual({ status: "succeeded", summary: "done", outputs: { count: 2, nested: { ok: true } } }); + }); + it("requires a failure reason and rejects unknown envelope fields", () => { + expect(() => parseJobResult('{"status":"failed"}')).toThrow(); + expect(() => parseJobResult('{"status":"succeeded","log":"done"}')).toThrow(); + }); + it("rejects invalid JSON and enforces the byte bound", () => { + expect(() => parseJobResult("{" )).toThrow(); + expect(() => parseJobResult(" ".repeat(JOB_RESULT_LIMIT + 1))).toThrow(/64 KiB/); + }); +}); diff --git a/packages/api/test/run-finalization.test.ts b/packages/api/test/run-finalization.test.ts index 38005b41..75d87d4f 100644 --- a/packages/api/test/run-finalization.test.ts +++ b/packages/api/test/run-finalization.test.ts @@ -59,6 +59,39 @@ describe("durable run finalization", () => { expect(f.stop).toHaveBeenCalledOnce(); expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true); }); + it("requires and persists a valid structured result before marking a new run succeeded", async () => { + const f = fixture(0); f.run.resultProtocolVersion = 1; + vi.spyOn(f.backend, "readJobResult").mockResolvedValue('{"status":"succeeded","summary":"ready","outputs":{"count":3}}'); + vi.spyOn(f.backend, "listJobFiles").mockResolvedValue([]); + const saved = vi.spyOn(RunRepository.prototype, "recordJobResult").mockImplementation(async () => { f.events.push("result"); }); + f.terminal.mockImplementation(async () => { expect(f.events.indexOf("result")).toBeLessThan(f.events.indexOf("cleanup")); }); + await f.scheduler.poll(f.run); + expect(saved).toHaveBeenCalledWith(f.run, { status: "succeeded", summary: "ready", outputs: { count: 3 } }); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true); + }); + it("retains regular job files before VM cleanup", async () => { + const f = fixture(0); f.run.resultProtocolVersion = 1; + Object.assign(f.scheduler.env, { SESSION_SIGNING_SECRET: "signing-secret", APP_ORIGIN: "https://app.example.test" }); + vi.spyOn(f.backend, "readJobResult").mockResolvedValue('{"status":"succeeded"}'); + vi.spyOn(f.backend, "listJobFiles").mockResolvedValue(["reports/summary.txt"]); + vi.spyOn(f.backend, "collectJobFile").mockImplementation(async (_handle, request) => { f.events.push(`job-file:${request.path}`); f.artifacts.push({ kind: "job_file", state: "stored", source_path: request.path }); return { ok: true, detail: undefined, command: { ok: true, status: 200, exitCode: 0, body: "", requestBody: "" } }; }); + vi.spyOn(RunRepository.prototype, "recordJobResult").mockResolvedValue(); + await f.scheduler.poll(f.run); + expect(f.events.indexOf("job-file:reports/summary.txt")).toBeLessThan(f.events.indexOf("cleanup")); + expect(f.artifacts).toContainEqual(expect.objectContaining({ kind: "job_file", source_path: "reports/summary.txt", state: "stored" })); + }); + it.each([ + [null, "Required structured job result is missing"], + ['{"status":"succeeded","outputs":[]}', "Invalid structured job result"], + ['{"status":"failed","reason":"tests failed"}', "tests failed"], + ] as const)("settles absent, invalid, and failed structured results as failed", async (raw, reason) => { + const f = fixture(0); f.run.resultProtocolVersion = 1; + vi.spyOn(f.backend, "readJobResult").mockResolvedValue(raw); + vi.spyOn(f.backend, "listJobFiles").mockResolvedValue([]); + vi.spyOn(RunRepository.prototype, "recordJobResult").mockResolvedValue(); + await f.scheduler.poll(f.run); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", expect.stringContaining(reason), true); + }); it.each(["native", "put"] as const)("bounds %s upload retries without replacing the primary failure", async target => { const f = fixture(); f[target].mockRejectedValue(new Error("Authorization: Bearer sensitive")); diff --git a/packages/app/src/features/runs/expanded-detail.tsx b/packages/app/src/features/runs/expanded-detail.tsx index e18ed2ea..13158a40 100644 --- a/packages/app/src/features/runs/expanded-detail.tsx +++ b/packages/app/src/features/runs/expanded-detail.tsx @@ -3,10 +3,15 @@ import { RunProvenance } from "./provenance"; import { useState } from "react"; import { useQuery } from "@tanstack/react-query"; import { runDetailQuery, diagnosticsQuery } from "./queries"; + export function ExpandedRunDetail({ runId }: { runId: string }) { const [details, setDetails] = useState(false), [diagnostics, setDiagnostics] = useState(false); const run = useQuery({ ...runDetailQuery(runId), enabled: details }), evidence = useQuery({ ...diagnosticsQuery(runId), enabled: diagnostics }); return setDetails(e.currentTarget.open)}>Prompt, context and provenance - {run.isPending &&

Loading run details…

}{run.error &&

{run.error.message}

}{run.data && <>{run.data.agent_error &&

Agent reported error

{(run.data.agent_error as any).reason}

Reported {new Date((run.data.agent_error as any).reported_at).toLocaleString()}

}{run.data.execution_diagnostics?.detail &&

Execution observer diagnostics

{run.data.execution_diagnostics.detail}

}

Prompt

{run.data.prompt}

Activity

    {run.data.activity.map((item, index) =>
  • {item.created_at} · {item.action}: {item.detail}
  • )}
} + {run.isPending &&

Loading run details…

}{run.error &&

{run.error.message}

}{run.data && <> + {run.data.job_result &&

Job result · {run.data.job_result.status}

{run.data.job_result.summary &&

{run.data.job_result.summary}

}{run.data.job_result.reason &&

{run.data.job_result.reason}

}{run.data.job_result.outputs && <>

Outputs

{JSON.stringify(run.data.job_result.outputs, null, 2)}
}
} + {run.data.run_artifacts?.filter(a => a.state === "stored").map(a =>

Download retained file ({a.byte_size} bytes)

)} + {run.data.agent_error &&

Agent reported error

{(run.data.agent_error as any).reason}

Reported {new Date((run.data.agent_error as any).reported_at).toLocaleString()}

} + {run.data.execution_diagnostics?.detail &&

Execution observer diagnostics

{String(run.data.execution_diagnostics.detail)}

}

Prompt

{run.data.prompt}

Activity

    {run.data.activity.map((item, index) =>
  • {item.created_at} · {item.action}: {item.detail}
  • )}
}
setDiagnostics(e.currentTarget.open)}>Diagnostics and artifacts{evidence.isPending &&

Loading diagnostics…

}{evidence.error &&

{evidence.error.message}

}{evidence.data &&
{JSON.stringify(evidence.data, null, 2)}
}
; } diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 2db39cc8..d47bec1e 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -166,6 +166,8 @@ Run pages return `items` and `nextCursor`; send that cursor for the next page. O Check that the intended trigger fired, the repository/task appears in the rendered prompt, and the browser/REST trace supports the reported result. A queued submission is not a successful execution. Browser run pages are at `https://app.factorize.sh/job-runs/RUN_ID`. Agent output stays in Factorize and is not automatically copied into Linear. +New agent runs must write a JSON result envelope to the absolute path in `FACTORIZE_RESULT_PATH` before exiting. The object requires `status` (`succeeded` or `failed`); it may include a `summary` and an `outputs` JSON object. Failed results require a non-empty `reason`. The file is limited to 64 KiB. A zero process exit without a valid `succeeded` result is a failed run. Put additional run files in `~/.factorize-job/`; regular files up to 10 MiB each (100 files, 50 MiB total) are retained. Symlinks and paths outside that directory are not collected. Run details show the result and authorized downloads. + For missing output or execution failures, call `get_run_diagnostics` and follow [failed-run troubleshooting](https://docs.factorize.sh/troubleshooting/runs). Failed runs keep the existing `failed` state filter and expose `failure_source` as `system` or `agent`. Historical failed runs read as system failures. An agent-reported reason appears in run detail and history; execution observer diagnostics remain available separately, and artifact/cleanup errors are separate diagnostics. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 413e24e7..59500292 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -698,112 +698,215 @@ components: reconciliation: type: object RunDetail: - allOf: - - $ref: "#/components/schemas/Run" type: object - required: - - id - - state - - execution_diagnostics - - harness_log - - prompt - - context - - invocation - - activity - - job_name properties: id: type: string + job_id: + type: string + project_id: + type: string + project_name: + type: string + job_name: + type: string + issue_id: + type: string + issue_url: + type: + - string + - "null" + issue_title: + type: string + run_name: + type: string + agent_name: + type: string + workspace_name: + type: string + agent_kind: + type: string state: type: string - trace_generation: + enum: + - queued + - reserved + - starting + - running + - blocked + - stopping + - succeeded + - failed + - stopped + - done + - ignored + provider: + type: string + backend_kind: + type: string + capabilities: + type: array + items: + type: string + destination_url: type: - string - "null" - description: Live file generation; clients reset trace pagination when it changes. - trace_projection: - $ref: "#/components/schemas/TraceProjection" - trace_sources: - $ref: "#/components/schemas/TraceSources" - execution_diagnostics: - $ref: "#/components/schemas/ExecutionDiagnostics" - harness_log: - $ref: "#/components/schemas/HarnessLog" + artifact_state: + type: string + enum: + - pending + - collecting + - stored + - partial + - failed artifact_error: type: - string - "null" - description: Secondary artifact or cleanup error; does not replace execution_diagnostics - job_name: + created_at: type: string - description: Current job name, included so run content does not require a separate job request. - prompt: + updated_at: type: string - context: - type: object - additionalProperties: true - invocation: - type: object - required: - - id - - source - - claim_key - - trigger_id - - context - - occurrence - - created_at - properties: - id: - type: string - source: - type: string - claim_key: - type: string - trigger_id: - type: - - string - - "null" - context: - type: object - additionalProperties: true - occurrence: - type: - - object - - "null" - additionalProperties: true - created_at: - type: string - activity: + started_at: + type: + - string + - "null" + failure_source: + anyOf: + - type: string + enum: + - system + - agent + - type: "null" + agent_error: + anyOf: + - type: object + properties: + reason: + type: string + reported_at: + type: string + reporter: + type: object + properties: + user_id: + type: string + kind: + type: string + enum: + - api_key + - oauth + - session + id: + type: string + required: + - user_id + - kind + - id + additionalProperties: false + required: + - reason + - reported_at + - reporter + additionalProperties: false + - type: "null" + elapsed_time: + anyOf: + - anyOf: + - type: object + properties: + duration: + type: number + required: + - duration + additionalProperties: false + - type: object + properties: + low: + type: number + high: + type: number + required: + - low + - high + additionalProperties: false + - type: "null" + job_result: + anyOf: + - type: object + properties: + status: + type: string + enum: + - succeeded + - failed + summary: + type: string + reason: + type: string + outputs: + type: object + propertyNames: + type: string + additionalProperties: {} + required: + - status + additionalProperties: false + - type: "null" + run_artifacts: type: array items: type: object - required: - - action - - detail - - created_at properties: - action: + id: type: string - detail: + kind: + type: string + provider: + type: string + format: type: string + byte_size: + type: number + sha256: + type: string + state: + type: string + media_type: + type: + - string + - "null" created_at: type: string + required: + - id + - kind + - provider + - format + - byte_size + - sha256 + - state + - media_type + - created_at + additionalProperties: false tenant_id: type: string invocation_id: type: string execution_handle: - type: - - object - - "null" - required: - - backendKind - - id - properties: - backendKind: - type: string - id: - type: string + anyOf: + - type: object + properties: + backendKind: + type: string + id: + type: string + required: + - backendKind + - id + additionalProperties: false + - type: "null" execution_backend_kind: type: string execution_capabilities: @@ -814,18 +917,64 @@ components: type: boolean vm_cleanup_attempt: type: integer - vm_cleanup_complete: - type: boolean + minimum: -9007199254740991 + maximum: 9007199254740991 cleanup_next_at: type: - string - "null" - format: date-time + vm_cleanup_complete: + type: boolean + prompt: + type: string + context: + type: object + propertyNames: + type: string + additionalProperties: {} occurrence: - type: - - object - - "null" - additionalProperties: true + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: {} + - type: "null" + invocation: + type: object + properties: + id: + type: string + source: + type: string + claim_key: + type: string + trigger_id: + type: + - string + - "null" + context: + type: object + propertyNames: + type: string + additionalProperties: {} + occurrence: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: {} + - type: "null" + created_at: + type: string + required: + - id + - source + - claim_key + - trigger_id + - context + - occurrence + - created_at + additionalProperties: false invocation_source: type: string invocation_claim_key: @@ -836,7 +985,170 @@ components: - "null" invocation_created_at: type: string - format: date-time + activity: + type: array + items: + type: object + properties: + action: + type: string + detail: + type: string + created_at: + type: string + required: + - action + - detail + - created_at + additionalProperties: false + execution_diagnostics: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: {} + - type: "null" + trace_sources: + anyOf: + - type: object + properties: + primary: + type: object + properties: + kind: + type: string + enum: + - execution_stream + - native_session + path: + type: string + mediaType: + type: string + const: application/x-ndjson + provider: + type: string + enum: + - codex + - claude + - pi + formatVersion: + type: string + cliVersion: + type: string + harnessVersion: + type: string + discoverCommand: + type: string + required: + - kind + - path + - mediaType + - provider + additionalProperties: false + nativeSession: + type: object + properties: + kind: + type: string + enum: + - execution_stream + - native_session + path: + type: string + mediaType: + type: string + const: application/x-ndjson + provider: + type: string + enum: + - codex + - claude + - pi + formatVersion: + type: string + cliVersion: + type: string + harnessVersion: + type: string + discoverCommand: + type: string + required: + - kind + - path + - mediaType + - provider + additionalProperties: false + required: + - primary + additionalProperties: false + - type: "null" + trace_projection: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: {} + - type: "null" + trace_generation: + type: + - string + - "null" + harness_log: + anyOf: + - type: object + propertyNames: + type: string + additionalProperties: {} + - type: "null" + required: + - id + - job_id + - job_name + - issue_id + - issue_url + - issue_title + - run_name + - agent_name + - workspace_name + - agent_kind + - state + - provider + - backend_kind + - capabilities + - destination_url + - artifact_state + - artifact_error + - created_at + - updated_at + - started_at + - failure_source + - agent_error + - job_result + - run_artifacts + - tenant_id + - invocation_id + - execution_handle + - execution_backend_kind + - execution_capabilities + - claim_released + - vm_cleanup_attempt + - cleanup_next_at + - vm_cleanup_complete + - prompt + - context + - occurrence + - invocation + - invocation_source + - invocation_claim_key + - invocation_trigger_id + - invocation_created_at + - activity + - execution_diagnostics + - trace_sources + - trace_projection + - trace_generation + - harness_log + additionalProperties: false RunDiagnostics: type: object required: @@ -10133,6 +10445,60 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + /api/v1/runs/{runId}/artifacts/{artifactId}: + get: + summary: Download a retained run artifact + responses: + "200": + description: Authorized artifact bytes + content: + application/octet-stream: + schema: + type: string + format: binary + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_runs_runId_artifacts_artifactId + tags: + - runs + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: runId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + - name: artifactId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ /api/v1/runs/{runId}/trace-pages: get: summary: Get revision-bound trace page diff --git a/packages/docs/work/results.mdx b/packages/docs/work/results.mdx index 7b8308b9..e760a090 100644 --- a/packages/docs/work/results.mdx +++ b/packages/docs/work/results.mdx @@ -9,6 +9,8 @@ Run pages return `items` and `nextCursor`; send that cursor for the next page. O Check that the intended trigger fired, the repository/task appears in the rendered prompt, and the browser/REST trace supports the reported result. A queued submission is not a successful execution. Browser run pages are at `https://app.factorize.sh/job-runs/RUN_ID`. Agent output stays in Factorize and is not automatically copied into Linear. +New agent runs must write a JSON result envelope to the absolute path in `FACTORIZE_RESULT_PATH` before exiting. The object requires `status` (`succeeded` or `failed`); it may include a `summary` and an `outputs` JSON object. Failed results require a non-empty `reason`. The file is limited to 64 KiB. A zero process exit without a valid `succeeded` result is a failed run. Put additional run files in `~/.factorize-job/`; regular files up to 10 MiB each (100 files, 50 MiB total) are retained. Symlinks and paths outside that directory are not collected. Run details show the result and authorized downloads. + For missing output or execution failures, call `get_run_diagnostics` and follow [failed-run troubleshooting](/troubleshooting/runs). Failed runs keep the existing `failed` state filter and expose `failure_source` as `system` or `agent`. Historical failed runs read as system failures. An agent-reported reason appears in run detail and history; execution observer diagnostics remain available separately, and artifact/cleanup errors are separate diagnostics.