diff --git a/tests/runner-e2e/PRODUCT-JOURNEYS.md b/tests/runner-e2e/PRODUCT-JOURNEYS.md index 4a5fb881869..1c843de2043 100644 --- a/tests/runner-e2e/PRODUCT-JOURNEYS.md +++ b/tests/runner-e2e/PRODUCT-JOURNEYS.md @@ -420,6 +420,15 @@ Cloud evidence is private; the public history publisher rejects these bundles. The private provider uses conditional S3 identity/stack leases and intent/receipt ownership manifests. An expired lease permits cleanup recovery, not reuse. +If the question/resume journey finds a failed agent run before a stable question +checkpoint, it saves `private-stories/question-answer-resume/clarification-run-failure.json`. +This private receipt contains only the bound task/run IDs, run status and a +bounded machine error code. It excludes raw errors and provider state. All run +bindings are checked before capture. The failed verdict and missing checkpoints +stay unchanged. A receipt write error keeps the original run failure and adds +`clarification_failure_evidence_write_failed` as its cause. This receipt does not +establish the cause of the agent failure or qualify a live run. + Managed self-hosted instances are removed after every attempt. Existing Cloud stacks retain the QA account and declared baseline while removing verified run-owned fixtures. Successful disposable stacks are deleted. Failed disposable diff --git a/tests/runner-e2e/product-journeys/agent-flows.ts b/tests/runner-e2e/product-journeys/agent-flows.ts index 48487f4b78c..f28f7a8a6a3 100644 --- a/tests/runner-e2e/product-journeys/agent-flows.ts +++ b/tests/runner-e2e/product-journeys/agent-flows.ts @@ -71,8 +71,7 @@ export function agentTaskSettled(state: TaskState, count: number) { && state.interactions.every(row => row.status !== "pending"); } -/** Owned-task observations only: other work in a persistent QA company cannot affect this grade. */ -export function validateAgentTaskState(context: JourneyContext, issueId: string, state: TaskState, maxRuns: number, allowedCancelled: string[] = [], deadlineAt?: number) { +export function validateAgentTaskBindings(context: JourneyContext, issueId: string, state: TaskState, maxRuns: number) { const agent = context.agent!; if (state.currentIssue.id !== issueId || state.currentIssue.companyId !== context.company.id || state.currentIssue.assigneeAgentId !== agent.id || state.taskRuns.length > maxRuns) throw new JourneyError("failed", "agent_task_binding_mismatch"); @@ -84,6 +83,14 @@ export function validateAgentTaskState(context: JourneyContext, issueId: string, if (retiredBeforeProviderStart(run)) continue; if (!active(run) && (run.runtimeMode !== "native" || run.contextSnapshot?.paperclipEnvironment?.id !== context.environmentId || provider?.kind !== agent.provider || provider?.model !== agent.model)) throw new JourneyError("failed", "agent_run_binding_mismatch"); + } +} + +/** Owned-task observations only: other work in a persistent QA company cannot affect this grade. */ +export function validateAgentTaskState(context: JourneyContext, issueId: string, state: TaskState, maxRuns: number, allowedCancelled: string[] = [], deadlineAt?: number) { + validateAgentTaskBindings(context, issueId, state, maxRuns); + for (const run of state.taskRuns) { + if (retiredBeforeProviderStart(run)) continue; // A projected exact-session retry is still work in progress. Keep observing // the same run under the original campaign deadline and run limit. if (deadlineAt !== undefined && isPendingNativeRecovery(run, deadlineAt)) continue; diff --git a/tests/runner-e2e/product-journeys/clarification-flow.test.ts b/tests/runner-e2e/product-journeys/clarification-flow.test.ts index 97711ca526a..b8b4aafa33a 100644 --- a/tests/runner-e2e/product-journeys/clarification-flow.test.ts +++ b/tests/runner-e2e/product-journeys/clarification-flow.test.ts @@ -1,12 +1,18 @@ import { expect, it, vi } from "vitest"; -import { readClarificationState } from "./clarification-flow.js"; -import type { JourneyContext } from "./types.js"; +import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { readClarificationState, runClarificationJourney } from "./clarification-flow.js"; +import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js"; + +vi.mock("../user-actions.js", async importOriginal => ({ ...await importOriginal(), + createTaskThroughUi: async () => ({ issueId: "11111111-1111-4111-8111-111111111111" }) })); const issueId = "11111111-1111-4111-8111-111111111111"; const companyId = "22222222-2222-4222-8222-222222222222"; const parent = { id: issueId, companyId, parentId: null, assigneeAgentId: "agent", status: "in_progress" }; const child = { id: "child", companyId, parentId: issueId }; -function fixture(rows = [parent, child]) { +function fixture(rows = [parent, child], runs: Record[] = []) { const get = vi.fn(async (route: string) => { const url = new URL(route, "https://qa.example.test"); if (url.pathname === `/api/companies/${companyId}/issues`) { @@ -14,6 +20,8 @@ function fixture(rows = [parent, child]) { return rows.filter(row => row.parentId === url.searchParams.get("parentIds")); } if (url.pathname === `/api/issues/${issueId}`) return parent; + if (url.pathname === `/api/issues/${issueId}/runs`) return runs.map(run => ({ runId: run.id })); + if (url.pathname.startsWith("/api/heartbeat-runs/")) return runs.find(run => url.pathname.endsWith(`/${run.id}`)); return []; }); const context = { company: { id: companyId }, environmentId: "daytona", api: { get }, @@ -25,6 +33,78 @@ it("reads the supported child projection while excluding the journey task and un expect((await readClarificationState(context, issueId)).children).toEqual([child]); expect(get).toHaveBeenCalledWith(`/api/companies/${companyId}/issues?view=index&parentIds=${issueId}&limit=2`); }); + +const failedRun = { id: "run", companyId, agentId: "agent", issueId, status: "failed", runtimeMode: "native", + errorCode: "native_provider_terminal_failed", error: "Synthetic provider failure", + contextSnapshot: { paperclipEnvironment: { id: "daytona" } }, + runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } } }; + +it("retains the bound failed run before the first stable question checkpoint, without accepting it", async () => { + const retained = vi.fn(async () => {}); + const { context } = fixture([parent], [failedRun]); + await expect(readClarificationState(context, issueId, retained)).rejects.toMatchObject({ code: "agent_run_failed" }); + expect(retained).toHaveBeenCalledExactlyOnceWith({ issueId, runs: [{ id: "run", status: "failed", errorCode: "native_provider_terminal_failed" }] }); + expect(JSON.stringify(retained.mock.calls)).not.toContain("Synthetic provider failure"); +}); + +it.each([ + { ...failedRun, id: "foreign", companyId: "other" }, + { ...failedRun, id: "foreign", issueId: "other" }, + { ...failedRun, id: "foreign", agentId: "other" }, + { ...failedRun, id: "foreign", contextSnapshot: { paperclipEnvironment: { id: "other" } } }, + { ...failedRun, id: "foreign", runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "other" } } } }, +])("does not retain a failure snapshot with a later foreign run: %j", async foreign => { + const retained = vi.fn(async () => {}); + const { context } = fixture([parent], [failedRun, foreign]); + await expect(readClarificationState(context, issueId, retained)).rejects.toMatchObject({ code: "agent_run_binding_mismatch" }); + expect(retained).not.toHaveBeenCalled(); +}); + +it("saves the failure receipt through final grading without inventing a question checkpoint", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "clarification-failure-")); + const { context } = fixture([parent], [failedRun]); + const evidence = { checks: [] } as unknown as JourneyEvidence; + try { + await expect(runClarificationJourney(context, { own: async () => {} } as unknown as TargetSession, + "synthetic-campaign", evidence, { deadlineAt: Date.now() + 10_000, directory, capture: async () => {} })) + .rejects.toMatchObject({ code: "agent_run_failed" }); + const receipt = JSON.parse(await readFile(path.join(directory, "clarification-run-failure.json"), "utf8")); + expect(receipt).toEqual({ issueId, runs: [{ id: "run", status: "failed", errorCode: "native_provider_terminal_failed" }] }); + const graded = JSON.parse(await readFile(path.join(directory, "clarification.json"), "utf8")); + expect(graded.checkpoints).toEqual([]); + expect(graded.checks).toHaveLength(11); + expect(graded.checks.every((check: { passed: boolean }) => !check.passed)).toBe(true); + } finally { await rm(directory, { recursive: true, force: true }); } +}); + +it("omits free-form error codes from the failure receipt", async () => { + const retained = vi.fn(async () => {}); + const { context } = fixture([parent], [{ ...failedRun, errorCode: "Provider refused token=synthetic-secret" }]); + await expect(readClarificationState(context, issueId, retained)).rejects.toMatchObject({ code: "agent_run_failed" }); + expect(retained).toHaveBeenCalledExactlyOnceWith({ issueId, runs: [{ id: "run", status: "failed" }] }); +}); + +it("keeps the original run failure when private evidence cannot be saved", async () => { + const retained = vi.fn(async () => { throw Error("Synthetic disk failure"); }); + const { context } = fixture([parent], [failedRun]); + await expect(readClarificationState(context, issueId, retained)).rejects.toMatchObject({ code: "agent_run_failed", + cause: expect.objectContaining({ message: "clarification_failure_evidence_write_failed" }) }); +}); +it("preserves agent_run_failed when both failure receipt and final clarification writes fail", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "clarification-write-fail-")); + await mkdir(path.join(directory, "clarification-run-failure.json")); + await mkdir(path.join(directory, "clarification.json")); + const { context } = fixture([parent], [failedRun]); + const evidence = { checks: [] } as unknown as JourneyEvidence; + try { + await expect(runClarificationJourney(context, { own: async () => {} } as unknown as TargetSession, + "synthetic-campaign", evidence, { deadlineAt: Date.now() + 10_000, directory, capture: async () => {} })) + .rejects.toMatchObject({ code: "agent_run_failed", + cause: expect.objectContaining({ message: "clarification_failure_evidence_write_failed" }) }); + expect(evidence.checks).toHaveLength(11); + expect(evidence.checks.every((check: { passed: boolean }) => !check.passed)).toBe(true); + } finally { await rm(directory, { recursive: true, force: true }); } +}); it("retains an empty child result for a task that did not delegate work", async () => { expect((await readClarificationState(fixture([parent]).context, issueId)).children).toEqual([]); }); diff --git a/tests/runner-e2e/product-journeys/clarification-flow.ts b/tests/runner-e2e/product-journeys/clarification-flow.ts index ec410c98de4..6fe5ee6b12b 100644 --- a/tests/runner-e2e/product-journeys/clarification-flow.ts +++ b/tests/runner-e2e/product-journeys/clarification-flow.ts @@ -7,7 +7,7 @@ import type { ContinuationCheckpoint } from "../continuation-scoring.js"; import { submittedReferencePattern } from "../submitted-reference.js"; import { answerResumeQuestionThroughUi } from "../question-resume-ui.js"; import { createTaskThroughUi } from "../user-actions.js"; -import { validateAgentTaskState } from "./agent-flows.js"; +import { validateAgentTaskBindings, validateAgentTaskState } from "./agent-flows.js"; import { clarificationQuestionFailure, gradeClarificationEvidence, type ClarificationReadback } from "./clarification-evidence.js"; import { openDocumentAuthoring } from "./task-document-flow.js"; import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js"; @@ -29,7 +29,10 @@ export async function waitForClarificationDocument(visible: Locator, marker: str remaining(); } -export async function readClarificationState(context: JourneyContext, issueId: string) { +interface RunFailureObservation { issueId: string; runs: Array<{ id: string; status: string; errorCode?: string }> } + +export async function readClarificationState(context: JourneyContext, issueId: string, + retainFailure?: (observation: RunFailureObservation) => Promise) { const route = `/api/issues/${issueId}`; const [currentIssue, summaries, interactions, documents, attachments, children] = await Promise.all([ context.api.get(route), context.api.get(`${route}/runs`), context.api.get(`${route}/interactions`), @@ -38,11 +41,25 @@ export async function readClarificationState(context: JourneyContext, issueId: s ]); if (!Array.isArray(summaries) || summaries.length > 3) throw new JourneyError("failed", "clarification_run_limit_exceeded"); const runs = await Promise.all(summaries.map(summary => context.api.get(`/api/heartbeat-runs/${summary.runId}`))); - validateAgentTaskState(context, issueId, { currentIssue: currentIssue as Row & { id: string; status: string }, - taskRuns: runs as Array, interactions: interactions as Array, comments: [], attachments: [] }, 3); + const state = { currentIssue: currentIssue as Row & { id: string; status: string }, + taskRuns: runs as Array, interactions: interactions as Array, comments: [], attachments: [] }; + validateAgentTaskBindings(context, issueId, state, 3); if (!Array.isArray(children) || children.some(child => child.parentId !== issueId || child.companyId !== context.company.id)) { throw new JourneyError("failed", "clarification_child_query_mismatch"); } + try { + validateAgentTaskState(context, issueId, state, 3); + } catch (error) { + if (error instanceof JourneyError && error.code === "agent_run_failed" && retainFailure) { + try { + await retainFailure({ issueId, runs: runs.map(run => ({ id: run.id, status: run.status, + ...(typeof run.errorCode === "string" && /^[a-z][a-z0-9_]{0,95}$/.test(run.errorCode) ? { errorCode: run.errorCode } : {}) })) }); + } catch { + error.cause = new Error("clarification_failure_evidence_write_failed"); + } + } + throw error; + } return { currentIssue, runs, interactions, documents, attachments, children }; } @@ -56,7 +73,8 @@ export async function runClarificationJourney(context: JourneyContext, session: let issue: Row | undefined, readback: ClarificationReadback | undefined; await mkdir(options.directory, { recursive: true, mode: 0o700 }); const retain = (name: string, value: unknown) => writeFile(path.join(options.directory, name), JSON.stringify(value, null, 2), { mode: 0o600 }); - const read = () => readClarificationState(context, issue!.id); + const read = () => readClarificationState(context, issue!.id, + observation => retain("clarification-run-failure.json", observation)); const settle = async (answeredId?: string, final = false) => { let stable = ""; while (Date.now() < options.deadlineAt) { @@ -85,6 +103,7 @@ export async function runClarificationJourney(context: JourneyContext, session: await options.capture(phase, `Clarification ${phase}`, `clarification-${phase}.png`); return point; }; + let primaryError: unknown; try { const title = `Journey QA question-answer-resume ${campaignId}`; const created = await createTaskThroughUi({ page: context.page, origin: context.api.origin, @@ -121,10 +140,17 @@ export async function runClarificationJourney(context: JourneyContext, session: const persisted = await context.api.get(`/api/issues/${issue.id}/documents/${encodeURIComponent(document.key)}`); readback = { issueId: persisted.issueId, key: persisted.key, revisionId: persisted.latestRevisionId, body: persisted.body, visibleBody: await visible.innerText() }; await options.capture("reloaded", "Saved answers after reload", "clarification-reloaded.png"); + } catch (error) { + primaryError = error; + throw error; } finally { const checks = gradeClarificationEvidence(context, issue?.id ?? "", scenario.marker, checkpoints, readback); evidence.checks.push(...checks.map(({ id, passed }) => ({ id, passed }))); - await retain("clarification.json", { checkpoints, readback, checks }); + try { + await retain("clarification.json", { checkpoints, readback, checks }); + } catch (writeError) { + if (primaryError === undefined) throw writeError; + } } if (evidence.checks.some(check => !check.passed)) throw new JourneyError("failed", "clarification_evidence_failed"); }