mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## 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>
157 lines
11 KiB
TypeScript
157 lines
11 KiB
TypeScript
import { mkdir, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { expect, type Locator } from "@playwright/test";
|
|
import { continuationScenario } from "../continuation-cases.js";
|
|
import { continuationAnswerCommitted, continuationCheckpointReady } from "../continuation-readiness.js";
|
|
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 { 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";
|
|
|
|
type Row = Record<string, any>;
|
|
export const DOCUMENT_READBACK_MS = 120_000;
|
|
interface Options { deadlineAt: number; directory: string; capture(id: string, label: string, file: string): Promise<void> }
|
|
|
|
export async function waitForClarificationDocument(visible: Locator, marker: string, deadlineAt: number) {
|
|
const remaining = () => {
|
|
const timeout = deadlineAt - Date.now();
|
|
if (!Number.isFinite(timeout) || timeout <= 0) throw new JourneyError("failed", "clarification_document_not_ready");
|
|
return timeout;
|
|
};
|
|
await expect(visible).toHaveCount(1, { timeout: remaining() });
|
|
await expect(visible).toBeVisible({ timeout: remaining() });
|
|
await expect(visible).toContainText(submittedReferencePattern(marker), { timeout: remaining() });
|
|
await expect(visible).toContainText(/afternoon/i, { timeout: remaining() });
|
|
remaining();
|
|
}
|
|
|
|
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`),
|
|
context.api.get<Row[]>(`${route}/documents`), context.api.get<Row[]>(`${route}/attachments`),
|
|
context.api.get<Row[]>(`/api/companies/${context.company.id}/issues?view=index&parentIds=${encodeURIComponent(issueId)}&limit=2`),
|
|
]);
|
|
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}`)));
|
|
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 };
|
|
}
|
|
|
|
export async function runClarificationJourney(context: JourneyContext, session: TargetSession,
|
|
campaignId: string, evidence: JourneyEvidence, options: Options) {
|
|
if (!context.agent || context.agent.runtimeMode !== "native" || !context.environmentId) {
|
|
throw new JourneyError("unsupported", "native_agent_and_environment_required");
|
|
}
|
|
const agent = context.agent, scenario = continuationScenario("question-answer-resume", campaignId.replaceAll("-", "_"));
|
|
const checkpoints: ContinuationCheckpoint[] = [];
|
|
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,
|
|
observation => retain("clarification-run-failure.json", observation));
|
|
const settle = async (answeredId?: string, final = false) => {
|
|
let stable = "";
|
|
while (Date.now() < options.deadlineAt) {
|
|
const state = await read();
|
|
const pending = state.interactions.filter(i => i.kind === "ask_user_questions" && i.status === "pending");
|
|
const ready = continuationAnswerCommitted(state.interactions, answeredId)
|
|
&& continuationCheckpointReady({ issue: state.currentIssue as { status: string; executionRunId?: string }, runs: state.runs as Array<Row & { id: string; status: string }>, interactions: state.interactions })
|
|
&& (final ? state.currentIssue.status === "done" && !pending.length : pending.length === 1)
|
|
&& !state.currentIssue.scheduledRetry && !state.currentIssue.activeRecoveryAction;
|
|
const key = ready ? JSON.stringify([state.currentIssue.status, state.currentIssue.executionRunId,
|
|
state.runs.map(run => [run.id, run.status]), state.interactions.map(i => [i.id, i.status])]) : "";
|
|
if (key && key === stable) return state;
|
|
stable = key;
|
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
}
|
|
throw new JourneyError("failed", final ? "clarification_not_completed" : "clarification_question_not_ready");
|
|
};
|
|
const open = () => context.page.goto(`${context.api.origin}/${encodeURIComponent(context.company.issuePrefix)}/issues/${encodeURIComponent(issue!.identifier ?? issue!.id)}`, { waitUntil: "domcontentloaded" });
|
|
const snapshot = async (phase: "initial" | "answered" | "final", state: Awaited<ReturnType<typeof read>>) => {
|
|
const documents = await Promise.all(state.documents.map(document => context.api.get<Row>(`/api/issues/${issue!.id}/documents/${encodeURIComponent(document.key)}`)));
|
|
const point = { phase, issue: state.currentIssue, runs: structuredClone(state.runs), interactions: structuredClone(state.interactions),
|
|
documents, attachments: state.attachments, children: state.children, comments: [] } as unknown as ContinuationCheckpoint;
|
|
checkpoints.push(point);
|
|
await retain("clarification.json", { checkpoints });
|
|
await open();
|
|
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,
|
|
issuePrefix: context.company.issuePrefix, agentName: agent.name, title, prompt: scenario.prompt,
|
|
workMode: "standard", requireExplicitTitle: true,
|
|
beforeDispatch: () => session.own({ kind: "issue", name: title, journeyId: "question-answer-resume" }) });
|
|
await session.own({ kind: "issue", name: title, id: created.issueId, journeyId: "question-answer-resume" });
|
|
issue = await context.api.get<Row>(`/api/issues/${created.issueId}`);
|
|
let state = await settle();
|
|
for (const [index, input] of [{ choice: "Afternoon" }, { text: scenario.answer, allowProviderCustomAnswer: true }].entries()) {
|
|
const point = await snapshot(index === 0 ? "initial" : "answered", state);
|
|
const question = state.interactions.find(i => i.kind === "ask_user_questions" && i.status === "pending")!;
|
|
const questionFailure = clarificationQuestionFailure(point, question, index === 0);
|
|
if (questionFailure) throw new JourneyError("failed", questionFailure);
|
|
if (point.documents.length || point.attachments.length || point.children.length || point.issue.status === "done") {
|
|
throw new JourneyError("failed", "clarification_premature_output");
|
|
}
|
|
await answerResumeQuestionThroughUi(context.page, question, input);
|
|
state = await settle(question.id, index === 1);
|
|
}
|
|
const final = await snapshot("final", state);
|
|
if (final.documents.length !== 1) throw new JourneyError("failed", "clarification_document_missing");
|
|
const document = final.documents[0]!;
|
|
const href = `/${encodeURIComponent(context.company.issuePrefix)}/issues/${encodeURIComponent(issue.identifier ?? issue.id)}#document-${encodeURIComponent(document.key)}`;
|
|
await context.page.goto(new URL(href, context.api.origin).href, { waitUntil: "domcontentloaded" });
|
|
await context.page.reload({ waitUntil: "domcontentloaded" });
|
|
// With the task chat shell and Artifacts V1, saved documents render in the
|
|
// properties pane's Artifacts tab, not the center column. Open it as a user would.
|
|
await openDocumentAuthoring(context);
|
|
const visible = context.page.locator(`[id=${JSON.stringify(`document-${document.key}`)}]:visible, [id=${JSON.stringify(`side-panel-content-document:${document.key}`)}]:visible`);
|
|
// The API already returned the saved document, so this is a bounded UI readback,
|
|
// not agent work time: a missing view must not hold the worker until the case deadline.
|
|
await waitForClarificationDocument(visible, scenario.marker, Math.min(options.deadlineAt, Date.now() + DOCUMENT_READBACK_MS));
|
|
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 })));
|
|
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");
|
|
}
|