From 61c315ebab762ace03225130734c49826d7b2578 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:56:53 -0600 Subject: [PATCH 1/8] perf(chat): keep GitHub review check deadlines on company-wide rebuilds (#21725) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The GitHub chat channel shows a check run on each pull request it reviews. The review-check sweep (`review-check-work.ts`) keeps one `github_review_check` action per check. It republishes the check when its status changes (queued, running, completed) and polls the pull request head on a saved deadline. > - Each time the sweep loads its checks, it computes the current check status of every `received` check (`githubReviewCheckState`: 3–5 statements) to see whether the status changed. > - Run lifecycle changes anywhere in a company send a company-wide hint. So the sweep rebuilds every company's checks every 30 s and recomputes the status of every waiting check, even when nothing about those checks changed. > - This pull request keeps the saved poll deadline on a company-wide rebuild and reads the status only on targeted hints, at startup, and in `check()`. > - The benefit is that an idle company with many waiting checks costs one page read per rebuild instead of 3–5 statements per check. ## Linked Issues or Issue Description Refs #21705, #21711 (the same class of idle reload in the GitHub response sweeps). No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/bug_report.yml`. **What happened?** On paperclip.staging at 89de6cbe3e (2026-11-15, 04:47–04:51Z, near idle at about 0.4 HTTP requests/s), the statements of `githubReviewCheckState` each ran at about 3/s: - `select … from chat_github_reviews where endpoint_id … and repository_id … and pull_number … and head_sha … order by created_at desc limit 1` (all columns: id, company_id, endpoint_id, issue_id, run_id, repository_id, …) at 3.04/s; - `select chat_message_links.comment_id from chat_deliveries join chat_message_links …` at 3.04/s; - `select id, status from heartbeat_runs where company_id = $1 and agent_id = $2 and context_snapshot->>'wakeCommentId' in (…)` at 3.04/s. Staging has 84 GitHub review checks waiting on runs that have not started. 84 checks reloaded every 30 s is 2.8 status computations per second. That matches the observed rate. **Root cause** `registerGitHubReviewCheckWork` loads with `githubReviewCheckReconstructionIntervalMs`, which allows one company-wide rebuild every 30 s. Run lifecycle changes elsewhere in the company keep sending `{ companyId }` hints, so the rebuild runs every 30 s. `entry()` calls `githubReviewCheckState` for every `received` row on every load, only to see whether the status differs from the published one. A waiting check's status does not change until its review, its run, its delivery or its connection changes. **Expected behavior** A company-wide rebuild reads the waiting checks without recomputing each status. A change to a check's run or pull request still publishes promptly. **Steps to reproduce** 1. Create 30 `received` GitHub review checks whose published status is `queued`, with a poll deadline 1 hour ahead. 2. Register the review-check sweep. Send a company-wide hint every 30 s. 3. On master, each rebuild runs one page read plus 2–5 statements per check. **Paperclip version or commit** master at 5acf27bc3b. ## What Changed - `server/src/services/chat-channels/github/review-check-work.ts`: - A company-wide load (company scope with no endpoint, repository, number or task) does not call `githubReviewCheckState`. It keeps each check's saved deadline: the head-poll `retryAt`, or the lease expiry. Dispatch reads the current status anyway when that deadline comes. - Startup (no scope) and targeted loads (endpoint, repository, pull request or task) still read every status, as before. So do `check()` and dispatch. - Run lifecycle changes send `{ companyId, issueId }` for the run's task, and publication lease releases send the pull request scope. Both still publish a status change at once. - New `mergeEntry`: an entry from a rebuild that did not read the status keeps an earlier due time that a status read found. A company-wide rebuild never postpones a pending publication. `check()` reads the status again before it dispatches. - `server/src/services/chat-channels/github/review-check-work.test.ts` (new, real PostgreSQL): - `does not recompute the status of every waiting check on each company rebuild` - `still publishes a check promptly when its review run starts` (a task-scoped hint after a review run starts makes only that check due) - `server/src/__tests__/chat-channels.integration.test.ts`: - `publishes a local change at once and still recovers a missed head after backing off` used a company-wide hint to stand for the review run starting. It now sends the task-scoped hint that a run milestone sends, and still expects the `in_progress` publication at once. - `rebuilds GitHub review checks for company-wide hints at most once per interval` is now `reads no GitHub review check status for company-wide hints and still reads it for the check's task`. Company-wide hints read 0 statuses. Hints for the check's task still read 1, and hints for another task or company read 0. No GitHub check content changes. The published status, title and conclusion are computed as before. ## Verification - `pnpm vitest run src/services/chat-channels/github/review-check-work.test.ts` (server), 30 waiting checks, 4 company rebuilds: - master: 244 statements, with 120 check status computations (red). - this branch: 4 statements (one page read each), with 0 status computations (green). A task-scoped hint still makes the started check due at once. - `pnpm vitest run src/services/chat-channels/github/`: 8 files, 62 passed. - Related suites (`chat-channels.integration.test.ts`, `app-private-hostname-gate.test.ts`, `idle-completed-history.test.ts`, `chat-github-review-repair.test.ts`) filtered to review-check, GitHub, history and hostname tests: 702 passed before the integration-test updates below; after updating the two review-check tests, the 15 review-check tests pass. - `pnpm typecheck` (server): passed. ## Risks - A status change that sends only a company-wide hint is now published at the check's next poll deadline, not at the next company rebuild. The poll backs off to at most 5 minutes. Run lifecycle changes for a review run carry its task, and connection or configuration changes are also checked by dispatch, so this affects only hints that name no task or pull request. - Startup still reads every status, so recovery after a restart is unchanged. > 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`), Anthropic, used through Claude Code with tool use (shell, file edits, local PostgreSQL tests) and extended reasoning. ## 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 - [ ] 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 --- .../chat-channels.integration.test.ts | 11 +- .../github/review-check-work.test.ts | 132 ++++++++++++++++++ .../chat-channels/github/review-check-work.ts | 23 ++- 3 files changed, 157 insertions(+), 9 deletions(-) create mode 100644 server/src/services/chat-channels/github/review-check-work.test.ts diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 5c6e071c913..268f13836f5 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -7850,7 +7850,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { await f.pass("*"); expect(f.pulls()).toBe(pulls); await db.update(chatGitHubReviews).set({ runId: f.run.id }).where(eq(chatGitHubReviews.id, f.review.id)); - await f.pass(JSON.stringify({ companyId: f.companyId })); + // A run change notifies its task, as run milestones do. + await f.pass(JSON.stringify({ companyId: f.companyId, issueId: f.review.issueId })); expect(f.writes.at(-1)).toMatchObject({ status: "in_progress" }); expect(await f.action()).toMatchObject({ status: "received", result: { state: "running", unchangedPolls: 0 } }); await f.window(400); @@ -7860,7 +7861,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect((await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, f.review.id)))[0].state).toBe("superseded"); }, 120_000); - it("rebuilds GitHub review checks for company-wide hints at most once per interval", async () => { + it("reads no GitHub review check status for company-wide hints and still reads it for the check's task", async () => { const f = await unresolvedReviewCheckPasses(); await f.window(400); const reads = async (hint: string) => { @@ -7868,12 +7869,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { await f.pass(hint); return f.states() - before; }; + // A company-wide rebuild keeps the saved poll deadline; dispatch reads + // the status when it comes. const company = JSON.stringify({ companyId: f.companyId }); const repeated = []; for (let index = 0; index < 10; index++) repeated.push(await reads(company)); - expect(repeated).toEqual([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + expect(repeated).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); for (let index = 0; index < GITHUB_REVIEW_CHECK_COMPANY_RECONSTRUCTION_MS / 1000 - 10; index++) await f.pass(); - expect(await reads(company)).toBe(1); + expect(await reads(company)).toBe(0); expect(await reads(JSON.stringify({ companyId: f.companyId, issueId: f.review.issueId }))).toBe(1); expect(await reads(JSON.stringify({ companyId: f.companyId, issueId: f.review.issueId }))).toBe(1); expect(await reads(JSON.stringify({ companyId: f.companyId, issueId: randomUUID() }))).toBe(0); diff --git a/server/src/services/chat-channels/github/review-check-work.test.ts b/server/src/services/chat-channels/github/review-check-work.test.ts new file mode 100644 index 00000000000..2bfb016f9e7 --- /dev/null +++ b/server/src/services/chat-channels/github/review-check-work.test.ts @@ -0,0 +1,132 @@ +import { randomUUID } from "node:crypto"; +import { setTimeout as delay } from "node:timers/promises"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { chatActions, chatGitHubReviews, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js"; +import { idleWorkSnapshot } from "../../task-admission.js"; +import { registerGitHubReviewCheckWork } from "./review-check-work.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +// Staging (2026-11-15) polled 84 GitHub review checks whose runs had not +// started. Their check status reads ran at about 3/s at idle. +const CHECKS = 30; + +describe.skipIf(!support.supported)("GitHub review check sweep", () => { + let temporary: Awaited>; + let db: Db; + let coordinator: ReturnType | undefined; + const errors: unknown[] = []; + const dispatched: string[] = []; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("github-review-check-work-"); + db = createDb(temporary.connectionString); + }, 60_000); + afterEach(async () => { + await coordinator?.stop(); coordinator = undefined; dispatched.length = 0; + vi.useRealTimers(); + expect(errors.splice(0)).toEqual([]); + }); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + async function seed() { + const client = db.$client; + const [{ company }] = await client.unsafe(`insert into companies (name, issue_prefix) values ('Checks', $1) returning id as company`, + [`C${randomUUID().slice(0, 7)}`]); + const [{ agent }] = await client.unsafe(`insert into agents (company_id, name) values ($1, 'Reviewer') returning id as agent`, [company]); + const [{ application }] = await client.unsafe(`insert into tool_applications (company_id, application_key, name, type) + values ($1, 'github', 'GitHub', 'chat') returning id as application`, [company]); + const [{ connection }] = await client.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose) + values ($1, $2, 'GitHub', $3, 'chat_sdk', 'channel') returning id as connection`, [company, application, `github-${company}`]); + const [{ endpoint }] = await client.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status) + values ($1, $2, 'github', $3, $4, 'active') returning id as endpoint`, [company, connection, `checks-${company}`, agent]); + await client.unsafe(`insert into chat_github_configurations (endpoint_id, company_id, configuration, updated_by_user_id) + values ($1, $2, $3::jsonb, 'owner')`, [endpoint, company, JSON.stringify({ toolsEnabled: true, defaults: {}, repositories: {} })]); + await client.unsafe(`insert into chat_endpoint_resources (company_id, endpoint_id, type, provider_resource_id, label, availability, enabled, metadata) + values ($1, $2, 'repository', 'paperclipai/paperclip', 'paperclipai/paperclip', 'available', true, $3::jsonb)`, + [company, endpoint, JSON.stringify({ providerRepositoryId: "418" })]); + const checks: Array<{ id: string; number: number; headSha: string }> = []; + const retryAt = new Date(Date.now() + 3_600_000).toISOString(); + for (let number = 1; number <= CHECKS; number++) { + const headSha = randomUUID().replaceAll("-", "").padEnd(40, "0"); + const [action] = await db.insert(chatActions).values({ companyId: company, endpointId: endpoint, kind: "github_review_check", + providerActionId: `github_review_check:${number}`, status: "received", + payload: { admitted: true, runtimeGeneration: 0, event: { repository: "paperclipai/paperclip", repositoryId: "418", + pullNumber: number, headSha, deliveryId: randomUUID() } }, + result: { state: "queued", retryAt } }).returning(); + checks.push({ id: action!.id, number, headSha }); + } + return { companyId: company as string, agentId: agent as string, endpointId: endpoint as string, checks }; + } + + async function start() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, + onError: error => errors.push(error) }); + await registerGitHubReviewCheckWork(db, coordinator, async id => { dispatched.push(id); }, () => true).ready; + } + async function advance(ms: number) { + const until = Date.now() + ms; + while (Date.now() < until) { + await vi.advanceTimersByTimeAsync(Math.min(1_000, until - Date.now())); await delay(1); + while (idleWorkSnapshot().active > 0) await delay(5); + } + } + async function hint(scope: Record) { + await db.transaction(async tx => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatGitHubReviewChecks, JSON.stringify(scope)); + }); + } + async function observe(work: () => Promise) { + const statements: string[] = [], prior = db.$client.options.debug; + db.$client.options.debug = (_connection, query) => { statements.push(query); }; + try { await work(); } finally { db.$client.options.debug = prior; } + return { + statements: statements.filter(query => /"chat_actions"|chat_github_reviews|heartbeat_runs|chat_deliveries/.test(query)).length, + // The first read of the check status of one check. + states: statements.filter(query => /from "chat_endpoints" inner join "companies"/.test(query)).length, + }; + } + + it("does not recompute the status of every waiting check on each company rebuild", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const f = await seed(); + await start(); await advance(5_000); + const rebuilds = await observe(async () => { + for (let pass = 0; pass < 4; pass++) { await hint({ companyId: f.companyId }); await advance(31_000); } + }); + console.info(`review check sweep: 4 company rebuilds cost ${rebuilds.statements} statements ` + + `(${rebuilds.states} check status reads) for ${CHECKS} waiting checks`); + expect(rebuilds.states).toBe(0); + expect(rebuilds.statements).toBeLessThanOrEqual(4); + expect(dispatched).toEqual([]); + }, 300_000); + + it("still publishes a check promptly when its review run starts", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const f = await seed(); + await start(); await advance(5_000); + const target = f.checks[4]!; + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + contextSnapshot: {} }).returning(); + const [{ issue }] = await db.$client.unsafe(`insert into issues (company_id, title, status) values ($1, 'Review', 'in_progress') + returning id as issue`, [f.companyId]); + await db.insert(chatGitHubReviews).values({ companyId: f.companyId, endpointId: f.endpointId, issueId: issue, + runId: run!.id, repositoryId: "418", repository: "paperclipai/paperclip", pullNumber: target.number, + headSha: target.headSha, state: "running", deliveryId: randomUUID(), configurationRevision: 1, + policySnapshot: {}, event: {} } as typeof chatGitHubReviews.$inferInsert); + // A run lifecycle change sends a hint for its task. + await hint({ companyId: f.companyId, issueId: issue }); + await advance(5_000); + // The stand-in dispatch saves nothing, so the check stays due; only it is due. + expect(new Set(dispatched)).toEqual(new Set([target.id])); + // A later company-wide rebuild, which does not read the status, keeps the + // changed check due instead of moving it to its saved poll deadline. + dispatched.length = 0; + await hint({ companyId: f.companyId }); + await advance(5_000); + expect(new Set(dispatched)).toEqual(new Set([target.id])); + }, 300_000); +}); diff --git a/server/src/services/chat-channels/github/review-check-work.ts b/server/src/services/chat-channels/github/review-check-work.ts index 49ebb3ab8f5..5fe7f567087 100644 --- a/server/src/services/chat-channels/github/review-check-work.ts +++ b/server/src/services/chat-channels/github/review-check-work.ts @@ -7,7 +7,7 @@ import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js"; import { githubReviewCheckState } from "./review-check-state.js"; type Scope = { companyId: string; endpointId?: string; repositoryId?: string; number?: number; issueId?: string }; -type Entry = Scope & { id: string; dueAt: number }; +type Entry = Scope & { id: string; dueAt: number; stateRead: boolean }; export const GITHUB_REVIEW_CHECK_COMPANY_RECONSTRUCTION_MS = 30_000; @@ -48,18 +48,21 @@ export function registerGitHubReviewCheckWork( cursor ? gt(chatActions.id, cursor) : undefined, actionId ? eq(chatActions.id, actionId) : undefined, )).orderBy(asc(chatActions.id)).limit(100); } - async function entry(row: Awaited>[number]): Promise { + /** `readState` compares the current check status with the published one, so + * a change is published before the saved poll deadline. */ + async function entry(row: Awaited>[number], readState = true): Promise { const { action } = row; const event = action.payload.event as GitHubReviewEventContext; let dueAt = action.result?.retryAt ? Date.parse(String(action.result.retryAt)) : 0; if (!Number.isFinite(dueAt)) throw new Error("GitHub review check has an invalid retry deadline"); - if (action.status === "received") { + if (action.status === "received" && readState) { const current = await githubReviewCheckState(db, action); if (current.disposition !== "publish" || current.state !== action.result?.state) dueAt = 0; } if (row.leaseExpiresAt) dueAt = Math.max(dueAt, Date.parse(row.leaseExpiresAt)); return { id: action.id, companyId: action.companyId, endpointId: action.endpointId, - repositoryId: event.repositoryId, number: event.pullNumber, issueId: row.reviewIssueId ?? undefined, dueAt }; + repositoryId: event.repositoryId, number: event.pullNumber, issueId: row.reviewIssueId ?? undefined, dueAt, + stateRead: readState || action.status !== "received" }; } return registerScopedDeadlineWork(coordinator, { queue: DELIVERY_QUEUES.chatGitHubReviewChecks, @@ -69,14 +72,24 @@ export function registerGitHubReviewCheckWork( (!scope.repositoryId || value.repositoryId === scope.repositoryId) && (!scope.number || value.number === scope.number) && (!scope.issueId || value.issueId === scope.issueId)), reconstructionIntervalMs: githubReviewCheckReconstructionIntervalMs, + // A rebuild that did not read the status must not postpone a change that + // an earlier read found due. check() reads the status again. + mergeEntry: (pending: Entry, loaded: Entry) => loaded.stateRead ? loaded + : { ...loaded, dueAt: Math.min(pending.dueAt, loaded.dueAt) }, load: async (scope?: Scope, signal?: AbortSignal) => { const entries: Entry[] = []; let cursor: string | undefined; + // A company-wide hint says only that something in the company changed. + // Its rebuild keeps each check's saved poll deadline, where dispatch reads + // the current status anyway. A change to a check's run or pull request + // sends a hint for its task or pull request, and startup (no scope) reads + // every status, so both still publish a change at once. + const readState = !scope || !!(scope.endpointId || scope.repositoryId || scope.number || scope.issueId); while (canRun() && !signal?.aborted) { const rows = await page(scope, cursor); for (const row of rows) { if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub review check recovery stopped"); - entries.push(await entry(row)); + entries.push(await entry(row, readState)); } if (rows.length < 100) return entries; cursor = rows[rows.length - 1].action.id; From 6400698a8ec5c50d2074746c97c6266d160ed5a5 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:12:41 -0600 Subject: [PATCH 2/8] test(e2e): find the native Plan chip in the Coordinator chat thread (#21727) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The QA Cloud plan-revise-accept journey checks that a person can revise and approve an agent's Plan > - It first checks that the saved Plan chip is visible, scoped to a settled `task-chat-turn` so a live "Writing plan" chip cannot count > - The Coordinator workspace renders the Plan chip directly in the chat thread; there is no `task-chat-turn` element and no `data-settled` attribute > - So the journey never finds the chip and fails before the person reviews the plan > - This pull request also accepts the chip in the chat thread > - The benefit is that the plan journey reaches the revision and approval steps it exists to test ## Linked Issues or Issue Description **What happened?** On QA Cloud (build 5acf27bc), plan-revise-accept failed with `journey_operation_failed`, no checks passed, one run. The agent saved a correct two-step Plan and a revision-bound confirmation. The confirmation stayed pending until cleanup closed the task, so the browser never reached it. **Steps to reproduce** 1. Open the failed journey task on QA (Coordinator workspace). 2. Query `[data-testid="task-chat-turn"][data-settled="true"] [data-testid="task-chat-plan-preview"]`: 0 matches. 3. Query `[data-testid="task-chat-thread"] [data-testid="task-chat-plan-preview"]`: 1 visible match, aria-label "Open Plan revision 1 in task sidebar". **Expected behavior** The journey finds the saved Plan chip and continues to "Request changes". ## What Changed - `planStageRootSelector(native)`: native root is a settled task-chat turn or the task chat thread. `expectPlanStageVisible` uses it. The revision-name check from #21701 is unchanged. Why this still detects the failure that matters: `runPlanRevisionAcceptance` waits through the API until every task run is terminal before this check, and the aria-label must name the exact revision, which a live "Writing plan" chip does not. ## Verification - On the live failed QA page: old scope finds 0 chips; new scope finds 1 visible chip whose label matches `planPreviewLabel(1)`. - `tests/runner-e2e` plan-revision tests: 4 pass (new selector test included). - QA Cloud rerun of plan-revise-accept follows after merge and the harness pin update. ## Risks - Low risk: journey code only. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 --- tests/runner-e2e/plan-revision-flow.test.ts | 7 ++++++- tests/runner-e2e/plan-revision-flow.ts | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/runner-e2e/plan-revision-flow.test.ts b/tests/runner-e2e/plan-revision-flow.test.ts index 39322920453..dabad3d46fb 100644 --- a/tests/runner-e2e/plan-revision-flow.test.ts +++ b/tests/runner-e2e/plan-revision-flow.test.ts @@ -1,6 +1,6 @@ import { expect, it, vi } from "vitest"; import type { Page } from "@playwright/test"; -import { planPreviewLabel, runPlanRevisionAcceptance } from "./plan-revision-flow.js"; +import { planPreviewLabel, planStageRootSelector, runPlanRevisionAcceptance } from "./plan-revision-flow.js"; const state = { currentIssue: { status: "in_progress" }, @@ -44,3 +44,8 @@ it("accepts the classic and Coordinator Plan preview names for the exact revisio expect(planPreviewLabel(2).test("Open Plan revision 1 in task sidebar")).toBe(false); expect(planPreviewLabel(1).test("Open Plan in task sidebar")).toBe(false); }); + +it("finds the native Plan chip in a settled turn or directly in the Coordinator chat thread", () => { + expect(planStageRootSelector(true).split(", ")).toEqual(['[data-testid="task-chat-turn"][data-settled="true"]', '[data-testid="task-chat-thread"]']); + expect(planStageRootSelector(false)).toBe("body"); +}); diff --git a/tests/runner-e2e/plan-revision-flow.ts b/tests/runner-e2e/plan-revision-flow.ts index 553926580bb..f8e0df77840 100644 --- a/tests/runner-e2e/plan-revision-flow.ts +++ b/tests/runner-e2e/plan-revision-flow.ts @@ -23,8 +23,12 @@ export function planPreviewLabel(revision: number): RegExp { return new RegExp(`^Open Plan revision ${revision}(?: in task sidebar)?$`); } +export function planStageRootSelector(native: boolean): string { + return native ? '[data-testid="task-chat-turn"][data-settled="true"], [data-testid="task-chat-thread"]' : "body"; +} + export async function expectPlanStageVisible(page: Page, options: { native: boolean; revision: number | null }) { - const root = options.native ? page.locator('[data-testid="task-chat-turn"][data-settled="true"]') : page.locator("body"); + const root = page.locator(planStageRootSelector(options.native)); const preview = root.getByTestId("task-chat-plan-preview").last(); await expect(preview).toBeVisible({ timeout: 30_000 }); if (options.revision !== null) await expect(preview).toHaveAttribute("aria-label", planPreviewLabel(options.revision)); From 9ebc276b4254cd2711307435117b0adc2289b317 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:02:31 -0600 Subject: [PATCH 3/8] test(restart-chaos): let R5 wait out a slow model request and stop calling held wakes undispatched (#21730) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness (`tests/restart-chaos`) grades each task of a chaos wave with rules R1–R6 > - R5 fails a run that stays `running` with no new evidence for more than 3 minutes (`silent_dead_run`) > - In wave w-20261115T044649-s7106, task t028 failed R5. Its run was quiet for 303.6 s (05:22:13.005 to 05:27:16.647) because one DeepSeek request through OpenRouter was slow. Every sample showed an active provider turn and no tool running. The run then finished normally. > - A slow model request is not a dead run. False failures hide real failures and make the wave number wrong. > - This pull request lets R5 wait up to 10 minutes while a provider turn is active and no tool runs. It also stops the release-swap grade from calling queued wakes "never dispatched" while a live run holds them. > - The benefit is a wave grade that counts only real dead runs and real lost wakes. ## Linked Issues or Issue Description **Bug description** R5 reports `silent_dead_run` for a run that waits on one slow model request. The samples show `providerTurnActive=true` and no tool in flight for the whole gap. The run then finishes normally. Separately, the release-swap grade detail says "2 queued wake(s) never dispatched" for a task whose run was still running. Those wakes wait behind the active run by design. **Steps to reproduce** Grade the t028 samples of wave w-20261115T044649-s7106 with `gradeR5`. The result is `fail: silent_dead_run 7b51b352… 182s`. Grade a release-swap task that has a stale running run and queued wakes. The detail contains "never dispatched". **Expected behavior** R5 passes a quiet run while a provider turn is active and no tool runs, up to 10 minutes. R5 still fails a quiet run with no active provider turn after 3 minutes, and a provider turn quiet for more than 10 minutes. The grade does not call wakes undispatched while a queued or running run holds them. ## What Changed - `grader.ts`: add `PROVIDER_TURN_LIMIT_MS` (10 minutes). `deadRunningRun` uses this limit instead of the 3-minute `STALL_LIMIT_MS` when the run sample has `providerTurnActive`. A run with a tool in flight or a live process is still skipped as before. - Why 10 minutes: the observed slow request took 303.6 s. Common provider HTTP clients (the OpenAI and Anthropic SDKs) time out a request at 10 minutes. After 10 minutes the provider client has given up, so continued quiet means the run is dead, not slow. A turn whose process died also keeps `providerTurnActive` set, so the bound still catches it. - `release-swap-grade.ts`: omit the "N queued wake(s) never dispatched" note while the task has a queued, running or scheduled-retry run. The stale-run note stays. - New fixture `fixtures/t028-slow-provider-turn.json`: the real t028 samples from 05:21:30 to the run's end (116 samples). - `README.md`: document the provider-turn bound for R5 and the queued-wake rule. ## Verification - Red on `origin/master`, green with this change: - `triggers.test.ts` › R5 live evidence › "does not flag a slow model request while the provider turn is active with no tool running (w-20261115T044649-s7106/t028)" - `triggers.test.ts` › R5 live evidence › "still fails a silent run with no active provider turn, and a provider turn silent past the provider-latency bound" (guards: 4 min quiet with no provider turn fails; 9.5 min quiet with a provider turn passes; 10.5 min quiet with a provider turn fails) - `release-swap-grade.test.ts` › "does not report queued wakes as never dispatched while a run holds them (w-20261115T044649-s7106/t019)" (also checks that wakes with no live run still get the note) - `npx vitest run --config tests/restart-chaos/vitest.config.ts`: 71 files, 826 tests pass. - `npx tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean. - No wave was run. ## Risks - Low risk. The change touches only the test harness grader. - A run whose provider turn is active but whose process is truly dead now fails R5 after 10 minutes instead of 3. The fault is still caught, but later. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used in Claude Code with tool use and code execution. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- tests/restart-chaos/README.md | 4 ++-- .../fixtures/t028-slow-provider-turn.json | 1 + tests/restart-chaos/grader.ts | 4 +++- .../restart-chaos/release-swap-grade.test.ts | 14 +++++++++++ tests/restart-chaos/release-swap-grade.ts | 3 ++- tests/restart-chaos/triggers.test.ts | 24 +++++++++++++++++++ 6 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 tests/restart-chaos/fixtures/t028-slow-provider-turn.json diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index 99faafee805..aba9ef36c23 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -661,7 +661,7 @@ cap. The quiet period lets a continuation the product wakes after a run ends (fo subtasks finish) start before the read, so the task is graded by that continuation, not as `nothing pending`. A task still running at the cap is not counted in the number; the headline reports how many with the age of their last activity, and the wave fails. The grade uses the same 5-minute threshold: after the drain, a run with no event for 5 minutes, a queued wake, a scheduled retry or a working notice with no -progressing run behind it is not pending work, so the task is `nothing pending`. The single read then covers every task of the wave's company that had a run (probes and agent-created subtasks included), the +progressing run behind it is not pending work, so the task is `nothing pending`. Queued wakes behind a queued or running run wait for that run by design, so the detail does not call them never dispatched. The single read then covers every task of the wave's company that had a run (probes and agent-created subtasks included), the way the board shows it: | Verdict | When | @@ -2155,7 +2155,7 @@ re-arms the task's own triggered faults instead of using their offsets. temporary instance is deleted. - Faults are serialized; each one hits every task running at that moment. - A `todo` or `in_progress` task with no live run and no named wait is not a rest. The observer keeps watching it until it resumes or passes the R5 stall limit. -- R5 also fails a run that stays `running` with no live evidence (no new run event, `lastUsefulActionAt` or `execution.lastConfirmedActivityAt`, and no start) for more than 3 minutes after the server is ready. A `running` status alone is not proof of life. A quiet run is still live while a tool it started has not ended (for example a 4-minute `bench.sh`) or while its recorded local runner process still runs with the same PID and start time. +- R5 also fails a run that stays `running` with no live evidence (no new run event, `lastUsefulActionAt` or `execution.lastConfirmedActivityAt`, and no start) for more than 3 minutes after the server is ready. A `running` status alone is not proof of life. A quiet run is still live while a tool it started has not ended (for example a 4-minute `bench.sh`) or while its recorded local runner process still runs with the same PID and start time. While a provider turn is active and no tool runs, one model request is outstanding: R5 allows up to 10 minutes of quiet before it counts a dead run. A slow OpenRouter request took 303.6 s in w-20261115T044649-s7106/t028, and common provider clients time out a request at 10 minutes. - The wave fingerprints the checkout and `packages/paperclip-runner/dist` at start and after every fault. A build, install or branch switch during a wave would make later restarts run different code, so it fails the wave as a harness error (`worktree_changed_mid_wave`). The baseline is taken after the harness's own setup (preflight rebuilds provider entrypoints) and covers the tracked diff, untracked file contents, the runner `dist` and the runnerd binary. Build before the wave, never during it. - `faults.json` and `task-faults.json` (each task's launch time and the faults that crossed it) are written after every fault, so `--replay` of a task in an interrupted or wedged wave, or a storm task, re-fires the faults that crossed it at the same offsets. - A fault that fails to complete fails the wave as a harness error (exit 2), even when recovery brings the server back. diff --git a/tests/restart-chaos/fixtures/t028-slow-provider-turn.json b/tests/restart-chaos/fixtures/t028-slow-provider-turn.json new file mode 100644 index 00000000000..b6e7cd5058d --- /dev/null +++ b/tests/restart-chaos/fixtures/t028-slow-provider-turn.json @@ -0,0 +1 @@ +{"source":"w-20261115T044649-s7106/t028: one model request outstanding for 303.6 s with no tool running; the run then finished normally","samples":[{"at":1794720090451,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720093681,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720096928,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720100201,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720103431,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720106662,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720109887,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720113084,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720116361,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720119564,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720122789,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720125995,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720129213,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720132430,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:20:42.672Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720135668,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720138872,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720142119,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720145347,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720148636,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720151833,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720155027,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720158267,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720161483,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720164772,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720167969,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720171180,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720174443,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720177664,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720180908,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720184170,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720187379,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720190604,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720193821,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720197053,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720200288,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720205769,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720208978,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720212186,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720215410,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720218570,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720221760,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720224934,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720228136,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720231363,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720234546,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720237738,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720240946,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720244141,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720247428,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720250593,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720253784,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720256987,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720260222,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720263428,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720266633,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720269802,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720273030,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720276200,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720279390,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720282558,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720285719,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720288923,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720292143,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720295391,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720298579,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720301778,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720304977,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720308194,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720311477,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720314705,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720317910,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720321160,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720324337,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720327502,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720330656,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720333800,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720336984,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720340189,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720343345,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720346542,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720349711,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720352877,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720356025,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720359227,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720362379,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720365552,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720368707,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720371862,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720375029,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720378183,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720381326,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720384610,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720387771,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720390941,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720394694,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720397848,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720401031,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720404250,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720407415,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720410584,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720413761,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720416917,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720420078,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720423237,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720426381,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720429508,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720432667,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720435805,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:22:13.005Z","providerTurnActive":true}]},{"at":1794720439018,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:17.498Z","providerTurnActive":true}]},{"at":1794720442150,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:20.825Z","providerTurnActive":true}]},{"at":1794720445276,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:25.321Z","providerTurnActive":true}]},{"at":1794720448443,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:26.394Z","providerTurnActive":true}]},{"at":1794720451590,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:26.394Z","providerTurnActive":true}]},{"at":1794720454752,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:33.880Z","toolInFlight":true,"providerTurnActive":true}]},{"at":1794720457882,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"running","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-15T05:27:37.123Z","providerTurnActive":true}]},{"at":1794720461035,"reachable":true,"serverReady":true,"issueStatus":"blocked","interruption":{"state":"resolved","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"7b51b352-85f1-4b6c-9224-c6170b8d4231","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"7b51b352-85f1-4b6c-9224-c6170b8d4231","status":"succeeded","createdAt":"2026-11-15T04:50:01.510Z","startedAt":"2026-11-15T05:09:16.731Z","finishedAt":"2026-11-15T05:27:40.304Z","errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":"blocked","lastEvidenceAt":"2026-11-15T05:27:40.246Z"}],"waitingOnChildren":true}]} diff --git a/tests/restart-chaos/grader.ts b/tests/restart-chaos/grader.ts index 8c494c7070c..5c2c3ff6ea4 100644 --- a/tests/restart-chaos/grader.ts +++ b/tests/restart-chaos/grader.ts @@ -7,6 +7,7 @@ import { enforcedUniversalFailures, gradeUniversal, type SlotFree, type Universa export const ACTIVE_RUN_STATUSES = new Set(["queued", "running", "scheduled_retry"]); export const STALL_LIMIT_MS = 3 * 60_000; +export const PROVIDER_TURN_LIMIT_MS = 10 * 60_000; const REST_STATUSES_WITH_WORK = new Set(["todo", "in_progress"]); const ms = (iso: string | null | undefined) => (iso ? Date.parse(iso) : NaN); @@ -210,8 +211,9 @@ export function deadRunningRun(sample: TaskSample, readySince: number): { id: st if (run.status !== "running") continue; // Quiet is not dead while a tool is still in flight or the run's process is verifiably alive. if (run.toolInFlight || run.processAlive) continue; + const limit = run.providerTurnActive ? PROVIDER_TURN_LIMIT_MS : STALL_LIMIT_MS; const evidence = Math.max(ms(run.lastEvidenceAt) || 0, ms(run.startedAt) || 0, readySince); - if (sample.at - evidence > STALL_LIMIT_MS) return { id: run.id, idleMs: sample.at - Math.max(ms(run.lastEvidenceAt) || 0, ms(run.startedAt) || 0) }; + if (sample.at - evidence > limit) return { id: run.id, idleMs: sample.at - Math.max(ms(run.lastEvidenceAt) || 0, ms(run.startedAt) || 0) }; } return null; } diff --git a/tests/restart-chaos/release-swap-grade.test.ts b/tests/restart-chaos/release-swap-grade.test.ts index b1313682a9f..c29ed103a06 100644 --- a/tests/restart-chaos/release-swap-grade.test.ts +++ b/tests/restart-chaos/release-swap-grade.test.ts @@ -128,6 +128,20 @@ describe("release swap task grade", () => { expect(gradeReleaseSwapTask(task({ status: "todo", runs: [failed], queuedWakes: 1 })).verdict).toBe("still_working"); }); + it("does not report queued wakes as never dispatched while a run holds them (w-20261115T044649-s7106/t019)", () => { + const now = 10_000_000; + const held = gradeReleaseSwapTask(task({ status: "in_progress", now, staleAfterMs: 60_000, queuedWakes: 2, + interruption: interruption({ state: "working" }), + runs: [{ runId: "9df2283c", status: "running", errorCode: null, createdAt: 0, startedAt: 1, finishedAt: null, lastActivityAt: now - 70_000 }] })); + expect(held.detail).toContain("run 9df2283c running with no activity for 1 min"); + expect(held.detail).not.toContain("never dispatched"); + const queued = gradeReleaseSwapTask(task({ status: "todo", now, staleAfterMs: 60_000, queuedWakes: 1, + runs: [{ runId: "q1", status: "queued", errorCode: null, createdAt: now - 120_000, startedAt: null, finishedAt: null, lastActivityAt: null }] })); + expect(queued.detail).not.toContain("never dispatched"); + const orphan = gradeReleaseSwapTask(task({ status: "todo", now, staleAfterMs: 60_000, runs: [failed], queuedWakes: 2 })); + expect(orphan.detail).toContain("2 queued wake(s) never dispatched"); + }); + it("keeps a task still running past the drain cap out of the number and reports it with its last activity", () => { const running = gradeReleaseSwapTask(task({ status: "in_progress", now: 1_000_000, staleAfterMs: 900_000, runs: [{ runId: "r5", status: "running", errorCode: null, createdAt: 0, startedAt: 1, finishedAt: null, lastActivityAt: 940_000 }] })); diff --git a/tests/restart-chaos/release-swap-grade.ts b/tests/restart-chaos/release-swap-grade.ts index 983f7433913..b8c0568ab1c 100644 --- a/tests/restart-chaos/release-swap-grade.ts +++ b/tests/restart-chaos/release-swap-grade.ts @@ -143,9 +143,10 @@ export function gradeReleaseSwapTask(task: GradeTaskInput): TaskGrade { const lastActivityAgeMs = task.now !== undefined && liveActivity.length ? task.now - Math.max(...liveActivity) : null; const verdict = (value: TaskVerdict, detail: string): TaskGrade => ({ ...base, verdict: value, detail, label: label(value), lastActivityAgeMs }); const stale = staleRuns(task); + const heldByRun = task.runs.some(run => LIVE_RUN.has(run.status)); const idle = task.now === undefined ? [] : [ ...stale.map(run => `run ${run.runId} ${run.status} with no activity for ${Math.round((task.now! - (run.lastActivityAt ?? run.createdAt ?? 0)) / 60_000)} min`), - ...(task.queuedWakes ? [`${task.queuedWakes} queued wake(s) never dispatched`] : []), ...(task.scheduledRetry ? ["a scheduled retry that never ran"] : []), + ...(task.queuedWakes && !heldByRun ? [`${task.queuedWakes} queued wake(s) never dispatched`] : []), ...(task.scheduledRetry ? ["a scheduled retry that never ran"] : []), ...(task.interruption && (task.interruption.state === "working" || task.interruption.state === "retry_scheduled" || task.interruption.retryWait) ? [`the board shows ${task.interruption.retryWait ? "a Retry waiting on the system" : task.interruption.state}`] : []), ...(task.activeRecoveryOwner && task.activeRecoveryOwner !== "board" ? [`a ${task.activeRecoveryOwner} recovery action that made no progress`] : [])]; diff --git a/tests/restart-chaos/triggers.test.ts b/tests/restart-chaos/triggers.test.ts index 25908cf61eb..2aa1415f659 100644 --- a/tests/restart-chaos/triggers.test.ts +++ b/tests/restart-chaos/triggers.test.ts @@ -416,6 +416,30 @@ describe("R5 live evidence", () => { expect(gradeR5(quietB5({}))).toMatchObject({ verdict: "fail", detail: expect.stringMatching(/^silent_dead_run r1/) }); }); + it("does not flag a slow model request while the provider turn is active with no tool running (w-20261115T044649-s7106/t028)", () => { + const slow = JSON.parse(readFileSync(path.join(import.meta.dirname, "fixtures/t028-slow-provider-turn.json"), "utf8")) as { samples: TaskSample[] }; + const gap = slow.samples.filter(sample => sample.runs?.[0]?.lastEvidenceAt === "2026-11-15T05:22:13.005Z"); + expect(gap.at(-1)!.at - gap[0]!.at).toBeGreaterThan(300_000); + expect(gap.every(sample => sample.runs![0]!.providerTurnActive && !sample.runs![0]!.toolInFlight)).toBe(true); + expect(gradeR5(record(slow.samples)).verdict).toBe("pass"); + }); + + const quietTurn = (live: { providerTurnActive?: boolean }, quietMs: number) => { + const start = Date.parse("2026-11-15T05:00:00Z"); + const run = { id: "r1", status: "running", createdAt: null, startedAt: new Date(start - 600_000).toISOString(), finishedAt: null, + errorCode: null, retryOfRunId: null, wakeCommentIds: [], livenessState: null, lastEvidenceAt: new Date(start).toISOString(), ...live }; + const offsets = Array.from({ length: Math.floor(quietMs / 30_000) + 1 }, (_, index) => index * 30_000); + return record(offsets.map(offset => ({ at: start + offset, reachable: true, serverReady: true, issueStatus: "in_progress", runs: [run] }))); + }; + + it("still fails a silent run with no active provider turn, and a provider turn silent past the provider-latency bound", () => { + expect(gradeR5(quietTurn({}, 240_000))).toMatchObject({ verdict: "fail", detail: expect.stringMatching(/^silent_dead_run r1/) }); + expect(gradeR5(quietTurn({ providerTurnActive: false }, 240_000))).toMatchObject({ verdict: "fail", detail: expect.stringMatching(/^silent_dead_run r1/) }); + expect(gradeR5(quietTurn({ providerTurnActive: true }, 570_000)).verdict).toBe("pass"); + expect(gradeR5(quietTurn({ providerTurnActive: true }, 630_000))).toMatchObject({ verdict: "fail", + detail: expect.stringMatching(/^silent_dead_run r1 .* for 630s/) }); + }); + it("derives tool-in-flight and process liveness from run events", async () => { const startedAt = new Date().toISOString(); const identity = { processPid: 4242, processGroupId: 4242, processStartedAt: "2026-11-06T10:00:00.000Z", targetKind: "local" }; From 41a3520a2f90084e2291a0f59ccf1784a73fe113 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:23:38 -0600 Subject: [PATCH 4/8] fix(issues): count a blocker covered when its wake already created a queued run (#21731) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A blocked parent task shows "covered" when its blockers have work that will start by itself, and "needs attention" when a person must act > - The blocker-attention read counts a blocker as active only through its current execution run, or through a waiting wake that has not created a run yet > - A child whose wake already created a queued run that has not started matches neither, so the parent shows "needs attention" and lands in the blocked inbox > - That work starts by itself when an agent slot frees, so the attention is false and asks a person to act for no reason > - This pull request also counts a blocker as active when its waiting wake points at a queued or running run > - The benefit is that the board and the blocked inbox stop showing false attention while queued child work waits for a slot ## Linked Issues or Issue Description **What happened?** A parent task was blocked by two child tasks. Each child had a queued run that a wake had created, and the runs waited for agent slots. The parent showed `needs_attention` / `attention_required` and appeared in the blocked inbox. The children started about 25 minutes later and the parent then finished without a person. **Expected behavior** The parent shows `covered` with reason `active_child` while a child's queued run waits to start. **Steps to reproduce** 1. Create a blocked parent task with one child blocker that is assigned to an agent. 2. Insert a queued wake for the child whose `runId` points at a queued `heartbeat_runs` row, and leave the child's `executionRunId` empty. 3. List blocked tasks. The parent shows `needs_attention`. **Paperclip version or commit** `master` at 6400698a8e. ## What Changed - `server/src/services/issues.ts`: the blocker-attention wake query left-joins `heartbeat_runs` on the wake's `runId`. A queued or deferred wake counts as an active path when its `runId` is empty or when its run is `queued` or `running`. - `server/src/__tests__/issue-blocker-attention.test.ts`: two tests. One covers a child whose wake created a queued run that has not started. One makes sure that a wake whose run already finished does not cover the blocker. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-blocker-attention.test.ts`: 27 passed. - Red on master: "classifies a blocked parent as covered when its child's wake already created a queued run that has not started" fails with `needs_attention` / `attention_required`. Green with this change. - Query plan (embedded Postgres, `enable_seqscan = off`): an index scan on `agent_wakeup_requests_company_payload_issue_idx` (company and payload issue id), then a nested-loop left join through `heartbeat_runs_pkey`. The query count does not change, so there is no N+1. - `pnpm verify`. ## Risks - Low risk. The change adds coverage only for a wake whose run is still `queued` or `running`. A wake whose run finished, failed or was cancelled stays uncovered, as before. - The join is a primary-key lookup per wake row, inside the same chunked query, so the board read cost does not change in a meaningful way. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use and code execution. ## 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 --- .../__tests__/issue-blocker-attention.test.ts | 63 +++++++++++++++++++ server/src/services/issues.ts | 12 +++- 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/issue-blocker-attention.test.ts b/server/src/__tests__/issue-blocker-attention.test.ts index 8cead6ccd3e..50ed40400bb 100644 --- a/server/src/__tests__/issue-blocker-attention.test.ts +++ b/server/src/__tests__/issue-blocker-attention.test.ts @@ -194,6 +194,69 @@ describeEmbeddedPostgres("issue blocker attention", () => { }); }); + it("classifies a blocked parent as covered when its child's wake already created a queued run that has not started", async () => { + const { companyId, agentId } = await createCompany("PBQ"); + const parentId = await insertIssue({ companyId, identifier: "PBQ-1", title: "Parent", status: "blocked" }); + const childId = await insertIssue({ + companyId, + identifier: "PBQ-2", + title: "Queued child", + status: "todo", + parentId, + assigneeAgentId: agentId, + }); + await block({ companyId, blockerIssueId: childId, blockedIssueId: parentId }); + const runId = await activeRun({ companyId, agentId, issueId: childId, status: "queued", current: false }); + await db.insert(agentWakeupRequests).values({ + companyId, + agentId, + source: "assignment", + status: "queued", + runId, + payload: { issueId: childId }, + }); + + const parent = (await svc.list(companyId, { status: "blocked" })).find((issue) => issue.id === parentId); + + expect(parent?.blockerAttention).toMatchObject({ + state: "covered", + reason: "active_child", + coveredBlockerCount: 1, + attentionBlockerCount: 0, + }); + }); + + it("does not cover a blocked parent through a wake whose created run already finished", async () => { + const { companyId, agentId } = await createCompany("PBF"); + const parentId = await insertIssue({ companyId, identifier: "PBF-1", title: "Parent", status: "blocked" }); + const childId = await insertIssue({ + companyId, + identifier: "PBF-2", + title: "Finished child run", + status: "todo", + parentId, + assigneeAgentId: agentId, + }); + await block({ companyId, blockerIssueId: childId, blockedIssueId: parentId }); + const runId = await activeRun({ companyId, agentId, issueId: childId, status: "failed", current: false }); + await db.insert(agentWakeupRequests).values({ + companyId, + agentId, + source: "assignment", + status: "queued", + runId, + payload: { issueId: childId }, + }); + + const parent = (await svc.list(companyId, { status: "blocked" })).find((issue) => issue.id === parentId); + + expect(parent?.blockerAttention).toMatchObject({ + state: "needs_attention", + coveredBlockerCount: 0, + attentionBlockerCount: 1, + }); + }); + it("classifies an assigned backlog blocker leaf without a waiting path as attention-needed", async () => { const { companyId, agentId } = await createCompany("PBB"); const parentId = await insertIssue({ companyId, identifier: "PBB-1", title: "Parent", status: "blocked" }); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 77aad51fcd2..e4d579abe1d 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -4179,6 +4179,13 @@ async function readIssueBlockerAttentionBatch( >`${agentWakeupRequests.payload} ->> 'issueId'`, }) .from(agentWakeupRequests) + .leftJoin( + heartbeatRuns, + and( + eq(heartbeatRuns.id, agentWakeupRequests.runId), + eq(heartbeatRuns.companyId, companyId), + ), + ) .where( and( eq(agentWakeupRequests.companyId, companyId), @@ -4186,7 +4193,10 @@ async function readIssueBlockerAttentionBatch( agentWakeupRequests.status, BLOCKER_ATTENTION_ACTIVE_WAKE_STATUSES, ), - sql`${agentWakeupRequests.runId} is null`, + or( + sql`${agentWakeupRequests.runId} is null`, + inArray(heartbeatRuns.status, BLOCKER_ATTENTION_ACTIVE_RUN_STATUSES), + ), inArray( sql`${agentWakeupRequests.payload} ->> 'issueId'`, chunk, From 7c0c116edf4fc2cad3c0da1a9c2f3a1b8e440060 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:29:19 -0600 Subject: [PATCH 5/8] test(e2e): accept every dependency wake producer for the one automatic resume (#21732) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When a blocker task is completed, Paperclip wakes the blocked dependent task automatically > - Two producers emit that `issue_blockers_resolved` wake: the issue update route and the issue-graph liveness backstop (plus workspace finalize); they share one idempotency key and coalesce into one wake run > - The QA task-dependency-resume journey requires the run's `contextSnapshot.source` to be exactly `issue.blockers_resolved` > - On QA both producers emitted 43 ms apart; the run was created once, but the later backstop wake recorded its source on the run, so the journey failed a resume that happened exactly once > - This pull request accepts any of the three producers and keeps every other resume condition > - The benefit is that the journey tests the user-visible promise (one automatic resume caused by this blocker) instead of which internal producer won a race ## Linked Issues or Issue Description **What happened?** QA run (launch 3937) failed task-dependency-resume on `dependency_one_automatic_resume`. The dependent's activity log shows `issue.blockers_resolved_wake_emitted` from `issue_update` at 06:59:39.973 and from `issue_graph_liveness_backstop` at 06:59:40.016 with the same idempotency key and the same wake run. Exactly one run executed, started after the blocker completed, and succeeded. **Expected behavior** The journey accepts one automatic, blocker-caused resume regardless of which producer's label the coalesced run kept. **Steps to reproduce** Grade the retained evidence with `contextSnapshot.source = "issue_graph_liveness.backstop"`: `dependency-one-automatic-resume` fails although every other condition holds. ## What Changed - `task-dependency-resume-evidence.ts`: the wake source must be one of `issue.blockers_resolved`, `issue_graph_liveness.backstop`, `workspace.finalize` (the producers of this wake reason in `server/src`). - Still required: one dependent run, `invocationSource` automation / `triggerDetail` system, wake reason `issue_blockers_resolved`, the resolved blocker id, start after blocker completion, committed native run, no leftover checkout. ## Verification - Red/green: new cases "accepts the same automatic resume when the issue_graph_liveness.backstop / workspace.finalize dependency wake recorded its source" fail before and pass after. - Existing mutants still fail: "mutation name used as wake source" (`issue.blocker_done`) and "missing saved wake source". - `tests/runner-e2e` task-dependency tests: 3 files, 108 tests pass. ## Risks - Low risk: journey grading only. Separate note: the coalesced run keeps the last producer's source label; whether it should keep the first is a provenance question, not addressed here. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 --- .../product-journeys/task-dependency-resume-evidence.test.ts | 5 +++++ .../product-journeys/task-dependency-resume-evidence.ts | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.test.ts b/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.test.ts index c10c27f6896..4f9274544c1 100644 --- a/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.test.ts +++ b/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.test.ts @@ -76,6 +76,11 @@ describe("task dependency resume evidence", () => { const f = dependencyEvidenceFixture(); mutate(f); expect(gradeTaskDependencyResume(f).some(check => !check.passed)).toBe(true); }); + it.each(["issue_graph_liveness.backstop", "workspace.finalize"])("accepts the same automatic resume when the %s dependency wake recorded its source", source => { + const f = dependencyEvidenceFixture(); + for (const p of [f.finished, f.reopened]) for (const r of [...p.dependentRuns, ...p.agentRuns]) r.contextSnapshot.source = source; + expect(gradeTaskDependencyResume(f)).toEqual(TASK_DEPENDENCY_RESUME_CHECKS.map(id => ({ id, passed: true }))); + }); it("missing input never becomes a pass", () => { expect(gradeTaskDependencyResume(undefined).every(c => !c.passed)).toBe(true); }); it.each([null, {}, { summary: "Compacted result" }])("accepts the public run projection without duplicate finalization metadata: %j", resultJson => { const f = dependencyEvidenceFixture(); diff --git a/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.ts b/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.ts index d212a1f3ce2..4a9fc619ec7 100644 --- a/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.ts +++ b/tests/runner-e2e/product-journeys/task-dependency-resume-evidence.ts @@ -7,6 +7,8 @@ export const TASK_DEPENDENCY_RESUME_CHECKS = [ "dependency-history-preserved", "configured-model-and-environment", ] as const; +const DEPENDENCY_WAKE_SOURCES: ReadonlySet = new Set(["issue.blockers_resolved", "issue_graph_liveness.backstop", "workspace.finalize"]); + export interface DependencyScope { companyId: string; userId: string; agentId: string; environmentId: string; provider: string; model: string; blockerId: string; blockerIdentifier: string; blockerTitle: string; blockerDescription: string; @@ -101,7 +103,7 @@ export function gradeTaskDependencyResume(value: DependencyEvidence | undefined) && nonempty(run?.id) && [reopened.dependentRuns[0], newRuns(finished)[0], newRuns(reopened)[0]].every(row => runFacts(row) === runFacts(run)) && run.companyId === s.companyId && run.agentId === s.agentId && dependencyRunIssueId(run) === s.dependentId && run.status === "succeeded" && run.invocationSource === "automation" && run.triggerDetail === "system" - && run.contextSnapshot?.wakeReason === "issue_blockers_resolved" && run.contextSnapshot?.source === "issue.blockers_resolved" + && run.contextSnapshot?.wakeReason === "issue_blockers_resolved" && DEPENDENCY_WAKE_SOURCES.has(run.contextSnapshot?.source) && run.contextSnapshot?.resolvedBlockerIssueId === s.blockerId && exactId(run.contextSnapshot?.blockerIssueIds, s.blockerId) && Number.isFinite(date(run.startedAt)) && date(run.startedAt) >= date(released.blocker.completedAt); const boundRun = scoped && [run, reopened.dependentRuns[0], newRuns(finished)[0], newRuns(reopened)[0]].every(row => From c7efca1eaf1daad10fbfebe2dc37873a2fddb495 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:34:08 -0600 Subject: [PATCH 6/8] perf(recovery): read an agent's own reporting chain and each pass's review waits once (#21724) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server runs its background recovery queues on one Node main thread. Each database statement and each byte returned costs main-thread time. The target is 1,000 concurrent agents per server. > - On the idle hosted staging instance, the stranded-task check is the top remaining cost. Each check read the full agent row (with its configuration blobs) and then every agent of the company, only to decide whether this one agent can run. Per check it also opened a repeatable-read budget transaction for the same company and agent. > - The org-chain evaluation only looks at the agent's own managers. Reading the whole company is work proportional to the size of the company, for an answer that depends on a few rows. > - The same check also read the external review wait of each in-review task one task at a time. > - This pull request reads only the agent's reporting chain (one recursive query up `reports_to`), gives the stranded check a lean agent read, and reads the review waits of a pass's tasks in one call. > - The benefit is half the bytes per check (17.2 KB to 8.6 KB), 87 percent fewer rows, and no per-task review-wait chain for tasks that wait, with the same answers. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** The per-task reads of the stranded-task recovery check (`reconcileStrandedAssignedIssues`) and of every caller of `evaluateAgentInvokabilityFromDb` and `agentService.getById`. **Subsystem affected** Server: issue recovery and agent invokability. **Current behavior** `evaluateAgentInvokabilityFromDb` reads `id, company_id, name, reports_to, status` for every agent of the company on each call. `getById` does the same for `orgChainHealth`. The stranded check calls it once per task, after a full-row agent read with the configuration blobs. On staging at idle these are the `agents where company_id = $1` read at 4.7/s and the full `agents where id = $1` read at 4.2/s. The check also calls `listExternalReviewWaits` for one task at a time (the `chat_message_links` / `chat_github_reviews` reads at about 3/s on staging). **Proposed behavior** Read only the agent's managers, with the same cycle, missing-manager, cross-company and terminated rules. Read nothing when the agent has no manager or when its own status already decides the answer. Read the stranded check's agent with only the fields it uses. Read the review waits of all tasks of a pass in one call, and use that answer only to skip a task that waits. **Reason and benefit** At idle, the average result size on staging is about 17 KB per statement. The stranded check is about 22 statements and 17 KB per task, and it runs about 3 times per second there. ## What Changed - `server/src/lib/agent-reporting-chain.ts` (new): `readAgentReportingChain` reads the agent's managers with one recursive CTE up `reports_to`, limited to the agent's company. `UNION` stops the walk at a cycle. A root agent costs no statement. - `server/src/services/agent-invokability.ts`: `evaluateAgentInvokabilityFromDb` evaluates against the chain, not the company list. It reads nothing when the agent's own status is not invokable, because the status then decides the answer and the chain is not part of it. Every caller benefits with no change: wake enqueue, queued-run claim, retries, run dispatch, wake-queue promotion, continuation delivery, task watchdogs, thread interactions, native completion feedback, native session resumption, native review participants, agent conversations and recovery. - `server/src/lib/agent-records.ts`: `getById` computes `orgChainHealth` from the chain, not from the company list. - `server/src/services/recovery/service.ts`, stranded check: - The agent read selects only `id, company_id, name, reports_to, status, lifecycle_state, lifecycle_holds`, not the full row. - `hasPersistedDurableWaitPath` takes the pass. When the task is in the pass, the first in-review task reads the external review waits of every task of the pass with one `listExternalReviewWaits` call. A task in that answer waits and is skipped. A task not in that answer is read again alone, exactly as before, so a missing answer never lets a check go further than a fresh read would. - A company-wide call without a pass gets a pass of its in-review candidates. - `server/src/services/scoped-deadline-work.ts`: an optional `beforeChecks(entries)` hook gets the entries of the batch before their checks run. - `server/src/services/recovery/pass-reads.ts` (new) and `server/src/services/recovery/work.ts`: the task queues build a pass from the batch in `beforeChecks` and give it to each check of that batch. - Tests: - `server/src/__tests__/agent-reporting-chain.test.ts` (new): property test, see Verification. - `server/src/__tests__/issue-recovery-pass-reads.test.ts` (new): statements and bytes per check, per pass and per full worker drain. - `server/src/__tests__/issue-recovery-review-wait-pass.test.ts` (new): review-wait answers and reads, see Verification. - `server/src/__tests__/monthly-spend-service.test.ts`: the select-sequence stub no longer serves a company agent list to `getById`. - `server/src/__tests__/helpers/recovery-population.ts` (new): seeds a company with an org chart, review tasks with succeeded native runs, and optional paused, terminated and recovery-action tasks. - `server/src/__tests__/issue-recovery.test-fixture.ts`: an optional statement meter, installed before the first connection. - `server/src/__tests__/agent-record-read-projections.test.ts`: `getById` now makes one typed `agents` select; the chain is a raw query. ### Why the shared review-wait read cannot start or escalate work that a fresh read would not - A pass is one coordinator batch: at most 25 checks, one after the other. Its read is never older than the start of the batch. Nothing is kept across batches. - Only the positive answer is used: "this task waits on an external review or reply", which leads to a skip. A skip only delays the task to its next check, and the end of a wait sends its own hint. - A negative answer is not used. The task is read again alone, so every decision that goes further (an enqueue or an escalation) uses a fresh read, as today. - A first version also kept the agent's invokability and the budget answer for the pass. Review found that a kept permissive answer can reach an escalation, which does not re-check those facts the way an enqueue does. That reuse is removed: those reads stay per task. No authorization, pause, approval or budget check is removed or reordered. ## Verification - Equality proof (`agent-reporting-chain.test.ts`, embedded PostgreSQL): - 60 generated org charts, 2 companies each, up to 45 agents. Shapes: deep chains (depth 44), trees, full cycles and mixed graphs. - Managers are missing (inserted with foreign keys off), in another company, terminated, paused or pending approval at random depths. Agent statuses include an unknown value. - For each agent, the test compares the old list-based result with the new result. `evaluateAgentInvokabilityFromDb` deep-equals `evaluateAgentInvokability(agent, companyRows)`. `getAgentWorkEligibility` on the chain deep-equals it on the company list (this is the `getById` path). The test also asserts that every block reason and every chain-health reason occurred. - The list-based evaluation has no depth cap (`reporting_chain_too_deep` is declared but never returned), so the chain read has none either. A cycle ends the walk in both. - Mutation check: when the recursive step does not walk up, both tests fail. - Review-wait equality (`issue-recovery-review-wait-pass.test.ts`, embedded PostgreSQL): two tasks with a direct chat reply wait, one task with an inherited GitHub review wait, one task with none, and one task with an inherited GitHub review wait in another company. One call for all of them gives the same per-task answer as one call per task, for both companies. - Review-wait reads per pass (same file): the pass makes 2 bound-run message reads (one shared, one for the task whose candidate is not a wait) where per-task reads make 3, and 89 statements instead of 91. The check results are identical. On master the pass is ignored, so the test fails (3 is not less than 3). - Statements and bytes (`issue-recovery-pass-reads.test.ts`, 50 agents, 200 review tasks with succeeded native runs and no review waits, embedded PostgreSQL, statement meter on the client sockets): | | master | this branch | | --- | --- | --- | | One check: statements | 22 | 22 | | One check: bytes received | 17,170 | 8,617 | | One check: rows | 57 | 8 | | 25 checks: bytes | 429,331 | 215,505 | | Real worker, full company drain (200 checks): statements | 4,414 | 4,422 | | Real worker, full company drain: bytes | 3,455,957 | 1,749,701 | | Real worker, full company drain: rows | 11,600 | 1,800 | | Company agent-list reads per drain | 200 | 0 | Here no task waits, so each batch pays one extra review-wait statement (8 per drain). Where tasks wait, the shared read replaces the per-task review, publication and authorization reads. - Regression after the review change, embedded PostgreSQL (664 tests): scoped-deadline-work, heartbeat-process-recovery, issue-recovery-deadlines, assigned-work-invariant, recovery-deadline-acceptance, heartbeat-issue-liveness-escalation, slack-conversation-lifecycle. Also issue-list-review-wait-authorization, external-review-wait, monthly-spend-service. - Regression of the first version, embedded PostgreSQL (757 tests): issue-assignee-invokability-routes, agent-record-read-projections, issue-graph-liveness-equivalence, heartbeat-paused-assignee-new-task, heartbeat-process-recovery, heartbeat-issue-liveness-escalation, assigned-work-invariant, recovery-deadline-acceptance, issue-recovery-actions, heartbeat-refused-assignment-wake, failed-continuation-continues-again, agent-invokability, agent-cross-tenant-authz-routes, heartbeat-stop-queued-task, issue-tree-pause-resume-run. - `tsc --noEmit -p server/tsconfig.json` passes. ## Risks - A test double that gives `evaluateAgentInvokabilityFromDb` an object with only `select` now needs `execute`, and a select-sequence stub of `getById` gets one select fewer. CI found one (`monthly-spend-service`), fixed here. - A batch with no waiting task pays one extra cheap review-wait statement. - This branch and #21729 both touch `server/src/services/recovery/work.ts` in nearby lines. The second one to merge may need a small rebase. - `server/src/services/recovery/service.ts` was already past 1,000 lines. This change adds about 25 lines to it, beside the check it changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, local PostgreSQL test runs). ## 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 - [ ] 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 --- .../agent-record-read-projections.test.ts | 2 +- .../__tests__/agent-reporting-chain.test.ts | 103 ++++++++++++++++ .../__tests__/helpers/recovery-population.ts | 54 ++++++++ .../issue-recovery-pass-reads.test.ts | 74 +++++++++++ .../issue-recovery-review-wait-pass.test.ts | 116 ++++++++++++++++++ .../__tests__/issue-recovery.test-fixture.ts | 8 +- .../__tests__/monthly-spend-service.test.ts | 21 ---- server/src/lib/agent-records.ts | 7 +- server/src/lib/agent-reporting-chain.ts | 22 ++++ server/src/services/agent-invokability.ts | 18 +-- server/src/services/recovery/pass-reads.ts | 5 + server/src/services/recovery/service.ts | 52 ++++++-- server/src/services/recovery/work.ts | 8 +- server/src/services/scoped-deadline-work.ts | 2 + 14 files changed, 440 insertions(+), 52 deletions(-) create mode 100644 server/src/__tests__/agent-reporting-chain.test.ts create mode 100644 server/src/__tests__/helpers/recovery-population.ts create mode 100644 server/src/__tests__/issue-recovery-pass-reads.test.ts create mode 100644 server/src/__tests__/issue-recovery-review-wait-pass.test.ts create mode 100644 server/src/lib/agent-reporting-chain.ts create mode 100644 server/src/services/recovery/pass-reads.ts diff --git a/server/src/__tests__/agent-record-read-projections.test.ts b/server/src/__tests__/agent-record-read-projections.test.ts index 7786b017d3e..c11140d3062 100644 --- a/server/src/__tests__/agent-record-read-projections.test.ts +++ b/server/src/__tests__/agent-record-read-projections.test.ts @@ -94,7 +94,7 @@ describe.skipIf(!support.supported)("agent roster read projections", () => { it("keeps detail reads small while returning the selected agent's complete current configuration", async () => { const f = await fixture(); const captured = await observe(observed => agentRecordQueries(observed).getById(f.workerId)); - expect(captured.calls).toBe(2); + expect(captured.calls).toBe(1); expect(captured.bytes).toBeLessThan(8192); expect(captured.result).toMatchObject({ id: f.workerId, companyId: f.companyId, adapterConfig: f.worker.adapterConfig, runtimeConfig: f.worker.runtimeConfig, metadata: f.worker.metadata, permissions: { canCreateAgents: true }, spentMonthlyCents: 19.5, diff --git a/server/src/__tests__/agent-reporting-chain.test.ts b/server/src/__tests__/agent-reporting-chain.test.ts new file mode 100644 index 00000000000..06c13d5bea0 --- /dev/null +++ b/server/src/__tests__/agent-reporting-chain.test.ts @@ -0,0 +1,103 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { expect, it } from "vitest"; +import { agents, companies } from "@paperclipai/db"; +import { getAgentWorkEligibility } from "@paperclipai/shared"; +import { readAgentReportingChain } from "../lib/agent-reporting-chain.js"; +import { evaluateAgentInvokability, evaluateAgentInvokabilityFromDb, type AgentOrgRow } from "../services/agent-invokability.js"; +import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; + +const STATUSES = ["active", "idle", "running", "error", "paused", "terminated", "pending_approval", "retired"]; + +function random(seed: number) { + let state = seed >>> 0; + return () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 2 ** 32; + }; +} + +describeEmbeddedPostgres("agent reporting chain", () => { + const ctx = useEmbeddedPostgres("agent-reporting-chain-"); + + async function company(name: string) { + const id = randomUUID(); + await ctx.db.insert(companies).values({ id, name, issuePrefix: `C${id.slice(0, 7).toUpperCase()}` }); + return id; + } + + async function generateOrgChart(seed: number) { + const next = random(seed); + const pick = (items: readonly T[]) => items[Math.floor(next() * items.length)]!; + const home = await company(`Home ${seed}`), other = await company(`Other ${seed}`); + const shape = (["deep", "tree", "cycle", "mixed"] as const)[seed % 4]!; + const size = shape === "deep" ? 45 : 2 + Math.floor(next() * 45); + const homeRows: AgentOrgRow[] = Array.from({ length: size }, (_, index) => ({ id: randomUUID(), companyId: home, + name: `agent-${seed}-${index}`, reportsTo: null, status: next() < 0.6 ? "idle" : pick(STATUSES) })); + const otherRows: AgentOrgRow[] = Array.from({ length: 4 }, (_, index) => ({ id: randomUUID(), companyId: other, + name: `other-${seed}-${index}`, reportsTo: null, status: pick(STATUSES) })); + for (const [index, row] of homeRows.entries()) { + const roll = next(); + if (shape === "deep") row.reportsTo = index === 0 ? null : homeRows[index - 1]!.id; + else if (shape === "cycle") row.reportsTo = homeRows[(index + 1) % homeRows.length]!.id; + else if (roll < 0.12) row.reportsTo = null; + else if (roll < 0.2) row.reportsTo = pick(otherRows).id; + else if (roll < 0.27) row.reportsTo = randomUUID(); + else if (roll < 0.35 || shape === "mixed") row.reportsTo = pick(homeRows).id; + else row.reportsTo = index === 0 ? null : homeRows[Math.floor(next() * index)]!.id; + } + for (const row of otherRows) row.reportsTo = next() < 0.5 ? pick(homeRows).id : null; + await ctx.db.transaction(async tx => { + await tx.execute(sql`set local session_replication_role = replica`); + await tx.insert(agents).values([...homeRows, ...otherRows].map(row => ({ ...row, role: "engineer", adapterType: "process", + adapterConfig: {} }))); + }); + return { home, other, shape, rows: [...homeRows, ...otherRows] }; + } + + it("gives the same invokability and org-chain health as the whole-company list for generated org charts", async () => { + const seen = { shapes: new Set(), reasons: new Set(), healths: new Set(), maxDepth: 0 }; + for (let seed = 1; seed <= 60; seed++) { + const chart = await generateOrgChart(seed); + seen.shapes.add(chart.shape); + for (const companyId of [chart.home, chart.other]) { + const companyRows = await ctx.db.select({ id: agents.id, companyId: agents.companyId, name: agents.name, + reportsTo: agents.reportsTo, status: agents.status }).from(agents).where(eq(agents.companyId, companyId)); + for (const agent of companyRows) { + const listBased = evaluateAgentInvokability(agent, companyRows); + expect(await evaluateAgentInvokabilityFromDb(ctx.db, agent), `${chart.shape} ${seed} ${agent.name}`).toEqual(listBased); + const chain = await readAgentReportingChain(ctx.db, agent); + const listHealth = getAgentWorkEligibility({ agent, agents: companyRows }); + expect(getAgentWorkEligibility({ agent, agents: chain }), `${chart.shape} ${seed} ${agent.name}`).toEqual(listHealth); + seen.reasons.add(listBased.invokable ? "invokable" : listBased.reason); + seen.healths.add(listHealth.orgChainHealth.reason); + seen.maxDepth = Math.max(seen.maxDepth, listHealth.orgChainHealth.fullChain.length - 1); + } + } + } + expect([...seen.shapes].sort()).toEqual(["cycle", "deep", "mixed", "tree"]); + expect([...seen.healths].sort()).toEqual(["cycle", "healthy", "missing_manager", "terminated_ancestor"]); + for (const reason of ["invokable", "paused", "terminated", "pending_approval", "unknown_status", "manager_missing", + "manager_terminated", "reporting_cycle"]) expect(seen.reasons).toContain(reason); + expect(seen.maxDepth).toBeGreaterThanOrEqual(40); + }, 300_000); + + it("reads only the agent's own managers, and nothing for a root agent", async () => { + const home = await company("Chain only"); + const ids = Array.from({ length: 50 }, () => randomUUID()); + await ctx.db.insert(agents).values(ids.map((id, index) => ({ id, companyId: home, name: `a${index}`, role: "engineer", + adapterType: "process", adapterConfig: {}, status: "idle", reportsTo: index === 0 ? null : ids[index < 10 ? index - 1 : 0] }))); + const [deep] = await ctx.db.select().from(agents).where(eq(agents.id, ids[9]!)); + expect((await readAgentReportingChain(ctx.db, deep!)).map(row => row.id)).toEqual(ids.slice(0, 9).reverse()); + const [root] = await ctx.db.select().from(agents).where(eq(agents.id, ids[0]!)); + const execute = ctx.db.execute.bind(ctx.db); + let statements = 0; + const counted = Object.assign(Object.create(ctx.db), { execute: (...args: Parameters) => { + statements += 1; return execute(...args); + } }); + expect(await evaluateAgentInvokabilityFromDb(counted, root!)).toEqual({ invokable: true }); + expect(await evaluateAgentInvokabilityFromDb(counted, { ...deep!, status: "paused" })).toMatchObject({ reason: "paused" }); + expect(statements).toBe(0); + expect(evaluateAgentInvokability(deep!, [])).toMatchObject({ reason: "manager_missing" }); + }); +}); diff --git a/server/src/__tests__/helpers/recovery-population.ts b/server/src/__tests__/helpers/recovery-population.ts new file mode 100644 index 00000000000..16947d39334 --- /dev/null +++ b/server/src/__tests__/helpers/recovery-population.ts @@ -0,0 +1,54 @@ +import { agents, heartbeatRuns, issueRecoveryActions, issues, type Db } from "@paperclipai/db"; + +const HOUR = 60 * 60_000; + +export type RecoveryPopulation = { + agentIds: string[]; + pausedAgentId: string; + terminatedAgentId: string; + inReview: string[]; + inProgress: string[]; + todo: string[]; + withRecoveryAction: string[]; + terminated: string[]; +}; + +export async function seedRecoveryPopulation(db: Db, companyId: string, counts: { + agents: number; inReview: number; inProgress?: number; todo?: number; recoveryActions?: number; terminated?: number; +}): Promise { + const config = { adapterType: "process", adapterConfig: { command: process.execPath, args: ["-e", "0"], cwd: process.cwd() }, + runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: true } }, role: "engineer" }; + const [ceo] = await db.insert(agents).values({ ...config, companyId, name: "Chief", status: "idle" }).returning({ id: agents.id }); + const managers = await db.insert(agents).values(Array.from({ length: 6 }, (_, index) => ({ ...config, companyId, + name: `Manager ${index}`, status: "idle", reportsTo: ceo!.id }))).returning({ id: agents.id }); + const workers = await db.insert(agents).values(Array.from({ length: Math.max(1, counts.agents - 9) }, (_, index) => ({ ...config, + companyId, name: `Worker ${index}`, status: "idle", reportsTo: managers[index % managers.length]!.id }))).returning({ id: agents.id }); + const [paused] = await db.insert(agents).values({ ...config, companyId, name: "Paused worker", status: "paused", + lifecycleHolds: ["manual"], reportsTo: managers[0]!.id }).returning({ id: agents.id }); + const [terminatedAgent] = await db.insert(agents).values({ ...config, companyId, name: "Former worker", status: "terminated", + reportsTo: managers[1]!.id }).returning({ id: agents.id }); + const workerIds = workers.map(row => row.id); + const finishedAt = new Date(Date.now() - HOUR); + + const insertTasks = async (count: number, values: (index: number) => Partial) => count === 0 ? [] + : (await db.insert(issues).values(Array.from({ length: count }, (_, index) => ({ companyId, title: `Task ${index}`, + ...values(index) }))).returning({ id: issues.id, assigneeAgentId: issues.assigneeAgentId })).map(row => row); + + const reviews = await insertTasks(counts.inReview, index => ({ status: "in_review", + assigneeAgentId: workerIds[index % workerIds.length] })); + if (reviews.length) await db.insert(heartbeatRuns).values(reviews.map(task => ({ companyId, agentId: task.assigneeAgentId!, + status: "succeeded", runtimeMode: "native", startedAt: finishedAt, finishedAt, contextSnapshot: { issueId: task.id } }))); + const progressing = await insertTasks(counts.inProgress ?? 0, () => ({ status: "in_progress", assigneeAgentId: paused!.id })); + if (progressing.length) await db.insert(heartbeatRuns).values(progressing.map(task => ({ companyId, agentId: paused!.id, + status: "cancelled", errorCode: "agent_paused", startedAt: finishedAt, finishedAt, contextSnapshot: { issueId: task.id } }))); + const todo = await insertTasks(counts.todo ?? 0, () => ({ status: "todo", assigneeAgentId: paused!.id })); + const terminated = await insertTasks(counts.terminated ?? 0, () => ({ status: "todo", assigneeAgentId: terminatedAgent!.id })); + const withAction = reviews.slice(0, counts.recoveryActions ?? 0); + if (withAction.length) await db.insert(issueRecoveryActions).values(withAction.map((task, index) => ({ companyId, + sourceIssueId: task.id, kind: "missing_disposition", status: "active", ownerType: "agent", ownerAgentId: task.assigneeAgentId, + cause: "seeded", fingerprint: `seeded-${index}`, nextAction: "seeded" }))); + return { agentIds: [ceo!.id, ...managers.map(row => row.id), ...workerIds, paused!.id, terminatedAgent!.id], + pausedAgentId: paused!.id, terminatedAgentId: terminatedAgent!.id, + inReview: reviews.map(row => row.id), inProgress: progressing.map(row => row.id), todo: todo.map(row => row.id), + withRecoveryAction: withAction.map(row => row.id), terminated: terminated.map(row => row.id) }; +} diff --git a/server/src/__tests__/issue-recovery-pass-reads.test.ts b/server/src/__tests__/issue-recovery-pass-reads.test.ts new file mode 100644 index 00000000000..e0b26bcad78 --- /dev/null +++ b/server/src/__tests__/issue-recovery-pass-reads.test.ts @@ -0,0 +1,74 @@ +import { setImmediate as immediate } from "node:timers/promises"; +import { asc, eq } from "drizzle-orm"; +import { expect, it, vi } from "vitest"; +import { issues } from "@paperclipai/db"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; +import { seedRecoveryPopulation } from "./helpers/recovery-population.js"; + +const PASS = 25; + +describeIssueRecovery("stranded-task check reads", () => { + const state = issueRecoveryFixture({ meter: true }); + + async function measure(work: () => Promise) { + const before = state.meter.read(); + state.meter.startLog(); + await work(); + const log = state.meter.stopLog(); + const after = state.meter.read(); + return { statements: after.statements - before.statements, bytes: after.bytesReceived - before.bytesReceived, + rows: after.rows - before.rows, log }; + } + + async function seed() { + const f = await state.fixture(); + const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 200 }); + return { ...f, population }; + } + + it("reads a lean agent row and the agent's own reporting chain for a 50-agent, 200-task company", async () => { + const { companyId } = await seed(); + const ordered = await state.db.select({ id: issues.id }).from(issues) + .where(eq(issues.companyId, companyId)).orderBy(asc(issues.id)); + const tasks = ordered.map(row => row.id); + const check = (issueId: string) => state.heartbeat.reconcileStrandedAssignedIssues({ companyId, issueId, + skipExternalConversationSettlement: true, skipRelatedRecovery: true }); + + await check(tasks[0]!); + const single = await measure(() => check(tasks[1]!)); + const passReads = await measure(async () => { for (const issueId of tasks.slice(0, PASS)) await check(issueId); }); + const companyAgentLists = passReads.log.filter(entry => /from "agents" where "agents"\."company_id" = \$1$/.test(entry.sql.trim())); + const fullAgentRows = passReads.log.filter(entry => /^select "id", "company_id", "name", "role"/.test(entry.sql.trim())); + const writes = passReads.log.filter(entry => /^(insert|update|delete)/i.test(entry.sql.trim())); + console.info(JSON.stringify({ singleCheck: { statements: single.statements, bytes: single.bytes, rows: single.rows }, + pass: { checks: PASS, statements: passReads.statements, bytes: passReads.bytes, rows: passReads.rows, + perCheckStatements: passReads.statements / PASS, perCheckBytes: Math.round(passReads.bytes / PASS) }, + companyAgentLists: companyAgentLists.length, fullAgentRows: fullAgentRows.length })); + + expect(writes).toEqual([]); + expect(companyAgentLists).toEqual([]); + expect(fullAgentRows).toEqual([]); + expect(passReads.bytes / PASS).toBeLessThan(10_000); + }, 300_000); + + it("drains a full company load through the real worker with fewer statements and bytes per check", async () => { + const { population } = await seed(); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + const drained = await measure(async () => { + await state.start({}); + const until = Date.now() + 60_000; + while (Date.now() < until) { + await vi.advanceTimersByTimeAsync(500); + await Promise.allSettled([...state.passes]); await immediate(); + } + }); + const checks = drained.log.filter(entry => /from "case_handoffs"/.test(entry.sql) && /"issues"\."id" = \$/.test(entry.sql)).length; + const companyAgentLists = drained.log.filter(entry => /from "agents" where "agents"\."company_id" = \$1$/.test(entry.sql.trim())); + console.info(JSON.stringify({ worker: { strandedChecks: checks, statements: drained.statements, bytes: drained.bytes, + rows: drained.rows, perCheckStatements: drained.statements / Math.max(1, checks), + perCheckBytes: Math.round(drained.bytes / Math.max(1, checks)), companyAgentLists: companyAgentLists.length } })); + expect(checks).toBeGreaterThanOrEqual(population.inReview.length); + expect(companyAgentLists).toEqual([]); + expect(drained.bytes / checks).toBeLessThan(10_000); + }, 600_000); +}); diff --git a/server/src/__tests__/issue-recovery-review-wait-pass.test.ts b/server/src/__tests__/issue-recovery-review-wait-pass.test.ts new file mode 100644 index 00000000000..6a7e8fe74f0 --- /dev/null +++ b/server/src/__tests__/issue-recovery-review-wait-pass.test.ts @@ -0,0 +1,116 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { expect, it } from "vitest"; +import { chatConversations, chatDeliveries, chatEndpoints, chatMessageLinks, heartbeatRuns, issueComments, issues, + statusDecisions, type Db } from "@paperclipai/db"; +import { listExternalReviewWaits } from "../services/native-runtime/external-review-wait.js"; +import { createRecoveryPassReads } from "../services/recovery/pass-reads.js"; +import { seedBoundChatAuthorization } from "./helpers/bound-chat-authorization.js"; +import { seedGitHubReviewWait } from "./helpers/github-review-wait.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +const boundRunLinkRead = /from "chat_message_links" inner join "chat_deliveries"/i; + +async function waitOnReply(db: Db, input: { companyId: string; issueId: string; runId: string }) { + const decisionId = randomUUID(); + await db.transaction(async (tx) => { + await tx.execute(sql`set local session_replication_role = replica`); + await tx.insert(statusDecisions).values({ id: decisionId, companyId: input.companyId, issueId: input.issueId, runId: input.runId, + assessmentId: randomUUID(), decisionVersion: 1, policyVersion: "test", fromStatus: "in_progress", toStatus: "in_review", + reasonCode: "external_chat_response_waiting", decisionJson: {}, decisionDigest: decisionId, applicationState: "applied", + appliedAt: new Date() }); + }); + await db.update(issues).set({ status: "in_review", lastStatusDecisionId: decisionId }).where(eq(issues.id, input.issueId)); +} + +describeIssueRecovery("stranded-task external review waits within one pass", () => { + const state = issueRecoveryFixture({ meter: true }); + + async function seed() { + const db = state.db; + const f = await seedBoundChatAuthorization(db); + const otherConversationId = randomUUID(), otherCommentId = randomUUID(), deliveryId = randomUUID(), otherRunId = randomUUID(); + await db.insert(chatConversations).values({ id: otherConversationId, companyId: f.companyId, endpointId: f.endpointId, + resourceId: f.resourceId, issueId: f.otherIssueId, externalConversationId: "channel-1", externalThreadId: "thread-2", + externalLabel: "Other thread", state: "active" }); + await db.insert(issueComments).values({ id: otherCommentId, companyId: f.companyId, issueId: f.otherIssueId, + authorType: "user", authorUserId: f.userId, body: "Another request" }); + await db.insert(chatDeliveries).values({ id: deliveryId, companyId: f.companyId, endpointId: f.endpointId, + conversationId: otherConversationId, principalId: f.principalId, providerEventId: deliveryId, deduplicationKey: deliveryId, + eventKind: "message", normalizedEvent: {}, state: "processed", processedAt: new Date() }); + await db.insert(chatMessageLinks).values({ companyId: f.companyId, endpointId: f.endpointId, conversationId: otherConversationId, + deliveryId, commentId: otherCommentId, providerMessageId: otherCommentId, direction: "inbound" }); + await db.insert(heartbeatRuns).values([ + { id: f.runId, companyId: f.companyId, agentId: f.agentId, status: "succeeded", runtimeMode: "native", nativeIssueId: f.issueId, + finishedAt: new Date(), contextSnapshot: { ...f.context, issueId: f.issueId } }, + { id: otherRunId, companyId: f.companyId, agentId: f.agentId, status: "succeeded", runtimeMode: "native", + nativeIssueId: f.otherIssueId, finishedAt: new Date(), + contextSnapshot: { ...f.context, issueId: f.otherIssueId, wakeCommentIds: [otherCommentId] } }, + ]); + await waitOnReply(db, { companyId: f.companyId, issueId: f.issueId, runId: f.runId }); + await waitOnReply(db, { companyId: f.companyId, issueId: f.otherIssueId, runId: otherRunId }); + + const inherited = await seedGitHubReviewWait(db, { companyId: f.companyId, agentId: f.agentId }); + await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native", finishedAt: new Date(), + contextSnapshot: { issueId: inherited.issueId } }).where(eq(heartbeatRuns.id, inherited.runId)); + await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, inherited.endpointId)); + await waitOnReply(db, { companyId: f.companyId, issueId: inherited.issueId, runId: inherited.runId }); + + const [none] = await db.insert(issues).values({ companyId: f.companyId, title: "No wait", status: "in_review", + assigneeAgentId: f.agentId }).returning({ id: issues.id }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded", runtimeMode: "native", + nativeIssueId: none!.id, finishedAt: new Date(), contextSnapshot: { issueId: none!.id } }); + + const foreign = await seedGitHubReviewWait(db); + await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native", finishedAt: new Date(), + contextSnapshot: { issueId: foreign.issueId } }).where(eq(heartbeatRuns.id, foreign.runId)); + await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, foreign.endpointId)); + await waitOnReply(db, { companyId: foreign.companyId, issueId: foreign.issueId, runId: foreign.runId }); + + return { companyId: f.companyId, direct: [f.issueId, f.otherIssueId], inherited: inherited.issueId, none: none!.id, + foreign: { companyId: foreign.companyId, issueId: foreign.issueId } }; + } + + it("answers each task's review wait the same from one read for the pass as from one read per task", async () => { + const f = await seed(); + const ids = [...f.direct, f.inherited, f.none, f.foreign.issueId]; + const single = new Set(); + for (const issueId of ids) { + if ((await listExternalReviewWaits(state.db, f.companyId, [issueId])).length) single.add(issueId); + } + const batched = new Set((await listExternalReviewWaits(state.db, f.companyId, ids)).map(wait => wait.issueId)); + expect(batched).toEqual(single); + for (const issueId of f.direct) expect(single).toContain(issueId); + expect(single).not.toContain(f.none); + expect(single).not.toContain(f.foreign.issueId); + const foreignSingle = (await listExternalReviewWaits(state.db, f.foreign.companyId, [f.foreign.issueId])).length > 0; + const foreignBatched = (await listExternalReviewWaits(state.db, f.foreign.companyId, ids)).some(wait => wait.issueId === f.foreign.issueId); + expect(foreignBatched).toBe(foreignSingle); + }); + + it("reads the review waits of a pass once and skips the same tasks as per-task reads", async () => { + const f = await seed(); + const ids = [...f.direct, f.inherited, f.none]; + const check = (issueId: string, pass?: ReturnType) => + state.heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId, skipExternalConversationSettlement: true, + skipRelatedRecovery: true, ...(pass ? { pass } : {}) }); + const run = async (pass?: ReturnType) => { + state.meter.startLog(); + const results = []; + for (const issueId of ids) { + const { issueIds: _ids, ...counts } = await check(issueId, pass); + results.push(counts); + } + const log = state.meter.stopLog(); + return { results, linkReads: log.filter(entry => boundRunLinkRead.test(entry.sql)).length, statements: log.length }; + }; + const perTask = await run(); + const perPass = await run(createRecoveryPassReads(ids)); + console.info(JSON.stringify({ perTask: { linkReads: perTask.linkReads, statements: perTask.statements }, + perPass: { linkReads: perPass.linkReads, statements: perPass.statements } })); + expect(perPass.results).toEqual(perTask.results); + expect(perTask.linkReads).toBeGreaterThanOrEqual(f.direct.length); + expect(perPass.linkReads).toBeLessThan(perTask.linkReads); + expect(perPass.statements).toBeLessThan(perTask.statements); + }); +}); diff --git a/server/src/__tests__/issue-recovery.test-fixture.ts b/server/src/__tests__/issue-recovery.test-fixture.ts index da4485f62e4..4aa0b6ac764 100644 --- a/server/src/__tests__/issue-recovery.test-fixture.ts +++ b/server/src/__tests__/issue-recovery.test-fixture.ts @@ -11,6 +11,7 @@ import { notifyIssueRecovery } from "../services/issue-recovery-notifications.js import { instanceSettingsService } from "../services/instance-settings.js"; import { issueService } from "../services/issues.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; vi.setConfig({ testTimeout: 90_000 }); @@ -18,7 +19,8 @@ const external = resolveExternalTestDatabaseUrl("PAPERCLIP_ISSUE_RECOVERY_TEST_D const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); export const describeIssueRecovery: ReturnType = describe.skipIf(!support.supported); -export function issueRecoveryFixture() { +export function issueRecoveryFixture(options: { meter?: boolean } = {}) { + let meter: ReturnType | undefined; let database: Awaited> | undefined; let db: ReturnType; let heartbeat: ReturnType; @@ -35,6 +37,7 @@ export function issueRecoveryFixture() { beforeAll(async () => { if (!external) database = await startEmbeddedPostgresTestDatabase("issue-recovery-work-"); db = createDb(external ?? database!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + if (options.meter) meter = meterDatabaseStatements(db, external ?? database!.connectionString); await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`))); }, 90_000); beforeEach(async () => { @@ -49,7 +52,7 @@ export function issueRecoveryFixture() { vi.useRealTimers(); vi.restoreAllMocks(); expect(errors).toEqual([]); }); - afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); }); + afterAll(async () => { meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await database?.cleanup(); }); async function start(options: { backstopMs?: number } = { backstopMs: 0 }) { coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, canReconcile: () => true, onError: error => errors.push(error) }); @@ -232,6 +235,7 @@ export function issueRecoveryFixture() { return { start, compete, fixture, completingProvider, settled, quiet, finish, completed, savedConversation, get db() { return db; }, + get meter() { return meter!; }, get heartbeat() { return heartbeat; }, set heartbeat(value: typeof heartbeat) { heartbeat = value; }, get coordinator() { return coordinator; }, diff --git a/server/src/__tests__/monthly-spend-service.test.ts b/server/src/__tests__/monthly-spend-service.test.ts index 92a67421fc0..c1531a2d681 100644 --- a/server/src/__tests__/monthly-spend-service.test.ts +++ b/server/src/__tests__/monthly-spend-service.test.ts @@ -54,27 +54,6 @@ describe("monthly spend hydration", () => { it("recomputes agent spentMonthlyCents from the current utc month instead of returning stale stored values", async () => { const dbStub = createSelectSequenceDb([ - [{ - id: "agent-1", - companyId: "company-1", - name: "Budget Agent", - role: "general", - title: null, - reportsTo: null, - capabilities: null, - adapterType: "claude-local", - adapterConfig: {}, - runtimeConfig: {}, - budgetMonthlyCents: 5000, - spentMonthlyCents: 999999, - metadata: null, - permissions: null, - status: "idle", - pauseReason: null, - pausedAt: null, - createdAt: new Date(), - updatedAt: new Date(), - }], [{ id: "agent-1", companyId: "company-1", diff --git a/server/src/lib/agent-records.ts b/server/src/lib/agent-records.ts index b5e2b01b5d4..f5b7500cabf 100644 --- a/server/src/lib/agent-records.ts +++ b/server/src/lib/agent-records.ts @@ -9,6 +9,7 @@ import { import { conflict, notFound, unprocessable } from "../errors.js"; import { REDACTED_EVENT_VALUE, sanitizeRecord } from "../redaction.js"; import { normalizeAgentPermissions } from "./agent-permissions.js"; +import { readAgentReportingChain } from "./agent-reporting-chain.js"; import { builtInAgentMarkersEqual, readBuiltInAgentMarker } from "./built-in-agent-metadata.js"; export function hashToken(token: string) { @@ -417,11 +418,11 @@ export function agentRecordQueries(db: Db) { .where(eq(agents.id, id)) .then((rows) => rows[0] ?? null); if (!row) return null; - const [companyRows, hydrated] = await Promise.all([ - listCompanyAgentEligibilityRows(row.companyId), + const [chainRows, hydrated] = await Promise.all([ + readAgentReportingChain(db, row), hydrateAgentSpend([row]).then((rows) => rows[0]!), ]); - return normalizeAgentRow(hydrated, companyRows); + return normalizeAgentRow(hydrated, chainRows); } async function ensureManager(companyId: string, managerId: string) { diff --git a/server/src/lib/agent-reporting-chain.ts b/server/src/lib/agent-reporting-chain.ts new file mode 100644 index 00000000000..c2ae6340ea5 --- /dev/null +++ b/server/src/lib/agent-reporting-chain.ts @@ -0,0 +1,22 @@ +import { sql } from "drizzle-orm"; +import type { agents, Db } from "@paperclipai/db"; + +export type AgentReportingChainRow = Pick; + +export async function readAgentReportingChain( + db: Pick, + agent: { companyId: string; reportsTo: string | null }, +): Promise { + if (!agent.reportsTo) return []; + const rows = await db.execute<{ id: string; company_id: string; name: string; reports_to: string | null; status: string }>(sql` + with recursive chain(id, company_id, name, reports_to, status) as ( + select id, company_id, name, reports_to, status from agents + where company_id = ${agent.companyId}::uuid and id = ${agent.reportsTo}::uuid + union + select manager.id, manager.company_id, manager.name, manager.reports_to, manager.status + from agents manager inner join chain on manager.id = chain.reports_to + where manager.company_id = ${agent.companyId}::uuid + ) select id::text, company_id::text, name, reports_to::text, status from chain`); + return rows.map(row => ({ id: row.id, companyId: row.company_id, name: row.name, reportsTo: row.reports_to, + status: row.status as AgentReportingChainRow["status"] })); +} diff --git a/server/src/services/agent-invokability.ts b/server/src/services/agent-invokability.ts index b9b39d59f5d..4d455580eab 100644 --- a/server/src/services/agent-invokability.ts +++ b/server/src/services/agent-invokability.ts @@ -1,7 +1,7 @@ import type { Db } from "@paperclipai/db"; import { agents } from "@paperclipai/db"; -import { getAgentWorkEligibility, type AgentEligibilityAgent, type AgentOrgChainHealth } from "@paperclipai/shared"; -import { eq } from "drizzle-orm"; +import { getAgentWorkEligibility, isAgentStatusInvokable, type AgentEligibilityAgent, type AgentOrgChainHealth } from "@paperclipai/shared"; +import { readAgentReportingChain } from "../lib/agent-reporting-chain.js"; type AgentStatus = (typeof agents.$inferSelect)["status"]; @@ -119,18 +119,8 @@ export async function evaluateAgentInvokabilityFromDb( db: Db, agent: AgentOrgRow | null | undefined, ): Promise { - if (!agent) return evaluateAgentInvokability(agent, []); - const companyAgents = await db - .select({ - id: agents.id, - companyId: agents.companyId, - name: agents.name, - reportsTo: agents.reportsTo, - status: agents.status, - }) - .from(agents) - .where(eq(agents.companyId, agent.companyId)); - return evaluateAgentInvokability(agent, companyAgents); + if (!agent || !isAgentStatusInvokable(agent.status)) return evaluateAgentInvokability(agent, []); + return evaluateAgentInvokability(agent, await readAgentReportingChain(db, agent)); } export function listInvalidOrgChainDescendantIds( diff --git a/server/src/services/recovery/pass-reads.ts b/server/src/services/recovery/pass-reads.ts new file mode 100644 index 00000000000..e01c8f13e75 --- /dev/null +++ b/server/src/services/recovery/pass-reads.ts @@ -0,0 +1,5 @@ +export type RecoveryPassReads = { issueIds: ReadonlySet; reads: Map> }; + +export function createRecoveryPassReads(issueIds: Iterable = []): RecoveryPassReads { + return { issueIds: new Set(issueIds), reads: new Map() }; +} diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 7a855a721d0..52b165c4bb5 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -159,7 +159,8 @@ import { buildIssueBlockersResolvedWakeStateKey, findExistingIssueBlockersResolvedWakeForReadyState, } from "../issue-dependency-wakeups.js"; -import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js"; +import { evaluateAgentInvokabilityFromDb, type AgentOrgRow } from "../agent-invokability.js"; +import { createRecoveryPassReads, type RecoveryPassReads } from "./pass-reads.js"; import { isHeartbeatWakeOnDemandEnabled } from "../heartbeat-policy.js"; import { DEFAULT_MAX_SUCCESSFUL_RUN_HANDOFF_ATTEMPTS, @@ -208,6 +209,17 @@ import { type DbTransaction = Parameters[0]>[0]; type DbOrTransaction = Db | DbTransaction; +const strandedAgentFields = { + id: agents.id, + companyId: agents.companyId, + name: agents.name, + reportsTo: agents.reportsTo, + status: agents.status, + lifecycleState: agents.lifecycleState, + lifecycleHolds: agents.lifecycleHolds, +}; +type StrandedAgent = { [K in keyof typeof strandedAgentFields]: (typeof agents.$inferSelect)[K] }; + const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = [ "queued", "running", @@ -1039,11 +1051,33 @@ export function recoveryService( } async function isAgentInvokable( - agent: typeof agents.$inferSelect | null | undefined, + agent: AgentOrgRow | null | undefined, ) { return (await evaluateAgentInvokabilityFromDb(db, agent)).invokable; } + async function readStrandedAgent(agentId: string, companyId: string) { + const agent: StrandedAgent | null = await db.select(strandedAgentFields).from(agents).where(eq(agents.id, agentId)) + .then((rows) => rows[0] ?? null); + const invokable = agent && agent.companyId === companyId && !isAgentAwaitingSetup(agent) + ? await isAgentInvokable(agent) : false; + return { agent, invokable }; + } + + async function hasExternalReviewWait(issue: RecoveryIssue, pass?: RecoveryPassReads) { + if (pass?.issueIds.has(issue.id)) { + const key = `external-review-waits:${issue.companyId}`; + let waiting = pass.reads.get(key) as Promise> | undefined; + if (!waiting) { + waiting = listExternalReviewWaits(db, issue.companyId, [...pass.issueIds]) + .then((waits) => new Set(waits.map((wait) => wait.issueId))); + pass.reads.set(key, waiting); + } + if ((await waiting).has(issue.id)) return true; + } + return (await listExternalReviewWaits(db, issue.companyId, [issue.id])).length > 0; + } + async function getLatestIssueRun( companyId: string, issueId: string, @@ -1562,10 +1596,11 @@ export function recoveryService( async function hasPersistedDurableWaitPath( issue: RecoveryIssue, latestRun: LatestIssueRun, + pass?: RecoveryPassReads, ) { if (issue.monitorNextCheckAt) return true; if (issue.status === "in_review" && latestRun?.status === "succeeded" && - (await listExternalReviewWaits(db, issue.companyId, [issue.id])).length > 0) return true; + await hasExternalReviewWait(issue, pass)) return true; if (issue.status === "in_progress" && latestRun?.status === "succeeded" && latestRun.agentId === issue.assigneeAgentId && await hasCommittedNativePlanWait(db, { companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId: latestRun.agentId })) return true; if (issue.status === "in_progress" && latestRun?.status === "succeeded" && latestRun.agentId === issue.assigneeAgentId && @@ -4752,6 +4787,7 @@ export function recoveryService( issueCreatedAtGte?: Date | null; skipExternalConversationSettlement?: boolean; skipRelatedRecovery?: boolean; + pass?: RecoveryPassReads; }) { const candidates = await db .select(recoveryIssueFields) @@ -4801,6 +4837,8 @@ export function recoveryService( issueIds: [] as string[], }; + const pass = opts?.pass ?? (candidates.length > 1 + ? createRecoveryPassReads(candidates.filter((issue) => issue.status === "in_review").map((issue) => issue.id)) : undefined); const handledIssueIds = await resumeShutdownStoppedRetryPreparations(candidates, result, opts?.onDeferredDeadline); const candidateIssueIds = candidates.map((issue) => issue.id); @@ -4955,15 +4993,11 @@ export function recoveryService( } } - const agent = await getAgent(agentId); + const { agent, invokable: agentInvokable } = await readStrandedAgent(agentId, issue.companyId); if (agent?.companyId === issue.companyId && isAgentAwaitingSetup(agent)) { result.skipped += 1; continue; } - const agentInvokable = - agent && agent.companyId === issue.companyId - ? await isAgentInvokable(agent) - : false; if ( agent?.status === "paused" && agent.companyId === issue.companyId && @@ -5204,7 +5238,7 @@ export function recoveryService( } if ( latestRun?.status === "succeeded" && - (await hasPersistedDurableWaitPath(issue, latestRun)) + (await hasPersistedDurableWaitPath(issue, latestRun, pass)) ) { result.skipped += 1; continue; diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index fc7b39b628b..6a8115737ed 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -8,9 +8,11 @@ import { decodeIssueRecoveryHint, ISSUE_RECOVERY_BACKSTOP_MS, issueRecoveryBacks import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; import { recoveryActionSweepCondition } from "./blocker-stall-wakeups.js"; +import { createRecoveryPassReads, type RecoveryPassReads } from "./pass-reads.js"; type Entry = { id: string; companyId: string; dueAt: number; fromDeadline?: true }; -type Scope = { companyId: string; issueId: string; onDeferredDeadline: (at: number, detail?: { unchanged: boolean }) => void }; +type Scope = { companyId: string; issueId: string; onDeferredDeadline: (at: number, detail?: { unchanged: boolean }) => void; + pass?: RecoveryPassReads }; const PAGE_SIZE = 100; export const resolvedDependencyCandidate = sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId} @@ -81,11 +83,13 @@ export function registerIssueRecoveryWork( const cursors = new Map(); const passes = fullPasses(); let enabled = false; + let pass = createRecoveryPassReads(); const worker: ReturnType> = registerScopedDeadlineWork(coordinator, { queue, reconstructionIntervalMs, backstop: passes.backstop, beforePass: async () => { enabled = !(await owner.schedulingSuppressed()); }, + beforeChecks: entries => { pass = createRecoveryPassReads(entries.map(entry => entry.id)); }, decodeScope: decodeIssueRecoveryHint, matches: issueRecoveryScopeMatches, load: async scope => { @@ -115,7 +119,7 @@ export function registerIssueRecoveryWork( if (workSignalDebug.enabled) workSignalDebug.event(queue, "check", { issueId: entry.id, companyId: entry.companyId, wake: entry.fromDeadline ? "deadline" : "load", dueAt: entry.dueAt }); let next: number | null = null; - await check({ companyId: entry.companyId, issueId: entry.id, + await check({ companyId: entry.companyId, issueId: entry.id, pass, onDeferredDeadline: at => { next = next === null ? at : Math.min(next, at); } }); return next === null ? null : { ...entry, dueAt: next, ...(workSignalDebug.enabled ? { fromDeadline: true as const } : {}) }; }, diff --git a/server/src/services/scoped-deadline-work.ts b/server/src/services/scoped-deadline-work.ts index b6ad70881c6..232b816e484 100644 --- a/server/src/services/scoped-deadline-work.ts +++ b/server/src/services/scoped-deadline-work.ts @@ -28,6 +28,7 @@ export function registerScopedDeadlineWork( reconstructionIntervalMs?: number | ((scope: Scope | undefined) => number); backstop?(scope: Scope | undefined): number | null; beforePass?(): Promise; + beforeChecks?(entries: readonly Entry[]): void; decodeScope(hint: string): Scope | undefined; matches(entry: Entry, scope?: Scope): boolean; /** @@ -197,6 +198,7 @@ export function registerScopedDeadlineWork( .sort((a, b) => (options.priority?.(b) ?? 0) - (options.priority?.(a) ?? 0) || a.dueAt - b.dueAt || a.id.localeCompare(b.id)); const batch = takeCompanyWorkBatch(due, options.batchSize ?? 25, lastCompany); lastCompany = batch.lastCompany; + options.beforeChecks?.(batch.entries); // An owner may share more than one resource (for example a task and an // endpoint). Merge intersecting keys before dispatch so waiting siblings // do not occupy the bounded check slots ahead of independent work. From 01c1e708e93507b5dfedb8dbfd08ba8e9d7ef2c4 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:52:50 -0600 Subject: [PATCH 7/8] fix(runner): stop a turn that keeps resending a refused tool call and continue fresh (#21734) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native agent runs call Paperclip tools, and `RepeatedToolFailureGuard` refuses an exact repeat of a call that already failed validation twice > - The refusals are not counted and never end the turn, so a model whose host drops an argument can resend the same refused call until the run's wall clock > - In a recorded restart-chaos wave, an opencode/DeepSeek agent sent the same `PATCH /api/issues/{id}` through `call_api` 431 times in 40 minutes without `body`; 427 were refused. The run held an agent slot and delayed other tasks > - The system knows the next step (stop the turn and continue on a fresh session), so the harness must own it, with no Retry banner > - This pull request counts refusals, stops the provider turn after a bounded number with the classified cause `agent_tool_call_loop`, and queues an automatic fresh-session continuation that tells the model to use a dedicated tool > - It also records the declared argument names that each opencode tool call delivered, so we can tell whether the bridge or the model drops `body` > - The benefit is that a looping agent frees its slot in seconds instead of 40 minutes, and the task continues by itself ## Linked Issues or Issue Description **What happened?** An opencode agent on DeepSeek created two subtasks and then tried to set their descriptions with `call_api` `PATCH /api/issues/{id}`. Every call arrived with `operationId`, `pathParams`, `query` and `responseText`, but without `body`. The guard refused each repeat. The model said "I need to include body" more than 20 times and kept sending the same call: 431 calls, 427 refused, over 40 minutes. The run stayed active and its agent slot delayed other queued work. **Expected behavior** After a small, bounded number of refusals, Paperclip stops the provider turn and continues the task automatically on a fresh session, with a hint to use a dedicated Paperclip tool. The board shows no Retry banner because the system owns this recovery. **Steps to reproduce** 1. Run a native agent whose model resends one tool call with a missing required argument. 2. The guard refuses the third and later identical calls. 3. On master, the refusals never end the turn. **Paperclip version or commit** `master` at 6400698a8e. ## What Changed - `repeated-tool-failure-guard.ts`: counts refusals per exact call and per run. At 6 refusals of one call, or 20 refusals in the run, it throws `ToolCallLoopError` (`code: "agent_tool_call_loop"`, tool, counts and argument names, never values). The message tells the model the turn stops and gives a short hint. - `paperclip-runner-tool-authority.ts`: `scheduleToolCallLoopContinuation` writes one idempotent native status-wake outbox row (key `agent_tool_call_loop:`) with `forceFreshSession: true` and the hint as the wake instruction. The outbox dispatcher admits it with `allowRunCoalescing: false`, so it never merges into a deferred comment wake or the active run. An assignee run uses `issue_continuation_needed`. A completion-review run uses `native_completion_review` with its review assignment, which the dispatcher revalidates, so the fresh reviewer session keeps the review. - `native-session-executor.ts`: the session authority epoch queues that continuation when the guard raises the loop error. The governed-wait lookup finds the wake on the next tool event and ends the provider turn as `yielded` with a `same_agent` continuation, the same way the connection-tools refresh ends a turn. If the wake cannot be queued, the refusal still reaches the model and the error is logged. - `status-decision-committer.ts`: a yielded continuation with that key binds to the queued wake instead of creating a second one. - `status-arbiter.ts` and `native-run-finalizer.ts`: a pending review run that ended through this continuation skips the `native_review_unresolved` resume recovery, because the queued review wake owns the next reviewer run. - `mcp-bridge.ts` and `opencode-proxy-finish-diagnostics.ts`: the opencode tool-delivery diagnostic records `argumentNames` (only names declared in the tool's input schema, sorted, at most 1,024 characters of JSON), `argumentNamesTruncated` and `undeclaredArgumentCount`. Values and undeclared names are never recorded. The forwarder's closed key allowlist accepts the new fields and validates them, so a record stays under its 2,048-character limit. ### Threshold choice - **6 refusals of one exact call.** The guard already runs a call twice and then refuses with an explicit correction. Six more refusals (eight identical attempts in total) give a model that reads errors many chances to change its arguments. In the recorded run the model never changed them in 427 refusals, so six refusals end that loop within seconds. - **20 refusals in the run.** A model can alternate between a few refused variants and keep each one under 6. Refusals happen only for exact repeats of a certain validation failure, so a healthy run almost never reaches 20. ### Previous-release story The guard counters live in memory for one run's tool authority, as before. A deploy or restart during a run starts the counters again at zero on the new process; that only delays the stop. The continuation is an ordinary wake row. If a server on the previous release finalizes a run that a new server parked, it does not know the key and queues its own `same_agent` continuation too; the issue execution lock lets one run and the other coalesces. ## Verification - Red then green, `repeated-tool-failure-guard.test.ts`: "after N refusals the guard raises a turn-stopping loop error" and "stops the turn once refusals across different calls reach the run limit". Both fail on master. - Red then green, `native-session-executor.test.ts`: "a turn whose model repeats a refused call N times ends with agent_tool_call_loop and schedules a continuation". With the epoch handling disabled it fails (13 calls instead of 8, nothing parked). Also "keeps the refused call's error when the loop continuation cannot be queued". - `paperclip-runner-tool-authority.test.ts`: "queues one fresh-session continuation outbox for the assignee / a completion reviewer stopped by a tool-call loop" (real Postgres; idempotent). - `native-tool-call-loop-continuation.test.ts`: with a comment wake already deferred behind the looping run, the continuation keeps its own keyed deferred wake, the comment wake is unchanged, and after release a run starts with `forceFreshSession` and the loop cause. - `status-arbiter.test.ts`: a pending reviewer stopped by a loop releases its checkout without a resume recovery. - `native-status-arbiter-corpus.test.ts`: the existing wake-binding test now also covers the `agent_tool_call_loop` key. - `mcp-bridge-delivery.test.ts` and `opencode-proxy-finish-diagnostics.test.ts`: argument names are recorded, values and undeclared names are not, invalid records are dropped, and a boundary test with 32 names of 64 characters stays forwardable with `argumentNamesTruncated: true`. - Server: the six touched test files pass (1755 tests). Runner: `src/drivers/opencode` and `src/cli` pass (569 tests). `tsc --noEmit` passes for `server` and `packages/paperclip-runner`. - `pnpm verify` exits 2 (runner package changes need broad coverage), so required CI supplies the broad run. ## Risks - A run that hits the limit ends its turn early. The limits are far above what a model that reads its errors needs, and the task continues automatically on a fresh session. - The fresh session loses the in-turn conversation. The task, its comments, documents and workspace stay, and the continuation names the cause and the hint. - The diagnostic now carries declared argument names. These are schema names, not values, and the forwarder validates the shape before it forwards a record. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use and code execution. ## 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 Refs #21360 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../opencode-proxy-finish-diagnostics.test.ts | 21 +++ .../cli/opencode-proxy-finish-diagnostics.ts | 6 +- .../opencode/mcp-bridge-delivery.test.ts | 57 ++++++++ .../src/drivers/opencode/mcp-bridge.ts | 31 ++++- .../native-status-arbiter-corpus.test.ts | 9 +- ...native-tool-call-loop-continuation.test.ts | 126 ++++++++++++++++++ .../native-runtime/native-run-finalizer.ts | 3 + .../native-session-executor.test.ts | 65 +++++++++ .../native-runtime/native-session-executor.ts | 60 ++++++++- .../paperclip-runner-tool-authority.test.ts | 28 ++++ .../paperclip-runner-tool-authority.ts | 21 +++ .../repeated-tool-failure-guard.test.ts | 34 +++++ .../repeated-tool-failure-guard.ts | 35 ++++- .../native-runtime/status-arbiter.test.ts | 6 + .../services/native-runtime/status-arbiter.ts | 3 +- .../status-decision-committer.ts | 3 +- 16 files changed, 493 insertions(+), 15 deletions(-) create mode 100644 server/src/__tests__/native-tool-call-loop-continuation.test.ts diff --git a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts index 2c0344cd19b..c1f2f98a8e2 100644 --- a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts +++ b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts @@ -115,6 +115,27 @@ it("forwards closed tool delivery records after binding and drops any record tha message: JSON.stringify({ ...delivery, socketRequestIndex: 2, socketIdleMs: 5270 }) } }]); }); +it("forwards delivery records with argument names and drops names that could carry values", () => { + const frames: { params: { message: string } }[] = []; + const forward = createOpenCodeFinishDiagnosticForwarder(frame => frames.push(frame as never)); + forward.bind("session"); + const delivery = { schema: "paperclip.opencode.tool-delivery-diagnostic/v1", callIdSha256: "e".repeat(64), + socketRequestIndex: 1, socketIdleMs: null, handlerMs: 4, outcome: "result", written: true, + argumentNames: ["operationId", "pathParams", "query", "responseText"], argumentNamesTruncated: false, undeclaredArgumentCount: 0 }; + for (const bad of [ + { ...delivery, argumentNames: ["body value"] }, + { ...delivery, argumentNames: "operationId" }, + { ...delivery, argumentNames: Array.from({ length: 20 }, (_, n) => `${n}${"a".repeat(60)}`) }, + { ...delivery, argumentNamesTruncated: "no" }, + { ...delivery, undeclaredArgumentCount: -1 }, + { ...delivery, undeclaredArgumentCount: "1" }, + ]) forward.diagnostic(JSON.stringify(bad)); + expect(frames).toEqual([]); + forward.diagnostic(JSON.stringify(delivery)); + forward.diagnostic(JSON.stringify({ ...delivery, argumentNames: null })); + expect(frames.map(frame => JSON.parse(frame.params.message).argumentNames)).toEqual([delivery.argumentNames, null]); +}); + it("forwards closed input-coercion records and drops any that could carry values", () => { const frames: { params: { message: string } }[] = []; const forward = createOpenCodeFinishDiagnosticForwarder(frame => frames.push(frame as never)); diff --git a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts index a718a856dd4..3e833bbafdb 100644 --- a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts +++ b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts @@ -52,11 +52,15 @@ export function createOpenCodeFinishDiagnosticForwarder(send: (frame: Warning) = } const TOOL_DELIVERY_KEYS = "callIdSha256,handlerMs,outcome,schema,socketIdleMs,socketRequestIndex,written"; +const TOOL_DELIVERY_KEYS_WITH_ARGUMENTS = "argumentNames,argumentNamesTruncated,callIdSha256,handlerMs,outcome,schema,socketIdleMs,socketRequestIndex,undeclaredArgumentCount,written"; +const validArgumentNames = (names: unknown) => names === null || (Array.isArray(names) && JSON.stringify(names).length <= 1_024 + && names.every(name => typeof name === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(name))); // Delivery records carry only hashes, counters and timings. Reject anything // else so this channel cannot forward tool inputs or results. function validToolDelivery(value: Record): boolean { const count = (entry: unknown) => typeof entry === "number" && Number.isSafeInteger(entry) && entry >= 0; - return Object.keys(value).sort().join(",") === TOOL_DELIVERY_KEYS + const keys = Object.keys(value).sort().join(","); + return (keys === TOOL_DELIVERY_KEYS || (keys === TOOL_DELIVERY_KEYS_WITH_ARGUMENTS && validArgumentNames(value.argumentNames) && typeof value.argumentNamesTruncated === "boolean" && count(value.undeclaredArgumentCount))) && typeof value.callIdSha256 === "string" && /^[a-f0-9]{64}$/.test(value.callIdSha256) && count(value.socketRequestIndex) && count(value.handlerMs) && (value.socketIdleMs === null || count(value.socketIdleMs)) diff --git a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts index d2543e2ce9e..3ca1f3a4ff3 100644 --- a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import { Agent, request } from "node:http"; import { afterEach, expect, it } from "vitest"; import { startOpenCodeMcpBridge, type OpenCodeMcpBridge } from "./mcp-bridge.js"; +import { createOpenCodeFinishDiagnosticForwarder } from "../../cli/opencode-proxy-finish-diagnostics.js"; const bridges: OpenCodeMcpBridge[] = []; const agents: Agent[] = []; @@ -88,6 +89,9 @@ it("answers each tool call, including a parallel pair on a pooled keep-alive cli socketRequestIndex: expect.any(Number), socketIdleMs: delivery.socketRequestIndex === 1 ? null : expect.any(Number), handlerMs: expect.any(Number), + argumentNames: [], + argumentNamesTruncated: false, + undeclaredArgumentCount: 0, outcome: "result", written: true, }); @@ -140,3 +144,56 @@ it("records a rejected call as an answered error", async () => { callIdSha256: createHash("sha256").update("11").digest("hex"), outcome: "error", written: true, }); }); + +it("records the declared argument names a call delivered, never their values or undeclared names", async () => { + const messages: string[] = []; + const bridge = await startOpenCodeMcpBridge({ + tools: [{ name: "call_api", inputSchema: { type: "object", properties: { + operationId: { type: "string" }, pathParams: { type: "object" }, query: { type: "object" }, body: {}, responseText: { type: "object" }, + } } }], + handler: async () => ({ ok: false, status: 400 }), + onDiagnostic: message => { if (message.includes("tool-delivery-diagnostic")) messages.push(message); }, + }); + bridges.push(bridge); + await (await fetch(bridge.url, { + method: "POST", + headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 12, method: "tools/call", params: { name: "call_api", arguments: { + operationId: "PATCH /api/issues/{id}", pathParams: { id: "secret-issue" }, query: {}, responseText: { limitBytes: 8192 }, PRIVATE_FIELD: 1, + } } }), + })).json(); + await expect.poll(() => messages.length).toBe(1); + expect(JSON.parse(messages[0]!)).toMatchObject({ argumentNames: ["operationId", "pathParams", "query", "responseText"], + argumentNamesTruncated: false, undeclaredArgumentCount: 1, outcome: "result" }); + expect(messages[0]).not.toMatch(/PATCH|secret-issue|8192|PRIVATE_FIELD/); +}); + +it("bounds many long argument names so the forwarder keeps the whole delivery record", async () => { + const names = Array.from({ length: 32 }, (_, n) => `${String(n).padStart(2, "0")}${"a".repeat(62)}`); + const messages: string[] = []; + const bridge = await startOpenCodeMcpBridge({ + tools: [{ name: "wide_tool", inputSchema: { type: "object", properties: Object.fromEntries(names.map(name => [name, {}])) } }], + handler: async () => ({ ok: true }), + onDiagnostic: message => { if (message.includes("tool-delivery-diagnostic")) messages.push(message); }, + }); + bridges.push(bridge); + await (await fetch(bridge.url, { + method: "POST", + headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 13, method: "tools/call", params: { name: "wide_tool", + arguments: Object.fromEntries(names.map(name => [name, 1])) } }), + })).json(); + await expect.poll(() => messages.length).toBe(1); + const record = JSON.parse(messages[0]!); + expect(record.argumentNamesTruncated).toBe(true); + expect(record.argumentNames.length).toBeGreaterThan(0); + expect(record.argumentNames.length).toBeLessThan(names.length); + expect(record.argumentNames).toEqual(names.slice(0, record.argumentNames.length)); + expect(JSON.stringify(record.argumentNames).length).toBeLessThanOrEqual(1_024); + expect(messages[0]!.length).toBeLessThanOrEqual(2_048); + const frames: unknown[] = []; + const forward = createOpenCodeFinishDiagnosticForwarder(frame => frames.push(frame)); + forward.bind("session"); + forward.diagnostic(messages[0]!); + expect(frames).toHaveLength(1); +}); diff --git a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts index 5e947b226bc..1f7efdca6d4 100644 --- a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts +++ b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts @@ -65,6 +65,8 @@ const MAX_RESULT_BYTES = 1_048_576; const TOOL_DELIVERY_DIAGNOSTIC_SCHEMA = "paperclip.opencode.tool-delivery-diagnostic/v1"; const MAX_TOOL_DELIVERY_DIAGNOSTICS = 256; const MAX_TOOL_INPUT_COERCION_DIAGNOSTICS = 64; +const MAX_TOOL_DELIVERY_ARGUMENT_NAMES_CHARS = 1_024; +const TOOL_DELIVERY_ARGUMENT_NAME = /^[A-Za-z0-9_.-]{1,64}$/; type SocketUse = { requests: number; lastResponseAt: number | null }; type ToolDelivery = { @@ -73,6 +75,7 @@ type ToolDelivery = { receivedAt: number; }; type ToolDeliveryOutcome = "result" | "error" | "unanswered"; +type ToolDeliveryInput = { argumentNames: string[] | null; argumentNamesTruncated: boolean; undeclaredArgumentCount: number }; export function canonicalOpenCodeMcpToolName(name: string): string { const trimmed = name.trim(); @@ -131,11 +134,14 @@ export async function startOpenCodeMcpBridge( delivery: ToolDelivery, outcome: ToolDeliveryOutcome, written: boolean, + input?: ToolDeliveryInput, ) => { if (!options.onDiagnostic || deliveryDiagnostics++ >= MAX_TOOL_DELIVERY_DIAGNOSTICS) return; const diagnostic = { schema: TOOL_DELIVERY_DIAGNOSTIC_SCHEMA, callIdSha256: createHash("sha256").update(callId).digest("hex"), + ...(input ? { argumentNames: input.argumentNames, argumentNamesTruncated: input.argumentNamesTruncated, + undeclaredArgumentCount: input.undeclaredArgumentCount } : {}), socketRequestIndex: delivery.socketRequestIndex, socketIdleMs: delivery.socketIdleMs, handlerMs: Date.now() - delivery.receivedAt, @@ -200,6 +206,18 @@ export async function startOpenCodeMcpBridge( }; } +function boundedArgumentNames(names: string[] | null): Pick { + if (!names) return { argumentNames: null, argumentNamesTruncated: false }; + const kept: string[] = []; + let size = 2; + for (const name of [...names].sort()) { + size += JSON.stringify(name).length + (kept.length ? 1 : 0); + if (size > MAX_TOOL_DELIVERY_ARGUMENT_NAMES_CHARS) return { argumentNames: kept, argumentNamesTruncated: true }; + kept.push(name); + } + return { argumentNames: kept, argumentNamesTruncated: false }; +} + function inputShape(input: unknown): "omitted" | "null" | "array" | "object" | "string" | "number" | "boolean" | "other" { if (input === undefined) return "omitted"; if (input === null) return "null"; @@ -250,7 +268,7 @@ async function handleRequest( response: ServerResponse, context: { delivery: ToolDelivery; - diagnoseToolDelivery: (callId: string, delivery: ToolDelivery, outcome: ToolDeliveryOutcome, written: boolean) => void; + diagnoseToolDelivery: (callId: string, delivery: ToolDelivery, outcome: ToolDeliveryOutcome, written: boolean, input?: ToolDeliveryInput) => void; secret: string; tools: OpenCodeMcpToolDefinition[]; admittedTools: OpenCodeMcpToolDefinition[]; @@ -345,8 +363,9 @@ async function handleRequest( // client that never consumes a written answer can be told apart from a // bridge that never answered it. let outcome: ToolDeliveryOutcome = "unanswered"; + let deliveredInput: ToolDeliveryInput | undefined; response.once("close", () => { - context.diagnoseToolDelivery(callId, context.delivery, outcome, response.writableFinished); + context.diagnoseToolDelivery(callId, context.delivery, outcome, response.writableFinished, deliveredInput); }); const rawName = typeof params.name === "string" ? params.name : ""; // A declared operation may itself start with paperclip_. Preserve that @@ -361,6 +380,14 @@ async function handleRequest( return; } const received = params.arguments ?? {}; + const declaredSchema = context.admittedTools.find(entry => entry.name === tool)?.inputSchema.properties; + const declaredArguments = isRecord(declaredSchema) ? declaredSchema : {}; + const receivedNames = isRecord(received) ? Object.keys(received) : null; + const declaredNames = receivedNames?.filter(name => Object.hasOwn(declaredArguments, name) && TOOL_DELIVERY_ARGUMENT_NAME.test(name)) ?? null; + deliveredInput = { + ...boundedArgumentNames(declaredNames), + undeclaredArgumentCount: (receivedNames?.length ?? 0) - (declaredNames?.length ?? 0), + }; const validator = context.validators.get(tool); const admitted = admitToolInput(validator, received); const { args, schemaValid } = admitted; diff --git a/server/src/__tests__/native-status-arbiter-corpus.test.ts b/server/src/__tests__/native-status-arbiter-corpus.test.ts index a3309bed6a5..f0701e88be0 100644 --- a/server/src/__tests__/native-status-arbiter-corpus.test.ts +++ b/server/src/__tests__/native-status-arbiter-corpus.test.ts @@ -3874,11 +3874,14 @@ describe("P6-31 Section 18.13 executable status-authority corpus", () => { ]); }); - it("binds a tools-refresh continuation to its existing durable wake without a duplicate", async () => { + it.each([ + ["tools-refresh", (runId: string) => `connection-intent:tools:${runId}:fixture-digest`], + ["tool-call-loop", (runId: string) => `agent_tool_call_loop:${runId}`], + ] as const)("binds a %s continuation to its existing durable wake without a duplicate", async (name, keyFor) => { const template = corpus.fixtures.find((candidate) => candidate.mode === "native")!; - const fixture = { ...template, id: "in-feed-tools-refresh", given: { ...template.given, priorIssueStatus: "in_progress" } }; + const fixture = { ...template, id: `in-feed-${name}`, given: { ...template.given, priorIssueStatus: "in_progress" } }; const seeded = await seedFixture(fixture); - const key = `connection-intent:tools:${seeded.runId}:fixture-digest`; + const key = keyFor(seeded.runId); const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "assignment", status: "queued", idempotencyKey: key, payload: { issueId: seeded.issueId, mutation: "connection_tools_refreshed" } }).returning(); const decision: NativeStatusDecision = { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, statusAction: "in_progress", toStatus: "in_progress", diff --git a/server/src/__tests__/native-tool-call-loop-continuation.test.ts b/server/src/__tests__/native-tool-call-loop-continuation.test.ts new file mode 100644 index 00000000000..34d7a706343 --- /dev/null +++ b/server/src/__tests__/native-tool-call-loop-continuation.test.ts @@ -0,0 +1,126 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, + agentWakeupRequests, + authUsers, + companies, + companyMemberships, + createDb, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + heartbeatRuns, + issues, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { type AdapterExecutionContext, type AdapterExecutionResult } from "../adapters/index.ts"; +import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; +import { ToolCallLoopError, toolCallLoopContinuationKey } from "../services/native-runtime/repeated-tool-failure-guard.js"; + +const mockAdapterExecute = vi.hoisted(() => + vi.fn(async (_context: AdapterExecutionContext): Promise => ({ + exitCode: 0, signal: null, timedOut: false, errorMessage: null, + summary: "Tool-call loop continuation test run.", provider: "test", model: "test-model", + })), +); + +vi.mock("../adapters/index.ts", async () => { + const actual = await vi.importActual("../adapters/index.ts"); + return { ...actual, getServerAdapter: vi.fn(() => ({ supportsLocalAgentJwt: false, execute: mockAdapterExecute })) }; +}); + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +if (!embeddedPostgresSupport.supported) { + console.warn( + `Skipping tool-call loop continuation tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, + ); +} + +describeEmbeddedPostgres("the continuation of a turn stopped by a tool-call loop", () => { + let db!: ReturnType; + let heartbeat!: ReturnType; + let tempDb: Awaited> | null = null; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-call-loop-continuation-"); + db = createDb(tempDb.connectionString); + heartbeat = heartbeatService(db, { runtimeEnv: { ...process.env, PAPERCLIP_IN_WORKTREE: "false" } }); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + + afterAll(async () => { + await drainHeartbeatRunsToQuiescence(db, heartbeat); + await db?.$client.end(); + await tempDb?.cleanup(); + }); + + it("keeps its own keyed wake when a comment wake is already deferred behind the looping run", async () => { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + await db.insert(companies).values({ + id: companyId, name: "Loop Co", issuePrefix: `L${companyId.replace(/-/g, "").slice(0, 5).toUpperCase()}`, + defaultResponsibleUserId: "responsible-user", requireBoardApprovalForNewAgents: false, + }); + await db.insert(authUsers).values({ + id: "responsible-user", name: "Fixture user", email: "responsible-user@example.test", + createdAt: new Date(), updatedAt: new Date(), + }).onConflictDoNothing(); + await db.insert(companyMemberships).values({ + companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member", + }); + await db.insert(agents).values({ + id: agentId, companyId, name: "Looper", role: "engineer", status: "idle", adapterType: "codex_local", + adapterConfig: {}, runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } }, permissions: {}, + }); + await db.insert(issues).values({ + id: issueId, companyId, title: "Describe the subtasks", status: "todo", priority: "medium", + assigneeAgentId: agentId, responsibleUserId: "responsible-user", + }); + + let finishLoopingRun!: () => void; + const loopingRunFinished = new Promise((resolve) => { finishLoopingRun = resolve; }); + mockAdapterExecute.mockImplementationOnce(async () => { + await loopingRunFinished; + return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, + summary: "Stopped after a tool-call loop.", provider: "test", model: "test-model" }; + }); + + const loopingRun = await heartbeat.wakeup(agentId, { + source: "assignment", triggerDetail: "system", reason: "issue_assigned", + requestedByActorType: "system", payload: { issueId }, contextSnapshot: { issueId, wakeReason: "issue_assigned" }, + }); + expect(loopingRun).not.toBeNull(); + await vi.waitFor(() => expect(mockAdapterExecute).toHaveBeenCalledTimes(1), { timeout: 30_000 }); + + const [commentWake] = await db.insert(agentWakeupRequests).values({ + companyId, agentId, source: "automation", triggerDetail: "system", reason: "issue_commented", + status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "responsible-user", + payload: { issueId, _paperclipWakeContext: { issueId, wakeReason: "issue_commented" } }, + }).returning(); + + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId: loopingRun!.id, workMode: "standard" }); + await authority.scheduleToolCallLoopContinuation(new ToolCallLoopError("call_api", 6, 6, ["operationId", "pathParams"], 400, "refused")); + await heartbeat.dispatchPendingNativeStatusWakeups({ companyId }); + await heartbeat.dispatchPendingNativeStatusWakeups({ companyId }); + + const key = toolCallLoopContinuationKey(loopingRun!.id); + const keyed = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.idempotencyKey, key), + )); + expect(keyed.some((wake) => wake.status === "deferred_issue_execution" && wake.id !== commentWake!.id)).toBe(true); + expect(keyed.every((wake) => !["skipped", "failed", "cancelled"].includes(wake.status))).toBe(true); + const [comment] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, commentWake!.id)); + expect(comment).toMatchObject({ status: "deferred_issue_execution", coalescedCount: 0, idempotencyKey: null }); + + finishLoopingRun(); + await vi.waitFor(async () => { + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)); + expect(runs.some((run) => run.id !== loopingRun!.id && run.contextSnapshot?.livenessContinuationReason === "agent_tool_call_loop" + && run.contextSnapshot?.forceFreshSession === true)).toBe(true); + }, { timeout: 30_000 }); + }, 90_000); +}); diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 70882ed0a8a..d9c07e2ab65 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -36,6 +36,7 @@ import { explainFailedRun, explainNativeTurnFailure, NATIVE_RUN_FAILED_UNEXPLAIN import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js"; import { findSupersededExternalReviewRequests } from "./superseded-external-review-requests.js"; import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js"; +import { toolCallLoopContinuationKey } from "./repeated-tool-failure-guard.js"; import { conversationNativeDecision, isConversation, settleConversationTurnForRun } from "../agent-conversations.js"; import { issueTreeControlService } from "../issue-tree-control.js"; import { COMPLETION_REVIEW_STAGE_REASON, completionReviewStageEntry } from "../issue-execution-policy.js"; @@ -1765,6 +1766,8 @@ export async function finalizeNativeRun(input: { // into a blocker; the committer rechecks that under the issue lock. failedTurnContinuationUsed: terminalState === "failed" && ownsProviderFailureDecision && !reviewContext && await isFailedTurnContinuationRun(input.db, run, authoritativeIssue.id), + toolCallLoopContinuation: assessment.reportedDisposition === "yielded" + && assessment.continuation?.idempotencyKey === toolCallLoopContinuationKey(run.id), ...(reviewContext ? { nativeReviewOutcome: nativeReview ? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const : "stale" as const } : {}), diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index c28c1295484..8e463045596 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -21,6 +21,7 @@ import { trace } from "@opentelemetry/api"; import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace"; import { configuredEnvironment, configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js"; import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; +import { TOOL_CALL_LOOP_REFUSAL_LIMIT, ToolCallLoopError, toolCallLoopContinuationKey } from "./repeated-tool-failure-guard.js"; import { enableReattachPhase, isReattachPhaseActive, joinReattachPhase, onReattachPhaseEnd, resetReattachPhaseForTests, type ReattachPhaseSummary } from "../heartbeat/run-admission.js"; import { createSystemRecovery, failSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "../system-recovery-state.js"; import { registerRunStartHandover } from "../run-start-handover.js"; @@ -81,7 +82,9 @@ import { type NativeExecutionInputV3, type NativeExecutionInput, type PrpEvent, + type PrpStructuredRunResult, } from "@paperclipai/paperclip-runner"; +import { HttpError } from "../../errors.js"; import { existsSync } from "node:fs"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; import { createServer as createNetServer } from "node:net"; @@ -468,6 +471,8 @@ import { nativeGovernedWaitResult, nativeConversationReplyResult, nativeToolsRefreshWaitResult, + nativeToolCallLoopWaitResult, + SessionAuthorityEpoch, parseRemoteExecutableCandidate, buildRemoteCodexLauncherCommand, mayUsePreinstalledRunnerArtifact, @@ -7912,6 +7917,66 @@ describe("native conversation replies", () => { }); describe("native governed waits", () => { + it("a turn whose model repeats a refused call N times ends with agent_tool_call_loop and schedules a continuation", async () => { + const wakes: Array<{ id: string; key: string; loop: ToolCallLoopError }> = []; + const authority = { + execute: vi.fn(async () => { throw new HttpError(400, "body is required"); }), + scheduleToolCallLoopContinuation: vi.fn(async (loop: ToolCallLoopError) => { + if (!wakes.length) wakes.push({ id: "wake-loop", key: toolCallLoopContinuationKey("run-1"), loop }); + return true; + }), + close: () => {}, + }; + const epoch = new SessionAuthorityEpoch("run-1", authority as never); + const contract = { revision: "4", objective: "Describe the subtasks", criteria: [{ id: "describe", requirement: "Describe them" }] }; + const observation = createGovernedWaitEventObservation(async () => wakes[0] + ? nativeToolCallLoopWaitResult({ wakeId: wakes[0].id, key: wakes[0].key, completionContract: contract }) : null); + const args = { operationId: "PATCH /api/issues/{id}", pathParams: { id: "issue-a" }, query: {}, responseText: { limitBytes: 8192 } }; + const toolEvent = (n: number): PrpEvent => ({ + schema: "paperclip.prp.event.v1", sourceInstanceId: "runner-1", sourceEventId: `runner-1:item:${n}`, sourceSeq: n, + sourceKind: "runner", runId: "run-1", normalizedSessionId: "session-1", turnId: "turn-1", itemId: `call-${n}`, + eventType: "item.completed", schemaVersion: 1, priority: 0, emittedAt: "2026-11-15T05:00:00.000Z", + payload: { kind: "dynamicToolCall", item: { type: "tool_result", is_error: true } }, + }); + + let parked: PrpStructuredRunResult | null = null; + let calls = 0; + let lastError: unknown; + while (!parked && calls < 2 + TOOL_CALL_LOOP_REFUSAL_LIMIT + 5) { + calls += 1; + lastError = await epoch.execute({ tool: "call_api", callId: `call-${calls}`, arguments: args }).then(() => null, (error: unknown) => error); + await observation.observe(toolEvent(calls), true); + parked = observation.consume(toolEvent(calls)); + } + + expect(calls).toBe(2 + TOOL_CALL_LOOP_REFUSAL_LIMIT); + expect(authority.execute).toHaveBeenCalledTimes(2); + expect(lastError).toBeInstanceOf(ToolCallLoopError); + expect(lastError).toMatchObject({ code: "agent_tool_call_loop", refusals: TOOL_CALL_LOOP_REFUSAL_LIMIT }); + expect(authority.scheduleToolCallLoopContinuation).toHaveBeenCalledTimes(1); + expect(parked).toMatchObject({ + reportedWorkDisposition: "yielded", + completionClaim: { objectiveSatisfied: false }, + evidence: [{ ref: "wakeup:wake-loop" }], + continuation: { kind: "same_agent", idempotencyKey: "agent_tool_call_loop:run-1", summary: "Continue the task in a fresh session." }, + }); + }); + + it("keeps the refused call's error when the loop continuation cannot be queued", async () => { + const authority = { + execute: vi.fn(async () => { throw new HttpError(400, "body is required"); }), + scheduleToolCallLoopContinuation: vi.fn(async () => { throw new Error("queue unavailable"); }), + close: () => {}, + }; + const epoch = new SessionAuthorityEpoch("run-1", authority as never); + let error: unknown; + for (let n = 0; n < 2 + TOOL_CALL_LOOP_REFUSAL_LIMIT; n++) { + error = await epoch.execute({ tool: "call_api", callId: `c-${n}`, arguments: {} }).then(() => null, (failure: unknown) => failure); + } + expect(error).toBeInstanceOf(ToolCallLoopError); + expect(authority.scheduleToolCallLoopContinuation).toHaveBeenCalledTimes(1); + }); + it("yields to an existing tools-refresh wake without claiming completion or a human interaction", () => { const result = nativeToolsRefreshWaitResult({ wakeId: "wake-1", diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index adb11edef8b..cffe9cd56c0 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -271,7 +271,7 @@ import { redactRunnerApiPayloads } from "./runner-api-log-redaction.js"; import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; import { createNativeCredentialUpdateOwner, appendNativeCredentialUpdate } from "./native-credential-updates.js"; import { canonicalNativeJson, nativeSha256 } from "./canonical.js"; -import { RepeatedToolFailureGuard } from "./repeated-tool-failure-guard.js"; +import { RepeatedToolFailureGuard, ToolCallLoopError, toolCallLoopContinuationKey } from "./repeated-tool-failure-guard.js"; import { lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; import { dispatchToolCallback, recoverToolCallback, type SemanticInputAdmission } from "../../vendor/paperclip-runner/index.js"; @@ -1933,6 +1933,29 @@ export function nativeToolsRefreshWaitResult(input: { }; } +export function nativeToolCallLoopWaitResult(input: { + wakeId: string; + key: string; + completionContract: NativeExecutionInput["completionContract"]["contract"]; +}): PrpStructuredRunResult { + const ref = `wakeup:${input.wakeId}`; + return { + ...nativeToolsRefreshWaitResult(input), + summary: "Paperclip stopped a tool call that kept failing the same way. The task continues in a fresh session.", + completionClaim: { + contractRevision: input.completionContract.revision, + objectiveSatisfied: false, + criteria: input.completionContract.criteria.map((criterion) => ({ + criterionId: criterion.id, + status: "unknown", + evidenceRefs: [ref], + })), + remainingWork: [{ description: "Continue the task in a fresh session.", blocksCompletion: true }], + }, + continuation: { kind: "same_agent", summary: "Continue the task in a fresh session.", idempotencyKey: input.key }, + }; +} + /** * Partial item-verdict responses deliberately leave their original durable * interaction pending. They are already authority-checked before entering the @@ -2293,7 +2316,14 @@ export class SessionAuthorityEpoch { async execute(call: Parameters[0]) { this.#assertCurrent(); - const execute = () => this.#repeatedFailures.run(call, () => this.#authority.execute(call)); + const execute = () => this.#repeatedFailures.run(call, () => this.#authority.execute(call)).catch(async (error: unknown) => { + if (error instanceof ToolCallLoopError) { + await this.#authority.scheduleToolCallLoopContinuation?.(error).catch((scheduleError: unknown) => { + logger.warn({ err: scheduleError, runId: this.runId, tool: error.tool }, "tool-call loop continuation was not queued"); + }); + } + throw error; + }); return dispatchToolCallback(this.runId, call.callId, async () => this.toolTrace ? await this.toolTrace.execute(call, execute) : await execute()); @@ -12254,10 +12284,28 @@ async function executePaperclipNativeSessionAttempt( ), ) .limit(1); - return refresh?.key - ? nativeToolsRefreshWaitResult({ - wakeId: refresh.id, - key: refresh.key, + if (refresh?.key) + return nativeToolsRefreshWaitResult({ + wakeId: refresh.id, + key: refresh.key, + completionContract: input.execution.completionContract.contract, + }); + const loopKey = toolCallLoopContinuationKey(input.execution.binding.runId); + const [loop] = await input.db + .select({ id: agentWakeupRequests.id }) + .from(agentWakeupRequests) + .where( + and( + eq(agentWakeupRequests.companyId, input.execution.binding.companyId), + eq(agentWakeupRequests.idempotencyKey, loopKey), + notInArray(agentWakeupRequests.status, ["skipped", "failed", "cancelled"]), + ), + ) + .limit(1); + return loop + ? nativeToolCallLoopWaitResult({ + wakeId: loop.id, + key: loopKey, completionContract: input.execution.completionContract.contract, }) : null; diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index d8fc0b129f7..c1f69eb2620 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -8,6 +8,7 @@ import { LOW_TRUST_REVIEW_PRESET, upsertIssueDocumentSchema } from "@paperclipai import { and, eq, inArray } from "drizzle-orm"; import { activityLog, + agentWakeupRequests, agents, authUsers, approvals, @@ -30,6 +31,7 @@ import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity import { documentService } from "../documents.js"; import { issueService } from "../issues.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; +import { TOOL_CALL_LOOP_HINT, ToolCallLoopError } from "./repeated-tool-failure-guard.js"; import { PaperclipRunnerSemanticAuthority } from "./runner-semantic-authority.js"; import { createAssignedMcpTools } from "./assigned-mcp-tools.js"; import type { ToolGatewayService } from "../tool-gateway.js"; @@ -1610,6 +1612,32 @@ describe("PaperclipRunnerToolAuthority", () => { .rejects.toThrow(/conversation cannot be a parent/i); }); + it.each([ + ["the assignee", null], + ["a completion reviewer", { nativeReviewInteractionId: "7f0b4f3e-2c1d-4a5b-8c6d-0e1f2a3b4c5d", nativeReviewDecisionId: "8a1c5e4f-3d2e-4b6c-9d7e-1f2a3b4c5d6e" }], + ] as const)("queues one fresh-session continuation outbox for %s stopped by a tool-call loop", async (_who, nativeReview) => { + const authority = new PaperclipRunnerToolAuthority(db, { + companyId, agentId, issueId, runId, workMode: "standard", ...(nativeReview ? { nativeReview } : {}), + }); + const key = `agent_tool_call_loop:${runId}`; + const loop = new ToolCallLoopError("call_api", 6, 6, ["operationId", "pathParams"], 400, "refused"); + await expect(authority.scheduleToolCallLoopContinuation(loop)).resolves.toBe(true); + await expect(authority.scheduleToolCallLoopContinuation(loop)).resolves.toBe(true); + const rows = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + agentId, status: "queued", runId: null, requestedByActorType: "system", requestedByActorId: "native-status-committer", + reason: nativeReview ? "native_completion_review" : "issue_continuation_needed", + payload: { + issueId, sourceRunId: runId, continuationCause: "agent_tool_call_loop", tool: "call_api", argumentNames: ["operationId", "pathParams"], + ...(nativeReview ?? {}), + _paperclipWakeContext: { issueId, forceFreshSession: true, livenessContinuationSourceRunId: runId, + livenessContinuationReason: "agent_tool_call_loop", livenessContinuationInstruction: TOOL_CALL_LOOP_HINT, ...(nativeReview ?? {}) }, + }, + }); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + }); + it("creates ordinary children, preserves blockers, and deduplicates across runs", async () => { const wakes: Array<{ agentId: string; options: Record }> = []; diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 8b61d8fcb8a..77406c5b089 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -79,6 +79,8 @@ import { assertRunnerApiDispatchable, executeRunnerApi, validateRunnerApiCall, R import { finishPendingRunnerApiCaptureDeletes, markRunnerApiCaptureEvictions, RUNNER_API_CAPTURE_EVICTION_PASSES, runnerApiCaptureCleanupStalled, runnerApiCaptureUsageBytes } from "./runner-api-capture-retention.js"; import { acquireRunnerApiResponseSlot, RUNNER_API_RESPONSE_DEADLINE_MS, RunnerApiCaptureReservationReclaimedError, runnerApiCompanyCaptureMaxBytes, RUNNER_API_RESPONSE_MAX_BYTES, RUNNER_API_RESPONSE_RUN_MAX_BYTES, RunnerApiResponseLimitError } from "./runner-api-response-limits.js"; import { and, desc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm"; +import { AGENT_TOOL_CALL_LOOP, TOOL_CALL_LOOP_HINT, toolCallLoopContinuationKey, type ToolCallLoopError } from "./repeated-tool-failure-guard.js"; +import { enqueueWake } from "./status-decision-committer.js"; import type { Db } from "@paperclipai/db"; import { authUsers, @@ -350,6 +352,25 @@ export class PaperclipRunnerToolAuthority { #taskAttachmentCache = new TaskAttachmentReadCache(); #skillLibraryCache = new SkillLibraryReadCache(); close() { this.#taskAttachmentCache.close(); this.#skillLibraryCache.close(); this.binding.assignedMcpTools?.close?.(); } + + async scheduleToolCallLoopContinuation(loop: ToolCallLoopError): Promise { + const review = this.binding.nativeReview; + const loopContext = { sourceRunId: this.binding.runId, continuationCause: AGENT_TOOL_CALL_LOOP, + tool: loop.tool, refusals: loop.refusals, runRefusals: loop.runRefusals, argumentNames: loop.argumentNames }; + await this.db.transaction(tx => enqueueWake({ + tx: tx as unknown as Db, + originRunId: this.binding.runId, + companyId: this.binding.companyId, + issueId: this.binding.issueId, + agentId: this.binding.agentId, + reason: review ? "native_completion_review" : "issue_continuation_needed", + idempotencyKey: toolCallLoopContinuationKey(this.binding.runId), + payload: { ...(review ?? {}), ...loopContext }, + contextSnapshot: { ...(review ?? {}), forceFreshSession: true, livenessContinuationSourceRunId: this.binding.runId, + livenessContinuationReason: AGENT_TOOL_CALL_LOOP, livenessContinuationInstruction: TOOL_CALL_LOOP_HINT }, + })); + return true; + } constructor(readonly db: Db, readonly binding: Binding) {} definitions(): Array> { diff --git a/server/src/services/native-runtime/repeated-tool-failure-guard.test.ts b/server/src/services/native-runtime/repeated-tool-failure-guard.test.ts index b51d5bb17e1..a522c014918 100644 --- a/server/src/services/native-runtime/repeated-tool-failure-guard.test.ts +++ b/server/src/services/native-runtime/repeated-tool-failure-guard.test.ts @@ -3,6 +3,7 @@ import { HttpError, badRequest } from "../../errors.js"; import { SessionAuthorityEpoch } from "./native-session-executor.js"; import type { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; import { executeRunnerApi } from "./runner-api-client.js"; +import { TOOL_CALL_LOOP_REFUSAL_LIMIT, TOOL_CALL_LOOP_RUN_REFUSAL_LIMIT, ToolCallLoopError } from "./repeated-tool-failure-guard.js"; const context = { companyId: "company-a", issueId: "issue-a", issueIdentifier: "API-1", runId: "run-a", workMode: "standard" }; @@ -53,6 +54,39 @@ describe("repeated identical failing tool calls", () => { expect(fetcher).not.toHaveBeenCalled(); }); + it("after N refusals the guard raises a turn-stopping loop error", async () => { + const { authority, epoch } = epochWith(async () => { throw badRequest("body is required"); }); + const call = (n: number) => ({ tool: "call_api", callId: `loop-${n}`, arguments: dropped }); + await failure(epoch, call(1)); + await failure(epoch, call(2)); + for (let n = 1; n < TOOL_CALL_LOOP_REFUSAL_LIMIT; n++) { + const refused = await failure(epoch, call(2 + n)); + expect(refused).not.toBeInstanceOf(ToolCallLoopError); + expect(refused?.message).toMatch(/^This call was not run/); + } + const stopped = await failure(epoch, call(2 + TOOL_CALL_LOOP_REFUSAL_LIMIT)); + expect(stopped).toBeInstanceOf(ToolCallLoopError); + expect(stopped).toMatchObject({ code: "agent_tool_call_loop", tool: "call_api", refusals: TOOL_CALL_LOOP_REFUSAL_LIMIT, + argumentNames: ["operationId", "pathParams", "query", "responseText"] }); + expect(authority.execute).toHaveBeenCalledTimes(2); + }); + + it("stops the turn once refusals across different calls reach the run limit", async () => { + const { epoch } = epochWith(async () => { throw badRequest("body is required"); }); + let stopped: Error | null = null; + let refusals = 0; + for (let variant = 0; !stopped && variant < TOOL_CALL_LOOP_RUN_REFUSAL_LIMIT; variant++) { + const args = { ...dropped, pathParams: { id: `issue-${variant}` } }; + for (let n = 0; n < 2 + TOOL_CALL_LOOP_REFUSAL_LIMIT - 1 && !stopped; n++) { + const error = await failure(epoch, { tool: "call_api", callId: `v${variant}-${n}`, arguments: args }); + if (error instanceof ToolCallLoopError) stopped = error; + else if (error?.message.startsWith("This call was not run")) refusals++; + } + } + expect(stopped).toBeInstanceOf(ToolCallLoopError); + expect(refusals + 1).toBe(TOOL_CALL_LOOP_RUN_REFUSAL_LIMIT); + }); + it("runs the call again once its arguments change", async () => { const { authority, epoch } = epochWith(async call => { if (!(call.arguments as { body?: unknown }).body) throw badRequest("body is required"); diff --git a/server/src/services/native-runtime/repeated-tool-failure-guard.ts b/server/src/services/native-runtime/repeated-tool-failure-guard.ts index 25c4c08dac3..f1739fcab9c 100644 --- a/server/src/services/native-runtime/repeated-tool-failure-guard.ts +++ b/server/src/services/native-runtime/repeated-tool-failure-guard.ts @@ -3,6 +3,16 @@ import { nativeSha256 } from "./canonical.js"; /** Identical failures after which the exact call is no longer run. */ export const REPEATED_TOOL_FAILURE_LIMIT = 2; +export const TOOL_CALL_LOOP_REFUSAL_LIMIT = 6; +export const TOOL_CALL_LOOP_RUN_REFUSAL_LIMIT = 20; +export const AGENT_TOOL_CALL_LOOP = "agent_tool_call_loop"; +export function toolCallLoopContinuationKey(runId: string): string { + return `${AGENT_TOOL_CALL_LOOP}:${runId}`; +} + +export const TOOL_CALL_LOOP_HINT = "The previous turn kept sending one tool call that Paperclip had already refused. " + + "Do not send it again unchanged. Prefer a dedicated Paperclip tool, such as set_task_title, report_progress or write_document, over call_api. " + + "If call_api is the only way, send every required argument, including body, as a top-level argument."; const MAX_TRACKED_FAILURES = 64; const MAX_RESPONSE_EXCERPT = 2_000; @@ -14,8 +24,18 @@ type Failure = { details?: unknown; /** Returned by the route as an `ok: false` response rather than refused before sending. */ returned: boolean; + refusals?: number; }; +export class ToolCallLoopError extends HttpError { + readonly code = AGENT_TOOL_CALL_LOOP; + constructor(readonly tool: string, readonly refusals: number, readonly runRefusals: number, + readonly argumentNames: string[], status: number, message: string, details?: unknown) { + super(status, message, details); + this.name = "ToolCallLoopError"; + } +} + /** * Stops a model from resending the same rejected tool call. Some model hosts * drop optional arguments, so the model can believe it fixed a call that @@ -36,6 +56,7 @@ export class RepeatedToolFailureGuard { // Identical calls a model sends in parallel run one after another, so each // sees the failures before it. Different calls never wait on each other. readonly #inFlight = new Map>(); + #runRefusals = 0; run(call: ToolCall, execute: () => Promise): Promise { const key = callKey(call); @@ -50,6 +71,14 @@ export class RepeatedToolFailureGuard { async #run(key: string, call: ToolCall, execute: () => Promise): Promise { const prior = this.#failures.get(key); if (prior && prior.count >= REPEATED_TOOL_FAILURE_LIMIT) { + prior.refusals = (prior.refusals ?? 0) + 1; + this.#runRefusals += 1; + if (prior.refusals >= TOOL_CALL_LOOP_REFUSAL_LIMIT || this.#runRefusals >= TOOL_CALL_LOOP_RUN_REFUSAL_LIMIT) { + throw new ToolCallLoopError(call.tool, prior.refusals, this.#runRefusals, argumentNames(call.arguments), prior.status, + `This call was not run, and Paperclip stopped this turn: ${call.tool} was refused ${prior.refusals} times in this run with these exact arguments. ` + + `${receivedArguments(call.arguments)} The task continues in a fresh session. ${TOOL_CALL_LOOP_HINT}`, + prior.details); + } throw new HttpError(prior.status, `This call was not run: ${call.tool} already failed ${prior.count} times in this run with these exact arguments. ` + `${receivedArguments(call.arguments)} ${prior.returned ? `The response each time was HTTP ${prior.status}: ` : "The error each time was: "}${prior.message} ` + "Repeating it unchanged cannot succeed. Send it again only with the change that error asks for, or stop calling it and tell the user what blocked you.", prior.details); @@ -131,7 +160,11 @@ function repeatedNote(count: number, call: ToolCall): string { + "Paperclip will not run this exact call again in this run. Change the arguments, or stop and tell the user what blocked you."; } +function argumentNames(value: unknown): string[] { + return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).sort() : []; +} + function receivedArguments(value: unknown): string { - const names = value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).sort() : []; + const names = argumentNames(value); return `Arguments received each time: ${names.length ? names.join(", ") : "none"}.`; } diff --git a/server/src/services/native-runtime/status-arbiter.test.ts b/server/src/services/native-runtime/status-arbiter.test.ts index 0e57f8f1b7b..579ddd39eaf 100644 --- a/server/src/services/native-runtime/status-arbiter.test.ts +++ b/server/src/services/native-runtime/status-arbiter.test.ts @@ -151,6 +151,12 @@ describe("native status authority", () => { expect(decision.effects.some((effect) => ["enqueue_continuation", "schedule_retry"].includes(effect.kind))).toBe(false); }); + it("lets a reviewer stopped by a tool-call loop continue through its queued review wake instead of a resume recovery", () => { + const decision = arbitrate({ priorIssueStatus: "in_review", nativeReviewOutcome: "pending", toolCallLoopContinuation: true }); + expect(decision).toMatchObject({ statusAction: "preserve", toStatus: "in_review", reasonCode: "native_review_unresolved" }); + expect(decision.effects).toEqual([{ kind: "release_checkout" }]); + }); + it("treats only the authorized Board response_wake as passive and preserves governance", () => { const passive = assessment({ reportedDisposition: "yielded", diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 7fd22e7506a..26e3643e5e2 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -240,6 +240,7 @@ export function arbitrateNativeStatus(input: { reviewOwnerUserId?: string | null; /** Review decisions own task state; a reviewer's finish report cannot override them. */ nativeReviewOutcome?: "resolved" | "pending" | "stale"; + toolCallLoopContinuation?: boolean; /** * This run, as the configured participant, recorded the approval that * completed the task's final execution-policy stage. That durable decision is @@ -375,7 +376,7 @@ export function arbitrateNativeStatus(input: { unblockDescriptor: null, effects: [ { kind: "release_checkout" }, - ...(input.nativeReviewOutcome === "pending" ? [{ + ...(input.nativeReviewOutcome === "pending" && !input.toolCallLoopContinuation ? [{ kind: "record_recovery" as const, cause: "native_review_unresolved", nextAction: "The named reviewer must resolve the pending completion review or explain the concrete blocker. Do not restart the worker's assignment or create another review request.", agentId: input.agentId, diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 37877b261d7..80da7787b0e 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -1,4 +1,5 @@ import { notifyNativeStatusWakeWork } from "../deferred-execution-notifications.js"; +import { toolCallLoopContinuationKey } from "./repeated-tool-failure-guard.js"; import { assertAgentInteraction } from "../agent-interaction-policy.js"; import { forbidden, HttpError } from "../../errors.js"; import { agentInteractionDeliveryDenial, agentWakeInteractionTexts, INTERACTION_DELIVERY_DENIED, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js"; @@ -795,7 +796,7 @@ async function materializeDecisionEffect(input: { if ( effect.idempotencyKey.startsWith( `connection-intent:tools:${input.runId}:`, - ) + ) || effect.idempotencyKey === toolCallLoopContinuationKey(input.runId) ) { const [refresh] = await input.tx .select({ id: agentWakeupRequests.id }) From 68f641ba0bb7e8e8740bf62cca1cbfab45da8264 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:15:41 -0600 Subject: [PATCH 8/8] fix(recovery): continue a native run cut off by a sandbox client timeout (#21736) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native runtime runs an agent's provider turn in a sandbox (for example Daytona) and records each failure on the run and its native coordinator > - A Daytona SDK request can hit its client-side deadline during a provider turn. The run then fails with `native_session_interrupted` in an ambiguous state, because the turn started and its outcome is unknown > - That failure blocks the task under a board-owned watchdog hold. No recovery owner selected the hold, because its cause is not an execution-reconciliation cause. The task never ran again, and only a person's Retry could continue it > - Recovery from an infrastructure fault must work automatically, without a person > - This pull request lets the execution-disposition pass hand that hold to the existing fresh-continuation fallback > - The benefit is that the task continues once, in an isolated fresh run, and the cut-off turn is never replayed ## Linked Issues or Issue Description **What happened?** A native run on a Daytona execution environment (native runtime, an OpenRouter model) started its provider turn. A Daytona request then failed with `HTTP request timed out after 300000ms waiting for a response. This is a client-side deadline (DaytonaConfig.requestTimeoutMs, or the per-call operation/execution timeout); any operation already started on the server may still be running.` The run failed with `native_session_interrupted`. The task had no further run: no automatic retry and no continuation. **Expected behavior** The task continues automatically, exactly once, in a fresh run from its saved work. The cut-off provider turn is not replayed. **Steps to reproduce** 1. Start a native run for an assigned task. Let its provider turn start (a `turn.started` event is saved). 2. Make a sandbox request in that turn fail with the Daytona client-side timeout error. 3. The executor saves the coordinator as `terminal_failure` with `recoveryMode: ambiguous_state`, blocks the task, and writes an active board hold with cause `native_session_interrupted`. 4. Run the execution-disposition worker (`settleUnrecoverableExecutions`). Before this change, nothing happens and the task stays blocked. **Paperclip version or commit** `master` at 9ebc276b42 (observed on a build from 5acf27bc3). **Deployment mode** Hosted cloud with a Daytona execution environment. Causal path: - The Daytona error is not a named class, so `nativeSessionFailureSourceCode` returns the generic `native_session_interrupted`. - `nativeProviderRecoveryEvidence` returns `ambiguous_state`: provider events exist, but there is no checkpoint with a provider identity. The executor then makes the failure terminal on the first attempt (no same-run resume) and writes a board hold whose cause is `native_session_interrupted`. - `unresolvedExecutionDispositions` and `heldExecutionWhere` select only holds with `EXECUTION_RECONCILIATION_CAUSES` (or a narrow `resume_native_run` shape). The safe replacement lane accepts `native_session_interrupted` only for the historical listener-unavailable case. The assigned-work sweep leaves a task blocked by an active hold to the hold's owner. So no owner continued the task. ## What Changed - `server/src/services/execution-recovery-resolution.ts`: the disposition pass also selects an active watchdog hold with a restart-class cause (`RESTART_CLASS_FAILURE_CODES`) for a terminal native run with no retry pending, unless the safe replacement lane owns that run. It hands the run to `continueFreshInTransaction` and records the fallback's result on the hold, so a run that does not continue is checked again only when due. - `server/src/services/fresh-continuation-fallback.ts`: the fallback treats an active watchdog hold with a restart-class cause as its own. When it continues the task, it settles that hold and unblocks the task, as it does for reconciliation holds. - New red/green test `server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts`. It drives the real native executor with a provider turn that starts and then fails with the Daytona client-timeout error. The cut-off turn is not replayed. The fresh continuation isolates the old run as it does for every continuation: the old run loses its write authority, its remote workspace epoch is fenced (or the continuation gets a new workspace), and the coordinator records `replacementDenied: fresh_continuation`. The fallback keeps its existing checks: person-owned causes, exact recovery still under way, and the per-task hourly cap. ## Verification - Red on `master`: `npx vitest run src/services/native-runtime/native-client-timeout-continuation.integration.test.ts` fails with no continuation recorded. - Green with this change. The test asserts that the run fails with `native_session_interrupted` and the Daytona error text in an ambiguous state, then that two disposition passes record exactly one fresh continuation, the task goes from `blocked` to `todo`, no active hold remains, the old run is marked `replacementDenied`, and two continuation-delivery passes wake the assignee exactly once. - Focused suites (all tests that use the disposition pass, the fresh-continuation fallback, or the execution-control schedule, 28 files): 27 files pass. `chat-channels.integration.test.ts` has 9 failures that are unrelated to this change (see the PR comment for the `master` baseline). - `npx tsc --noEmit -p server/tsconfig.json` passes. - `pnpm verify --explain` selects 2751 of 3578 files (a near-full run). I did not run it locally. CI supplies that coverage. ## Risks - Behavior change: a terminal native interruption hold that before stayed with the board now continues automatically in a fresh run. This is the intended product behavior. The fallback still refuses person-owned causes and still respects the per-task cap. - Holds with restart-class causes are now settled by the fallback when it continues a run. Before, they could stay active next to the continuation record. - No migration. No API or UI contract change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits) and code execution for tests. ## 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 --- server/src/services/execution-control-work.ts | 7 +- .../services/execution-recovery-resolution.ts | 17 +- .../services/fresh-continuation-fallback.ts | 3 +- .../native-interruption-continuation.ts | 44 +++++ ...t-timeout-continuation.integration.test.ts | 154 ++++++++++++++++++ 5 files changed, 214 insertions(+), 11 deletions(-) create mode 100644 server/src/services/native-interruption-continuation.ts create mode 100644 server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts diff --git a/server/src/services/execution-control-work.ts b/server/src/services/execution-control-work.ts index eb3e1983964..125824b1193 100644 --- a/server/src/services/execution-control-work.ts +++ b/server/src/services/execution-control-work.ts @@ -11,6 +11,7 @@ import { nextAbandonedNativeOwnerReleaseAt } from "./native-runtime/native-faile import { hasPendingPauseResume } from "./issue-tree-resume.js"; import { hasPendingBudgetResume } from "./budget-resume-continuation.js"; import { continuationDeliveryDue } from "./recovery/continuation-delivery-attempt.js"; +import { nextNativeInterruptionCheckAt } from "./native-interruption-continuation.js"; export function registerExecutionControlWork( coordinator: ReturnType, @@ -113,13 +114,15 @@ export function executionControlSchedule(db: Db) { }, async disposition() { const now = new Date(); - const [conversation, execution, held, nextCheck] = await Promise.all([ + const [conversation, execution, held, nextCheck, nextInterruptionCheck] = await Promise.all([ db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(obsoleteExecutionConversationHold()).limit(1), unresolvedExecutionDispositions(db, 1), heldExecutionsAwaitingFreshContinuation(db, now, 1), nextFreshContinuationCheckAt(db), + nextNativeInterruptionCheckAt(db), ]); - return conversation.length || execution.length || held.length ? retry() : deadline([nextCheck ? new Date(nextCheck) : null]); + return conversation.length || execution.length || held.length ? retry() + : deadline([nextCheck ? new Date(nextCheck) : null, nextInterruptionCheck ? new Date(nextInterruptionCheck) : null]); }, async localLogin() { const rows = await db.select({ at: adapterAuthSessions.expiresAt }).from(adapterAuthSessions).where(and( diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.ts index d3dc9e68a94..7b0cb23dd52 100644 --- a/server/src/services/execution-recovery-resolution.ts +++ b/server/src/services/execution-recovery-resolution.ts @@ -43,6 +43,7 @@ import { reserveAutomaticRunCreation } from "./recovery/automatic-run-brake.js"; import { continuationDeliveryDue, deferForUnwakeableAssignee, recordContinuationDeliveryAttempt } from "./recovery/continuation-delivery-attempt.js"; import { continueFreshInTransaction, continueHeldExecutions, freshContinuationCheckDue, recordFreshContinuationCheck, settleCoalescedFreshContinuationHolds } from "./fresh-continuation-fallback.js"; +import { continueNativeInterruption, nativeInterruptionHold } from "./native-interruption-continuation.js"; import { alias } from "drizzle-orm/pg-core"; import { RECOVERY_BACKLOG_AGE_MS, RECOVERY_WAKE_REASONS } from "./heartbeat/queued-run-dispatch-order.js"; import { agentRecoveryQueueIsFull } from "./recovery-queue-admission.js"; @@ -680,7 +681,7 @@ export function unresolvedExecutionDispositions(db: Db, limit: number) { sql`${issueRecoveryActions.wakePolicy}->>'runId' = ${heartbeatRuns.id}::text`, exists(supersedingNativeWorkspaceHold(db, { companyId: heartbeatRuns.companyId, issueId: issueRecoveryActions.sourceIssueId, runId: heartbeatRuns.id })), - )), + ), nativeInterruptionHold()), inArray(heartbeatRuns.status, [ "failed", "timed_out", @@ -818,14 +819,14 @@ export async function settleUnrecoverableExecutions( ) return; if (!EXECUTION_RECONCILIATION_CAUSES.includes(action.cause as (typeof EXECUTION_RECONCILIATION_CAUSES)[number])) { - if (run.runtimeMode !== "native" || run.nativePhase !== "terminal_failure" - || coordinator?.phase !== "terminal_failure" || coordinator.leaseOwner || coordinator.resultId - || coordinator.nextAttemptAt || coordinator.failureDetail?.successorRunId - || action.wakePolicy?.kind !== "resume_native_run" || action.wakePolicy.runId !== run.id) return; - const [hold] = await supersedingNativeWorkspaceHold(tx as unknown as Db, { + const resumeHold = run.runtimeMode === "native" && run.nativePhase === "terminal_failure" + && coordinator?.phase === "terminal_failure" && !coordinator.leaseOwner && !coordinator.resultId + && !coordinator.nextAttemptAt && !coordinator.failureDetail?.successorRunId + && action.wakePolicy?.kind === "resume_native_run" && action.wakePolicy.runId === run.id; + const [hold] = resumeHold ? await supersedingNativeWorkspaceHold(tx as unknown as Db, { companyId: run.companyId, issueId: task.id, runId: run.id, - }).limit(1).for("update"); - if (!hold) return; + }).limit(1).for("update") : []; + if (!hold) return void await continueNativeInterruption(tx as unknown as Db, { action, run, coordinator, now }); await notifyExecutionRunWork(tx, { companyId: run.companyId }); const note = "Exact session recovery stopped. The recorded workspace recovery holds this execution without replaying its actions."; await tx.update(issueRecoveryActions).set({ status: "cancelled", outcome: "cancelled", diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts index 4dce0254bb3..12b197ed3d4 100644 --- a/server/src/services/fresh-continuation-fallback.ts +++ b/server/src/services/fresh-continuation-fallback.ts @@ -301,7 +301,8 @@ const blocksExecution = (hold: typeof issueRecoveryActions.$inferSelect) => /** A reconciliation hold that blocks the task and that this decision settles. */ function isOwnedReconciliationHold(hold: typeof issueRecoveryActions.$inferSelect) { if (hold.kind === "stranded_assigned_issue") return false; - if (!(EXECUTION_RECONCILIATION_CAUSES as readonly string[]).includes(hold.cause) || !blocksExecution(hold)) return false; + const interruption = hold.kind === "active_run_watchdog" && (RESTART_CLASS_FAILURE_CODES as readonly string[]).includes(hold.cause); + if ((!(EXECUTION_RECONCILIATION_CAUSES as readonly string[]).includes(hold.cause) && !interruption) || !blocksExecution(hold)) return false; if (isHumanGate(hold)) return false; // A restore hold is owned only once its saved-work recovery completed. return !isRestoreHold(hold) || readSystemRecovery(hold.evidence)?.state === "complete"; diff --git a/server/src/services/native-interruption-continuation.ts b/server/src/services/native-interruption-continuation.ts new file mode 100644 index 00000000000..fedea0357a9 --- /dev/null +++ b/server/src/services/native-interruption-continuation.ts @@ -0,0 +1,44 @@ +import { and, eq, inArray, isNull, not, sql } from "drizzle-orm"; +import { heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, type Db } from "@paperclipai/db"; +import { RESTART_CLASS_FAILURE_CODES, isRestartClassFailureCode } from "./continuation-cause.js"; +import { canonicalExecutionUuid } from "./execution-identity.js"; +import { continueFreshInTransaction, recordFreshContinuationCheck } from "./fresh-continuation-fallback.js"; +import { nativeReplacementPending } from "./native-runtime/native-safe-replacement.js"; + +export function nativeInterruptionHold() { + return and( + inArray(issueRecoveryActions.cause, [...RESTART_CLASS_FAILURE_CODES]), + eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.nativePhase, "terminal_failure"), + eq(nativeRunFinalizations.phase, "terminal_failure"), isNull(nativeRunFinalizations.nextAttemptAt), + not(nativeReplacementPending()!), + )!; +} + +export async function continueNativeInterruption(tx: Db, input: { + action: typeof issueRecoveryActions.$inferSelect; + run: typeof heartbeatRuns.$inferSelect; + coordinator: typeof nativeRunFinalizations.$inferSelect | undefined; + now: Date; +}): Promise { + const { action, run, coordinator, now } = input; + if (!isRestartClassFailureCode(action.cause) || run.runtimeMode !== "native" || run.nativePhase !== "terminal_failure" + || coordinator?.phase !== "terminal_failure" || coordinator.nextAttemptAt || coordinator.leaseOwner || coordinator.resultId) + return false; + const fresh = await continueFreshInTransaction(tx, { companyId: action.companyId, runId: run.id, trigger: "recovery_refused", now }); + await recordFreshContinuationCheck(tx, { companyId: action.companyId, actionId: action.id }, fresh, now); + return true; +} + +export async function nextNativeInterruptionCheckAt(db: Db): Promise { + const [row] = await db.select({ at: sql`min((${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}')::bigint)` }) + .from(issueRecoveryActions) + .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, issueRecoveryActions.companyId), + eq(heartbeatRuns.id, canonicalExecutionUuid(sql`${issueRecoveryActions.evidence}->>'runId'`)))) + .innerJoin(nativeRunFinalizations, and(eq(nativeRunFinalizations.companyId, heartbeatRuns.companyId), + eq(nativeRunFinalizations.runId, heartbeatRuns.id))) + .where(and(inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.kind, "active_run_watchdog"), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}' is not null`, + inArray(heartbeatRuns.status, ["failed", "timed_out", "interrupted", "cancelled"]), + isNull(nativeRunFinalizations.leaseOwner), isNull(nativeRunFinalizations.resultId), nativeInterruptionHold())); + return row?.at ? Number(row.at) : null; +} diff --git a/server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts b/server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts new file mode 100644 index 00000000000..f965260d097 --- /dev/null +++ b/server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts @@ -0,0 +1,154 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, agents, companies, completionContracts, createDb, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, +} from "@paperclipai/db"; +import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent } from "@paperclipai/paperclip-runner"; +import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; + +const provider = vi.hoisted(() => ({ execute: vi.fn() })); +vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), + executeNativeSession: provider.execute, +})); + +import { executePaperclipNativeSession } from "./native-session-executor.js"; +import { buildNativeCompletionContract } from "./completion-contracts.js"; +import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { deliverReconciledExecutions, settleUnrecoverableExecutions } from "../execution-recovery-resolution.js"; +import { executionControlSchedule } from "../execution-control-work.js"; +import { ASSIGNED_WORK_CONTINUED_ACTION } from "../recovery/continuation-ledger.js"; +import { FRESH_CONTINUATION_WINDOW_MS } from "../fresh-continuation-fallback.js"; + +const DAYTONA_CLIENT_TIMEOUT = "HTTP request timed out after 300000ms waiting for a response. This is a client-side deadline " + + "(DaytonaConfig.requestTimeoutMs, or the per-call operation/execution timeout); any operation already started on the " + + "server may still be running."; + +describe("a native turn cut off by a sandbox client timeout", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(); + const agentId = randomUUID(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-client-timeout-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Client timeout", issuePrefix: "NCT" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Builder", status: "active", adapterType: "paperclip_runner", + adapterConfig: { provider: "opencode", model: "openrouter/test-model" } }); + }, 240_000); + afterAll(async () => { + await db?.$client.end({ timeout: 0 }); + await temporary?.cleanup(); + }); + + async function failTurnWithClientTimeout(issueId: string) { + const runId = randomUUID(); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", + nativeIssueId: issueId, invocationSource: "assignment", triggerDetail: "system", + contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" } }).returning(); + await db.update(issues).set({ executionRunId: runId, checkoutRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "opencode", model: "openrouter/test-model" }, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Build it.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: "opencode_server", protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", + contract: buildNativeCompletionContract(issue, { revision: contract.revision }) }, + interactionResponses: [], credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + const turnStarted: PrpEvent = { + schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId, + turnId: native.turnId, sourceInstanceId: native.runnerInstanceId, sourceEventId: "turn-started", sourceSeq: 1, + sourceKind: "runner", eventType: "turn.started", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), + payload: {}, + }; + provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => { + await options.controlPlane.openRun({ identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, + backendKind: "mock", sourceInstanceId: native.runnerInstanceId }); + await options.controlPlane.appendEvent(turnStarted); + throw new Error(DAYTONA_CLIENT_TIMEOUT); + }); + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { + descriptor: async () => { throw new Error("Unexpected provider call"); }, + openSession: async () => { throw new Error("Unexpected provider call"); }, + } }).catch(() => undefined); + return runId; + } + + const continuationsOf = (runId: string) => db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, companyId), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,sourceRunId}' = ${runId}`)); + + it("continues the task automatically exactly once in a fresh run, without replaying the cut-off turn", async () => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Build the feature", status: "in_progress", + workMode: "standard", assigneeAgentId: agentId }); + const runId = await failTurnWithClientTimeout(issueId); + + const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(failed).toMatchObject({ status: "failed", errorCode: "native_session_interrupted", error: DAYTONA_CLIENT_TIMEOUT }); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + expect(coordinator).toMatchObject({ phase: "terminal_failure", failureCode: "native_session_interrupted", nextAttemptAt: null, + failureDetail: expect.objectContaining({ recoveryMode: "ambiguous_state", providerEventsExist: true }) }); + + await settleUnrecoverableExecutions(db); + await settleUnrecoverableExecutions(db); + + const continuations = await continuationsOf(runId); + expect(continuations).toHaveLength(1); + expect(continuations[0]!.evidence).toMatchObject({ continuationDelivery: "pending", + freshContinuation: { sourceRunId: runId, failureCode: "native_session_interrupted" }, + freshContinuationSettlement: { replay: "none", decision: "continue_in_fresh_run" } }); + const [task] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(task).toMatchObject({ status: "todo", assigneeAgentId: agentId }); + const open = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId), + sql`${issueRecoveryActions.status} in ('active', 'escalated')`)); + expect(open).toEqual([]); + const [settled] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + expect(settled.failureDetail).toMatchObject({ replacementDenied: "fresh_continuation" }); + expect(provider.execute).toHaveBeenCalledOnce(); + + const wake = vi.fn(async () => ({ id: randomUUID() }) as never); + await deliverReconciledExecutions(db, wake); + await deliverReconciledExecutions(db, wake); + expect(wake).toHaveBeenCalledOnce(); + expect(wake).toHaveBeenCalledWith(agentId, expect.objectContaining({ + payload: expect.objectContaining({ issueId }) })); + }, 120_000); + + it("registers the capped continuation's next check with the disposition worker and continues the task when it is due", async () => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Build the capped feature", status: "in_progress", + workMode: "standard", assigneeAgentId: agentId }); + const runId = await failTurnWithClientTimeout(issueId); + const firstAt = new Date(Date.now() - 10 * 60_000); + const capped = await db.insert(activityLog).values(Array.from({ length: 6 }, (_, index) => ({ companyId, actorId: "test", + action: ASSIGNED_WORK_CONTINUED_ACTION, entityType: "issue", entityId: issueId, details: { outcome: "queued" }, + createdAt: new Date(firstAt.getTime() + index * 1_000) }))).returning({ id: activityLog.id }); + + await settleUnrecoverableExecutions(db); + expect(await continuationsOf(runId)).toHaveLength(0); + const [hold] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId), + eq(issueRecoveryActions.status, "active"))); + const nextCheckAt = firstAt.getTime() + FRESH_CONTINUATION_WINDOW_MS; + expect(hold?.evidence).toMatchObject({ freshContinuationCheck: { kind: "backoff", nextCheckAt } }); + expect(await executionControlSchedule(db).disposition()).toBe(nextCheckAt); + + await db.delete(activityLog).where(sql`${activityLog.id} in ${capped.map(row => row.id)}`); + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,nextCheckAt}', to_jsonb(${Date.now() - 1}::bigint))` }).where(eq(issueRecoveryActions.id, hold!.id)); + await settleUnrecoverableExecutions(db); + expect(await continuationsOf(runId)).toHaveLength(1); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "todo" }); + }, 120_000); +});