mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
test(e2e): retain bound question-run failure evidence (#23041)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - Product E2E tests check real tasks and their saved results. > - The question journey must keep evidence when an agent run fails. > - It currently rejects that run before the first stable checkpoint is saved. > - The private report then has checks but no run failure code. > - This PR saves a small, bound failure receipt before rejection. > - The test still fails. The receipt helps the next diagnosis. ## Linked Issues or Issue Description **Describe the bug** When a native run fails before the first question checkpoint, `readClarificationState` throws `agent_run_failed`. The final `clarification.json` has no checkpoints. The report cannot show the run's machine error code. **Steps to reproduce** 1. Give the question journey an owned native task with a terminal failed run. 2. Read the first question state. 3. Inspect the private report after the journey fails. **Expected behavior** Keep a private receipt with the bound task and run IDs, status, and machine error code. Preserve the failed verdict and the empty checkpoint list. **Additional context** This repairs missing evidence. It does not repair or establish the cause of an agent failure. The reference-grading repair in #22949 is separate and remains unchanged. ## What Changed - Split binding checks from outcome checks in the shared journey validator. Check every run's company, task, agent, model, and environment before retaining a failure. Existing consumers still use the full validator. - Save `clarification-run-failure.json` in the private story directory when the question journey rejects a failed run. Keep only IDs, status, and a bounded machine code. Exclude raw errors, prompts, and provider state. - Keep the original failure if the receipt write fails. Add a fixed secondary cause code. - Add failure, binding, privacy, and final-grading regressions. Document the private receipt. ## Verification - Red: the initial regression had 6 failures and 4 passes on the old code. It reproduced the lost receipt and the first-error binding gap. - Green: 175 tests in 9 affected agent and clarification support files pass with the repository's Product E2E Vitest config. - `pnpm test:e2e:runner:typecheck` passes. - `pnpm verify` could not select tests. The managed Git storage guard rejects `git ls-files`. The focused checks above ran directly. Final CI must supply its required coverage. - The journey regression calls the real observer and validator, saves the private files, and reads them after final grading. It checks that all 11 checks still fail and no question checkpoint is invented. The task-creation UI boundary is simulated. - No live provider run was started. This is local report-path evidence, not a new staging pass. The reviewed harness must be adopted and checked through the authorized QA process after merge. ## Risks Low scope. Only Product E2E support code and its docs change. The shared validator now checks all bindings before it reports the first failed outcome. Foreign evidence still fails closed. The existing outcome, run limit, cancellation, and recovery checks remain in place. The private receipt is not added to the public report. ## Model Used - OpenAI Codex, based on GPT-6, with reasoning, tools, and code execution. This run does not expose a more specific provider model ID. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
ab099dc379
commit
f14929d21b
4 files changed
+133
-11
No files matched your search
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<typeof import("../user-actions.js")>(),
|
||||
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<string, any>[] = []) {
|
||||
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([]);
|
||||
});
|
||||
|
||||
@@ -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<void>) {
|
||||
const route = `/api/issues/${issueId}`;
|
||||
const [currentIssue, summaries, interactions, documents, attachments, children] = await Promise.all([
|
||||
context.api.get<Row>(route), context.api.get<Row[]>(`${route}/runs`), context.api.get<Row[]>(`${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<Row>(`/api/heartbeat-runs/${summary.runId}`)));
|
||||
validateAgentTaskState(context, issueId, { currentIssue: currentIssue as Row & { id: string; status: string },
|
||||
taskRuns: runs as Array<Row & { status: string }>, interactions: interactions as Array<Row & { id: string; status: string }>, comments: [], attachments: [] }, 3);
|
||||
const state = { currentIssue: currentIssue as Row & { id: string; status: string },
|
||||
taskRuns: runs as Array<Row & { status: string }>, interactions: interactions as Array<Row & { id: string; status: string }>, 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<Row>(`/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");
|
||||
}
|
||||
Reference in new issue
Block a user