fix(e2e): wait for hire retries and keep API failure codes in journey evidence (#22914)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys test real hiring and delegation on a hosted test
stack every day.
> - The hire-delegate-reuse journey failed on three attempts today, at
three different steps.
> - One failure graded a hired agent's run as final while its
exact-session retry was still scheduled. #22826 fixed the same gap for
agent task journeys, but the hire observer has its own run check.
> - The other two failures recorded only `journey_operation_failed`. The
API client gives fixed failure codes, but the journey result dropped
them.
> - This pull request makes the hire observer wait for a scheduled
same-run retry, and it keeps the fixed API failure codes in the
evidence.
> - The benefit is fewer false failures, and a clear failure code when a
hosted API call fails.

## Linked Issues or Issue Description

Refs #22826, #22825

**What happened?**
The daily QA staging smoke failed `hire-delegate-reuse` three times on
2026-11-25:
1. Setup failed after the lead agent was created. The result said only
`journey_operation_failed`.
2. The lead hired the teammate and replied. On the next observation the
journey failed with `journey_operation_failed`.
3. The first delegated task completed. During the review task, the hired
agent's run was `running`. One second later the journey failed with
`hire_native_run_failed`.

**Expected behavior**
A failed native run with an agent-owned exact-session retry scheduled
inside the campaign deadline is still in progress. The journey keeps
observing it. A failure caused by an API status or transport error is
recorded with that fixed code, for example `api_status_500`.

**Steps to reproduce**
Run the new tests against the previous code. `assertHireRuns` throws
`hire_native_run_failed` for a pending same-run retry. `journeyFailure`
turns `ConnectionFailure("api_status_500")` into
`journey_operation_failed`.

**Paperclip version or commit**
Harness pin 6d5541b109 on the QA staging
smoke.

## What Changed

- `assertHireRuns` takes an optional campaign deadline. With it, a run
that `isPendingNativeRecovery` accepts is not treated as failed. The
observer passes `options.deadlineAt`. The idle wait still needs every
run to succeed, so a pending retry never counts as completion.
- `journeyFailure` keeps a `ConnectionFailure` code when it is one of
the fixed codes: `api_status_NNN`, `api_request_failed`,
`sensitive_api_request_failed`, `invalid_api_route`,
`invalid_api_timeout`. It matches the class by name as well, because the
Cloud provider can load its own copy of the class. Other errors still
become `journey_operation_failed`.

## Verification

- Red: the new hire recovery test and three new `journeyFailure` tests
failed on the previous code.
- Green: `npx vitest run --config tests/runner-e2e/vitest.config.ts` on
`hire-delegate-evidence`, `hire-delegate-flow`, `journey-failure`,
`agent-recovery` and `campaign`: 124 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/runner-e2e` passes.
- SDK input pins refreshed with `source-sdk-public-inputs.mjs --write`.
No change.
- After merge, I will pin `QA_SMOKE_HARNESS_SHA` to the merge commit and
run `hire-delegate-reuse` alone on staging.

## Risks

- Low risk. The change is test harness code only.
- The retry wait uses the same strict predicate as #22826: native
runtime, agent-owned recovery, remaining attempts, no successor, and a
retry time inside the deadline. Terminal and exhausted failures still
fail at once.
- Only fixed, identifier-shaped codes are kept. Free-form messages, URLs
and response bodies are still dropped.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, GitHub CLI, read-only AWS S3 evidence access).

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 05:18:07 -06:00
1 parent 91e9365d59
commit 0e4dcd9be8
6 files changed
+67 -4

No files matched your search

+6
View File
@@ -571,3 +571,9 @@ The recovery wait gates the shared task snapshot before it reaches any journey
consumer. Plan revision, Plan approval and protected-action decisions cannot use
a pending card while its producing run is still recovering. A recovery that
outlives the original campaign deadline fails without making a decision.
The hire-delegate-reuse observer applies the same exact-session retry wait to
lead and hired-agent runs. Its idle check still requires every run to succeed.
A journey failure from a hosted API call keeps its fixed code, such as
`api_status_500` or `api_request_failed`; other errors stay
`journey_operation_failed`.
@@ -146,6 +146,25 @@ describe("deployment hiring qualification", () => {
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.taskRun, f.taskRun])).toThrow();
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.leadRun, f.taskRun], 5)).toThrow();
});
it("keeps observing a hired task run while its exact-session retry is scheduled inside the deadline", () => {
const f = fixture(), now = Date.now(), deadline = now + 60_000;
const pending = { ...f.taskRun, status: "failed", nativeIssueId: f.task.id, nativePhase: "retryable_failure", errorCode: "native_session_interrupted",
finishedAt: new Date(now - 1_000).toISOString(), execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: 1,
maxAttempts: 3, recoveryOwner: "agent", retryAt: new Date(now + 1_000).toISOString() } };
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.leadRun, pending], undefined, undefined, undefined, deadline)).not.toThrow();
// A pending retry is never completion, and the deadline is required to wait at all.
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.leadRun, pending], 2, undefined, undefined, deadline)).not.toThrow();
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.leadRun, pending])).toThrow("hire_native_run_failed");
for (const change of [{ execution: { ...pending.execution, attempt: 3 } }, { execution: { ...pending.execution, recoveryOwner: "user" } },
{ execution: { ...pending.execution, retryAt: new Date(deadline + 1_000).toISOString() } }, { nativePhase: "terminal_failure" },
{ execution: { ...pending.execution, successorRunId: "other-run" } }]) {
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.leadRun, { ...pending, ...change }], undefined, undefined, undefined, deadline))
.toThrow("hire_native_run_failed");
}
// Recovery never relaxes the task, agent and company bindings.
expect(() => assertHireRuns(scope, f.agent.id, [f.task], [f.leadRun, { ...pending, agentId: scope.leadId }], undefined, undefined, undefined, deadline))
.toThrow("hire_run_scope_mismatch");
});
it("rejects a lead task run from create-self-then-reassign even after the saved assignee is correct", () => {
const f = fixture();
const delegation = { ...f.run("delegate-chat", scope.chatId, scope.leadId), status: "running" };
@@ -3,6 +3,7 @@ import { createRequire } from "node:module";
import { applyCompanyPrefix } from "../../../ui/src/lib/company-routes.js";
import { parseIssueReferenceFromHref, remarkLinkIssueReferences } from "../../../ui/src/lib/issue-reference.js";
import { JourneyError } from "./types.js";
import { isPendingNativeRecovery } from "./workspace-deferral.js";
type Row = Record<string, any>;
const uiRequire = createRequire(new URL("../../../ui/package.json", import.meta.url));
@@ -134,7 +135,9 @@ export function hireResultLinkMatches(scope: Pick<HireScope, "origin" | "issuePr
&& url.pathname === `/${scope.issuePrefix}/issues/${id}`);
} catch { return false; }
}
export function assertHireRuns(scope: HireScope, hiredId: string | undefined, tasks: Row[], runs: Row[], count?: number, requestedCommentIds?: string[], comments?: Row[]) {
/** With a deadline, a failed run whose exact-session retry is scheduled inside it is
* still in progress: callers keep observing until the same run succeeds. */
export function assertHireRuns(scope: HireScope, hiredId: string | undefined, tasks: Row[], runs: Row[], count?: number, requestedCommentIds?: string[], comments?: Row[], deadlineAt?: number) {
const bindings = new Map([[scope.chatId, scope.leadId], ...tasks.map(task => [task.id, hiredId] as [string, string | undefined])]);
if (runs.length > 7 || count !== undefined && runs.length !== count || new Set(runs.map(run => run.id)).size !== runs.length) {
throw new JourneyError("failed", "hire_run_limit_mismatch");
@@ -180,7 +183,8 @@ export function assertHireRuns(scope: HireScope, hiredId: string | undefined, ta
requests.add(context.wakeCommentId);
}
}
if (!["queued", "running", "succeeded"].includes(run.status)) throw new JourneyError("failed", "hire_native_run_failed");
const recovering = deadlineAt !== undefined && isPendingNativeRecovery(run, deadlineAt);
if (!recovering && !["queued", "running", "succeeded"].includes(run.status)) throw new JourneyError("failed", "hire_native_run_failed");
if (run.status === "succeeded" && (run.runtimeMode !== "native" || provider?.kind !== scope.provider || provider?.model !== scope.model
|| run.contextSnapshot?.paperclipEnvironment?.id !== scope.environmentId)) throw new JourneyError("failed", "hire_run_runtime_mismatch");
if (run.status === "succeeded" && scope.connectionChoice) {
@@ -148,8 +148,8 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target
const runs = [...canonical.values()];
const comments = await readObserved<Row[]>(`/api/issues/${chat.id}/comments?order=asc`);
const requestIds = comments.filter(row => row.authorUserId === context.user.id).map(row => row.id);
const completionRepliesReady = assertHireRuns(scope, hiredId, owned.tasks, runs, undefined, requestIds, comments);
for (const run of projectedRuns) assertHireRuns(scope, hiredId, owned.tasks, [run], undefined, requestIds, comments);
const completionRepliesReady = assertHireRuns(scope, hiredId, owned.tasks, runs, undefined, requestIds, comments, options.deadlineAt);
for (const run of projectedRuns) assertHireRuns(scope, hiredId, owned.tasks, [run], undefined, requestIds, comments, options.deadlineAt);
await retain("hire-delegate-observation.json", { scope: { ...scope, connectionBinding: undefined, connectionChoice: undefined }, chat, project,
agents: owned.agents.map(row => ({ id: row.id, name: row.name, reportsTo: row.reportsTo })), tasks: owned.tasks,
runs: runs.map(run => ({ id: run.id, issueId: hireRunIssueId(run), agentId: run.agentId, status: run.status })) });
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { ConnectionFailure } from "../connection-config.js";
import { journeyFailure } from "./launch.js";
describe("journeyFailure", () => {
it("keeps the controlled HTTP status code from a failed API request", () => {
expect(journeyFailure(new ConnectionFailure("api_status_500"))).toEqual({ outcome: "failed", code: "api_status_500" });
expect(journeyFailure(new ConnectionFailure("api_status_409"))).toEqual({ outcome: "failed", code: "api_status_409" });
});
it("keeps the controlled transport failure codes", () => {
for (const code of ["api_request_failed", "sensitive_api_request_failed", "invalid_api_route", "invalid_api_timeout"]) {
expect(journeyFailure(new ConnectionFailure(code))).toEqual({ outcome: "failed", code });
}
});
it("matches a connection failure loaded from another module instance by its class name", () => {
class ConnectionFailure extends Error {}
expect(journeyFailure(new ConnectionFailure("api_status_502"))).toEqual({ outcome: "failed", code: "api_status_502" });
});
it("never retains free-form messages", () => {
expect(journeyFailure(new ConnectionFailure("api_status_500 https://example.test/?token=secret"))).toEqual({ outcome: "failed", code: "journey_operation_failed" });
expect(journeyFailure(new Error("api_status_500"))).toEqual({ outcome: "failed", code: "journey_operation_failed" });
expect(journeyFailure(new Error("page.click: Timeout 30000ms exceeded"))).toEqual({ outcome: "failed", code: "journey_operation_failed" });
});
});
@@ -29,6 +29,7 @@ import { companyAccessIsolation } from "./company-access-flow.js";
import { inboxTriage } from "./inbox-triage-flow.js";
import { JourneyError, type JourneyContext, type JourneyEvidence, type JourneyOutcome, type TargetLifecycleInput, type TargetProvider, type TargetSession } from "./types.js";
import type { RunnerE2EResult } from "../types.js";
import { ConnectionFailure } from "../connection-config.js";
import { regenerateRunnerDashboard } from "../dashboard-regenerate.js";
import { resolveRunnerE2ESource } from "../source.js";
import { validateRetainedRunnerResult } from "../result-validation.js";
@@ -75,6 +76,12 @@ export function journeyFailure(error: unknown): { outcome: Exclude<JourneyOutcom
if (candidate && ["failed", "blocked", "unsupported"].includes(candidate.outcome ?? "") && /^[a-z][a-z0-9_-]{0,100}$/.test(candidate.code ?? "")) {
return { outcome: candidate.outcome as Exclude<JourneyOutcome, "passed">, code: candidate.code! };
}
// ConnectionApi failures carry only these fixed codes. Providers may load
// their own copy of the class, so match the name as well as the instance.
if ((error instanceof ConnectionFailure || error instanceof Error && error.constructor?.name === "ConnectionFailure")
&& /^(api_status_[1-5][0-9]{2}|(sensitive_)?api_request_failed|invalid_api_route|invalid_api_timeout)$/.test(error.message)) {
return { outcome: "failed", code: error.message };
}
// Browser errors may contain keys, codes, URLs and form values. Never retain them.
return { outcome: "failed", code: "journey_operation_failed" };
}