Merge remote-tracking branch 'origin/master' into swarm-neon-tmp

* origin/master:
  refactor(ui): prune 36 thin mocked jsdom UI tests and consolidate replay masking checks (#22834)
  docs: correct three budget claims from the review of the budget docs (#22833)
  refactor(test): prune 28 completed migration, prose-grep, and Storybook fixture tests (#22832)
  fix(e2e): observe scheduled native retries before grading tasks (#22826)
This commit is contained in:
Dotta committed 2026-11-24 16:57:44 -06:00
commit 83bf07cac4
85 files changed
+397 -15059

No files matched your search

+14
View File
@@ -557,3 +557,17 @@ retains the five allowlisted task observations. The adjacent
Valid, wrong and missing evidence
controls calibrate the independent oracle. Registration and local checks do not
claim a Cloud staging pass or admission to a daily plan.
Agent task journeys keep observing an exact native-session retry when the API
reports a retryable failure, agent-owned recovery, remaining attempts and a retry
time inside the original campaign deadline. Older projections can omit the
optional successor field when there is no successor. The same run must later
succeed; the temporary failed state never counts as completion. Terminal,
unbound, exhausted and out-of-deadline failures still fail immediately. The
original run limit, budgets, deadline and artifact checks stay in effect.
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.
@@ -19,6 +19,8 @@ import { createTaskThroughUi, submitTaskReply } from "../user-actions.js";
import { agentJourneyRuns } from "./catalog.js";
import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js";
import { isPendingNativeRecovery } from "./workspace-deferral.js";
type Row = Record<string, any>;
type AgentJourney = Exclude<keyof typeof agentJourneyRuns,
"ask-question"
@@ -32,7 +34,10 @@ type AgentJourney = Exclude<keyof typeof agentJourneyRuns,
| "saved-skill-use">;
interface TaskState { currentIssue: Row & { id: string; status: string }; taskRuns: Array<Row & { status: string }>; comments: Row[]; interactions: Array<Row & { id: string; status: string }>; attachments: StoryDelivery[] }
interface Options { deadlineAt: number; directory: string; capture(id: string, label: string, file: string): Promise<void> }
const active = (run: Row) => ["queued", "running"].includes(run.status);
const ACTIVE_RUN_STATUSES = ["queued", "running"];
const SETTLED_RUN_STATUSES = ["succeeded", "cancelled"];
const active = (run: Row) => ACTIVE_RUN_STATUSES.includes(run.status);
const settledRun = (run: Row) => SETTLED_RUN_STATUSES.includes(run.status);
/** These fixture replies are plain text. The rich editor escapes underscores in
* its persisted Markdown; compare the intended text while retaining exact count
@@ -59,14 +64,15 @@ export function startedTaskRuns(state: Pick<TaskState, "taskRuns">) {
return state.taskRuns.filter(run => !retiredBeforeProviderStart(run));
}
/** The task is done after exactly `count` started runs, with nothing active or pending. */
/** The task is done after exactly `count` started runs, and every run finished as succeeded or cancelled:
* an active run, or a failed run still waiting for its scheduled same-run retry, is not settled. */
export function agentTaskSettled(state: TaskState, count: number) {
return state.currentIssue.status === "done" && startedTaskRuns(state).length === count && state.taskRuns.every(run => !active(run))
return state.currentIssue.status === "done" && startedTaskRuns(state).length === count && state.taskRuns.every(settledRun)
&& 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[] = []) {
export function validateAgentTaskState(context: JourneyContext, issueId: string, state: TaskState, maxRuns: number, allowedCancelled: string[] = [], deadlineAt?: 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");
@@ -78,7 +84,10 @@ 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");
if (!["queued", "running", "succeeded"].includes(run.status) && !(run.status === "cancelled" && allowedCancelled.includes(run.id))) throw new JourneyError("failed", "agent_run_failed");
// 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;
if (!active(run) && run.status !== "succeeded" && !(run.status === "cancelled" && allowedCancelled.includes(run.id))) throw new JourneyError("failed", "agent_run_failed");
}
}
@@ -114,7 +123,7 @@ export async function runAgentJourney(id: AgentJourney, context: JourneyContext,
await session.own({ kind: "issue", name: title, id: created.issueId, journeyId: id });
return context.api.get<Row>(`/api/issues/${created.issueId}`);
};
const read = async (issue: Row): Promise<TaskState> => {
const read = async (issue: Row): Promise<TaskState> => waitFor(options.deadlineAt, async () => {
const route = `/api/issues/${issue.id}`;
const [currentIssue, summaries, comments, interactions, attachments] = await Promise.all([
context.api.get<TaskState["currentIssue"]>(route), context.api.get<Row[]>(`${route}/runs`), context.api.get<Row[]>(`${route}/comments?order=asc`),
@@ -124,9 +133,11 @@ export async function runAgentJourney(id: AgentJourney, context: JourneyContext,
const taskRuns = await Promise.all(summaries.map(summary => context.api.get<TaskState["taskRuns"][number]>(`/api/heartbeat-runs/${summary.runId}`)));
const state = { currentIssue, taskRuns, comments, interactions, attachments };
await retain(`${issue.id}-latest.json`, state);
validateAgentTaskState(context, issue.id, state, maxRuns, cancelled);
validateAgentTaskState(context, issue.id, state, maxRuns, cancelled, options.deadlineAt);
return state;
};
// No consumer may act on a card, reply or artifact produced by an unsettled
// retry. Gate the shared read so Plan and protected-action waits stay safe too.
}, state => !state.taskRuns.some(run => isPendingNativeRecovery(run, options.deadlineAt)), "agent_recovery_not_completed");
const settled = (issue: Row, count: number) => waitFor(options.deadlineAt, () => read(issue), state =>
agentTaskSettled(state, count), "agent_task_not_completed");
const finalReply = async (issue: Row, state: TaskState, marker?: string) => {
@@ -0,0 +1,96 @@
import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { runAgentJourney } from "./agent-flows.js";
import { runnerTasks } from "../catalog.js";
import { createTaskThroughUi } from "../user-actions.js";
import { decideProtectedActionThroughUi } from "../protected-action-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: vi.fn() }));
vi.mock("../protected-action-flow.js", async importOriginal => ({ ...await importOriginal<typeof import("../protected-action-flow.js")>(), decideProtectedActionThroughUi: vi.fn() }));
vi.mock("@playwright/test", () => ({ expect: () => ({ toBeVisible: async () => {}, toHaveAttribute: async () => {} }) }));
type Row = Record<string, any>;
const directories: string[] = [];
afterEach(async () => {
vi.clearAllMocks();
await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true })));
});
async function fixture(journey: "plan-revise-accept" | "protected-actions", neverRecovers = false) {
const directory = await mkdtemp(path.join(os.tmpdir(), "agent-recovery-decision-")); directories.push(directory);
const campaign = "journey-fixture", deadlineAt = Date.now() + (neverRecovers ? 1_500 : 15_000);
const markers = runnerTasks.find(row => row.id === "plan-revise-accept")!.buildPlanMarkers!(campaign.replaceAll("-", "_"));
const now = Date.now();
let stage = 1, rejects = 0;
const reads = new Map<number, number>(), decisions: number[] = [];
const stop = new Error("stop-after-proven-decision");
const issue = { id: "task", identifier: "QA-1", companyId: "company", assigneeAgentId: "agent", status: "in_progress" };
const recovering = () => neverRecovers || (reads.get(stage) ?? 0) < 3;
const pending = () => ({ id: `card-${stage}`, status: "pending", kind: "request_confirmation",
payload: { target: { type: "issue_document", key: "plan", revisionId: `revision-${stage}` } } });
const run = (n: number) => ({ id: `run-${n}`, issueId: "task", nativeIssueId: "task", companyId: "company", agentId: "agent",
runtimeMode: "native", status: n === stage && recovering() ? "failed" : "succeeded",
nativePhase: n === stage && recovering() ? "retryable_failure" : "committed", errorCode: "native_session_interrupted",
finishedAt: new Date(now - 1_000).toISOString(), contextSnapshot: { issueId: "task", paperclipEnvironment: { id: "environment" } },
runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } },
execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: 1, maxAttempts: 3,
recoveryOwner: "agent", retryAt: new Date(now + 1_000).toISOString() } });
const api = { origin: "https://qa.example.test", get: vi.fn(async (route: string) => {
if (route === "/api/issues/task") return { ...issue };
if (route === "/api/issues/task/runs") return Array.from({ length: stage }, (_, i) => ({ runId: `run-${i + 1}` }));
const match = /^\/api\/heartbeat-runs\/run-(\d+)$/.exec(route);
if (match) {
const n = Number(match[1]);
if (n === stage) reads.set(stage, (reads.get(stage) ?? 0) + 1);
return run(n);
}
if (route === "/api/issues/task/interactions") return [pending()];
if (route === "/api/issues/task/comments?order=asc" || route === "/api/issues/task/attachments") return [];
if (route === "/api/tool-connections/service") return { id: "service", enabled: true };
if (route === "/api/issues/task/documents/plan") {
expect(recovering(), "must not read the decision's Plan while its producing turn recovers").toBe(false);
return { id: "plan", key: "plan", latestRevisionId: `revision-${stage}`, latestRevisionNumber: stage,
body: stage === 1 ? `1. ${markers.draft}\n2. Check it` : `1. ${markers.revised}\n2. Check it\n3. Finish` };
}
throw new Error(`Unexpected read ${route}`);
}) };
const locator: Row = { last() { return this; }, first() { return this; }, getByTestId() { return this; }, locator() { return this; }, fill: async () => {} };
const page = { goto: async () => {}, reload: async () => {}, locator: () => locator, getByTestId: () => locator,
getByRole: (_role: string, options: { name: string }) => ({ last() { return this; }, click: async () => {
expect(recovering(), "a human decision must wait for the producing native turn").toBe(false);
if (options.name === "Reject") { if (++rejects === 2) stage = 2; }
else { decisions.push(stage); throw stop; }
} }) };
vi.mocked(createTaskThroughUi).mockResolvedValue({ issueId: "task" } as any);
vi.mocked(decideProtectedActionThroughUi).mockImplementation(async () => {
expect(recovering(), "protected approval must wait for the producing turn").toBe(false);
decisions.push(stage); throw stop;
});
const context = { api, page, company: { id: "company", issuePrefix: "QA" }, user: { id: "user" }, environmentId: "environment",
agent: { id: "agent", name: "QA agent", provider: "opencode", model: "model", runtimeMode: "native" },
fixtures: { reviewService: { id: "service", name: "Review", connectionId: "service", invocationCount: () => 0 } } } as unknown as JourneyContext;
return { api, reads, decisions, stop, execute: () => runAgentJourney(journey, context, { own: async () => {} } as unknown as TargetSession,
campaign, { checks: [] } as unknown as JourneyEvidence, { directory, deadlineAt, capture: async () => {} }) };
}
it("waits through both draft and revised Plan recovery before requesting changes or approving", async () => {
const f = await fixture("plan-revise-accept");
await expect(f.execute()).rejects.toBe(f.stop);
expect([...f.reads.entries()]).toEqual([[1, 3], [2, 3]]);
expect(f.decisions).toEqual([2]);
});
it("waits through pending protected-action recovery before making its first decision", async () => {
const f = await fixture("protected-actions");
await expect(f.execute()).rejects.toBe(f.stop);
expect(f.reads.get(1)).toBe(3);
expect(f.decisions).toEqual([1]);
});
it.each(["plan-revise-accept", "protected-actions"] as const)("does not decide %s when recovery outlives the original deadline", async journey => {
const f = await fixture(journey, true);
await expect(f.execute()).rejects.toMatchObject({ code: "agent_recovery_not_completed" });
expect(f.decisions).toEqual([]);
expect(f.api.get.mock.calls.some(([route]) => route.endsWith("/documents/plan"))).toBe(false);
expect(decideProtectedActionThroughUi).not.toHaveBeenCalled();
});
@@ -0,0 +1,75 @@
import { afterEach, expect, it, vi } from "vitest";
import { agentTaskSettled, validateAgentTaskState, waitFor } from "./agent-flows.js";
import type { JourneyContext } from "./types.js";
type Row = Record<string, any>;
const context = { company: { id: "company" }, environmentId: "environment",
agent: { id: "agent", provider: "opencode", model: "model", runtimeMode: "native" } } as JourneyContext;
function snapshot() {
const now = Date.now();
const run: Row & { status: string } = { id: "run", companyId: "company", agentId: "agent", issueId: "task", nativeIssueId: "task",
runtimeMode: "native", status: "failed", nativePhase: "retryable_failure", errorCode: "native_session_interrupted",
finishedAt: new Date(now - 1_000).toISOString(), contextSnapshot: { issueId: "task", paperclipEnvironment: { id: "environment" } },
runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } },
execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: 1, maxAttempts: 3,
recoveryOwner: "agent", retryAt: new Date(now + 1_000).toISOString() } };
return { currentIssue: { id: "task", companyId: "company", assigneeAgentId: "agent", status: "in_progress" },
taskRuns: [run], comments: [], interactions: [], attachments: [] };
}
afterEach(() => vi.useRealTimers());
it("observes a scheduled exact-run recovery through success within the original deadline and run limit", async () => {
vi.useFakeTimers();
const state = snapshot(), deadline = Date.now() + 5_000;
const pending = waitFor(deadline, async () => {
validateAgentTaskState(context, "task", state, 1, [], deadline);
return state;
}, value => agentTaskSettled(value, 1), "agent_task_not_completed");
const assertion = expect(pending).resolves.toBe(state);
await vi.advanceTimersByTimeAsync(1_000);
state.taskRuns[0]!.status = "succeeded";
state.taskRuns[0]!.nativePhase = "committed";
state.currentIssue.status = "done";
await vi.advanceTimersByTimeAsync(1_000);
await assertion;
expect(state.taskRuns.map(run => run.id)).toEqual(["run"]);
});
it.each([
["terminal phase", (run: Row) => { run.nativePhase = "terminal_failure"; }],
["terminal cause", (run: Row) => { run.errorCode = run.execution.cause = "native_provider_terminal_failed"; }],
["no retry owner", (run: Row) => { run.execution.recoveryOwner = "board"; }],
["exhausted retry", (run: Row) => { run.execution.attempt = 3; }],
["late retry", (run: Row) => { run.execution.retryAt = new Date(Date.now() + 6_000).toISOString(); }],
["different successor", (run: Row) => { run.execution.successorRunId = "other-run"; }],
["foreign model", (run: Row) => { run.runnerProfileJson.nativeExecutionInput.provider.model = "other"; }],
["foreign task", (run: Row) => { run.nativeIssueId = "other"; }],
] as const)("keeps %s fatal", (_label, change) => {
const state = snapshot(); change(state.taskRuns[0]!);
expect(() => validateAgentTaskState(context, "task", state, 1, [], Date.now() + 5_000)).toThrow();
});
it("never counts a pending recovery as settled even if the task snapshot says done", () => {
const state = snapshot(); state.currentIssue.status = "done";
expect(agentTaskSettled(state, 1)).toBe(false);
});
it("keeps the original campaign deadline when recovery never completes", async () => {
vi.useFakeTimers();
const state = snapshot(), deadline = Date.now() + 2_000;
const pending = waitFor(deadline, async () => {
validateAgentTaskState(context, "task", state, 1, [], deadline);
return state;
}, value => agentTaskSettled(value, 1), "agent_task_not_completed");
const assertion = expect(pending).rejects.toMatchObject({ code: "agent_task_not_completed" });
await vi.advanceTimersByTimeAsync(2_000);
await assertion;
});
it.each([null, undefined])("accepts an explicitly scheduled same-run retry with successor %s", successor => {
const state = snapshot(); state.taskRuns[0]!.execution.successorRunId = successor;
expect(() => validateAgentTaskState(context, "task", state, 1, [], Date.now() + 5_000)).not.toThrow();
expect(() => validateAgentTaskState(context, "task", state, 1)).toThrow("agent_run_failed");
expect(() => validateAgentTaskState(context, "task", state, 0, [], Date.now() + 5_000)).toThrow("agent_task_binding_mismatch");
});
@@ -292,7 +292,7 @@ describe("Cloud canonical onboarding first task", () => {
await expect(onboardingFirstTask(f.input)).resolves.toMatchObject({ artifact: { originatingRunId: "child-run" } });
expect(connectionDelay).toHaveBeenCalledOnce();
});
it.each(["active", "native-recovery", "workspace-replacement"])("waits past an old child blocker while %s remains pending", async mode => {
it.each(["active", "native-recovery", "native-recovery-without-successor-field", "workspace-replacement"])("waits past an old child blocker while %s remains pending", async mode => {
let waiting = true;
const now = Date.now();
vi.mocked(connectionDelay).mockImplementation(async () => { waiting = false; });
@@ -306,6 +306,10 @@ describe("Cloud canonical onboarding first task", () => {
withBoardBlockedChild(state);
if (mode === "active") Object.assign(state.runs[1]!, { status: "running", finishedAt: null });
if (mode === "native-recovery") withPendingNativeRecovery(state.runs[1]!, now - 1000, now + 30_000);
if (mode === "native-recovery-without-successor-field") {
withPendingNativeRecovery(state.runs[1]!, now - 1000, now + 30_000);
delete state.runs[1]!.execution.successorRunId;
}
} });
await expect(onboardingFirstTask(f.input)).resolves.toMatchObject({ artifact: { originatingRunId: "child-run" } });
expect(connectionDelay).toHaveBeenCalledOnce();
@@ -448,7 +452,6 @@ describe("Cloud canonical onboarding first task", () => {
["noninteger attempt", (run: Row) => { run.execution.attempt = 1.5; }],
["unexpected ceiling", (run: Row) => { run.execution.maxAttempts = 4; }],
["different successor", (run: Row) => { run.execution.successorRunId = "other-run"; }],
["missing successor state", (run: Row) => { delete run.execution.successorRunId; }],
] as const)("keeps a failed native run fatal with %s", async (_label, change) => {
const now = Date.now();
vi.spyOn(Date, "now").mockReturnValue(now);
@@ -27,6 +27,8 @@ export function isPendingNativeRecovery(run: RecordValue, deadlineAt: number): b
const execution = object(run.execution);
const finishedAt = typeof run.finishedAt === "string" ? Date.parse(run.finishedAt) : NaN;
const retryAt = typeof execution.retryAt === "string" ? Date.parse(execution.retryAt) : NaN;
// Older deployed projections omit the optional successor field when there
// is no successor. Both forms preserve the exact same-run retry contract.
return run.runtimeMode === "native" && run.status === "failed" && run.nativePhase === "retryable_failure" &&
typeof run.errorCode === "string" && run.errorCode.trim().length > 0 && execution.cause === run.errorCode &&
!nativeRecoveryTerminalCauses.has(run.errorCode) &&
@@ -34,7 +36,7 @@ export function isPendingNativeRecovery(run: RecordValue, deadlineAt: number): b
(run.issueId == null || run.issueId === run.nativeIssueId) &&
(execution.phase === "retry_scheduled" || execution.phase === "reconnecting") && execution.recoveryOwner === "agent" &&
Number.isInteger(execution.attempt) && Number(execution.attempt) >= 1 &&
execution.maxAttempts === 3 && Number(execution.attempt) < execution.maxAttempts && execution.successorRunId === null &&
execution.maxAttempts === 3 && Number(execution.attempt) < execution.maxAttempts && execution.successorRunId == null &&
Number.isFinite(finishedAt) && Number.isFinite(retryAt) && Number.isFinite(deadlineAt) &&
retryAt > finishedAt && retryAt <= deadlineAt;
}
@@ -225,7 +225,6 @@
"packages/shared/src/config-schema.ts": "f9c8d41cb09fbc51c3e7a038089b54376cc9150c",
"packages/shared/src/connection-instructions.test.ts": "5095a9eeaa378b8d881feafa699c1705f207717f",
"packages/shared/src/connection-instructions.ts": "61b3e102838bd8bcab20eb9d0497a182f86eaac0",
"packages/shared/src/connection-intent-guidance.test.ts": "ae89f72dff415181d07c29a75d005c229d5c61b8",
"packages/shared/src/connection-intent-guidance.ts": "c121d7e31f3c44c7b0879db3929c23be20ef7987",
"packages/shared/src/connection-routing.test.ts": "95f6d30b790a2ef69f409fb72e4ba83256d7771e",
"packages/shared/src/connection-routing.ts": "6c506acd09b75d4f70ecde6cc5b652a244a7eb8a",
@@ -390,7 +389,6 @@
"packages/shared/src/telemetry/generated/paperclip-telemetry.ts": "c1a5e4e7679d9a4a1d2e420a1c65be608874b518",
"packages/shared/src/telemetry/index.ts": "6e609229bc9e37feb231fb13d8bc39fc3697d35f",
"packages/shared/src/telemetry/product-events.test.ts": "d3182c7e18fbe9c2915497fc1e2048fb2a250a04",
"packages/shared/src/telemetry/readme-contract.test.ts": "eec9d4511ddc3085a9af1a2dab6bf8487e49dfd7",
"packages/shared/src/telemetry/retention.test.ts": "9d54db1371bf20f22b8d2f8373f84433107a7408",
"packages/shared/src/telemetry/retention.ts": "838957cb8f9812d7d75680fbf42173d425d12006",
"packages/shared/src/telemetry/server-started-event.test.ts": "3d0e0e2289badb41c92ba0d69e3668d00b3b5fdb",
@@ -490,7 +488,7 @@
"packages/shared/src/validators/asset.ts": "93b9a747b0e7a2bce216db4ac3ab82ee42eb5cc3",
"packages/shared/src/validators/attention.ts": "137f6ca363e2c9b81961de5621c69a87a8c3d461",
"packages/shared/src/validators/budget.ts": "76ad91791c89d5be0f64cb23dd5587c493a7ead5",
"packages/shared/src/validators/chat-channels.test.ts": "eb157fcb00128a62d381e3e06630ed38c9a80314",
"packages/shared/src/validators/chat-channels.test.ts": "4f58b4abfbc76bd29fbe3ee321fa664c9eb0a86c",
"packages/shared/src/validators/chat-channels.ts": "9d0adf5ce89655d22071061d5e085d2ed84625d6",
"packages/shared/src/validators/chat-github.ts": "828c560fdad771389928f18c01e1eb14d4caeed5",
"packages/shared/src/validators/claude-setup-token-session.test.ts": "9eca823f24a9f85a20bddc6e61867b73362017e0",