mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
fix(e2e): wait for reset preparation and repository recovery (#23288)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Product E2E tests check real user work through the app and native agents. > - A chat reset gets its reset marker during run preparation. > - The observer can count that active reset as extra model work before preparation ends. > - The repository observer also omits the deadline needed to recognize a scheduled same-run recovery. > - This pull request keeps both observations open until the existing bounded transition completes. > - The final success checks still require the original run counts, saved results, and evidence. ## Linked Issues or Issue Description **What happened?** The chat observer can throw `chat_continuity_extra_run` while `/new` is queued or running without its reset marker. The repository observer throws `agent_run_failed` for an exact-session recovery that the server has already scheduled. **Expected behavior** Observe each transition under the original campaign deadline. Require the same final reset receipt, model turn count, completed repository runs, and artifact checks. An active or failed run must never count as a pass. **Steps to reproduce** 1. Return an unmarked queued or running reset between the second model reply and the completed reset receipt. 2. Run the chat journey observer. Before this change it reports extra model work. 3. Return a bound native repository run with `retryable_failure` and an eligible `retry_scheduled` projection. Before this change the observer rejects it before its scheduled recovery. Related: https://github.com/paperclipai/paperclip/pull/18784 and https://github.com/paperclipai/paperclip/pull/22826. The latter adds the shared recovery rule. This change supplies the repository caller's missing deadline. ## What Changed - Count excess unmarked provider runs after they succeed. Keep the existing reset count, scope, run cap, deadline and final grading checks. - Supply the repository campaign deadline to the existing native recovery validator. - Add observer regressions for queued and running reset preparation, completed extra work, immediate failed/cancelled rejection, scheduled repository recovery through success, exhausted or late recovery and the original deadline. ## Verification - Chat regression before the fix: 2 failed and 16 passed. Both failures report `chat_continuity_extra_run`. - Repository regression before the fix: 2 failed and 1 passed. Both failures report `agent_run_failed`. - After the fixes: 109 tests pass in five affected observer, grading and recovery files. - `pnpm test:e2e:runner:typecheck` passes on the final source. - `pnpm verify` cannot select tests because the managed Git storage guard rejects `git ls-files`. The focused command above supplies local test evidence. Final-head CI 46425283547 passes the selected Runner support, package, static, typecheck, policy and verification gates. General/build jobs are path-skipped. - The real observer functions ran with simulated API/browser boundaries. No new hosted provider run or deployment was made. A fresh hosted journey with the reviewed harness is still required for staging acceptance. ## Risks The chat observer can wait longer before it rejects active extra work. The original deadline and four-run cap still bound it. A completed extra provider run remains fatal. Failed or cancelled chat runs already fail in the reader before the excess-work predicate; tests prove first-read rejection with no new message. Repository recovery uses the existing shared eligibility rules; terminal, exhausted, foreign or late recovery still fails. This change does not repair or explain an underlying provider timeout. No prompt, grading rule, test selection, budget, pin or production behavior changes. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact model build is not exposed in this session. ## 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 - [x] All Paperclip CI gates are green - [x] 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
00a792999c
commit
caaa013a69
4 files changed
+159
-8
No files matched your search
@@ -24,16 +24,30 @@ afterEach(async () => {
|
||||
});
|
||||
async function fixture(options: { preexisting?: boolean; intentFails?: boolean; sendFails?: boolean; foreignRun?: boolean;
|
||||
compactRuns?: boolean; unrelatedActivity?: number; ignoreActivityScope?: boolean; priorAgentStatus?: string; mixedAgentHistory?: boolean;
|
||||
provisioningActor?: "board" | "owned-agent" } = {}) {
|
||||
provisioningActor?: "board" | "owned-agent"; pendingReset?: "queued" | "running"; unmarkedReset?: "succeeded" | "failed" | "cancelled" } = {}) {
|
||||
const f = options.compactRuns ? compactChatContinuityFixture() : chatContinuityFixture();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "chat-continuity-flow-"));
|
||||
directories.push(directory);
|
||||
let stage = options.preexisting ? 0 : -1;
|
||||
const messages: string[] = [], actions: string[] = [];
|
||||
let resetPrepared = false;
|
||||
const realTimeout = globalThis.setTimeout;
|
||||
vi.spyOn(globalThis, "setTimeout").mockImplementation(((callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) =>
|
||||
realTimeout(callback, delay === 1000 ? 0 : delay, ...args)) as typeof setTimeout);
|
||||
realTimeout(() => {
|
||||
if (delay === 1000 && stage === 3) resetPrepared = true;
|
||||
callback(...args);
|
||||
}, delay === 1000 ? 0 : delay)) as typeof setTimeout);
|
||||
const current = () => f.points[stage]!;
|
||||
const observedRuns = () => {
|
||||
const runs = structuredClone(current().runs);
|
||||
if (stage === 3 && (options.unmarkedReset || options.pendingReset && !resetPrepared)) {
|
||||
const reset = runs.find(run => run.id === "run-2")!;
|
||||
delete reset.contextSnapshot.conversationReset;
|
||||
reset.resultJson = null;
|
||||
reset.status = options.unmarkedReset ?? options.pendingReset;
|
||||
}
|
||||
return runs;
|
||||
};
|
||||
const companyActivity = [
|
||||
...Array.from({ length: options.unrelatedActivity ?? 0 }, (_, index) => ({ id: `unrelated-${index}`,
|
||||
companyId: f.scope.companyId, agentId: "other-agent", runId: "other-run", action: "project.created", entityType: "project", entityId: `other-project-${index}` })),
|
||||
@@ -52,9 +66,11 @@ async function fixture(options: { preexisting?: boolean; intentFails?: boolean;
|
||||
return companyRuns.filter(run => run.agentId === f.scope.agentId).slice(0, 1);
|
||||
}
|
||||
if (route === "/api/companies/company/chats/agent") return stage < 0 ? null : structuredClone(current().chat);
|
||||
if (route === "/api/issues/chat/runs") return current().runs.map(run => ({ runId: run.id, agentId: run.agentId, status: run.status,
|
||||
contextIssueId: run.contextSnapshot.issueId, wakeCommentId: run.contextSnapshot.wakeCommentId,
|
||||
resultJson: run.contextSnapshot.conversationReset ? { conversationReset: true } : {} }));
|
||||
if (route === "/api/issues/chat/runs") {
|
||||
return observedRuns().map(run => ({ runId: run.id, agentId: run.agentId, status: run.status,
|
||||
contextIssueId: run.contextSnapshot.issueId, wakeCommentId: run.contextSnapshot.wakeCommentId,
|
||||
resultJson: run.contextSnapshot.conversationReset ? { conversationReset: true } : {} }));
|
||||
}
|
||||
if (route === "/api/issues/chat/comments?order=asc") return structuredClone(current().comments);
|
||||
if (route === "/api/companies/company/issues?view=index&assigneeAgentId=agent&includeAgentCreatedTasks=true&limit=2") return [];
|
||||
if (route === "/api/companies/company/activity?agentId=agent&limit=500") {
|
||||
@@ -63,7 +79,7 @@ async function fixture(options: { preexisting?: boolean; intentFails?: boolean;
|
||||
if (/\/api\/heartbeat-runs\/run-\d\/events\?/.test(route)) return structuredClone(current().events ?? []);
|
||||
const id = route.match(/^\/api\/heartbeat-runs\/(run-\d)$/)?.[1];
|
||||
if (id) {
|
||||
const run = structuredClone(current().runs.find(row => row.id === id)!);
|
||||
const run = observedRuns().find(row => row.id === id)!;
|
||||
if (options.foreignRun) run.nativeIssueId = "foreign";
|
||||
return run;
|
||||
}
|
||||
@@ -100,6 +116,31 @@ async function fixture(options: { preexisting?: boolean; intentFails?: boolean;
|
||||
{ directory, deadlineAt: Date.now() + 10_000 }) };
|
||||
}
|
||||
describe("chat continuity journey controls", () => {
|
||||
it.each(["queued", "running"] as const)("waits for a %s reset to receive its control-plane marker", async pendingReset => {
|
||||
const f = await fixture({ pendingReset });
|
||||
await f.run();
|
||||
expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new", f.scenario.fresh]);
|
||||
expect(f.evidence.checks).toHaveLength(9);
|
||||
expect(f.evidence.checks.every(check => check.passed)).toBe(true);
|
||||
const saved = JSON.parse(await readFile(path.join(f.directory, "chat-continuity.json"), "utf8"));
|
||||
expect(saved.points.find((point: { phase: string }) => point.phase === "reset").runs[2]).toMatchObject({
|
||||
status: "succeeded", contextSnapshot: { conversationReset: true },
|
||||
});
|
||||
});
|
||||
it("rejects a completed extra provider run in place of the reset", async () => {
|
||||
const f = await fixture({ unmarkedReset: "succeeded" });
|
||||
await expect(f.run()).rejects.toThrow("chat_continuity_extra_run");
|
||||
expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new"]);
|
||||
expect(f.evidence.checks.every(check => !check.passed)).toBe(true);
|
||||
});
|
||||
it.each(["failed", "cancelled"] as const)("rejects a %s extra run before another poll or user message", async unmarkedReset => {
|
||||
const f = await fixture({ unmarkedReset });
|
||||
await expect(f.run()).rejects.toThrow("chat_continuity_run_mismatch");
|
||||
expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new"]);
|
||||
const runs = f.get.mock.calls.filter(([route]) => route === "/api/heartbeat-runs/run-2");
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(f.evidence.checks.every(check => !check.passed)).toBe(true);
|
||||
});
|
||||
it("uses ordinary user messages once, owns the fresh chat before dispatch, and retains the independently graded result", async () => {
|
||||
const f = await fixture();
|
||||
await f.run();
|
||||
|
||||
@@ -83,7 +83,12 @@ export async function runChatContinuity(context: JourneyContext, session: Target
|
||||
if (state) {
|
||||
const providerRuns = state.runs.filter(run => !chatContinuityResetRun(run));
|
||||
const resetRuns = state.runs.filter(chatContinuityResetRun);
|
||||
if (providerRuns.length > providerCount || resetRuns.length > resetCount) throw new JourneyError("failed", "chat_continuity_extra_run");
|
||||
// Reset identity is written during preparation. A queued/running reset
|
||||
// has no marker yet, so classify excess work only after it settles.
|
||||
const completedProviderRuns = providerRuns.filter(run => run.status === "succeeded");
|
||||
if (completedProviderRuns.length > providerCount || resetRuns.length > resetCount) {
|
||||
throw new JourneyError("failed", "chat_continuity_extra_run");
|
||||
}
|
||||
const ready = providerRuns.length === providerCount && resetRuns.length === resetCount
|
||||
&& state.runs.every(run => run.status === "succeeded")
|
||||
&& providerRuns.every(run => run.nativePhase === "committed")
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js";
|
||||
import { repositoryContinuationSource } from "./repository-continuation-contract.js";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ create: vi.fn() }));
|
||||
vi.mock("../user-actions.js", async original => ({
|
||||
...await original<typeof import("../user-actions.js")>(), createTaskThroughUi: mocks.create,
|
||||
}));
|
||||
import { runRepositoryContinuation } from "./repository-continuation-flow.js";
|
||||
|
||||
const directories: string[] = [];
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
vi.resetAllMocks();
|
||||
for (const directory of directories.splice(0)) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function fixture(options: { exhausted?: boolean; neverCompletes?: boolean; lateRetry?: boolean; succeeds?: boolean } = {}) {
|
||||
let now = Date.now();
|
||||
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||
const realTimeout = globalThis.setTimeout;
|
||||
vi.spyOn(globalThis, "setTimeout").mockImplementation(((callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) =>
|
||||
realTimeout(() => {
|
||||
if (delay === 1000) now += 1000;
|
||||
callback(...args);
|
||||
}, delay === 1000 ? 0 : delay)) as typeof setTimeout);
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "repository-recovery-"));
|
||||
directories.push(directory);
|
||||
const deadlineAt = Date.now() + 5_000;
|
||||
const run = { id: "run", companyId: "company", agentId: "agent", nativeIssueId: "task", runtimeMode: "native",
|
||||
finishedAt: new Date(Date.now() - 1_000).toISOString(), status: "failed", nativePhase: "retryable_failure", errorCode: "native_session_interrupted",
|
||||
contextSnapshot: { issueId: "task", paperclipEnvironment: { id: "environment" } },
|
||||
runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } },
|
||||
execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: options.exhausted ? 3 : 1,
|
||||
maxAttempts: 3, recoveryOwner: "agent", retryAt: new Date(Date.now() + (options.lateRetry ? 6_000 : 1_000)).toISOString() } };
|
||||
let observations = 0;
|
||||
const get = vi.fn(async (route: string) => {
|
||||
if (route === "/api/projects/project") return { companyId: "company", workspaces: [{ id: "primary", isPrimary: true,
|
||||
repoUrl: repositoryContinuationSource.url, repoRef: repositoryContinuationSource.commit }] };
|
||||
if (route === "/api/issues/task") {
|
||||
observations += 1;
|
||||
return { id: "task", companyId: "company", assigneeAgentId: "agent", projectId: "project", status: options.succeeds && observations > 1 ? "done" : "in_progress" };
|
||||
}
|
||||
if (route === "/api/issues/task/runs") return [{ runId: "run" }];
|
||||
if (route === "/api/heartbeat-runs/run") {
|
||||
// Prove the observer keeps reading the same native run after its scheduled retry.
|
||||
if (observations > 1 && options.succeeds) return { ...structuredClone(run), status: "succeeded", nativePhase: "committed",
|
||||
resultJson: { finalizationPhase: "committed" } };
|
||||
if (observations > 1 && !options.neverCompletes) throw new Error("same-run recovery observed again");
|
||||
return structuredClone(run);
|
||||
}
|
||||
if (route === "/api/issues/task/workspace") throw new Error("recovered workspace reached");
|
||||
if (route.endsWith("/comments?order=asc") || route.endsWith("/interactions")) return [];
|
||||
throw new Error(`Unexpected read: ${route}`);
|
||||
});
|
||||
mocks.create.mockResolvedValue({ issueId: "task" });
|
||||
const context = { api: { origin: "https://qa.example.test", get, post: vi.fn(async () => ({ id: "project" })) }, page: {},
|
||||
company: { id: "company", issuePrefix: "QA" }, environmentId: "environment",
|
||||
agent: { id: "agent", name: "Agent", runtimeMode: "native", provider: "opencode", model: "model" } } as unknown as JourneyContext;
|
||||
const evidence = { checks: [] } as unknown as JourneyEvidence;
|
||||
const promise = runRepositoryContinuation(context, { own: vi.fn() } as unknown as TargetSession, "journey-1234567890123-abcdef12", evidence,
|
||||
{ directory, deadlineAt });
|
||||
return { promise, directory, get, evidence };
|
||||
}
|
||||
|
||||
it("keeps observing an eligible same-run retry under the original repository deadline", async () => {
|
||||
const f = await fixture();
|
||||
const assertion = expect(f.promise).rejects.toThrow("same-run recovery observed again");
|
||||
await assertion;
|
||||
expect(f.get.mock.calls.filter(([route]) => route === "/api/heartbeat-runs/run")).toHaveLength(2);
|
||||
const saved = JSON.parse(await readFile(path.join(f.directory, "repository-latest-task.json"), "utf8"));
|
||||
expect(saved.taskRuns[0]).toMatchObject({ id: "run", status: "failed", execution: { phase: "retry_scheduled" } });
|
||||
expect(f.evidence.checks).toEqual([]);
|
||||
});
|
||||
|
||||
it("still rejects an exhausted recovery", async () => {
|
||||
const f = await fixture({ exhausted: true });
|
||||
await expect(f.promise).rejects.toThrow("agent_run_failed");
|
||||
});
|
||||
|
||||
it("does not extend the campaign deadline for a recovery that never completes", async () => {
|
||||
const f = await fixture({ neverCompletes: true });
|
||||
const assertion = expect(f.promise).rejects.toThrow("repository_task_not_completed");
|
||||
await assertion;
|
||||
});
|
||||
|
||||
it("reaches the workspace oracle after the same run recovers successfully", async () => {
|
||||
const f = await fixture({ succeeds: true });
|
||||
await expect(f.promise).rejects.toThrow("recovered workspace reached");
|
||||
const saved = JSON.parse(await readFile(path.join(f.directory, "repository-latest-task.json"), "utf8"));
|
||||
expect(saved.currentIssue.status).toBe("done");
|
||||
expect(saved.taskRuns).toHaveLength(1);
|
||||
expect(saved.taskRuns[0]).toMatchObject({ id: "run", status: "succeeded", nativePhase: "committed" });
|
||||
expect(f.get.mock.calls.some(([route]) => route === "/api/issues/task/workspace")).toBe(true);
|
||||
expect(mocks.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects a retry scheduled after the original campaign deadline", async () => {
|
||||
const f = await fixture({ lateRetry: true });
|
||||
await expect(f.promise).rejects.toThrow("agent_run_failed");
|
||||
expect(f.get.mock.calls.filter(([route]) => route === "/api/heartbeat-runs/run")).toHaveLength(1);
|
||||
});
|
||||
@@ -61,7 +61,7 @@ export async function runRepositoryContinuation(context: JourneyContext, session
|
||||
.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)) || String(a.id).localeCompare(String(b.id)));
|
||||
const state = { currentIssue, taskRuns, comments, interactions, attachments: [] };
|
||||
await retain("repository-latest-task.json", state);
|
||||
validateAgentTaskState(context, created.issueId, state, 2);
|
||||
validateAgentTaskState(context, created.issueId, state, 2, [], options.deadlineAt);
|
||||
if (currentIssue.projectId !== project.id) throw new JourneyError("failed", "repository_project_binding_mismatch");
|
||||
return state;
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user