diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 1e4190c8064..0ef42ec0b23 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1648,7 +1648,7 @@ timeout retries still require a fresh allocation under the policy above. A person's task Retry on a connected task first asks the chat retry owner to repeat the exact failed chat request. When the latest run is that person's own saved board turn that cannot be certified for replay, when no chat retry owner is available, or when that owner refuses (`chat_failed_run_retry_not_authorized`), the refusal and any writes it made are rolled back and the same Retry receipt becomes an ordinary board continuation: the clicking person is the responsible user, the run starts a fresh session from saved work, and no chat action, chat authority, or output replay is created. This is the same authority as a new message from that person. When the conversation still holds saved or unadmitted chat input for the task, Retry keeps the exact-replay path and its refusal, because that input continues through its own admission. Dispatch keeps every normal gate (current task access, executor containment, recovery holds, unadmitted chat input). Projection and the route therefore agree: a shown Retry on a connected task is accepted. Retry that Paperclip requests by itself on a person's behalf (restart recovery, provider limit reset) keeps the exact-replay requirement and still settles on the refusal. A budget resume continues the person's own Retry, so it takes the board continuation too. No migration is needed; tasks blocked by an earlier release become retryable at the next click. -A task whose run was interrupted and whose fresh continuation is recorded reads as continuing (`working`, no Retry) while the continuation waits to be delivered and while it waits in the agent's queue. Once the delivered continuation run has waited in the queue for 15 minutes, the task also offers Retry with `retryAction: "move_forward"`, labelled "Move it forward now". The Retry names that queued run as its observed run, so admission joins it to the run (`coalesced`) and starts no second run; a run that a person joined starts ahead of system recovery work. The offer ends once a person has joined the run or the run starts. While the continuation is still waiting to be delivered, no Retry is offered: a Retry there would start its own run beside the recorded continuation. +A task whose run was interrupted and whose fresh continuation is recorded reads as continuing (`working`, no Retry) while the continuation waits to be delivered and while it waits in the agent's queue. Once the delivered continuation run has waited in the queue for 15 minutes, the task also offers Retry with `retryAction: "move_forward"`, labelled "Move it forward now". The Retry names that queued run as its observed run, so admission joins it to the run (`coalesced`) and starts no second run; a run that a person joined starts ahead of system recovery work. The offer ends once a person has joined the run or the run starts. The same action is offered while the continuation is recorded but not yet delivered (`continuationDelivery: "pending"`) once it has waited 15 minutes since it was recorded. The Retry then names the interrupted run as its observed run, and admission delivers the recorded continuation as the one run, with its recorded isolation; the delivery pass afterwards finds nothing left to start. When the continuation is delivered, the task moves to another run, or the system gives up the delivery between the offer and the click, the click starts no run (`stale` or `alreadyMovedOn`). No move-forward is offered for a continuation recorded without a delivery request (`not_requested`), when a person's Retry for the interrupted run already waits, or when the task's assignee changed; a held restore keeps its own blocker. The exact replay can also be refused after the click is accepted. This happens when chat source authorization was deferred by a busy identity or endpoint lock, or when it later fails, so the chat retry action settles `failed` with no admitted run. The task Retry receipt is then not failed. If it is a person's Retry, its source run is still the latest run, its chat wake has no run, and no saved or unadmitted chat input remains, the same receipt drops its chat action and becomes the board continuation described above, recorded as `issue.retry_continued_from_saved_work`. Saved chat input whose source comment was written no later than the failed run's stop boundary (the user's recorded Stop request, otherwise `finishedAt`, the same boundary admission uses) does not block this: admission holds such input as `message_predates_stop`, so it can never start alone. The continuation adopts it (the input receipt is coalesced into the Retry receipt) and the task continues from saved work. Saved input that arrived after the stop keeps its own admission path, and the Retry still settles as failed. When the latest run is an admission that the recovery hold cancelled before dispatch (`execution_reconciliation_required`), the saved work that counts is the recovered work of the run whose recovery action held it. The deferred-receipt worker dispatches it with every normal gate. Retry that Paperclip requests by itself still settles as failed. When a failed run's saved work is recovered, the task's execution blocker offers Retry (also on a connected task) and says "Saved work recovered. Retry continues from it." A stopped (cancelled) run keeps "Send a message to continue." diff --git a/server/src/__tests__/recovery-wake-herd.test.ts b/server/src/__tests__/recovery-wake-herd.test.ts index e83b7fb2735..5ef2ca9844e 100644 --- a/server/src/__tests__/recovery-wake-herd.test.ts +++ b/server/src/__tests__/recovery-wake-herd.test.ts @@ -536,12 +536,13 @@ suite("recovery wake herd", () => { expect(await deliveryOf(healthy.action.id)).toBe("delivered"); }, 120_000); - it("shows a task as continuing, never as needing Retry, while its recorded continuation is pending past the delivery bound", async () => { + it("shows a task as continuing, never as failed, while its recorded continuation is pending past the delivery bound", async () => { const agentId = await seedCompany(1); const record = await pendingContinuation(agentId, 240); await holdPastBound(record, RECOVERY_CONTINUATION_DELIVERY_BOUND_MS); const [issueRow] = await db.select().from(issues).where(eq(issues.id, record.issue.id)); - expect(await taskInterruptionPresentation(db, issueRow!)).toMatchObject({ state: "working", canRetry: false, responsibility: "system" }); + expect(await taskInterruptionPresentation(db, issueRow!)).toMatchObject({ state: "working", responsibility: "system", + canRetry: true, retryAction: "move_forward", observedRunId: record.source.id }); const wake = fakeWake(); await deliverReconciledExecutions(db, wake as never); diff --git a/server/src/__tests__/task-interruption-automatic-path.test.ts b/server/src/__tests__/task-interruption-automatic-path.test.ts index 9ef720cfacc..44717859f7b 100644 --- a/server/src/__tests__/task-interruption-automatic-path.test.ts +++ b/server/src/__tests__/task-interruption-automatic-path.test.ts @@ -108,10 +108,10 @@ describe.skipIf(!support.supported)("Retry is offered only when no automatic pat } it("shows a task whose recorded continuation is still waiting to start as continuing, however long delivery takes", async () => { - for (const minutesAgo of [1, 30, 110]) { + for (const minutesAgo of [1, 14, 30, 110]) { const { issue, runId } = await seedRecordedContinuation(minutesAgo); expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "system", state: "working", - canRetry: false, observedRunId: runId }); + canRetry: minutesAgo >= 15, observedRunId: runId }); } }); @@ -119,7 +119,7 @@ describe.skipIf(!support.supported)("Retry is offered only when no automatic pat const { issue, primary } = await seedRecordedContinuation(45); await db.update(issueRecoveryActions).set({ evidence: { ...primary.evidence, continuationDeliveryAttemptedAt: new Date(Date.now() - 60_000).toISOString() } }).where(eq(issueRecoveryActions.id, primary.id)); - expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "working", canRetry: false }); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "working", canRetry: true, retryAction: "move_forward" }); }); it("offers Retry once the system gives up on a recorded continuation", async () => { @@ -174,15 +174,48 @@ describe.skipIf(!support.supported)("Retry is offered only when no automatic pat expect(presentation?.retryAction).toBeUndefined(); }); - it("offers no Retry while a recorded continuation is still being delivered, however long it waits", async () => { - for (const minutesAgo of [16, 45, 110]) { - const { issue } = await seedRecordedContinuation(minutesAgo); - const presentation = await taskInterruptionPresentation(db, issue); - expect(presentation).toMatchObject({ state: "working", canRetry: false }); - expect(presentation?.retryAction).toBeUndefined(); + it("offers to move a recorded continuation forward once it has waited 15 minutes for delivery, without calling it failed", async () => { + for (const minutesAgo of [15, 45, 110]) { + const { issue, runId } = await seedRecordedContinuation(minutesAgo); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "system", state: "working", + canRetry: true, retryAction: "move_forward", observedRunId: runId }); } }); + it("offers no Retry while a recorded continuation has waited under 15 minutes for delivery", async () => { + const { issue } = await seedRecordedContinuation(14); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("offers no Retry for a continuation recorded without a delivery request", async () => { + const { issue, primary } = await seedRecordedContinuation(45); + await db.update(issueRecoveryActions).set({ evidence: { ...primary.evidence, continuationDelivery: "not_requested" } }) + .where(eq(issueRecoveryActions.id, primary.id)); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("offers no second Retry once a person already asked to move the undelivered continuation forward", async () => { + const { companyId, agentId, issue, runId } = await seedRecordedContinuation(45); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", triggerDetail: "manual", + reason: "task_retry", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: randomUUID(), + payload: { issueId: issue.id, taskRetry: { sourceRunId: runId } } }); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("offers no move-forward for an undelivered continuation once the task is reassigned", async () => { + const { companyId, issue } = await seedRecordedContinuation(45); + const otherAgentId = randomUUID(); + await db.insert(agents).values({ id: otherAgentId, companyId, name: "Other agent", adapterType: "paperclip_runner" }); + const [reassigned] = await db.update(issues).set({ assigneeAgentId: otherAgentId }).where(eq(issues.id, issue.id)).returning(); + expect((await taskInterruptionPresentation(db, reassigned!))?.retryAction).toBeUndefined(); + }); + it("offers no Retry for a continuation that is already running", async () => { const { issue } = await seedQueuedContinuation(45, "running"); const presentation = await taskInterruptionPresentation(db, issue); diff --git a/server/src/services/fresh-continuation-move-forward-offer.test.ts b/server/src/services/fresh-continuation-move-forward-offer.test.ts new file mode 100644 index 00000000000..cc694f7f7f1 --- /dev/null +++ b/server/src/services/fresh-continuation-move-forward-offer.test.ts @@ -0,0 +1,200 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agentWakeupRequests, agents, authUsers, companies, createDb, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { deliverReconciledExecutions } from "./execution-recovery-resolution.js"; +import { ensureFreshContinuation, resetBacklogContinuationPacingForTests } from "./fresh-continuation-fallback.js"; +import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js"; +import { heartbeatService } from "./heartbeat.js"; +import { requestTaskRetry } from "./task-retry.js"; +import { taskInterruptionPresentation } from "./task-interruption-presentation.js"; + +vi.mock("../sentry.js", async importOriginal => ({ ...await importOriginal(), captureTaskInterruptionFailure: vi.fn() })); + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; + +const KINDS = ["fresh_isolated_workspace", "writer_ended", "native"] as const; +type Kind = (typeof KINDS)[number]; +const RECORDED_ISOLATION: Record = { + fresh_isolated_workspace: "fresh_isolated_workspace", writer_ended: "writer_ended", native: "remote_epoch" }; + +suite("Move it forward now while a recorded continuation waits for delivery", () => { + let db!: ReturnType; + let temporary: Awaited> | null = null; + let companyId = "", agentId = "", userId = ""; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-move-forward-offer-"); + db = createDb(temporary.connectionString); + companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID(); + await db.insert(authUsers).values({ id: userId, name: "Board", email: `${userId}@example.test`, + emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: "MFO", + requireBoardApprovalForNewAgents: false, defaultResponsibleUserId: userId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Coder", role: "engineer", status: "idle", + adapterType: "paperclip_runner", adapterConfig: {}, runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } }, permissions: {} }); + }, 60_000); + + afterEach(async () => { + resetBacklogContinuationPacingForTests(db); + await db.execute(sql`truncate table issue_recovery_actions, native_run_finalizations, activity_log, + agent_wakeup_requests, heartbeat_runs, issues cascade`); + }); + + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + async function pendingContinuation(kind: Kind, waitingMinutes: number) { + const issueId = randomUUID(), runId = randomUUID(); + const finishedAt = new Date(Date.now() - (waitingMinutes + 1) * 60_000); + const native = kind === "native"; + await db.insert(issues).values({ id: issueId, companyId, title: "Ship the release notes", status: "blocked", + assigneeAgentId: agentId, statusVersion: 4, blockedTransitionAt: finishedAt }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", issueId, + nativeIssueId: native ? issueId : null, runtimeMode: native ? "native" : "legacy", + status: "failed", errorCode: native ? "native_session_interrupted" : kind === "writer_ended" ? "process_lost" : "controller_lease_lost", + error: "cut off", startedAt: new Date(finishedAt.getTime() - 10 * 60_000), finishedAt, + createdAt: new Date(finishedAt.getTime() - 11 * 60_000), responsibleUserId: userId, + contextSnapshot: { issueId, wakeReason: "issue_assigned" }, + ...(native ? { nativePhase: "terminal_failure", runnerProfileJson: { remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", + workspaceId: randomUUID(), leaseId: randomUUID(), providerLeaseId: "sandbox-1", remoteCwd: "/home/daytona/work", epoch: 3, + state: "prepared", snapshotId: null } } } + : { runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }), + ...(kind === "fresh_isolated_workspace" + ? { processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000) } : {}) }); + if (native) { + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure", + recoveryState: "blocked", failureCode: "native_continuation_requires_reconciliation", leaseOwner: null }); + } + const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", + status: "active", ownerType: "board", returnOwnerAgentId: agentId, + cause: native ? "native_continuation_requires_reconciliation" : "legacy_execution_requires_reconciliation", + fingerprint: `${native ? "native-continuation" : "legacy-execution"}:${runId}`, nextAction: "Held.", maxAttempts: 3, + createdAt: finishedAt, evidence: { runId, originalFailureCode: "cut_off", nativeFailureBlock: { runId, statusVersion: 4 } } }) + .returning(); + await db.update(issues).set({ projectId: null, projectWorkspaceId: null, executionWorkspaceId: null }).where(eq(issues.id, issueId)); + expect(await ensureFreshContinuation(db, { companyId, runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", delivery: "recorded", isolation: RECORDED_ISOLATION[kind] }); + const recordedAt = new Date(Date.now() - waitingMinutes * 60_000).toISOString(); + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, '{freshContinuation,recordedAt}', + to_jsonb(${recordedAt}::text))` }).where(eq(issueRecoveryActions.id, action!.id)); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + return { issue: issue!, issueId, runId, actionId: action!.id, isolation: RECORDED_ISOLATION[kind] }; + } + + async function occupySlot() { + const [other] = await db.insert(issues).values({ companyId, title: "Other work", status: "in_progress", assigneeAgentId: agentId }).returning(); + await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: other!.id, status: "running", contextSnapshot: { issueId: other!.id } }); + } + const taskRuns = (f: { issueId: string; runId: string }) => db.select().from(heartbeatRuns).where(and( + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${f.issueId}`, sql`${heartbeatRuns.id} <> ${f.runId}`)); + const record = async (actionId: string) => (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, actionId)))[0]!; + const wake = async (id: string) => (await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, id)))[0]!; + const deliveryPass = () => deliverReconciledExecutions(db, heartbeatService(db).wakeup); + async function deliver() { await deliveryPass(); await deliveryPass(); } + + async function shownOffer(f: Awaited>) { + const shown = await taskInterruptionPresentation(db, f.issue); + expect(shown).toMatchObject({ responsibility: "system", state: "working", canRetry: true, retryAction: "move_forward", + observedRunId: f.runId }); + return shown!; + } + const click = (f: { issueId: string }, shown: { observedRunId: string | null; retryAction?: "move_forward" }) => + requestTaskRetry({ db, companyId, issueId: f.issueId, actorId: userId, observedRunId: shown.observedRunId, + retryAction: shown.retryAction, idempotencyKey: randomUUID(), actorSource: "local_implicit" }); + + async function expectTheRecordedContinuation(f: Awaited>) { + const runs = await taskRuns(f); + expect(runs).toHaveLength(1); + const run = runs[0]!; + expect(run.contextSnapshot).toMatchObject({ recoveryActionId: f.actionId, previousRunId: f.runId, forceFreshSession: true }); + expect(run.retryOfRunId).toBe(f.runId); + if (f.isolation === "fresh_isolated_workspace") { + expect(run.contextSnapshot).toMatchObject({ freshContinuationIsolation: f.actionId }); + expect(await readFreshWorkspaceReadiness(db, run)).toMatchObject({ mode: "fresh_isolated_workspace", retryIntentId: f.actionId }); + } else expect(run.contextSnapshot?.freshContinuationIsolation).toBeUndefined(); + expect((await record(f.actionId)).evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: run.id }); + return run; + } + + it.each(KINDS)("delivers the recorded continuation as the one run when a person clicks Move it forward now (%s)", async kind => { + const f = await pendingContinuation(kind, 16); + await occupySlot(); + const shown = await shownOffer(f); + const receipt = await click(f, shown); + expect(receipt).toMatchObject({ accepted: true }); + await heartbeatService(db).resumeTaskRetry(companyId, receipt.requestId!); + const run = await expectTheRecordedContinuation(f); + expect(await wake(receipt.requestId!)).toMatchObject({ status: "coalesced", runId: run.id, requestedByActorType: "user" }); + await deliver(); + await heartbeatService(db).resumeTaskRetry(companyId, receipt.requestId!); + expect((await taskRuns(f)).map(row => row.id)).toEqual([run.id]); + const after = await taskInterruptionPresentation(db, f.issue); + expect(after).toMatchObject({ state: "working", canRetry: false, observedRunId: run.id }); + expect(after?.retryAction).toBeUndefined(); + }, 60_000); + + it.each(KINDS)("starts one run when Move it forward now and the delivery pass race (%s)", async kind => { + const f = await pendingContinuation(kind, 16); + await occupySlot(); + const receipt = await click(f, await shownOffer(f)); + expect(receipt).toMatchObject({ accepted: true }); + await Promise.all([heartbeatService(db).resumeTaskRetry(companyId, receipt.requestId!), deliveryPass(), deliveryPass()]); + await deliver(); + await heartbeatService(db).resumeTaskRetry(companyId, receipt.requestId!); + const run = await expectTheRecordedContinuation(f); + expect(await wake(receipt.requestId!)).toMatchObject({ status: "coalesced", runId: run.id }); + }, 60_000); + + it.each(KINDS)("starts no second run when the continuation was delivered between the offer and the click (%s)", async kind => { + const f = await pendingContinuation(kind, 16); + await occupySlot(); + const shown = await shownOffer(f); + await deliver(); + const delivered = await expectTheRecordedContinuation(f); + const receipt = await click(f, shown); + expect(receipt).toMatchObject({ accepted: false, requestId: null }); + await deliver(); + expect((await taskRuns(f)).map(row => row.id)).toEqual([delivered.id]); + expect(await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.reason, "task_retry"), + sql`${agentWakeupRequests.payload}->>'issueId' = ${f.issueId}`))).toEqual([]); + }, 60_000); + + it.each(KINDS)("starts nothing when the system gave up the delivery between the offer and the click (%s)", async kind => { + const f = await pendingContinuation(kind, 16); + await occupySlot(); + const shown = await shownOffer(f); + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || '{"continuationDelivery":"invalidated"}'::jsonb` }) + .where(eq(issueRecoveryActions.id, f.actionId)); + const receipt = await click(f, shown); + expect(receipt).toMatchObject({ accepted: false, alreadyMovedOn: true, requestId: null }); + await deliver(); + expect(await taskRuns(f)).toEqual([]); + const after = await taskInterruptionPresentation(db, f.issue); + expect(after?.retryAction).toBeUndefined(); + }, 60_000); + + it("starts no second run when the task moved on to another run between the offer and the click", async () => { + const f = await pendingContinuation("writer_ended", 16); + await occupySlot(); + const shown = await shownOffer(f); + const [moved] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, status: "queued", + contextSnapshot: { issueId: f.issueId, wakeReason: "issue_commented" } }).returning(); + const receipt = await click(f, shown); + expect(receipt).toMatchObject({ accepted: false, requestId: null }); + await deliver(); + expect((await taskRuns(f)).map(row => row.id)).toEqual([moved!.id]); + expect((await record(f.actionId)).evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: moved!.id }); + }, 60_000); + + it("offers no button while the recorded continuation has waited under 15 minutes", async () => { + const f = await pendingContinuation("writer_ended", 14); + await occupySlot(); + const shown = await taskInterruptionPresentation(db, f.issue); + expect(shown).toMatchObject({ responsibility: "system", state: "working", canRetry: false, observedRunId: f.runId }); + expect(shown?.retryAction).toBeUndefined(); + }, 60_000); +}); diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index a4895f42acc..47ed6119208 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -99,7 +99,7 @@ type ProjectionState = { cleanupSettling?: boolean; /** The fresh-continuation fallback is continuing this run's task (recorded, * not yet started) or will check it again at `nextCheckAt`. */ - freshContinuation?: { state: "continuing" } | { state: "scheduled"; nextCheckAt: number }; + freshContinuation?: { state: "continuing"; pendingSince?: number } | { state: "scheduled"; nextCheckAt: number }; automaticDispositionAt?: number; waitingContinuation?: { queuedAt: number; personRequested: boolean }; recoveryHandedToPerson?: boolean; @@ -283,7 +283,13 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS return { ...base, state: "working", canRetry: true, retryAction: "move_forward" }; if (["running", "queued"].includes(run.status)) return { ...base, state: "working" }; // Paperclip is continuing the task by itself: no failed attempt and no Retry. - if (input.freshContinuation?.state === "continuing") return { ...base, state: "working", canRetry: false }; + if (input.freshContinuation?.state === "continuing") { + const pendingSince = input.freshContinuation.pendingSince; + if (pendingSince !== undefined && !input.retryWait && run.agentId === issue.assigneeAgentId + && now - pendingSince >= WAITING_CONTINUATION_MOVE_FORWARD_MS) + return { ...base, state: "working", canRetry: true, retryAction: "move_forward" }; + return { ...base, state: "working", canRetry: false }; + } if (input.freshContinuation?.state === "scheduled" && input.freshContinuation.nextCheckAt > now) return { ...base, state: "retry_scheduled", nextRetryAt: new Date(input.freshContinuation.nextCheckAt).toISOString(), canRetry: false }; if (input.automaticDispositionAt !== undefined && ["failed", "timed_out", "interrupted", "cancelled"].includes(run.status) @@ -610,16 +616,26 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i runId: sql`${issueRecoveryActions.evidence}->>'runId'`, delivery: sql`${issueRecoveryActions.evidence}->>'continuationDelivery'`, recorded: sql`${issueRecoveryActions.evidence} ? 'freshContinuation'`, + status: issueRecoveryActions.status, + schema: sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}'`, + recordedAt: sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'`, + reconciledRunId: sql`${issueRecoveryActions.evidence}#>>'{executionReconciliation,runId}'`, checkKind: sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,kind}'`, nextCheckAt: sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}'` }) .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), sql`(${issueRecoveryActions.evidence} ? 'freshContinuationSettlement' or ${issueRecoveryActions.evidence} ? 'freshContinuationCheck')`)) : []; + const pendingSchema = freshRows.some(row => row.delivery === "pending") + ? (await import("./fresh-continuation-fallback.js")).FRESH_CONTINUATION_SCHEMA : null; const freshContinuationFor = (issueId: string, runId: string | undefined): ProjectionState["freshContinuation"] => { const rows = freshRows.filter(row => row.issueId === issueId && row.runId === runId); // Only the primary record (it carries `freshContinuation`) says whether a // continuation is still on its way; holds coalesced into it never do. - if (rows.some(row => row.recorded && ["not_requested", "pending"].includes(row.delivery ?? ""))) return { state: "continuing" }; + if (rows.some(row => row.recorded && ["not_requested", "pending"].includes(row.delivery ?? ""))) { + const pendingSince = Math.max(...rows.filter(row => row.recorded && row.delivery === "pending" && row.status === "resolved" + && row.schema === pendingSchema && row.reconciledRunId === runId).map(row => Date.parse(row.recordedAt ?? ""))); + return Number.isFinite(pendingSince) ? { state: "continuing", pendingSince } : { state: "continuing" }; + } const scheduled = rows.filter(row => ["exact_recovery_pending", "backoff"].includes(row.checkKind ?? "") && row.nextCheckAt) .map(row => Number(row.nextCheckAt)).sort((a, b) => a - b)[0]; return scheduled ? { state: "scheduled", nextCheckAt: scheduled } : undefined;