The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(e2e): retain verified onboarding artifact evidence (#17370)
Dottaa967d479bdc0
diff --git a/tests/runner-e2e/PRODUCT-JOURNEYS.md b/tests/runner-e2e/PRODUCT-JOURNEYS.mdindex e2320997bb..2d23dc214e 100644--- a/tests/runner-e2e/PRODUCT-JOURNEYS.md+++ b/tests/runner-e2e/PRODUCT-JOURNEYS.md@@ -81,6 +81,20 @@ prerequisite remains failed at that boundary; every dependent selection receivesa blocked result. Unsupported target capabilities are distinct from failures.Deployment/configuration drift during a journey fails its result.+New onboarding attempts retain a bounded `productJourney.artifact` receipt in+the existing private `normalized-results.json`, before disposable cleanup. It+includes the exact downloaded `connection-proof.json` bytes as base64, attachment+and originating-run IDs, byte count and SHA-256, plus the harness-generated input+and independent expected result. Reinspection can decode the original bytes,+recompute their checksum, and recompute the expected nonce, count, sum, and input+checksum after the workspace is deleted. Only this exact four-field synthetic+fixture is admitted, with a 4 KiB download limit and a closed receipt schema;+arbitrary agent output is excluded. Capture follows attribution and independent+download verification. The receipt survives later document, link, reload, or+trace failures without turning those failed journey steps into passes.+Historical attempts without it remain readable and do not gain retained-artifact+proof retroactively. Descendant stories reuse context without copying the receipt.+Collection must finish within the campaign deadline. Cleanup and evidencepublication then share a separate ten-minute grace period, with the last thirtyseconds reserved for a twenty-second stop-only fallback and ten-second browserdiff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.mdindex 2a84a315e5..26a326b9cc 100644--- a/tests/runner-e2e/SECURITY.md+++ b/tests/runner-e2e/SECURITY.md@@ -7,6 +7,13 @@ and normalized operations receipts cross the private target-provider boundary.The private Cloud repository owns operator credentials, conditional S3 leases,ownership manifests, cleanup recovery, and environment-protected CI dispatch.+Cloud onboarding retains only the independently checked synthetic+`connection-proof.json` download (at most 4 KiB) and its closed oracle receipt+inside private normalized results. The receipt contains generated numeric inputs,+their expected four-field result, exact base64 download bytes, checksums, size,+and attachment/run IDs. Extra fields and arbitrary agent output are rejected.+It contains no credentials, browser state, request headers, or provider text.+## Attended connection authenticationSee [PROVIDER-CONNECTIONS.md](PROVIDER-CONNECTIONS.md) for the explicit-onlydiff --git a/tests/runner-e2e/product-journeys/artifact-evidence.test.ts b/tests/runner-e2e/product-journeys/artifact-evidence.test.tsnew file mode 100644index 0000000000..3118820d20--- /dev/null+++ b/tests/runner-e2e/product-journeys/artifact-evidence.test.ts@@ -0,0 +1,66 @@+import { createHash } from "node:crypto";+import { describe, expect, it } from "vitest";+import { createConnectionProof } from "../connection-evidence.js";+import { retainOnboardingArtifact, validateOnboardingArtifact } from "./artifact-evidence.js";+import type { OnboardingArtifactEvidence } from "./types.js";++function fixture() {+ const proof = createConnectionProof();+ const bytes = Buffer.from(`${JSON.stringify(proof.expected, null, 2)}\n`);+ return retainOnboardingArtifact({ id: "attachment-1", originatingRunId: "run-1", bytes, proof });+}+function replaceBytes(receipt: OnboardingArtifactEvidence, bytes: Buffer) {+ receipt.contentBase64 = bytes.toString("base64");+ receipt.byteSize = bytes.byteLength;+ receipt.sha256 = createHash("sha256").update(bytes).digest("hex");+}++describe("private onboarding artifact receipt", () => {+ it("preserves the original formatted bytes and independently recomputable input oracle", () => {+ const receipt = fixture();+ const retained = JSON.parse(JSON.stringify(receipt));+ expect(() => validateOnboardingArtifact(retained)).not.toThrow();+ expect(Buffer.from(retained.contentBase64, "base64").toString("utf8")).toBe(`${JSON.stringify(retained.expected, null, 2)}\n`);+ const input = JSON.parse(retained.input);+ expect(retained.expected).toEqual({ nonce: input.nonce, count: input.values.length,+ total: input.values.reduce((sum:number, n:number) => sum + n, 0), sha256: createHash("sha256").update(retained.input).digest("hex") });+ expect(retained.sha256).not.toBe(retained.expected.sha256);+ });+ it("preserves equivalent escaped JSON and integer number representations accepted by the independent oracle", () => {+ const receipt = fixture();+ const escaped = (value: string) => value.split("").map(char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`).join("");+ const bytes = Buffer.from(`{\n "${escaped("sha256")}": "${escaped(receipt.expected.sha256)}",\n "${escaped("total")}": ${receipt.expected.total}e0,\n "${escaped("count")}": 7.0,\n "${escaped("nonce")}": "${escaped(receipt.expected.nonce)}"\n}\n`);+ replaceBytes(receipt, bytes);+ expect(() => validateOnboardingArtifact(receipt)).not.toThrow();+ expect(Buffer.from(JSON.parse(JSON.stringify(receipt)).contentBase64, "base64")).toEqual(bytes);+ });+ it.each([+ ["changed download", (receipt: OnboardingArtifactEvidence) => { receipt.contentBase64 = Buffer.from("{}").toString("base64"); }],+ ["wrong declared size", (receipt: OnboardingArtifactEvidence) => { receipt.byteSize++; }],+ ["wrong download checksum", (receipt: OnboardingArtifactEvidence) => { receipt.sha256 = "0".repeat(64); }],+ ["noncanonical base64", (receipt: OnboardingArtifactEvidence) => { receipt.contentBase64 += "\n"; }],+ ["changed independent input", (receipt: OnboardingArtifactEvidence) => { receipt.input = receipt.input.replace("values", "privateValues"); }],+ ["matching but incorrect model result and expectation", (receipt: OnboardingArtifactEvidence) => {+ receipt.expected.total++;+ replaceBytes(receipt, Buffer.from(JSON.stringify(receipt.expected)));+ }],+ ["oversized whitespace", (receipt: OnboardingArtifactEvidence) => { replaceBytes(receipt, Buffer.from(`${" ".repeat(4096)}${JSON.stringify(receipt.expected)}`)); }],+ ["arbitrary agent output", (receipt: OnboardingArtifactEvidence) => { replaceBytes(receipt, Buffer.from(JSON.stringify({ ...receipt.expected, message: "unreviewed output" }))); }],+ ["discarded duplicate key text", (receipt: OnboardingArtifactEvidence) => {+ replaceBytes(receipt, Buffer.from(`{"nonce":"unreviewed output",${JSON.stringify(receipt.expected).slice(1)}`));+ }],+ ["escaped duplicate key text", (receipt: OnboardingArtifactEvidence) => {+ replaceBytes(receipt, Buffer.from(`{"\\u006eonce":"unreviewed output",${JSON.stringify(receipt.expected).slice(1)}`));+ }],+ ] as const)("rejects %s", (_name, mutate) => {+ const receipt = fixture();+ mutate(receipt);+ expect(() => validateOnboardingArtifact(receipt)).toThrow("invalid_onboarding_artifact_evidence");+ });+ it("rejects additional receipt fields rather than retaining arbitrary metadata", () => {+ expect(() => validateOnboardingArtifact({ ...fixture(), requestHeaders: {} })).toThrow("invalid_onboarding_artifact_evidence");+ const receipt = fixture();+ Object.assign(receipt.expected, { message: "unreviewed output" });+ expect(() => validateOnboardingArtifact(receipt)).toThrow("invalid_onboarding_artifact_evidence");+ });+});diff --git a/tests/runner-e2e/product-journeys/artifact-evidence.ts b/tests/runner-e2e/product-journeys/artifact-evidence.tsnew file mode 100644index 0000000000..807831e8f2--- /dev/null+++ b/tests/runner-e2e/product-journeys/artifact-evidence.ts@@ -0,0 +1,58 @@+import { createHash } from "node:crypto";+import { type createConnectionProof, verifyConnectionArtifact } from "../connection-evidence.js";+import type { OnboardingArtifactEvidence } from "./types.js";++const maxBytes = 4096;+const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");+const exactKeys = (value: unknown, keys: string[]): value is Record<string, unknown> => Boolean(value &&+ typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length &&+ keys.every(key => Object.hasOwn(value, key)));+function fail(): never { throw new Error("invalid_onboarding_artifact_evidence"); }++export function validateOnboardingArtifact(value: unknown): asserts value is OnboardingArtifactEvidence {+ if (!exactKeys(value, ["schema", "id", "originatingRunId", "filename", "byteSize", "sha256", "contentBase64", "input", "expected"])) fail();+ const receipt = value as unknown as OnboardingArtifactEvidence;+ if (receipt.schema !== "paperclip.product-journey.artifact/v1" || receipt.filename !== "connection-proof.json" ||+ ![receipt.id, receipt.originatingRunId].every(id => typeof id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(id)) ||+ !Number.isSafeInteger(receipt.byteSize) || receipt.byteSize < 1 || receipt.byteSize > maxBytes ||+ typeof receipt.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(receipt.sha256) ||+ typeof receipt.contentBase64 !== "string" || receipt.contentBase64.length > Math.ceil(maxBytes / 3) * 4 ||+ typeof receipt.input !== "string" || receipt.input.length > 1024 ||+ !exactKeys(receipt.expected, ["nonce", "count", "total", "sha256"])) fail();+ const bytes = Buffer.from(receipt.contentBase64, "base64");+ if (bytes.toString("base64") !== receipt.contentBase64 || bytes.byteLength !== receipt.byteSize || hash(bytes) !== receipt.sha256) fail();+ let input: unknown;+ try { input = JSON.parse(receipt.input); } catch { fail(); }+ if (!exactKeys(input, ["nonce", "values"]) || typeof input.nonce !== "string" || !/^[a-f0-9]{24}$/.test(input.nonce) ||+ !Array.isArray(input.values) || input.values.length !== 7 ||+ !input.values.every(n => Number.isSafeInteger(n) && n >= 0 && n <= 65535)) fail();+ const expected = { nonce: input.nonce, count: input.values.length, total: input.values.reduce((sum, n) => sum + n, 0), sha256: hash(receipt.input) };+ if (receipt.input !== `${JSON.stringify({ nonce: input.nonce, values: input.values })}\n` ||+ Object.entries(expected).some(([key, entry]) => receipt.expected[key as keyof typeof expected] !== entry) ||+ !verifyConnectionArtifact(bytes, expected)) fail();+ const compact = bytes.toString("utf8").replace(/[ \t\r\n]/g, "");+ const pairs = compact.slice(1, -1).split(",");+ if (!compact.startsWith("{") || !compact.endsWith("}") || pairs.length !== Object.keys(expected).length) fail();+ const seen = new Set<string>();+ for (const pair of pairs) {+ let field: unknown;+ try { field = JSON.parse(`{${pair}}`); } catch { fail(); }+ if (!field || typeof field !== "object" || Array.isArray(field) || Object.keys(field).length !== 1) fail();+ const [key, entry] = Object.entries(field)[0]!;+ if (!Object.hasOwn(expected, key) || seen.has(key) || entry !== expected[key as keyof typeof expected]) fail();+ seen.add(key);+ }+}++export function retainOnboardingArtifact(input: {+ id: string; originatingRunId: string; bytes: Buffer; proof: ReturnType<typeof createConnectionProof>;+}): OnboardingArtifactEvidence {+ const receipt: OnboardingArtifactEvidence = {+ schema: "paperclip.product-journey.artifact/v1", id: input.id, originatingRunId: input.originatingRunId,+ filename: "connection-proof.json", byteSize: input.bytes.byteLength, sha256: hash(input.bytes),+ contentBase64: input.bytes.toString("base64"), input: input.proof.input,+ expected: { ...input.proof.expected },+ };+ validateOnboardingArtifact(receipt);+ return receipt;+}diff --git a/tests/runner-e2e/product-journeys/campaign.test.ts b/tests/runner-e2e/product-journeys/campaign.test.tsindex ff1a068901..27d42b934f 100644--- a/tests/runner-e2e/product-journeys/campaign.test.ts+++ b/tests/runner-e2e/product-journeys/campaign.test.ts@@ -3,6 +3,8 @@ import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises";import path from "node:path";import os from "node:os";import { pathToFileURL } from "node:url";+import { createConnectionProof } from "../connection-evidence.js";+import { retainOnboardingArtifact, validateOnboardingArtifact } from "./artifact-evidence.js";const persistenceFault = vi.hoisted(() => ({ kind: null as "write" | "rename" | null, active: false, latestReport: null as any }));vi.mock("node:fs/promises", async importOriginal => {const actual = await importOriginal<typeof import("node:fs/promises")>();@@ -31,16 +33,18 @@ import { regenerateRunnerDashboard } from "../dashboard-regenerate.js";const roots: string[]=[];afterEach(async()=>{vi.useRealTimers(); vi.restoreAllMocks(); persistenceFault.kind=null; persistenceFault.active=false; persistenceFault.latestReport=null; process.exitCode=0; await Promise.all(roots.splice(0).map(root=>rm(root,{recursive:true,force:true})));});type Hook = "collect" | "release" | "stop" | "finalizeEvidence" | "checkpointEvidence";-async function run(options:{authFailure?:boolean;onboardingFailure?:boolean;drift?:boolean;cleanupFailure?:boolean;collectionFailure?:boolean;mini?:boolean;missingReceipt?:boolean;zeroRequests?:boolean;missingCheck?:boolean;finalizationFailure?:boolean;persistenceFailure?:"write"|"rename";persistenceAfter?:"collection"|"release";stallHook?:Hook;onHook?:(hook:Hook,signal?:AbortSignal)=>void}={}) {+async function run(options:{authFailure?:boolean;onboardingFailure?:boolean;missingArtifact?:boolean;drift?:boolean;cleanupFailure?:boolean;collectionFailure?:boolean;mini?:boolean;missingReceipt?:boolean;zeroRequests?:boolean;missingCheck?:boolean;finalizationFailure?:boolean;persistenceFailure?:"write"|"rename";persistenceAfter?:"collection"|"release";stallHook?:Hook;onHook?:(hook:Hook,signal?:AbortSignal)=>void}={}) {const root=await mkdtemp(path.join(os.tmpdir(),"journey-campaign-test-")); roots.push(root);const module=path.join(root,"provider.mjs");+ const proof = createConnectionProof();+ const artifact = retainOnboardingArtifact({ id: "artifact-1", originatingRunId: "run-1", bytes: Buffer.from(`${JSON.stringify(proof.expected, null, 2)}\n`), proof });await writeFile(module, `import {readFile,writeFile} from 'node:fs/promises';const identity={kind:'cloud',targetId:'qa',origin:'https://qa.example.test',commit:'${"a".repeat(40)}',cloudRelease:'v1',runtimeImage:'image',configurationHash:'config'};let onboarded=false;const context={identity,company:{id:'company-1',issuePrefix:'QA'},api:{post:async()=>({id:'issue-fixture-1',identifier:'QA-1'})},startingState:'onboarding',capabilities:['company','board-user','task-write'],page:{async screenshot(){} }};export const provider={version:1, async acquire(input){return {async authenticate(){${options.authFailure ? "throw {outcome:'failed',code:'login_code_expired'};" : ""}},-async onboard(evidence){${options.onboardingFailure ? "throw {outcome:'failed',code:'onboarding_failed'};" : `evidence.checks.push(...['fresh-workspace','ui-connection-and-native-agent','first-task-complete','downloadable-artifact-verified'${options.missingCheck ? "" : ",'native-trace-verified'"}].map(id=>({id,passed:true})));onboarded=true;return context;`}},+async onboard(evidence){${options.onboardingFailure ? "throw {outcome:'failed',code:'onboarding_failed'};" : `${options.missingArtifact ? "" : `evidence.artifact=${JSON.stringify(artifact)};`}evidence.checks.push(...['fresh-workspace','ui-connection-and-native-agent','first-task-complete','downloadable-artifact-verified'${options.missingCheck ? "" : ",'native-trace-verified'"}].map(id=>({id,passed:true})));onboarded=true;return context;`}},async prepare(){throw Error('onboarding receipt was not reused')},async identity(){return {...identity,commit:'${(options.drift?"b":"a").repeat(40)}'}},async collect(){${options.collectionFailure ? "throw Error('private collection error');" : options.missingReceipt ? "return [];" : `return onboarded?[{journeyId:'cloud-onboarding',runIds:['run-1'],usage:{runs:[{runId:'run-1',usage:{costUsd:0.01}}]},operations:{campaignId:input.campaignId,attemptId:input.campaignId+':cloud-onboarding:1',modelCostUsd:0.01,setupCostUsd:0.005,requestCount:${options.zeroRequests ? 0 : 2},feedback:{collection:'complete',complaints:0,suggestions:0},traceIds:['a'.repeat(32)]}}]:[];`}}, async own(){}, async release(){${options.cleanupFailure ? "throw Error('private raw error');" : "return 'released';"}}, async stop(){}@@ -56,6 +60,7 @@ await writeFile(input.outputDir+'/failure-checkpoint.json',JSON.stringify(reportconst config={version:1,id:"qa",mode:"new-cloud",adapterModule:module,journeys:["cloud-onboarding","task-properties"],executionEnvironment:"daytona",baseline:{features:{},connections:[]},limits:{durationMs:60000,modelBudgetCents:1000,maxRuns:1},...(options.mini?{modelProfileId:"runner-codex-mini"}:{})};const file=path.join(root,"target.json"),output=path.join(root,"report"); await writeFile(file,JSON.stringify(config));const lifecycle: string[] = [];+ let artifactBeforeRelease: unknown;{persistenceFault.kind=options.persistenceFailure ?? null;const { provider } = await import(pathToFileURL(module).href);@@ -64,7 +69,7 @@ await writeFile(input.outputDir+'/failure-checkpoint.json',JSON.stringify(reportconst session = await acquire(...args);return { ...session,async collect(input?: {signal:AbortSignal}) { options.onHook?.("collect",input?.signal); if(options.stallHook==="collect")await new Promise(()=>{}); try { return await session.collect(); } finally { if (options.persistenceAfter !== "release" && options.persistenceFailure) persistenceFault.active=true; } },- async release(outcome: string,input?: {signal:AbortSignal}) { lifecycle.push(`release:${outcome}`); options.onHook?.("release",input?.signal); if(options.stallHook==="release")await new Promise(()=>{}); try { return await session.release(outcome); } finally { if (options.persistenceAfter === "release" && options.persistenceFailure) persistenceFault.active=true; } },+ async release(outcome: string,input?: {signal:AbortSignal}) { lifecycle.push(`release:${outcome}`); artifactBeforeRelease=JSON.parse(await readFile(path.join(output,"normalized-results.json"),"utf8")).results[0].productJourney.artifact; options.onHook?.("release",input?.signal); if(options.stallHook==="release")await new Promise(()=>{}); try { return await session.release(outcome); } finally { if (options.persistenceAfter === "release" && options.persistenceFailure) persistenceFault.active=true; } },async stop(input?: {signal:AbortSignal}) { lifecycle.push("stop"); options.onHook?.("stop",input?.signal); if(options.stallHook==="stop")await new Promise(()=>{}); },async finalizeEvidence(input?: {signal:AbortSignal}) { lifecycle.push("finalizeEvidence"); options.onHook?.("finalizeEvidence",input?.signal); if(options.stallHook==="finalizeEvidence")await new Promise(()=>{}); return session.finalizeEvidence(); },async checkpointEvidence(input?: {signal:AbortSignal}) { lifecycle.push("checkpointEvidence"); options.onHook?.("checkpointEvidence",input?.signal); if(options.stallHook==="checkpointEvidence")await new Promise(()=>{}); return session.checkpointEvidence(); },@@ -73,7 +78,7 @@ await writeFile(input.outputDir+'/failure-checkpoint.json',JSON.stringify(report}await launchProductJourneys(["--target-config",file,"--output",output],path.resolve(import.meta.dirname,"../../.."));return { ...JSON.parse(await readFile(path.join(output,"normalized-results.json"),"utf8")),- lifecycle, outputDir:output, attemptedReport: persistenceFault.latestReport,+ lifecycle, outputDir:output, attemptedReport: persistenceFault.latestReport, artifactBeforeRelease, expectedArtifact:artifact,failureCheckpoint: await readFile(path.join(output,"failure-checkpoint.json"),"utf8").then(JSON.parse).catch(()=>null) };}describe("product journey campaign boundary outcomes",()=>{@@ -110,6 +115,22 @@ describe("product journey campaign boundary outcomes",()=>{expect(campaign.results.map((r:any)=>r.productJourney.startingState)).toEqual(["onboarding","onboarding"]);expect(campaign.results[1]).toMatchObject({provider:null,model:null,runtimeMode:"none"});});+ it("writes exact artifact bytes and independent expectations before disposable cleanup", async () => {+ const campaign = await run();+ const retained = campaign.results[0].productJourney.artifact;+ expect(campaign.artifactBeforeRelease).toEqual(campaign.expectedArtifact);+ expect(retained).toEqual(campaign.expectedArtifact);+ expect(() => validateOnboardingArtifact(retained)).not.toThrow();+ expect(Buffer.from(retained.contentBase64, "base64").toString("utf8")).toBe(`${JSON.stringify(retained.expected, null, 2)}\n`);+ expect(campaign.results[1].productJourney.artifact).toBeUndefined();+ expect(campaign.lifecycle[0]).toBe("release:passed");+ });+ it("fails new onboarding and blocks reuse when its artifact evidence was discarded", async () => {+ const campaign = await run({ missingArtifact: true });+ expect(campaign.results[0].error).toBe("onboarding_artifact_evidence_missing");+ expect(campaign.results.map((result:any) => result.productJourney.outcome)).toEqual(["failed", "blocked"]);+ expect(campaign.lifecycle[0]).toBe("release:failed");+ });it("fails deployment drift and blocks descendants",async()=>{const campaign=await run({drift:true});expect(campaign.results[0].error).toBe("deployment_changed_during_journey");diff --git a/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts b/tests/runner-e2e/product-journeys/cloud-onboarding.test.tsindex 30085b0ab4..94589ca506 100644--- a/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts+++ b/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts@@ -1,18 +1,26 @@import { describe, expect, it, vi } from "vitest";import { cloudOnboarding, type CloudOnboardingInput } from "./cloud-onboarding.js";import { onboardingFirstTask } from "./onboarding-first-task.js";+import { retainOnboardingArtifact } from "./artifact-evidence.js";vi.mock("@playwright/test", () => ({ expect: (locator: { isVisible(): Promise<boolean> }) => ({toBeVisible: async () => { expect(await locator.isVisible()).toBe(true); },not: { toBeVisible: async () => { expect(await locator.isVisible()).toBe(false); } },}) }));-vi.mock("./onboarding-first-task.js", () => ({ onboardingFirstTask: vi.fn(async () => ({ artifact: { originatingRunId: "artifact-run" } })) }));+vi.mock("./onboarding-first-task.js", async () => {+ const { retainOnboardingArtifact } = await import("./artifact-evidence.js");+ return { onboardingFirstTask: vi.fn(async ({ proof, onArtifact }) => {+ const artifact = retainOnboardingArtifact({ id: "artifact", originatingRunId: "artifact-run", bytes: Buffer.from(JSON.stringify(proof.expected)), proof });+ onArtifact?.(artifact);+ return { artifact };+ }) };+});type Entry = "first-run" | "portfolio" | "create-form";type Control = { role: string; name: string; scope?: string; fill?(value: string): void; click?(): void; select?(value: string): void };/** Visible control contracts only; no browser, Cloud API, or provider is started. */-function fixture(entry: Entry, options: { intentFailure?: boolean; qualificationFailure?: boolean } = {}) {+function fixture(entry: Entry, options: { intentFailure?: boolean; qualificationFailure?: boolean; traceFailure?: boolean } = {}) {let stage: string = entry, name = "", apiMode = false, source = false, advanced = false, runnerOpen = false;let modelsOpen = false, model = "", runner = "", saved = false, hired = false;const fields: Record<string, string> = {}, events: string[] = [];@@ -97,7 +105,11 @@ function fixture(entry: Entry, options: { intentFailure?: boolean; qualificationasync own(resource: { kind: string }) { events.push(`intent:${resource.kind}`); },async phase() {}, async observeRun() {},async qualify() { if (options.qualificationFailure) throw new Error("admission denied"); events.push("qualified"); },- async verifyExecution(_context: unknown, runIds: string[]) { expect(runIds).toEqual(["artifact-run"]); events.push("native:verified"); },+ async verifyExecution(_context: unknown, runIds: string[]) {+ expect(runIds).toEqual(["artifact-run"]);+ if (options.traceFailure) throw new Error("trace verification failed");+ events.push("native:verified");+ },} as unknown as CloudOnboardingInput;return { input, events };}@@ -124,4 +136,24 @@ describe("Cloud onboarding visible controls", () => {expect(f.events).not.toContain("paid:connect");expect(vi.mocked(onboardingFirstTask).mock.calls).toHaveLength(previous);});+ it("keeps verified artifact bytes and the independent oracle when later trace verification fails", async () => {+ const f = fixture("portfolio", { traceFailure: true });+ await expect(cloudOnboarding(f.input)).rejects.toThrow("trace verification failed");+ const retained = JSON.parse(JSON.stringify(f.input.evidence)).artifact;+ expect(JSON.parse(Buffer.from(retained.contentBase64, "base64").toString("utf8"))).toEqual(retained.expected);+ expect(retained.originatingRunId).toBe("artifact-run");+ expect(f.input.evidence.checks).not.toContainEqual({ id: "native-trace-verified", passed: true });+ });+ it("retains the artifact but fails the journey without pass markers when first-task readback fails", async () => {+ const f = fixture("portfolio");+ vi.mocked(onboardingFirstTask).mockImplementationOnce(async ({ proof, onArtifact }) => {+ onArtifact?.(retainOnboardingArtifact({ id: "artifact", originatingRunId: "artifact-run", bytes: Buffer.from(JSON.stringify(proof.expected)), proof }));+ throw new Error("first-task readback failed");+ });+ await expect(cloudOnboarding(f.input)).rejects.toThrow("first-task readback failed");+ const retained = JSON.parse(JSON.stringify(f.input.evidence)).artifact;+ expect(JSON.parse(Buffer.from(retained.contentBase64, "base64").toString("utf8"))).toEqual(retained.expected);+ expect(f.input.evidence.checks.map(check => check.id)).toEqual(["fresh-workspace", "ui-connection-and-native-agent"]);+ expect(f.events).not.toContain("native:verified");+ });});diff --git a/tests/runner-e2e/product-journeys/cloud-onboarding.ts b/tests/runner-e2e/product-journeys/cloud-onboarding.tsindex 1d5f2d4bbd..3173676c3a 100644--- a/tests/runner-e2e/product-journeys/cloud-onboarding.ts+++ b/tests/runner-e2e/product-journeys/cloud-onboarding.ts@@ -81,7 +81,7 @@ export async function cloudOnboarding(input: CloudOnboardingInput): Promise<Jourawait input.phase("agent");const completed = await onboardingFirstTask({ context, agent: { id: agent.id }, connectionId: connection.id,proof: createConnectionProof(), campaignId, maxRuns: input.maxRuns, deadlineAt: input.deadlineAt,- own: input.own, observeRun: input.observeRun });+ own: input.own, observeRun: input.observeRun, onArtifact: artifact => { evidence.artifact = artifact; } });await input.verifyExecution(context, [completed.artifact.originatingRunId]);evidence.checks.push({ id: "first-task-complete", passed: true },{ id: "downloadable-artifact-verified", passed: true }, { id: "native-trace-verified", passed: true });diff --git a/tests/runner-e2e/product-journeys/contracts.test.ts b/tests/runner-e2e/product-journeys/contracts.test.tsindex 5e90e3c2e2..754d6c7bab 100644--- a/tests/runner-e2e/product-journeys/contracts.test.ts+++ b/tests/runner-e2e/product-journeys/contracts.test.ts@@ -11,6 +11,8 @@ import { discoverReportCatalog } from "../report-catalog.js";import { isIncompleteFirstTaskResult, renderCaseOutcome } from "../case-outcome.js";import type { RunnerE2EResult } from "../types.js";import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js";+import { createConnectionProof } from "../connection-evidence.js";+import { retainOnboardingArtifact } from "./artifact-evidence.js";vi.mock("@playwright/test", () => ({expect: Object.assign((locator: { textContent(): Promise<string> }) => ({ async toContainText(value: string) { expect(await locator.textContent()).toContain(value); } }),@@ -28,6 +30,21 @@ function result(): RunnerE2EResult {productJourney: { outcome: "passed", startingState: "recipe", phases: [{phase: "journey", outcome: "passed"}], checks: [{id:"assignment-persisted", passed:true},{id:"no-agent-work",passed:true}], privacy: "private", resourceDisposition: "released", deployment: { kind: "self-hosted", targetId: "local-qa", origin: "http://127.0.0.1:3100", commit: "a".repeat(40), cloudRelease: null, runtimeImage: null, configurationHash: "test" } } };}describe("deployment journey contracts", () => {+ it("validates optional historical artifact evidence without trusting extra fields or a different run", () => {+ const retained = result();+ retained.caseId = "cloud-onboarding";+ retained.status = "failed";+ expect(() => validateRetainedRunnerResult(retained)).not.toThrow();+ const proof = createConnectionProof();+ retained.productJourney!.artifact = retainOnboardingArtifact({ id: "artifact", originatingRunId: "artifact-run", bytes: Buffer.from(JSON.stringify(proof.expected)), proof });+ retained.runIds = ["artifact-run"];+ expect(() => validateRetainedRunnerResult(JSON.parse(JSON.stringify(retained)))).not.toThrow();+ retained.runIds = ["other-run"];+ expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.artifact");+ retained.runIds = ["artifact-run"];+ Object.assign(retained.productJourney!.artifact, { requestHeaders: {} });+ expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.artifact");+ });it("resolves only requested prerequisites, once, and unwinds on failure", async () => {const calls: string[] = [];const registry = new FixtureRegistry().register({id:"a", async setup(){calls.push("a"); return 1;}, async teardown(){calls.push("-a");}})diff --git a/tests/runner-e2e/product-journeys/launch.ts b/tests/runner-e2e/product-journeys/launch.tsindex 26d8817c0f..2d0233bd2e 100644--- a/tests/runner-e2e/product-journeys/launch.ts+++ b/tests/runner-e2e/product-journeys/launch.ts@@ -15,6 +15,7 @@ import { regenerateRunnerDashboard } from "../dashboard-regenerate.js";import { resolveRunnerE2ESource } from "../source.js";import { validateRetainedRunnerResult } from "../result-validation.js";import { validateJourneyCollection } from "./collection.js";+import { validateOnboardingArtifact } from "./artifact-evidence.js";const cleanupGraceMs = 600_000;const stopReserveMs = 20_000;@@ -98,7 +99,7 @@ export async function launchProductJourneys(args: string[], repositoryRoot: stritry { sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repositoryRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { /* Packaged harnesses may not include Git metadata. */ }const source = resolveRunnerE2ESource({ sha, ref: null, workflowRunUrl: null });const definitionHash = createHash("sha256").update(JSON.stringify(productJourneys));- for (const name of ["catalog.ts", "task-properties.ts", "cloud-onboarding.ts", "onboarding-first-task.ts", "fixtures.ts", "launch.ts", "types.ts", "collection.ts", "local-target.ts"]) definitionHash.update(await readFile(path.join(import.meta.dirname, name)));+ for (const name of ["catalog.ts", "task-properties.ts", "cloud-onboarding.ts", "onboarding-first-task.ts", "artifact-evidence.ts", "fixtures.ts", "launch.ts", "types.ts", "collection.ts", "local-target.ts"]) definitionHash.update(await readFile(path.join(import.meta.dirname, name)));const suiteDefinitionHash = definitionHash.digest("hex");const expected = config.journeys.map(id => `product-journeys.${config.id}.${id === "cloud-onboarding" ? config.modelProfileId : "browser"}.${config.executionEnvironment}.${id}`);let reportPersisted = false;@@ -176,6 +177,8 @@ export async function launchProductJourneys(args: string[], repositoryRoot: striif (id === "cloud-onboarding") {if (!session!.onboard) throw new JourneyError("unsupported", "target_has_no_onboarding");ready = await session!.onboard(evidence);+ if (!evidence.artifact) throw new JourneyError("failed", "onboarding_artifact_evidence_missing");+ validateOnboardingArtifact(evidence.artifact);fixtures!.provide(ready);} else {ready = await fixtures!.resolve(productJourneys.find(j => j.id === id)!.requires);diff --git a/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts b/tests/runner-e2e/product-journeys/onboarding-first-task.test.tsindex d7ab78a64f..ab452f1901 100644--- a/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts+++ b/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts@@ -3,12 +3,14 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { createConnectionProof } from "../connection-evidence.js";import { connectionDelay } from "../connection-target.js";import { onboardingFirstTask, type OnboardingFirstTaskInput } from "./onboarding-first-task.js";+import { validateOnboardingArtifact } from "./artifact-evidence.js";vi.mock("../connection-target.js", () => ({ connectionDelay: vi.fn(async () => {}) }));type Row = { id: string; [key: string]: any };type Options = {plan?: boolean;wrongProof?: boolean;+ readbackFailure?: "reload" | "download-link";mutate?(phase: string, state: { tasks: Row[]; runs: Row[]; interactions: Row[]; documents: Row[]; attachments: Row[]; comments: Row[] }): void;};@@ -70,14 +72,14 @@ function fixture(options: Options = {}) {},async check() { events.push(`check:${name}`); },async fill(text: string) { expect(text).toContain(title); events.push("fill:request"); },- async waitFor() { events.push("visible:download"); expect(phase).toBe("accepted"); },+ async waitFor() { events.push("visible:download"); expect(phase).toBe("accepted"); if (options.readbackFailure === "download-link") throw Error("synthetic download-link failure"); },});const page = {getByRole(_role: string, { name }: { name: string }) { return locator(name); },getByTestId(name: string) { return locator(name); },locator(selector: string) { expect(selector).toContain("/api/attachments/artifact/content"); return locator(selector); },async goto(url: string) { expect(url).toBe("https://qa.example.test/QA/issues/QA-1"); events.push("open:parent"); },- async reload() { events.push("reload:parent"); },+ async reload() { events.push("reload:parent"); if (options.readbackFailure === "reload") throw Error("synthetic reload failure"); },};const own = vi.fn(async (resource: { name: string; id?: string }) => { events.push(`own:${resource.id ?? resource.name}`); });const observeRun = vi.fn(async (row: Row) => { events.push(`run:${row.id}`); });@@ -90,6 +92,30 @@ function fixture(options: Options = {}) {afterEach(() => { vi.restoreAllMocks(); vi.mocked(connectionDelay).mockReset().mockResolvedValue(undefined); });describe("Cloud canonical onboarding first task", () => {+ it.each(["reload", "download-link"] as const)("retains the independently verified download when later %s fails", async readbackFailure => {+ const f = fixture({ readbackFailure });+ const capture = vi.fn();+ f.input.onArtifact = capture;+ await expect(onboardingFirstTask(f.input)).rejects.toThrow(`synthetic ${readbackFailure} failure`);+ expect(capture).toHaveBeenCalledOnce();+ const retained = JSON.parse(JSON.stringify(capture.mock.calls[0]![0]));+ expect(() => validateOnboardingArtifact(retained)).not.toThrow();+ expect(JSON.parse(Buffer.from(retained.contentBase64, "base64").toString("utf8"))).toEqual(f.input.proof.expected);+ expect(retained.input).toBe(f.input.proof.input);+ expect(retained.originatingRunId).toBe("child-run");+ });+ it("retains the original download and independently generated expectation after JSON serialization", async () => {+ const f = fixture();+ const result = await onboardingFirstTask(f.input);+ const retained = JSON.parse(JSON.stringify({ productJourney: { artifact: result.artifact } })).productJourney.artifact;+ const bytes = Buffer.from(retained.contentBase64, "base64");+ expect(bytes.toString("utf8")).toBe(JSON.stringify(f.input.proof.expected));+ expect(retained.byteSize).toBe(bytes.byteLength);+ expect(retained.sha256).toBe(createHash("sha256").update(bytes).digest("hex"));+ expect(retained.input).toBe(f.input.proof.input);+ expect(retained.expected).toEqual(f.input.proof.expected);+ expect(retained.expected.sha256).toBe(createHash("sha256").update(retained.input).digest("hex"));+ });it.each([false, true])("answers the opening and approves one child, including plan mode %s", async plan => {const f = fixture({ plan });const result = await onboardingFirstTask(f.input);diff --git a/tests/runner-e2e/product-journeys/onboarding-first-task.ts b/tests/runner-e2e/product-journeys/onboarding-first-task.tsindex 9923c81ba4..ee50b6466a 100644--- a/tests/runner-e2e/product-journeys/onboarding-first-task.ts+++ b/tests/runner-e2e/product-journeys/onboarding-first-task.ts@@ -4,7 +4,8 @@ import { type createConnectionProof, verifyConnectionArtifact, verifyConnectionRimport { connectionDelay } from "../connection-target.js";import { activeRuns, firstTaskCompletionSettled, type Row } from "../first-task-scoring.js";import { isBlockedUnstartedWake, isTerminalUnstartedWake } from "../non-execution-wake.js";-import { JourneyError, type JourneyContext, type TargetSession } from "./types.js";+import { JourneyError, type JourneyContext, type OnboardingArtifactEvidence, type TargetSession } from "./types.js";+import { retainOnboardingArtifact } from "./artifact-evidence.js";export interface OnboardingFirstTaskInput {context: JourneyContext;@@ -16,12 +17,13 @@ export interface OnboardingFirstTaskInput {deadlineAt: number;own: TargetSession["own"];observeRun(run: Row): Promise<void>;+ onArtifact?(artifact: OnboardingArtifactEvidence): void;}export interface OnboardingFirstTaskResult {runIds: string[];onboardingIssueId: string;childIssueId: string;- artifact: { id: string; originatingRunId: string; sha256: string };+ artifact: OnboardingArtifactEvidence;}interface Snapshot {tasks: Row[];@@ -177,13 +179,16 @@ export async function onboardingFirstTask(input: OnboardingFirstTaskInput): Promconst bytes = await api.bytes(`/api/attachments/${artifact.id}/content`);const sha256 = createHash("sha256").update(bytes).digest("hex");if (artifact.byteSize !== bytes.byteLength || artifact.sha256 !== sha256 || !verifyConnectionArtifact(bytes, proof.expected)) fail("artifact_independent_check_failed");+ const retained = retainOnboardingArtifact({ id: artifact.id, originatingRunId: run.id, bytes, proof });+ input.onArtifact?.(retained);if (!snapshot.documents.some(row => row.issueId === child.id && !isPlanningDocument(row) && row.updatedByAgentId === agent.id &&typeof row.body === "string" && row.body.includes(proof.expected.nonce) && row.body.includes("connection-proof.json"))) fail("onboarding_child_document_missing");if (!snapshot.comments.some(row => row.authorAgentId === agent.id && String(row.body).includes(artifact.id) &&(String(row.body).includes(child.id) || String(row.body).includes(child.identifier ?? child.id)))) fail("onboarding_parent_result_links_missing");await page.reload({ timeout: remaining() });await page.locator(`a[href*="/api/attachments/${artifact.id}/content"]`).first().waitFor({ state: "visible", timeout: remaining() });- return { runIds: [...seen.keys()], onboardingIssueId: parent.id, childIssueId: child.id, artifact: { id: artifact.id, originatingRunId: run.id, sha256 } };+ return { runIds: [...seen.keys()], onboardingIssueId: parent.id, childIssueId: child.id,+ artifact: retained };}await wait(); snapshot = await load(parent.id);}diff --git a/tests/runner-e2e/product-journeys/types.ts b/tests/runner-e2e/product-journeys/types.tsindex 6c9b79ac63..65941f30d8 100644--- a/tests/runner-e2e/product-journeys/types.ts+++ b/tests/runner-e2e/product-journeys/types.ts@@ -27,6 +27,18 @@ export interface JourneyEvidence {campaignId?: string;attemptId?: string;operations?: JourneyOperations;+ artifact?: OnboardingArtifactEvidence;+}+export interface OnboardingArtifactEvidence {+ schema: "paperclip.product-journey.artifact/v1";+ id: string;+ originatingRunId: string;+ filename: "connection-proof.json";+ byteSize: number;+ sha256: string;+ contentBase64: string;+ input: string;+ expected: { nonce: string; count: number; total: number; sha256: string };}/** Normalized receipt from the private, Cloud-qualified eval-operations adapter. */export interface JourneyOperations {diff --git a/tests/runner-e2e/result-validation.ts b/tests/runner-e2e/result-validation.tsindex 460855184f..ea99d9a155 100644--- a/tests/runner-e2e/result-validation.ts+++ b/tests/runner-e2e/result-validation.ts@@ -3,6 +3,7 @@ import { connectionCheckpoints, connectionEvidencePasses, connectionRunSignals }import { STARTUP_REUSE_LAYERS, STARTUP_REUSE_REASONS } from "../../packages/adapter-utils/src/startup-reuse.js";import type { RunnerE2ECampaignAccounting, RunnerE2EResult } from "./types.js";import { DEPENDABLE_CELLS } from "./dependable-qualification.js";+import { validateOnboardingArtifact } from "./product-journeys/artifact-evidence.js";type Rule = (value: unknown, at: string) => void;const invalid = (at: string): never => {@@ -342,6 +343,7 @@ const fields = {productJourney: optional(shape({targetId: optional(string),campaignId: optional(string), attemptId: optional(string),+ artifact: optional((value, at) => { try { validateOnboardingArtifact(value); } catch { invalid(at); } }),operations: optional(closedShape({ campaignId: string, attemptId: string, modelCostUsd: nullable(number), setupCostUsd: nullable(number), requestCount: integer,feedback: closedShape({ collection: oneOf("complete", "partial", "unavailable"), complaints: integer, suggestions: integer }), traceIds: array(string) })),outcome: oneOf("passed", "failed", "blocked", "unsupported"),@@ -387,6 +389,9 @@ export function validateRetainedRunnerResult(): asserts value is RunnerE2EResult {result(value, "result");const checked = value as RunnerE2EResult;+ const artifact = checked.productJourney?.artifact;+ if (artifact && (checked.suiteId !== "product-journeys" || checked.caseId !== "cloud-onboarding" ||+ checked.runIds && !checked.runIds.includes(artifact.originatingRunId))) invalid("result.productJourney.artifact");if (checked.workerTiming !== undefined) {try { validateWorkerTiming(checked.workerTiming, checked); } catch { invalid("result.workerTiming"); }}