mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat queue starts an agent's queued runs. #21234, #21277
and #21349 order them: person work first, a recovery share, aging, and a
share for the longest-waiting run
> - On hosted staging, one agent had about 250 queued runs. For 90
minutes after #21349 deployed, every run that started was a retry or
continuation with `retryOfRunId`. The oldest queued runs, from 15 hours
earlier, never started
> - The dispatch order was not bypassed. The oldest-run share offered
those runs, but the claim refused them every time, without a log at info
level or a visible state
> - The refusal came from the chat-control recovery gate. It needs
`retryOfRunId` to trace an automatic continuation. The assigned-work
invariant sweep queues continuations that name their source only in
context, so the gate returned "unresolved", and an unresolved claim
stays queued forever
> - This pull request lets the gate check such a continuation against
the task's previous run, and makes the recovery share count only system
recovery starts
> - The benefit is that the sweep's continuations start (it already told
people "you don't need to press Retry"), and system recovery gets its
share even when a person's recovery restarts keep starting
## Linked Issues or Issue Description
Refs #21234, #21277, #21324, #21349, #21242
**What happened?**
On hosted staging (build e23549cd9c), one agent with `maxConcurrentRuns`
20 had about 250 queued runs. From 12:06Z to 13:30Z, all 30 runs that
started had `retryOfRunId` set. The oldest queued runs were automatic
continuations (`issue_continuation_needed`) created from 22:53Z the day
before. Each task's activity shows "Continued automatically after an
interruption ... you don't need to press Retry" from the assigned-work
invariant sweep, at the time the run was queued. None of these runs
started. Assignments created at 07:51Z and later did start, in creation
order. Those starts came through the oldest-run share after the share
passed over the refused continuations.
**Why did it happen?**
1. `assignedWorkSweep` queues the continuation with `previousRunId` in
its context and no `retryOfRunId`. Its wake is a system wake
(`requestedByActorId` null) with reason `issue_continuation_needed`.
2. At claim, `withChatControlRecoveryGate` calls
`readChatControlRecoveryStop`. For an automatic continuation without
`retryOfRunId`, it returned `unresolved`. At the claim stage,
`unresolved` returns null: the run stays queued and nothing changes. So
every dispatch pass offered these runs and every claim refused them.
Retries and continuations with `retryOfRunId` pass the gate, so they
were the only recovery work that started.
3. Separately, the recovery share (#21234) read the agent's recent
starts and counted every start with a recovery wake reason as a recovery
start. A person's `issue_recovery_action_restored` restart ranks as
person work in the dispatcher, but it still reset the share. So the
recovery share almost never fired while those restarts kept starting.
**Free slots.** The "14 of 20 running" figure came from a capped run
list. A full read at 14:03Z showed 22 runs `running` on that agent, so
there were no free slots. The agent was over its limit, not under it.
Overlapping dispatch passes after the 30 s stale agent start lock are a
likely cause (each pass re-tried every refused run, so passes were
slow). This pull request removes the refused runs that made passes slow.
#21242 changes the claim-then-execute timing.
**Expected behavior**
An automatic continuation that the system queued starts in its turn. A
chat close of the task's previous run still stops it. The recovery share
goes to system recovery after three starts that were not system
recovery.
**Steps to reproduce**
1. Give an agent one slot. Interrupt a run on an in-progress task so
that the assigned-work invariant finds a violation.
2. Run the assigned-work check. It queues an `issue_continuation_needed`
continuation.
3. Queue fresher recovery runs on other tasks and dispatch.
4. See that the continuation stays queued on every pass.
## What Changed
- `server/src/services/chat-control-recovery-stop.ts`: for an automatic
continuation that has no `retryOfRunId`, the gate now walks to the
task's latest earlier run (by `issueId`, `nativeIssueId` or the context
task id, in the same company) and checks that run. If the task has no
earlier run, the result is `clear`. A continuation with `retryOfRunId`
is unchanged. A chat close of the previous run still stops the
continuation.
- `server/src/services/heartbeat/queue.ts`: the recovery-share counter
reads which recent recovery-reason starts were person-originated, with
the same source-chain query that the dispatcher already uses
(`listPersonOriginSourceRunIds`, at most 4 ids). Only system recovery
starts reset the share. This matches the in-pass rule
(`isSystemRecoveryRun`).
## Verification
- Red/green, embedded Postgres, real heartbeat queue
(`server/src/__tests__/recovery-wake-herd.test.ts`):
- "starts the assigned-work sweep's continuation of a task whose run was
interrupted, ahead of fresher retries": on master the continuation stays
queued for 60 s of dispatch passes; with the fix it starts.
- "gives system recovery its share when the agent's recent starts were a
person's recovery restarts": on master a person run starts first; with
the fix the system recovery run starts.
- `server/src/__tests__/heartbeat-process-recovery.test.ts`: "checks an
automatic continuation that names no retry source against the task's
previous run" proves that a chat close of the previous run still stops
the continuation (`stopped`) and that it is `clear` when the close is
not published.
- `node server/scripts/typecheck-layers.mjs`: passes.
- Related suites: `recovery-wake-herd`, `queued-run-dispatch-order`,
`assigned-work-invariant`, `run-authority-read-projections`,
`chat-run-milestone-work`, `legacy-preparation-retry-hold`,
`explicit-native-continuation`, `saved-work-retry-eligibility`,
`native-failed-turn-continuation.integration`,
`heartbeat-process-recovery` pass, except:
- `heartbeat-process-recovery` "schedules bounded retries for failed
accepted interaction continuation wakes" is flaky on master too (1 of 3
runs failed on master source, same line).
- `recovery-wake-herd` "delivers the continuation after a restart..."
failed once with a hook timeout under parallel load and passes alone.
- `runtime-selection.test.ts` fails locally in a nested worktree because
a bundled skill file path does not exist there (environment, not this
change).
- After deploy: the queued `issue_continuation_needed` runs on the
affected staging agent should start within the oldest-run share, and no
run should stay queued longer than the aging bound plus a few starts.
## Risks
- Behavior change: an automatic continuation without `retryOfRunId` was
refused at claim and failed at dispatch with
`chat_control_recovery_proof_unresolved`. It now inherits the chat-close
check of the task's previous run instead. A chat close still stops it.
- Already-queued stuck continuations on hosted instances will start
after deploy. On the staging agent that is about 30 runs. They go
through the normal order and shares, so they do not take all slots at
once.
- One extra indexed read per gate check of this shape, and one small
recursive query per dispatch pass when recovery runs are queued. No
schema change. Mixed versions are safe.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edit, built-in browser for read-only staging API
reads).
## 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 <noreply@anthropic.com>
17628 lines
716 KiB
TypeScript
17628 lines
716 KiB
TypeScript
import { persistHeartbeatRunProcessMetadata } from "../services/heartbeat/run-lifecycle.js";
|
|
import { BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS } from "../services/heartbeat/retries.js";
|
|
import { SERVER_RESTART_RETRY_MAX_ATTEMPTS, SERVER_RESTART_RETRY_WINDOW_MS } from "../services/execution-recovery-attempt.js";
|
|
import { enableRunFailureReporting } from "./helpers/run-failure-reporting.js";
|
|
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
|
import { createSystemRecovery } from "../services/system-recovery-state.js";
|
|
import * as conversationContinuation from "../services/conversation-continuation.js";
|
|
import { classifyEnvironmentCapabilities, environmentRuntimeService } from "../services/environment-runtime.js";
|
|
import * as workspaceRuntime from "../services/workspace-runtime.js";
|
|
import * as workspacePreparation from "../services/heartbeat/workspace-preparation.js";
|
|
import { nativeWorkspaceSyncInternals } from "../services/native-runtime/native-workspace-sync.js";
|
|
import { ensureNativeCompletionContract } from "../services/native-runtime/completion-contracts.js";
|
|
import { readNativePlanWait, hasCommittedNativePlanWait } from "../services/native-runtime/native-plan-wait.js";
|
|
import { hasCommittedNativeConversationTurnWait } from "../services/native-runtime/native-response-wake-wait.js";
|
|
import { nativeSha256 } from "../services/native-runtime/canonical.js";
|
|
import { buildQuestionResponseDeliveryEnvelope } from "../services/question-response-delivery.js";
|
|
import * as aiConnectionRuntime from "../services/ai-connection-runtime.js";
|
|
import { forbidden, unprocessable } from "../errors.js";
|
|
import { aiConnectionCredentialNotSharedFailure } from "../services/ai-connection-configuration-failure.js";
|
|
import * as executionContinuation from "../services/execution-continuation.js";
|
|
import * as environmentOrchestrator from "../services/environment-run-orchestrator.js";
|
|
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
|
|
import { legacyDispositionFingerprint, LEGACY_DISPOSITION_REPAIR_INSTRUCTION } from "../services/recovery/legacy-continuation.js";
|
|
import * as controllerLeases from "../services/legacy-controller-lease.js";
|
|
import * as instructionWorkingCopies from "../services/agent-instruction-working-copies.js";
|
|
import * as runEvents from "../services/heartbeat-run-events.js";
|
|
import { waitForPendingRunFailureReports } from "../services/run-failure-report.js";
|
|
import { instanceSettingsService } from "../services/instance-settings.js";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { recordLegacyWorkspaceRestoreFailure, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
|
|
import { issueService } from "../services/issues.js";
|
|
import { getExecutionBlocker } from "../services/execution-blocker.js";
|
|
import { executionProjectionForRun } from "../services/execution-projection.js";
|
|
import { JsonRpcCallError } from "@paperclipai/plugin-sdk";
|
|
import { leaseFaultError } from "../services/environment-lease-fault-injection.js";
|
|
import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js";
|
|
import { requestTaskRetry } from "../services/task-retry.js";
|
|
import { adapterExecutionControls, createAdapterExecutionControl } from "../services/adapter-execution-control.js";
|
|
import { execFileSync, spawn, spawnSync, type ChildProcess } from "node:child_process";
|
|
import { currentControllerProcessStamp } from "../services/controller-process-identity.js";
|
|
import { registerControllerInstanceDb, resetControllerInstanceLeaseForTests } from "../services/controller-instance-lease.js";
|
|
import { settleUnrecoverableExecutions } from "../services/execution-recovery-resolution.js";
|
|
import { createOwnershipReportState, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
|
|
import fs from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { and, eq, or, inArray, sql } from "drizzle-orm";
|
|
import {
|
|
afterAll,
|
|
afterEach,
|
|
beforeAll,
|
|
beforeEach,
|
|
describe,
|
|
expect,
|
|
it,
|
|
vi,
|
|
} from "vitest";
|
|
import {
|
|
activityLog,
|
|
agents,
|
|
controllerInstances,
|
|
agentTaskSessions,
|
|
agentRuntimeState,
|
|
agentWakeupRequests,
|
|
approvals,
|
|
authUsers,
|
|
budgetIncidents,
|
|
budgetPolicies,
|
|
budgetReservations,
|
|
chatActions,
|
|
chatConversations,
|
|
chatDeliveries,
|
|
chatEndpoints,
|
|
chatExternalPrincipals,
|
|
chatMessageLinks,
|
|
chatPublications,
|
|
companyMemberships,
|
|
companySecretBindings,
|
|
companySecrets,
|
|
companySkills,
|
|
companies,
|
|
completionContracts,
|
|
costEvents,
|
|
documentAnnotationAnchorSnapshots,
|
|
documentAnnotationComments,
|
|
documentAnnotationThreads,
|
|
createDb,
|
|
closeRegisteredClients,
|
|
documentRevisions,
|
|
documents,
|
|
environmentLeases,
|
|
environments,
|
|
executionWorkspaces,
|
|
heartbeatRunEvents,
|
|
heartbeatRuns,
|
|
issueComments,
|
|
issueQuestionResponseDeliveries,
|
|
issueApprovals,
|
|
issueDocuments,
|
|
issuePlanDecompositions,
|
|
issueRecoveryActions,
|
|
issueRelations,
|
|
issueThreadInteractions,
|
|
issueTreeHoldMembers,
|
|
issueTreeHolds,
|
|
issueWorkProducts,
|
|
issues,
|
|
nativeRunFinalizations,
|
|
nativeRunResults,
|
|
plugins,
|
|
projects,
|
|
projectWorkspaces,
|
|
statusDecisionEffects,
|
|
statusDecisions,
|
|
toolApplications,
|
|
toolConnections,
|
|
workAssessments,
|
|
workspaceOperations,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import type { EnvironmentLease } from "@paperclipai/shared";
|
|
import type { NativeExecutionInput } from "../vendor/paperclip-runner/index.js";
|
|
import { runningProcesses, type AdapterExecutionContext, type AdapterExecutionResult } from "../adapters/index.ts";
|
|
import {
|
|
resolveDefaultAgentWorkspaceDir,
|
|
resolvePaperclipInstanceRoot,
|
|
} from "../home-paths.js";
|
|
import { buildNativeExecutionInput } from "../services/native-runtime/native-execution-input.js";
|
|
import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js";
|
|
import { NativeRunnerOwnershipUnverifiedError } from "../services/native-runtime/native-runner-ownership.js";
|
|
import { nativeCompletionSource } from "../services/native-runtime/completion-contracts.js";
|
|
import { nativeCompletionFeedback } from "../services/native-runtime/native-completion-feedback.js";
|
|
import type { PrpStructuredRunResult } from "../vendor/paperclip-runner/index.js";
|
|
import { buildNativeModelEnvelope } from "@paperclipai/paperclip-runner";
|
|
import {
|
|
CHAT_CONTROL_RECOVERY_ADMISSION_KEY,
|
|
CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE,
|
|
chatControlRecoveryAdmission,
|
|
readChatControlRecoveryAdmission,
|
|
readChatControlRecoveryStop,
|
|
} from "../services/chat-control-recovery-stop.js";
|
|
import { prepareNativeHeartbeatRun } from "../services/native-runtime/prepare-native-run.js";
|
|
import {
|
|
hasCommittedNativeBoardResponseWait,
|
|
readNativeBoardResponseWaitOrigin,
|
|
readNativeBoardResponseWaitSource,
|
|
} from "../services/native-runtime/native-board-response-wait.js";
|
|
import {
|
|
commitNativeStatusDecision,
|
|
NativeStatusRaceError,
|
|
} from "../services/native-runtime/status-decision-committer.js";
|
|
const mockTelemetryClient = vi.hoisted(() => ({
|
|
track: vi.fn(),
|
|
hashPrivateRef: vi.fn(() => "test-private-reference"),
|
|
}));
|
|
const mockTrackAgentFirstHeartbeat = vi.hoisted(() => vi.fn());
|
|
const mockTerminateLocalService = vi.hoisted(() => vi.fn());
|
|
const mockDetachNativeSessionsForRestart = vi.hoisted(() => vi.fn());
|
|
const mockCloseIdleWarmNativeSessionsForRestart = vi.hoisted(() => vi.fn());
|
|
const mockRetainedNativeCleanup = vi.hoisted(() =>
|
|
vi.fn<
|
|
typeof import("../services/native-runtime/native-session-executor.js").reconcileRetainedNativeSessionCleanup
|
|
>(),
|
|
);
|
|
const mockExecutePaperclipNativeSession = vi.hoisted(() =>
|
|
vi.fn<
|
|
typeof import("../services/native-runtime/native-session-executor.js").executePaperclipNativeSession
|
|
>(),
|
|
);
|
|
const mockAdapterExecute = vi.hoisted(() =>
|
|
vi.fn(async (_input: AdapterExecutionContext): Promise<AdapterExecutionResult> => ({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Recovered stranded heartbeat work.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
})),
|
|
);
|
|
|
|
vi.mock("../telemetry.ts", () => ({
|
|
getTelemetryClient: () => mockTelemetryClient,
|
|
}));
|
|
|
|
const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
|
|
vi.mock("../sentry.ts", async () => {
|
|
const actual = await vi.importActual<typeof import("../sentry.ts")>("../sentry.ts");
|
|
return {
|
|
...actual,
|
|
captureRunFailure: mockCaptureRunFailure,
|
|
};
|
|
});
|
|
|
|
vi.mock("../services/native-runtime/native-session-executor.js", async () => {
|
|
const actual = await vi.importActual<
|
|
typeof import("../services/native-runtime/native-session-executor.js")
|
|
>("../services/native-runtime/native-session-executor.js");
|
|
mockRetainedNativeCleanup.mockImplementation(
|
|
actual.reconcileRetainedNativeSessionCleanup,
|
|
);
|
|
mockExecutePaperclipNativeSession.mockImplementation(
|
|
actual.executePaperclipNativeSession,
|
|
);
|
|
mockDetachNativeSessionsForRestart.mockImplementation(actual.detachNativeSessionsForRestart);
|
|
mockCloseIdleWarmNativeSessionsForRestart.mockImplementation(actual.closeIdleWarmNativeSessionsForRestart);
|
|
return {
|
|
...actual,
|
|
reconcileRetainedNativeSessionCleanup: mockRetainedNativeCleanup,
|
|
executePaperclipNativeSession: mockExecutePaperclipNativeSession,
|
|
detachNativeSessionsForRestart: mockDetachNativeSessionsForRestart,
|
|
closeIdleWarmNativeSessionsForRestart: mockCloseIdleWarmNativeSessionsForRestart,
|
|
};
|
|
});
|
|
|
|
vi.mock("../services/local-service-supervisor.js", async () => {
|
|
const actual = await vi.importActual<
|
|
typeof import("../services/local-service-supervisor.js")
|
|
>("../services/local-service-supervisor.js");
|
|
mockTerminateLocalService.mockImplementation(actual.terminateLocalService);
|
|
return {
|
|
...actual,
|
|
terminateLocalService: mockTerminateLocalService,
|
|
};
|
|
});
|
|
|
|
vi.mock("@paperclipai/shared/telemetry", async () => {
|
|
const actual = await vi.importActual<
|
|
typeof import("@paperclipai/shared/telemetry")
|
|
>("@paperclipai/shared/telemetry");
|
|
return {
|
|
...actual,
|
|
trackAgentFirstHeartbeat: mockTrackAgentFirstHeartbeat,
|
|
};
|
|
});
|
|
|
|
vi.mock("../adapters/index.ts", async () => {
|
|
const actual = await vi.importActual<typeof import("../adapters/index.ts")>(
|
|
"../adapters/index.ts",
|
|
);
|
|
return {
|
|
...actual,
|
|
getServerAdapter: vi.fn(() => ({
|
|
supportsLocalAgentJwt: false,
|
|
execute: mockAdapterExecute,
|
|
})),
|
|
};
|
|
});
|
|
|
|
import {
|
|
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
heartbeatService,
|
|
parseSandboxProviderPluginNotReadyFailureMessage,
|
|
redactDetectedSuccessfulRunProgressSummaryForBoard,
|
|
redactSuccessfulRunHandoffEvidence,
|
|
} from "../services/heartbeat.ts";
|
|
import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts";
|
|
import {
|
|
claimNativeRestartRecoveries,
|
|
currentNativeControllerIdentity,
|
|
} from "../services/native-runtime/native-restart-recovery.ts";
|
|
import { claimNativeSessionResumptions } from "../services/native-runtime/native-finalization-reconciler.ts";
|
|
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
|
|
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
|
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
|
|
import { createWakeQueue } from "../modules/wake-queue/index.js";
|
|
import { recordNativeAttentionAssessment } from "../services/native-runtime/work-assessments.js";
|
|
import { routeNativeAttention } from "../services/native-runtime/native-interaction-bridge.js";
|
|
import * as paperclipRunner from "../vendor/paperclip-runner/index.js";
|
|
import {
|
|
CONTROL_PLANE_CONFORMANCE_OPEN,
|
|
CONTROL_PLANE_CONFORMANCE_RESULT,
|
|
CONTROL_PLANE_CONFORMANCE_TERMINAL,
|
|
} from "../vendor/paperclip-runner/testing.js";
|
|
import { recoveryService } from "../services/recovery/service.ts";
|
|
import {
|
|
readHotRestartIntent,
|
|
readProcessStartedAt,
|
|
resolveLegacyHotRestartIntentPath,
|
|
resolveHotRestartReportPath,
|
|
writeHotRestartIntent,
|
|
} from "../services/hot-restart.ts";
|
|
import { secretService } from "../services/secrets.ts";
|
|
import {
|
|
SUCCESSFUL_RUN_HANDOFF_EXHAUSTED_NOTICE_BODY,
|
|
SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY,
|
|
SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
noticeMetadataReferencesRecoveryAction,
|
|
} from "../services/recovery/index.ts";
|
|
import { collectDispositionRepairSourceState } from "../services/recovery/disposition-repair.ts";
|
|
import {
|
|
UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON,
|
|
UNMANAGED_BACKGROUND_TASK_STOP_REASON,
|
|
} from "@paperclipai/adapter-utils/server-utils";
|
|
const externalTestDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL?.trim();
|
|
const embeddedPostgresSupport = externalTestDatabaseUrl
|
|
? { supported: true }
|
|
: await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported
|
|
? describe
|
|
: describe.skip;
|
|
|
|
if (!embeddedPostgresSupport.supported) {
|
|
console.warn(
|
|
`Skipping embedded Postgres heartbeat recovery tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
|
);
|
|
}
|
|
|
|
function commentMetadataRows(
|
|
comment: { metadata?: unknown } | null | undefined,
|
|
) {
|
|
const metadata = comment?.metadata as
|
|
{ sections?: Array<{ rows?: unknown[] }> } | null | undefined;
|
|
return (metadata?.sections ?? []).flatMap(
|
|
(section) => section.rows ?? [],
|
|
) as Array<Record<string, unknown>>;
|
|
}
|
|
|
|
function spawnAliveProcess() {
|
|
return spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
|
|
stdio: "ignore",
|
|
});
|
|
}
|
|
|
|
function isPidAlive(pid: number | null | undefined) {
|
|
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
|
|
return false;
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function waitForPidExit(pid: number, timeoutMs = 2_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
if (!isPidAlive(pid)) return true;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
return !isPidAlive(pid);
|
|
}
|
|
|
|
async function waitForRunToSettle(
|
|
heartbeat: ReturnType<typeof heartbeatService>,
|
|
runId: string,
|
|
timeoutMs = 3_000,
|
|
) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
const run = await heartbeat.getRun(runId);
|
|
if (!run || (run.status !== "queued" && run.status !== "running"))
|
|
return run;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
return heartbeat.getRun(runId);
|
|
}
|
|
|
|
async function waitForValue<T>(
|
|
read: () => Promise<T | null | undefined>,
|
|
timeoutMs = 3_000,
|
|
) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
let latest: T | null | undefined = null;
|
|
while (Date.now() < deadline) {
|
|
latest = await read();
|
|
if (latest) return latest;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
return latest ?? null;
|
|
}
|
|
|
|
async function waitForHeartbeatIdle(
|
|
db: ReturnType<typeof createDb>,
|
|
timeoutMs = 3_000,
|
|
) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
const runs = await db
|
|
.select({
|
|
status: heartbeatRuns.status,
|
|
})
|
|
.from(heartbeatRuns);
|
|
if (
|
|
!runs.some((run) => run.status === "queued" || run.status === "running")
|
|
) {
|
|
return;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
|
|
async function stopRegisteredProcessesForCleanup() {
|
|
await Promise.all([...runningProcesses.values()].map(async ({ child, processGroupId }) => {
|
|
if (child.exitCode !== null || child.signalCode !== null || typeof child.kill !== "function") return;
|
|
await new Promise<void>((resolve) => {
|
|
child.once("close", () => resolve());
|
|
try {
|
|
if (processGroupId) process.kill(-processGroupId, "SIGKILL");
|
|
else child.kill("SIGKILL");
|
|
} catch {
|
|
child.kill("SIGKILL");
|
|
}
|
|
});
|
|
}));
|
|
runningProcesses.clear();
|
|
}
|
|
|
|
async function cancelActiveRunsForCleanup(
|
|
db: ReturnType<typeof createDb>,
|
|
timeoutMs = 3_000,
|
|
) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
const activeRuns = await db
|
|
.select({
|
|
id: heartbeatRuns.id,
|
|
wakeupRequestId: heartbeatRuns.wakeupRequestId,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
or(
|
|
eq(heartbeatRuns.status, "queued"),
|
|
eq(heartbeatRuns.status, "running"),
|
|
),
|
|
);
|
|
|
|
if (activeRuns.length === 0) return;
|
|
|
|
const now = new Date();
|
|
const runIds = activeRuns.map((run) => run.id);
|
|
const wakeupRequestIds = activeRuns
|
|
.map((run) => run.wakeupRequestId)
|
|
.filter(
|
|
(value): value is string =>
|
|
typeof value === "string" && value.length > 0,
|
|
);
|
|
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "cancelled",
|
|
finishedAt: now,
|
|
updatedAt: now,
|
|
errorCode: "test_cleanup",
|
|
error: "Cancelled by heartbeat-process-recovery test cleanup",
|
|
processPid: null,
|
|
processGroupId: null,
|
|
})
|
|
.where(inArray(heartbeatRuns.id, runIds));
|
|
|
|
if (wakeupRequestIds.length > 0) {
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
status: "cancelled",
|
|
finishedAt: now,
|
|
error: "Cancelled by heartbeat-process-recovery test cleanup",
|
|
})
|
|
.where(inArray(agentWakeupRequests.id, wakeupRequestIds));
|
|
}
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
|
|
async function spawnOrphanedProcessGroup() {
|
|
const leader = spawn(
|
|
process.execPath,
|
|
[
|
|
"-e",
|
|
[
|
|
"const { spawn } = require('node:child_process');",
|
|
"const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });",
|
|
"process.stdout.write(String(child.pid));",
|
|
"setTimeout(() => process.exit(0), 25);",
|
|
].join(" "),
|
|
],
|
|
{
|
|
detached: true,
|
|
stdio: ["ignore", "pipe", "ignore"],
|
|
},
|
|
);
|
|
|
|
let stdout = "";
|
|
leader.stdout?.on("data", (chunk) => {
|
|
stdout += String(chunk);
|
|
});
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
leader.once("error", reject);
|
|
leader.once("exit", () => resolve());
|
|
});
|
|
|
|
const descendantPid = Number.parseInt(stdout.trim(), 10);
|
|
if (!Number.isInteger(descendantPid) || descendantPid <= 0) {
|
|
throw new Error(
|
|
`Failed to capture orphaned descendant pid from detached process group: ${stdout}`,
|
|
);
|
|
}
|
|
|
|
return {
|
|
processPid: leader.pid ?? null,
|
|
processGroupId: leader.pid ?? null,
|
|
descendantPid,
|
|
};
|
|
}
|
|
|
|
|
|
/** Failure retry accounting with every automatic failure retry already used. */
|
|
const spentFailureRetryAccounting = {
|
|
version: 1,
|
|
failureRetries: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS,
|
|
maxTurnContinuations: 0,
|
|
};
|
|
|
|
/** Spent failure budget and every server-restart continuation of the open
|
|
* window already used: a restart-ended run gets no further automatic run. */
|
|
const spentRestartRetryAccounting = () => ({
|
|
...spentFailureRetryAccounting,
|
|
serverRestarts: SERVER_RESTART_RETRY_MAX_ATTEMPTS,
|
|
serverRestartWindowStartedAt: new Date().toISOString(),
|
|
});
|
|
|
|
describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let tempDb: Awaited<
|
|
ReturnType<typeof startEmbeddedPostgresTestDatabase>
|
|
> | null = null;
|
|
const childProcesses = new Set<ChildProcess>();
|
|
const cleanupPids = new Set<number>();
|
|
|
|
async function seedRecoveryCompany(
|
|
companyId: string,
|
|
issuePrefix: (typeof companies.$inferInsert)["issuePrefix"],
|
|
) {
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix,
|
|
defaultResponsibleUserId: "responsible-user",
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
// The account created in beforeAll also needs an active membership for
|
|
// admission's current responsible-user authorization intersection.
|
|
await db.insert(companyMemberships).values({
|
|
companyId,
|
|
principalType: "user",
|
|
principalId: "responsible-user",
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
}
|
|
|
|
function recoveryAgentRow(
|
|
rowId: (typeof agents.$inferInsert)["id"],
|
|
companyId: (typeof agents.$inferInsert)["companyId"],
|
|
name: (typeof agents.$inferInsert)["name"],
|
|
role: (typeof agents.$inferInsert)["role"],
|
|
status: (typeof agents.$inferInsert)["status"],
|
|
): typeof agents.$inferInsert {
|
|
return {
|
|
id: rowId,
|
|
companyId,
|
|
name,
|
|
role,
|
|
status,
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
};
|
|
}
|
|
|
|
function selectRecoveryRunsByAgent(agentId: (typeof heartbeatRuns.$inferSelect)["agentId"]) {
|
|
return db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId));
|
|
}
|
|
|
|
function selectRecoveryIssueById(issueId: (typeof issues.$inferSelect)["id"]) {
|
|
return db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
}
|
|
|
|
function selectRecoveryCommentsForIssue(issueId: (typeof issueComments.$inferSelect)["issueId"]) {
|
|
return db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.issueId, issueId));
|
|
}
|
|
|
|
function selectRecoveryActionForIssue(
|
|
companyId: (typeof issueRecoveryActions.$inferSelect)["companyId"],
|
|
issueId: (typeof issueRecoveryActions.$inferSelect)["sourceIssueId"],
|
|
) {
|
|
return db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(
|
|
and(
|
|
eq(issueRecoveryActions.companyId, companyId),
|
|
eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
),
|
|
)
|
|
.then((rows) => rows[0] ?? null);
|
|
}
|
|
|
|
function selectStrandedRecoveryIssuesForCompany(companyId: (typeof issues.$inferSelect)["companyId"]) {
|
|
return db
|
|
.select()
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, companyId),
|
|
eq(issues.originKind, "stranded_issue_recovery"),
|
|
),
|
|
);
|
|
}
|
|
|
|
function selectRecoveryActionsForIssue(issueId: (typeof issueRecoveryActions.$inferSelect)["sourceIssueId"]) {
|
|
return db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
|
}
|
|
|
|
function selectRecoveryWakesByAgent(agentId: (typeof agentWakeupRequests.$inferSelect)["agentId"]) {
|
|
return db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.agentId, agentId));
|
|
}
|
|
|
|
function selectStrandedRecoveryIssuesForSource(
|
|
companyId: (typeof issues.$inferSelect)["companyId"],
|
|
issueId: string,
|
|
) {
|
|
return db
|
|
.select()
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, companyId),
|
|
eq(issues.originKind, "stranded_issue_recovery"),
|
|
eq(issues.originId, issueId),
|
|
),
|
|
);
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
if (externalTestDatabaseUrl) {
|
|
db = createDb(externalTestDatabaseUrl);
|
|
} else {
|
|
tempDb = await startEmbeddedPostgresTestDatabase(
|
|
"paperclip-heartbeat-recovery-",
|
|
);
|
|
db = createDb(tempDb.connectionString);
|
|
}
|
|
const now = new Date();
|
|
await db.insert(authUsers).values({
|
|
id: "responsible-user",
|
|
name: "Responsible User",
|
|
email: "responsible-user@example.test",
|
|
emailVerified: true,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
|
|
|
afterEach(async () => {
|
|
vi.clearAllMocks();
|
|
// A recovery policy can stop before adapter dispatch; do not leak an
|
|
// unused one-shot failure into the next test's otherwise healthy run.
|
|
mockAdapterExecute.mockReset();
|
|
const nativeExecutor = await vi.importActual<
|
|
typeof import("../services/native-runtime/native-session-executor.js")
|
|
>("../services/native-runtime/native-session-executor.js");
|
|
mockRetainedNativeCleanup
|
|
.mockReset()
|
|
.mockImplementation(nativeExecutor.reconcileRetainedNativeSessionCleanup);
|
|
const localServiceSupervisor = await vi.importActual<
|
|
typeof import("../services/local-service-supervisor.js")
|
|
>("../services/local-service-supervisor.js");
|
|
mockTerminateLocalService.mockImplementation(
|
|
localServiceSupervisor.terminateLocalService,
|
|
);
|
|
mockAdapterExecute.mockImplementation(async () => ({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Recovered stranded heartbeat work.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
}));
|
|
await stopRegisteredProcessesForCleanup();
|
|
for (const child of childProcesses) {
|
|
child.kill("SIGKILL");
|
|
}
|
|
childProcesses.clear();
|
|
for (const pid of cleanupPids) {
|
|
try {
|
|
process.kill(pid, "SIGKILL");
|
|
} catch {
|
|
// Ignore already-dead cleanup targets.
|
|
}
|
|
}
|
|
cleanupPids.clear();
|
|
await cancelActiveRunsForCleanup(db, 5_000);
|
|
let idlePolls = 0;
|
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
const runs = await db
|
|
.select({
|
|
status: heartbeatRuns.status,
|
|
processPid: heartbeatRuns.processPid,
|
|
processGroupId: heartbeatRuns.processGroupId,
|
|
})
|
|
.from(heartbeatRuns);
|
|
const managedExecutionStillActive = runs.some(
|
|
(run) =>
|
|
(run.status === "queued" || run.status === "running") &&
|
|
!run.processPid &&
|
|
!run.processGroupId,
|
|
);
|
|
if (!managedExecutionStillActive) {
|
|
idlePolls += 1;
|
|
if (idlePolls >= 3) break;
|
|
} else {
|
|
idlePolls = 0;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
await waitForHeartbeatIdle(db, 5_000);
|
|
// Terminal rows do not mean their background finalizers have returned.
|
|
// Drain tracked wakeups too: one can still create a run after the row poll.
|
|
await heartbeatService(db).drainActiveRunExecutions();
|
|
await db.delete(activityLog);
|
|
await db.delete(agentRuntimeState);
|
|
await db.delete(companySkills);
|
|
await db.delete(costEvents);
|
|
await db.delete(workspaceOperations);
|
|
await db.delete(environmentLeases);
|
|
await db.delete(environments);
|
|
await db.delete(plugins);
|
|
await db.delete(issuePlanDecompositions);
|
|
await db.delete(issueThreadInteractions);
|
|
await db.delete(chatMessageLinks);
|
|
await db.delete(chatPublications);
|
|
await db.delete(chatActions);
|
|
await db.delete(chatDeliveries);
|
|
await db.delete(chatConversations);
|
|
await db.delete(chatEndpoints);
|
|
await db.delete(toolConnections);
|
|
await db.delete(toolApplications);
|
|
await db.delete(documentAnnotationComments);
|
|
await db.delete(documentAnnotationAnchorSnapshots);
|
|
await db.delete(documentAnnotationThreads);
|
|
await db.delete(issueWorkProducts);
|
|
await db.delete(issueComments);
|
|
await db.delete(issueDocuments);
|
|
await db.delete(documentRevisions);
|
|
await db.delete(documents);
|
|
await db.delete(issueRelations);
|
|
await db.delete(issueRecoveryActions);
|
|
await db.delete(issueTreeHoldMembers);
|
|
await db.delete(issueTreeHolds);
|
|
await db.delete(agentTaskSessions);
|
|
await db.delete(issueApprovals);
|
|
await db.delete(budgetIncidents);
|
|
await db.delete(approvals);
|
|
await db.update(issues).set({ lastStatusDecisionId: null });
|
|
await db.delete(statusDecisionEffects);
|
|
await db.delete(nativeRunFinalizations);
|
|
await db.delete(statusDecisions);
|
|
await db.delete(workAssessments);
|
|
await db.delete(nativeRunResults);
|
|
await db.update(heartbeatRuns).set({ completionContractId: null });
|
|
await db.delete(completionContracts);
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
await db.delete(issueComments);
|
|
await db.delete(issueDocuments);
|
|
try {
|
|
await db.delete(issues);
|
|
break;
|
|
} catch (error) {
|
|
if (attempt === 4) throw error;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
await db.delete(activityLog);
|
|
await db.delete(heartbeatRunEvents);
|
|
try {
|
|
await db.delete(heartbeatRuns);
|
|
break;
|
|
} catch (error) {
|
|
if (attempt === 4) throw error;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
await db.delete(agentWakeupRequests);
|
|
await db.delete(budgetPolicies);
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
// A still-alive recovery child process can insert a new wakeup request
|
|
// or runtime-state row after the first delete. Re-clear both rows each
|
|
// attempt so a late insert cannot hold the agents foreign key.
|
|
await db.delete(agentWakeupRequests);
|
|
await db.delete(agentRuntimeState);
|
|
try {
|
|
await db.delete(agents);
|
|
break;
|
|
} catch (error) {
|
|
if (attempt === 4) throw error;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
await db.delete(companySkills);
|
|
await db.delete(workspaceOperations);
|
|
await db.delete(executionWorkspaces);
|
|
await db.delete(projectWorkspaces);
|
|
await db.delete(projects);
|
|
await db.delete(issuePlanDecompositions);
|
|
await db.delete(issueThreadInteractions);
|
|
await db.delete(documentAnnotationComments);
|
|
await db.delete(documentAnnotationAnchorSnapshots);
|
|
await db.delete(documentAnnotationThreads);
|
|
await db.delete(issueDocuments);
|
|
await db.delete(documentRevisions);
|
|
await db.delete(documents);
|
|
await db.delete(companySecretBindings);
|
|
await db.delete(companySecrets);
|
|
try {
|
|
await db.delete(companyMemberships);
|
|
await db.delete(companies);
|
|
break;
|
|
} catch (error) {
|
|
if (attempt === 4) throw error;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
});
|
|
|
|
afterAll(async () => {
|
|
for (const child of childProcesses) {
|
|
child.kill("SIGKILL");
|
|
}
|
|
childProcesses.clear();
|
|
for (const pid of cleanupPids) {
|
|
try {
|
|
process.kill(pid, "SIGKILL");
|
|
} catch {
|
|
// Ignore already-dead cleanup targets.
|
|
}
|
|
}
|
|
cleanupPids.clear();
|
|
await stopRegisteredProcessesForCleanup();
|
|
if (externalTestDatabaseUrl) {
|
|
await closeRegisteredClients(externalTestDatabaseUrl);
|
|
}
|
|
await tempDb?.cleanup();
|
|
});
|
|
|
|
async function seedRunFixture(input?: {
|
|
adapterType?: string;
|
|
agentStatus?: "paused" | "idle" | "running";
|
|
runStatus?: "running" | "queued" | "failed" | "interrupted" | "cancelled";
|
|
processPid?: number | null;
|
|
processGroupId?: number | null;
|
|
processLossRetryCount?: number;
|
|
failureRetryBudgetSpent?: boolean;
|
|
runtimeMode?: "legacy" | "native";
|
|
includeIssue?: boolean;
|
|
runErrorCode?: string | null;
|
|
runError?: string | null;
|
|
contextSnapshot?: Record<string, unknown>;
|
|
}) {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const runId = randomUUID();
|
|
const wakeupRequestId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const now = new Date("2026-03-19T00:00:00.000Z");
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: input?.agentStatus ?? "paused",
|
|
adapterType: input?.adapterType ?? "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeupRequestId,
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: input?.includeIssue === false ? {} : { issueId },
|
|
status: "claimed",
|
|
runId,
|
|
claimedAt: now,
|
|
});
|
|
|
|
if (input?.includeIssue !== false) {
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
title: "Recover local adapter after lost process",
|
|
status: "in_progress",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
});
|
|
}
|
|
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
status: input?.runStatus ?? "running",
|
|
wakeupRequestId,
|
|
contextSnapshot: {
|
|
...(input?.includeIssue === false
|
|
? (input?.contextSnapshot ?? {})
|
|
: { ...(input?.contextSnapshot ?? {}), issueId }),
|
|
...(input?.failureRetryBudgetSpent ? { executionRetryAccounting: spentFailureRetryAccounting } : {}),
|
|
},
|
|
processPid: input?.processPid ?? null,
|
|
processGroupId: input?.processGroupId ?? null,
|
|
processLossRetryCount: input?.processLossRetryCount ?? 0,
|
|
...(input?.runtimeMode ? { runtimeMode: input.runtimeMode } : {}),
|
|
errorCode: input?.runErrorCode ?? null,
|
|
error: input?.runError ?? null,
|
|
nextEventSeq: 2,
|
|
startedAt: now,
|
|
updatedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
});
|
|
|
|
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId,
|
|
seq: 1, eventType: "adapter.invoke", payload: { adapterType: input?.adapterType ?? "codex_local" } });
|
|
|
|
if (input?.includeIssue !== false) {
|
|
await db.update(issues).set({ checkoutRunId: runId, executionRunId: runId }).where(eq(issues.id, issueId));
|
|
}
|
|
|
|
return { companyId, agentId, runId, wakeupRequestId, issueId };
|
|
}
|
|
|
|
async function seedEnvironmentLeaseFixture(input: {
|
|
companyId: string;
|
|
runId: string;
|
|
issueId: string;
|
|
provider?: string;
|
|
driver?: string;
|
|
}) {
|
|
const environmentId = randomUUID();
|
|
const leaseId = randomUUID();
|
|
const now = new Date("2026-03-19T00:00:00.000Z");
|
|
|
|
await db.insert(environments).values({
|
|
id: environmentId,
|
|
name: "Local test environment",
|
|
driver: input.driver ?? "local",
|
|
status: "active",
|
|
config: {},
|
|
metadata: null,
|
|
});
|
|
|
|
await db.insert(environmentLeases).values({
|
|
id: leaseId,
|
|
companyId: input.companyId,
|
|
environmentId,
|
|
issueId: input.issueId,
|
|
heartbeatRunId: input.runId,
|
|
status: "active",
|
|
leasePolicy: "ephemeral",
|
|
provider: input.provider ?? "local",
|
|
providerLeaseId: null,
|
|
acquiredAt: now,
|
|
lastUsedAt: now,
|
|
metadata: {
|
|
driver: "local",
|
|
},
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
|
|
return { environmentId, leaseId };
|
|
}
|
|
|
|
it("does not reap active adapter executions started by another heartbeat service instance", async () => {
|
|
let releaseAdapter!: () => void;
|
|
const adapterRelease = new Promise<void>(resolve => { releaseAdapter = resolve; });
|
|
const adapterStarted = new Promise<void>((resolve) => {
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
resolve();
|
|
await adapterRelease;
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Remote run completed.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
});
|
|
});
|
|
|
|
const { runId, wakeupRequestId } = await seedRunFixture({
|
|
adapterType: "openclaw_gateway",
|
|
agentStatus: "idle",
|
|
runStatus: "queued",
|
|
processPid: null,
|
|
processGroupId: null,
|
|
includeIssue: false,
|
|
});
|
|
const executorHeartbeat = heartbeatService(db);
|
|
const reaperHeartbeat = heartbeatService(db);
|
|
|
|
try {
|
|
await executorHeartbeat.resumeQueuedRuns();
|
|
// Starting the run includes real runtime skill preparation for this
|
|
// fresh company, which alone takes several seconds. A fixed 3s budget
|
|
// raced that work, so wait for the adapter itself and fail fast only
|
|
// when the run settles without reaching it. The test timeout bounds a
|
|
// start that hangs.
|
|
let started = false;
|
|
void adapterStarted.then(() => { started = true; });
|
|
const settledBeforeStart = (async () => {
|
|
while (!started) {
|
|
const run = await executorHeartbeat.getRun(runId);
|
|
if (!run || (run.status !== "queued" && run.status !== "running")) {
|
|
throw new Error(
|
|
`Run settled as ${run?.status ?? "missing"} (${run?.errorCode ?? "no error code"}) before adapter execution started`,
|
|
);
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
})();
|
|
await Promise.race([adapterStarted, settledBeforeStart]);
|
|
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
updatedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const result = await reaperHeartbeat.reapOrphanedRuns({
|
|
staleThresholdMs: 1,
|
|
});
|
|
expect(result).toEqual({ reaped: 0, runIds: [] });
|
|
|
|
const activeRun = await reaperHeartbeat.getRun(runId);
|
|
expect(activeRun?.status).toBe("running");
|
|
expect(activeRun?.errorCode).toBeNull();
|
|
|
|
const wakeup = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(wakeup?.status).toBe("claimed");
|
|
|
|
releaseAdapter();
|
|
const settledRun = await waitForRunToSettle(
|
|
executorHeartbeat,
|
|
runId,
|
|
5_000,
|
|
);
|
|
expect(settledRun?.status).toBe("succeeded");
|
|
} finally {
|
|
releaseAdapter();
|
|
await executorHeartbeat.drainActiveRunExecutions();
|
|
}
|
|
// Start alone measures 3-6s locally, before the 5s settle wait.
|
|
}, 30_000);
|
|
|
|
async function seedStrandedIssueFixture(input: {
|
|
status: "todo" | "in_progress";
|
|
runStatus: "failed" | "timed_out" | "cancelled" | "succeeded";
|
|
retryReason?:
|
|
| "assignment_recovery"
|
|
| "issue_continuation_needed"
|
|
| "execution_review_participant_recovery"
|
|
| null;
|
|
runSource?: string | null;
|
|
assignToUser?: boolean;
|
|
activePauseHold?: boolean;
|
|
livenessState?:
|
|
| "completed"
|
|
| "advanced"
|
|
| "plan_only"
|
|
| "empty_response"
|
|
| "blocked"
|
|
| "failed"
|
|
| "needs_followup"
|
|
| null;
|
|
runErrorCode?: string | null;
|
|
runError?: string | null;
|
|
resultJson?: Record<string, unknown> | null;
|
|
monitorNextCheckAt?: Date | null;
|
|
}) {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const runId = randomUUID();
|
|
const wakeupRequestId = randomUUID();
|
|
const rootIssueId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const now = new Date("2026-03-19T00:00:00.000Z");
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
|
|
await db.insert(agents).values(recoveryAgentRow(agentId, companyId, "CodexCoder", "engineer", "idle"));
|
|
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeupRequestId,
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason:
|
|
input.retryReason === "assignment_recovery"
|
|
? "issue_assignment_recovery"
|
|
: "issue_assigned",
|
|
payload: { issueId },
|
|
status: input.runStatus === "cancelled" ? "cancelled" : "failed",
|
|
runId,
|
|
claimedAt: now,
|
|
finishedAt: new Date("2026-03-19T00:05:00.000Z"),
|
|
error:
|
|
input.runStatus === "succeeded"
|
|
? null
|
|
: "runError" in input
|
|
? input.runError
|
|
: "run failed before issue advanced",
|
|
});
|
|
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
status: input.runStatus,
|
|
wakeupRequestId,
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason:
|
|
input.retryReason === "assignment_recovery"
|
|
? "issue_assignment_recovery"
|
|
: (input.retryReason ?? "issue_assigned"),
|
|
...(input.retryReason ? { retryReason: input.retryReason } : {}),
|
|
...(input.runSource ? { source: input.runSource } : {}),
|
|
},
|
|
startedAt: now,
|
|
finishedAt: new Date("2026-03-19T00:05:00.000Z"),
|
|
updatedAt: new Date("2026-03-19T00:05:00.000Z"),
|
|
errorCode:
|
|
input.runStatus === "succeeded"
|
|
? null
|
|
: "runErrorCode" in input
|
|
? input.runErrorCode
|
|
: "process_lost",
|
|
error:
|
|
input.runStatus === "succeeded"
|
|
? null
|
|
: "runError" in input
|
|
? input.runError
|
|
: "run failed before issue advanced",
|
|
livenessState: input.livenessState ?? null,
|
|
// Graph-repair fixtures model failures before any provider work. Unknown
|
|
// execution outcomes are covered by the process-loss and adapter-failure cases.
|
|
resultJson: input.resultJson ?? {
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
});
|
|
|
|
await db.insert(issues).values([
|
|
...(input.activePauseHold
|
|
? [
|
|
{
|
|
id: rootIssueId,
|
|
companyId,
|
|
title: "Paused recovery root",
|
|
status: "todo",
|
|
priority: "medium",
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
},
|
|
]
|
|
: []),
|
|
{
|
|
id: issueId,
|
|
companyId,
|
|
parentId: input.activePauseHold ? rootIssueId : null,
|
|
title: "Recover stranded assigned work",
|
|
status: input.status,
|
|
priority: "medium",
|
|
assigneeAgentId: input.assignToUser ? null : agentId,
|
|
assigneeUserId: input.assignToUser ? "user-1" : null,
|
|
checkoutRunId: input.status === "in_progress" ? runId : null,
|
|
executionRunId: null,
|
|
monitorNextCheckAt: input.monitorNextCheckAt ?? null,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: input.activePauseHold ? 2 : 1,
|
|
identifier: `${issuePrefix}-${input.activePauseHold ? 2 : 1}`,
|
|
startedAt: input.status === "in_progress" ? now : null,
|
|
},
|
|
]);
|
|
|
|
if (input.activePauseHold) {
|
|
await db.insert(issueTreeHolds).values({
|
|
companyId,
|
|
rootIssueId,
|
|
mode: "pause",
|
|
status: "active",
|
|
reason: "pause recovery subtree",
|
|
releasePolicy: { strategy: "manual" },
|
|
});
|
|
}
|
|
|
|
return { companyId, agentId, runId, wakeupRequestId, issueId, rootIssueId };
|
|
}
|
|
|
|
async function bindChatConversation(input: {
|
|
agentId: string;
|
|
companyId: string;
|
|
issueId: string;
|
|
state: "active" | "waiting" | "completed";
|
|
}) {
|
|
const applicationId = randomUUID();
|
|
const connectionId = randomUUID();
|
|
const endpointId = randomUUID();
|
|
await db.insert(toolApplications).values({
|
|
id: applicationId,
|
|
companyId: input.companyId,
|
|
applicationKey: `chat:slack:${endpointId}`,
|
|
name: `Slack ${endpointId}`,
|
|
type: "chat",
|
|
status: "active",
|
|
});
|
|
await db.insert(toolConnections).values({
|
|
id: connectionId,
|
|
companyId: input.companyId,
|
|
applicationId,
|
|
name: "Slack channel",
|
|
uid: `chat-slack-${endpointId}`,
|
|
connectionPurpose: "channel",
|
|
transport: "chat_sdk",
|
|
status: "active",
|
|
enabled: true,
|
|
});
|
|
await db.insert(chatEndpoints).values({
|
|
id: endpointId,
|
|
companyId: input.companyId,
|
|
connectionId,
|
|
provider: "slack",
|
|
publicId: randomUUID(),
|
|
assignedAgentId: input.agentId,
|
|
status: "active",
|
|
});
|
|
const [conversation] = await db
|
|
.insert(chatConversations)
|
|
.values({
|
|
companyId: input.companyId,
|
|
endpointId,
|
|
issueId: input.issueId,
|
|
externalConversationId: `slack-conversation-${input.issueId}`,
|
|
externalThreadId: `slack:CCHATWAIT:${randomUUID()}`,
|
|
externalLabel: "Slack thread",
|
|
state: input.state,
|
|
})
|
|
.returning({ id: chatConversations.id });
|
|
return { endpointId, conversationId: conversation!.id };
|
|
}
|
|
|
|
async function seedInReviewParticipantRunFixture(input?: {
|
|
wakeReason?: string;
|
|
retryReason?: string | null;
|
|
}) {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const runId = randomUUID();
|
|
const wakeupRequestId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const stageId = randomUUID();
|
|
const now = new Date("2026-03-19T00:00:00.000Z");
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
const wakeReason = input?.wakeReason ?? "execution_review_requested";
|
|
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
|
|
await db.insert(agents).values(recoveryAgentRow(agentId, companyId, "CodexReviewer", "engineer", "idle"));
|
|
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeupRequestId,
|
|
companyId,
|
|
agentId,
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: wakeReason,
|
|
payload: {
|
|
issueId,
|
|
...(input?.retryReason ? { retryReason: input.retryReason } : {}),
|
|
},
|
|
status: "queued",
|
|
runId,
|
|
requestedAt: now,
|
|
updatedAt: now,
|
|
});
|
|
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "queued",
|
|
wakeupRequestId,
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason,
|
|
...(input?.retryReason ? { retryReason: input.retryReason } : {}),
|
|
},
|
|
updatedAt: now,
|
|
});
|
|
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
title: "Review participant stayed pending",
|
|
status: "in_review",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
assigneeUserId: null,
|
|
executionRunId: runId,
|
|
executionAgentNameKey: "codexreviewer",
|
|
executionLockedAt: now,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
executionState: {
|
|
status: "pending",
|
|
currentStageId: stageId,
|
|
currentStageIndex: 0,
|
|
currentStageType: "review",
|
|
currentParticipant: { type: "agent", agentId, userId: null },
|
|
returnAssignee: { type: "agent", agentId, userId: null },
|
|
reviewRequest: null,
|
|
completedStageIds: [],
|
|
lastDecisionId: null,
|
|
lastDecisionOutcome: null,
|
|
},
|
|
});
|
|
|
|
return { companyId, agentId, runId, wakeupRequestId, issueId, stageId };
|
|
}
|
|
|
|
async function seedAssignedTodoNoRunFixture(input?: {
|
|
agentStatus?: "paused" | "idle" | "running";
|
|
}) {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: input?.agentStatus ?? "idle",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
title: "Assigned todo work that never received a heartbeat",
|
|
status: "todo",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
assigneeUserId: null,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
});
|
|
|
|
return { companyId, agentId, issueId };
|
|
}
|
|
|
|
async function seedIdleTimerAgentFixture() {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
enabled: true,
|
|
intervalSec: 60,
|
|
wakeOnDemand: true,
|
|
skipTimerWhenNoActionableWork: true,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
|
|
return { companyId, agentId };
|
|
}
|
|
|
|
async function expectSourceScopedStrandedRecoveryAction(input: {
|
|
companyId: string;
|
|
agentId: string;
|
|
issueId: string;
|
|
runId: string;
|
|
previousStatus: "todo" | "in_progress" | "in_review";
|
|
retryReason?:
|
|
| "assignment_recovery"
|
|
| "issue_continuation_needed"
|
|
| "execution_review_participant_recovery"
|
|
| null;
|
|
cause?: string;
|
|
kind?: string;
|
|
previousOwnerAgentId?: string | null;
|
|
returnOwnerAgentId?: string | null;
|
|
}) {
|
|
const action = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(
|
|
and(
|
|
eq(issueRecoveryActions.companyId, input.companyId),
|
|
eq(issueRecoveryActions.sourceIssueId, input.issueId),
|
|
),
|
|
)
|
|
.then((rows) => rows[0] ?? null),
|
|
);
|
|
if (!action)
|
|
throw new Error(
|
|
"Expected source-scoped stranded recovery action to be created",
|
|
);
|
|
|
|
expect(action).toMatchObject({
|
|
companyId: input.companyId,
|
|
sourceIssueId: input.issueId,
|
|
recoveryIssueId: null,
|
|
kind: input.kind ?? "stranded_assigned_issue",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
previousOwnerAgentId: input.previousOwnerAgentId ?? input.agentId,
|
|
returnOwnerAgentId: input.returnOwnerAgentId ?? input.agentId,
|
|
cause: input.cause ?? "stranded_assigned_issue",
|
|
attemptCount: 1,
|
|
maxAttempts: null,
|
|
});
|
|
expect(action.evidence).toMatchObject({
|
|
sourceIssueId: input.issueId,
|
|
...(input.kind === "deliberate_wait_without_target" ? {} : { previousStatus: input.previousStatus, retryReason: input.retryReason ?? null }),
|
|
latestRunId: input.runId,
|
|
routingPolicy: "board_escalation_no_takeover_v1",
|
|
});
|
|
if (input.cause === "execution_review_participant_recovery") {
|
|
expect(action.nextAction).toContain("The reviewer did not finish the review");
|
|
} else if (input.cause === "process_lost") {
|
|
expect(action.nextAction).toContain("Press Retry to start it again from the saved work");
|
|
} else {
|
|
expect(action.nextAction).toContain(
|
|
input.kind === "deliberate_wait_without_target" ? "without saying what happens next" : input.kind === "missing_disposition"
|
|
? "without saying whether the task is done"
|
|
: "Press Retry to start it again from the saved work",
|
|
);
|
|
}
|
|
expect(action.nextAction).not.toMatch(/Board operator|inspect/i);
|
|
|
|
const recoveryIssues = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, input.companyId),
|
|
eq(issues.originKind, "stranded_issue_recovery"),
|
|
eq(issues.originId, input.issueId),
|
|
),
|
|
);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
|
|
const recoveryWakeups = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
sql`${agentWakeupRequests.payload} ->> 'recoveryActionId' = ${action.id}`,
|
|
);
|
|
expect(recoveryWakeups).toHaveLength(0);
|
|
await waitForHeartbeatIdle(db);
|
|
const sourceIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, input.issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(sourceIssue?.status).toBe("blocked");
|
|
|
|
return action;
|
|
}
|
|
|
|
async function sourceBlockerIssueIds(
|
|
companyId: string,
|
|
sourceIssueId: string,
|
|
) {
|
|
return db
|
|
.select({ blockerIssueId: issueRelations.issueId })
|
|
.from(issueRelations)
|
|
.where(
|
|
and(
|
|
eq(issueRelations.companyId, companyId),
|
|
eq(issueRelations.relatedIssueId, sourceIssueId),
|
|
eq(issueRelations.type, "blocks"),
|
|
),
|
|
)
|
|
.then((rows) => rows.map((row) => row.blockerIssueId));
|
|
}
|
|
|
|
async function seedQueuedIssueRunFixture() {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const runId = randomUUID();
|
|
const wakeupRequestId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const now = new Date("2026-03-19T00:00:00.000Z");
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 1,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeupRequestId,
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId },
|
|
status: "queued",
|
|
runId,
|
|
requestedAt: now,
|
|
updatedAt: now,
|
|
});
|
|
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
status: "queued",
|
|
wakeupRequestId,
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_assigned",
|
|
},
|
|
updatedAt: now,
|
|
createdAt: now,
|
|
});
|
|
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
title: "Retry transient Codex failure without blocking",
|
|
description:
|
|
"Verify the successful-run handoff and choose an honest disposition.",
|
|
status: "in_progress",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
checkoutRunId: runId,
|
|
executionRunId: runId,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
startedAt: now,
|
|
});
|
|
|
|
// Complete the circular issue/run fixture after both FK targets exist.
|
|
await db.update(heartbeatRuns)
|
|
.set({ scopeKind: "issue", issueId })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
return { companyId, agentId, runId, wakeupRequestId, issueId };
|
|
}
|
|
|
|
it.each(["owned", "forged"] as const)("keeps unresolved-ref recovery and reporting while persisting only owned diagnostics: %s", async provenance => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId } = await seedQueuedIssueRunFixture();
|
|
const repoRoot = await fs.mkdtemp(path.join(os.tmpdir(), "base-ref-heartbeat-"));
|
|
execFileSync("git", ["init", "-b", "master"], { cwd: repoRoot, stdio: "ignore" });
|
|
execFileSync("git", ["-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "--allow-empty", "-m", "Fixture"], { cwd: repoRoot, stdio: "ignore" });
|
|
const original = await workspaceRuntime.realizeExecutionWorkspace({
|
|
base: { baseCwd: repoRoot, source: "project_primary", projectId: null, workspaceId: null, repoUrl: null, repoRef: "absent-fixture" },
|
|
config: { workspaceStrategy: { type: "git_worktree" } },
|
|
issue: { id: issueId, identifier: "FIXTURE-1", title: "Fixture" }, agent: { id: agentId, companyId, name: "Fixture" },
|
|
}).catch(error => error);
|
|
expect(original).toBeInstanceOf(workspaceRuntime.UnresolvedWorkspaceBaseRefError);
|
|
const diagnostic = workspaceRuntime.readUnresolvedWorkspaceBaseRefDiagnostic(original);
|
|
expect(diagnostic).toMatchObject({ remoteLookup: "failed", fetch: "not_attempted" });
|
|
const error = provenance === "owned" ? original : Object.assign(new workspaceRuntime.UnresolvedWorkspaceBaseRefError({
|
|
requestedRef: "absent-fixture", recoveryIdentityRef: "origin/absent-fixture", attemptedRefs: ["origin/absent-fixture"],
|
|
}), { baseRefDiagnostic: diagnostic });
|
|
const realize = vi.spyOn(workspaceRuntime, "realizeExecutionWorkspace").mockRejectedValueOnce(error);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await waitForPendingRunFailureReports();
|
|
expect(realize).toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
const failed = await heartbeat.getRun(runId);
|
|
expect(failed).toMatchObject({ status: "failed", errorCode: "configuration_incomplete", resultJson: {
|
|
configurationIncomplete: { reason: "workspace_base_ref_unresolved" },
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
} });
|
|
if (provenance === "owned") expect(failed?.resultJson?.configurationIncomplete).toHaveProperty("baseRefDiagnostic", diagnostic);
|
|
else expect(failed?.resultJson?.configurationIncomplete).not.toHaveProperty("baseRefDiagnostic");
|
|
expect(mockCaptureRunFailure).toHaveBeenCalledWith(expect.objectContaining({ runId, errorCode: "configuration_incomplete" }));
|
|
const captured = mockCaptureRunFailure.mock.calls.find(([entry]) => entry.runId === runId)?.[0];
|
|
if (provenance === "owned") expect(captured?.diagnostics.execution).toMatchObject({ workspaceBaseRefRemoteLookup: "failed", workspaceBaseRefFetch: "not_attempted" });
|
|
else expect(captured?.diagnostics.execution).not.toHaveProperty("workspaceBaseRefFetch");
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(issue).toMatchObject({ status: "blocked", executionRunId: null });
|
|
const [action] = await selectRecoveryActionsForIssue(issueId);
|
|
expect(action).toMatchObject({ status: "active", kind: "configuration_validation", ownerType: "board" });
|
|
const [wakeup] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
expect(wakeup.status).toBe("failed");
|
|
} finally { realize.mockRestore(); await fs.rm(repoRoot, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it("keeps a repair notice on the latest run when an unresolved branch fails twice", async () => {
|
|
const { agentId, issueId, runId } = await seedQueuedIssueRunFixture();
|
|
const error = new workspaceRuntime.UnresolvedWorkspaceBaseRefError({
|
|
requestedRef: "main", recoveryIdentityRef: "origin/main", attemptedRefs: ["origin/main"], defaultBranch: "master",
|
|
});
|
|
const realize = vi.spyOn(workspaceRuntime, "realizeExecutionWorkspace").mockRejectedValue(error);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
const [firstAction] = await selectRecoveryActionsForIssue(issueId);
|
|
const next = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual",
|
|
reason: "retry_failed_run", failedRunId: runId, payload: { issueId }, contextSnapshot: { issueId },
|
|
requestedByActorType: "user", requestedByActorId: "responsible-user" });
|
|
expect(next).toHaveProperty("id");
|
|
await waitForRunToSettle(heartbeat, next!.id, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(next!.id);
|
|
const actions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(actions).toHaveLength(1);
|
|
expect(actions[0]).toMatchObject({ id: firstAction.id, status: "active", evidence: { latestRunId: next!.id } });
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments.filter(c => c.authorType === "system" && c.metadata?.sourceRunId === next!.id)).toHaveLength(1);
|
|
expect(comments.filter(c => c.authorType === "system" && c.metadata?.sourceRunId === runId)).toHaveLength(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
} finally { realize.mockRestore(); }
|
|
});
|
|
|
|
it.each(["missing_default", "credential_not_shared", "database_error", "unmarked_http_error", "unmarked_forbidden", "provider_error"] as const)(
|
|
"preserves AI configuration recovery and reports only unexpected causes: %s", async (cause) => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId } = await seedQueuedIssueRunFixture();
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" }).onConflictDoNothing();
|
|
await db.update(agents).set({ runtimeConfig: {
|
|
heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 },
|
|
aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" },
|
|
} }).where(eq(agents.id, agentId));
|
|
const prepare = vi.spyOn(aiConnectionRuntime, "prepareManagedAiRuntime");
|
|
if (cause !== "missing_default") prepare.mockRejectedValueOnce(
|
|
cause === "credential_not_shared"
|
|
? aiConnectionCredentialNotSharedFailure()
|
|
: cause === "unmarked_forbidden"
|
|
? forbidden("This credential is not shared with the responsible user", { code: "ai_connection_credential_not_shared" })
|
|
: cause === "unmarked_http_error"
|
|
? unprocessable("Connect an account and choose your personal default", { code: "ai_connection_default_missing" })
|
|
: new Error(cause),
|
|
);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await waitForPendingRunFailureReports();
|
|
expect(prepare).toHaveBeenCalled();
|
|
const failed = await heartbeat.getRun(runId);
|
|
expect(failed).toMatchObject({ status: "failed", errorCode: "configuration_incomplete",
|
|
resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable" }, executionRecovery: { kind: "bootstrap", providerWorkStarted: false } },
|
|
});
|
|
if (cause === "missing_default" || cause === "credential_not_shared") {
|
|
expect(failed?.error).toBe(cause === "missing_default"
|
|
? "Connect an account and choose your personal default"
|
|
: "This credential is not shared with the responsible user");
|
|
expect(failed?.resultJson?.configurationIncomplete).toMatchObject({ selectionFailure: cause === "missing_default"
|
|
? "ai_connection_default_missing" : "ai_connection_credential_not_shared" });
|
|
expect(mockCaptureRunFailure).not.toHaveBeenCalled();
|
|
} else {
|
|
expect(failed?.resultJson?.configurationIncomplete).not.toHaveProperty("selectionFailure");
|
|
expect(mockCaptureRunFailure).toHaveBeenCalledWith(expect.objectContaining({ runId, errorCode: "configuration_incomplete" }));
|
|
}
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(issue).toMatchObject({ status: "blocked", executionRunId: null });
|
|
const [action] = await selectRecoveryActionsForIssue(issueId);
|
|
expect(action).toMatchObject({ status: "active", kind: "configuration_validation", cause: "configuration_incomplete", ownerType: "board" });
|
|
const [wakeup] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
expect(wakeup.status).toBe("failed");
|
|
} finally {
|
|
prepare.mockRestore();
|
|
await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId));
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(["timeout", "upstream", "cleanup_pending", "cleanup_pending_edited", "cleanup_pending_exhausted", "edited", "exhausted", "new_message", "no_claim", "reassigned", "superseded", "stopped"])(
|
|
"settles explicit retry admission through real executor cleanup: %s", async scenario => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const sourceRunId = randomUUID(), commentId = randomUUID(), nextCommentId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId, status: "failed",
|
|
createdAt: new Date("2020-01-01T00:00:00Z"), finishedAt: new Date("2020-01-01T00:00:01Z"),
|
|
contextSnapshot: { issueId } });
|
|
const [comment] = await db.insert(issueComments).values({ id: commentId, companyId, issueId,
|
|
authorType: "user", authorUserId: "responsible-user", body: "Continue the task." }).returning();
|
|
await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId,
|
|
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", fingerprint: sourceRunId,
|
|
status: "resolved", outcome: "cancelled", nextAction: "User continued.", evidence: { explicitUserContinuation: {
|
|
runId, previousRunId: sourceRunId, commentId, actorId: "responsible-user", recordedAt: new Date().toISOString(),
|
|
commentUpdatedAt: comment!.updatedAt.toISOString(), commentBodyHash: createHash("sha256").update(comment!.body).digest("hex"),
|
|
} } });
|
|
await db.update(heartbeatRuns).set({ createdAt: new Date(), contextSnapshot: {
|
|
issueId, taskId: issueId, wakeReason: "issue_commented", wakeCommentId: commentId,
|
|
previousRunId: sourceRunId, explicitUserContinuation: { previousRunId: sourceRunId, commentId },
|
|
} }).where(eq(heartbeatRuns.id, runId));
|
|
const identity = { id: randomUUID(), companyId, heartbeatRunId: runId, provider: "daytona", providerLeaseId: "fixture-explicit-sandbox" };
|
|
const supersedingRunId = randomUUID();
|
|
let heartbeat: ReturnType<typeof heartbeatService>;
|
|
let cancellation: ReturnType<typeof heartbeat.cancelRun> | undefined;
|
|
let cleanupObserved = false;
|
|
let cleanupPending = scenario.startsWith("cleanup_pending");
|
|
const originalFactory = environmentOrchestrator.environmentRunOrchestrator;
|
|
const release = vi.fn(async () => {
|
|
const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, identity.id));
|
|
if (!lease) return { released: [], errors: [] };
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
|
if (!cleanupObserved) {
|
|
cleanupObserved = true;
|
|
const denied = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId),
|
|
eq(heartbeatRunEvents.message, "The automatic retry could not revalidate the original user continuation.")));
|
|
// Upstream failure first tries the direct scheduler, then the release
|
|
// tail. Both must defer admission until the executor releases ownership.
|
|
if (scenario === "upstream") expect(denied.length).toBeGreaterThanOrEqual(2);
|
|
if (scenario === "timeout") expect(denied.length).toBeGreaterThanOrEqual(1);
|
|
if (scenario === "new_message") {
|
|
await db.insert(issueComments).values({ id: nextCommentId, companyId, issueId, authorType: "user",
|
|
authorUserId: "responsible-user", body: "Use these new instructions." });
|
|
await heartbeat.wakeup(agentId, { source: "automation", reason: "issue_commented",
|
|
requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
payload: { issueId, commentId: nextCommentId },
|
|
contextSnapshot: { issueId, commentId: nextCommentId, wakeReason: "issue_commented" } });
|
|
}
|
|
if (scenario === "reassigned") {
|
|
const [other] = await db.insert(agents).values({ companyId, name: "New assignee", role: "engineer",
|
|
adapterType: "codex_local" }).returning();
|
|
await db.update(issues).set({ assigneeAgentId: other!.id }).where(eq(issues.id, issueId));
|
|
}
|
|
if (scenario === "superseded") {
|
|
await db.insert(heartbeatRuns).values({ id: supersedingRunId, companyId, agentId, status: "running",
|
|
contextSnapshot: { issueId } });
|
|
await db.update(issues).set({ executionRunId: supersedingRunId }).where(eq(issues.id, issueId));
|
|
}
|
|
}
|
|
await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date() })
|
|
.where(and(eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId),
|
|
eq(environmentLeases.provider, "local")));
|
|
await db.update(environmentLeases).set(cleanupPending
|
|
? { status: "pending_cleanup", cleanupStatus: "failed", releasedAt: new Date() }
|
|
: { status: "released", cleanupStatus: "success", releasedAt: new Date(), metadata: {
|
|
remoteExecutionTermination: remoteTerminationReceipt(identity, { providerLeaseId: identity.providerLeaseId, state: "destroyed" }),
|
|
} }).where(eq(environmentLeases.id, identity.id));
|
|
return { released: [], errors: [] };
|
|
});
|
|
const factory = vi.spyOn(environmentOrchestrator, "environmentRunOrchestrator").mockImplementation((...args) => ({
|
|
...originalFactory(...args), releaseForRun: release,
|
|
}));
|
|
heartbeat = heartbeatService(db);
|
|
mockAdapterExecute.mockImplementationOnce(async (input?: unknown) => {
|
|
const invocation = input as { onCancellationReady: () => Promise<void>; onDispatch: () => void };
|
|
await invocation.onCancellationReady();
|
|
invocation.onDispatch();
|
|
expect(adapterExecutionControls.has(runId)).toBe(true);
|
|
await db.insert(environmentLeases).values({ ...identity, status: "active", leasePolicy: "ephemeral" });
|
|
if (scenario === "edited") await db.update(issueComments).set({ body: "Changed after dispatch" }).where(eq(issueComments.id, commentId));
|
|
if (scenario === "no_claim") await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, issueId));
|
|
if (scenario === "exhausted") await db.update(heartbeatRuns).set({ scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure" }).where(eq(heartbeatRuns.id, runId));
|
|
if (scenario === "stopped") {
|
|
cancellation = heartbeat.cancelRun(runId, "Operator Stop");
|
|
void cancellation.catch(() => undefined);
|
|
await waitForValue(async () => adapterExecutionControls.get(runId)?.controller.signal.aborted);
|
|
}
|
|
return { exitCode: 1, signal: scenario === "stopped" ? "SIGTERM" : null,
|
|
timedOut: scenario !== "upstream" && scenario !== "stopped",
|
|
errorMessage: scenario === "upstream" ? "Upstream temporarily unavailable" : "Execution timed out",
|
|
errorCode: scenario === "upstream" ? "upstream_unavailable" : "timeout",
|
|
resultJson: scenario === "upstream" ? { errorFamily: "transient_upstream" }
|
|
: scenario === "stopped" ? { executionCancellation: { state: "acknowledged" } } : {},
|
|
summary: "Stopped turn", provider: "test", model: "test-model" };
|
|
});
|
|
mockAdapterExecute.mockImplementation(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, errorMessage: null,
|
|
summary: "New message handled.", provider: "test", model: "test-model" };
|
|
});
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
if (cancellation) expect((await cancellation)?.status).toBe("cancelled");
|
|
expect(release).toHaveBeenCalled();
|
|
expect(adapterExecutionControls.has(runId)).toBe(false);
|
|
const children = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
const receipts = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
eq(issueRecoveryActions.cause, "explicit_user_continuation_retry")));
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
if (scenario === "timeout" || scenario === "upstream") {
|
|
expect(children).toHaveLength(1);
|
|
expect(receipts).toHaveLength(1);
|
|
expect(task!.executionRunId).toBe(children[0]!.id);
|
|
await expect(executionContinuation.buildExecutionContinuation({ db, companyId, issueId, agentId,
|
|
runId: children[0]!.id, context: children[0]!.contextSnapshot!, summary: null, exposeLowTrustRaw: false }))
|
|
.resolves.toMatchObject({ interruptedRunId: runId });
|
|
expect(await heartbeat.scheduleBoundedRetry(runId)).toMatchObject({ outcome: "scheduled", run: { id: children[0]!.id } });
|
|
} else {
|
|
expect(children).toHaveLength(0);
|
|
expect(receipts).toHaveLength(0);
|
|
expect(task!.executionRunId).toBe(cleanupPending ? runId : scenario === "superseded" ? supersedingRunId : null);
|
|
}
|
|
if (scenario === "new_message") expect(await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), sql`${heartbeatRuns.contextSnapshot}->>'wakeCommentId' = ${nextCommentId}`)))
|
|
.toHaveLength(1);
|
|
if (cleanupPending) {
|
|
if (scenario === "cleanup_pending") {
|
|
const svc = issueService(db);
|
|
const [other] = await db.insert(agents).values({ companyId, name: "Other worker", role: "engineer",
|
|
adapterType: "codex_local" }).returning();
|
|
const actorRunId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: actorRunId, companyId, agentId, status: "running", contextSnapshot: {} });
|
|
// Neither a rejected checkout nor stale checkout adoption may erase
|
|
// the exact pending retry claim, including mixed checkout owners.
|
|
for (const checkoutRunId of [null, runId, sourceRunId]) {
|
|
await db.update(issues).set({ checkoutRunId }).where(eq(issues.id, issueId));
|
|
expect(await svc.clearExecutionRunIfTerminal(issueId)).toBe(false);
|
|
expect(await svc.clearCheckoutRunIfTerminal(issueId)).toBe(false);
|
|
await expect(svc.checkout(issueId, other!.id, ["in_progress"], actorRunId)).rejects.toMatchObject({ status: 409 });
|
|
await expect(svc.assertCheckoutOwner(issueId, other!.id, actorRunId)).rejects.toMatchObject({ status: 409 });
|
|
await expect(svc.checkout(issueId, agentId, ["in_progress"], actorRunId)).rejects.toMatchObject({ status: 409 });
|
|
await expect(svc.assertCheckoutOwner(issueId, agentId, actorRunId)).rejects.toMatchObject({ status: 409 });
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.executionRunId).toBe(runId);
|
|
}
|
|
await db.update(issues).set({ checkoutRunId: null }).where(eq(issues.id, issueId));
|
|
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, actorRunId));
|
|
}
|
|
await heartbeat.sweepStaleIssueLocks();
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.executionRunId).toBe(runId);
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
|
expect(await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
eq(issueRecoveryActions.cause, "explicit_user_continuation_retry")))).toHaveLength(0);
|
|
if (scenario === "cleanup_pending_edited") await db.update(issueComments).set({ body: "Changed while cleanup waited" })
|
|
.where(eq(issueComments.id, commentId));
|
|
if (scenario === "cleanup_pending_exhausted") await db.update(heartbeatRuns).set({ scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure" }).where(eq(heartbeatRuns.id, runId));
|
|
cleanupPending = false;
|
|
await heartbeat.releaseEnvironmentLeasesForRun({ runId, companyId, agentId, status: "timed_out" });
|
|
await heartbeat.sweepStaleIssueLocks();
|
|
await heartbeat.sweepStaleIssueLocks();
|
|
const afterCleanup = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(afterCleanup).toHaveLength(scenario === "cleanup_pending" ? 1 : 0);
|
|
expect(await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
eq(issueRecoveryActions.cause, "explicit_user_continuation_retry")))).toHaveLength(afterCleanup.length);
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.executionRunId).toBe(afterCleanup[0]?.id ?? null);
|
|
}
|
|
} finally { factory.mockRestore(); }
|
|
},
|
|
);
|
|
|
|
it("does not reuse a completed explicit turn's receipt for a missing-comment follow-up", async () => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const sourceRunId = randomUUID(), commentId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId, status: "failed",
|
|
finishedAt: new Date(), contextSnapshot: { issueId } });
|
|
await db.insert(issueComments).values({ id: commentId, companyId, issueId,
|
|
authorType: "user", authorUserId: "responsible-user", body: "Continue the task." });
|
|
await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId,
|
|
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", fingerprint: sourceRunId,
|
|
status: "resolved", outcome: "cancelled", nextAction: "User continued.",
|
|
evidence: { explicitUserContinuation: { runId, previousRunId: sourceRunId, commentId,
|
|
actorId: "responsible-user", recordedAt: new Date().toISOString() } } });
|
|
await db.update(heartbeatRuns).set({ contextSnapshot: {
|
|
issueId, taskId: issueId, wakeReason: "issue_assigned",
|
|
explicitUserContinuation: { previousRunId: sourceRunId, commentId },
|
|
} }).where(eq(heartbeatRuns.id, runId));
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, errorMessage: null,
|
|
summary: "Task completed.", provider: "test", model: "test-model" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "succeeded", issueCommentStatus: "not_applicable" });
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
|
expect(await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
|
|
eq(agentWakeupRequests.reason, "missing_issue_comment")))).toHaveLength(0);
|
|
});
|
|
|
|
it("persists the normalized failure without permanently blocking the conversation", async () => {
|
|
mockAdapterExecute.mockResolvedValueOnce({
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
provider: "test",
|
|
model: "test-model",
|
|
});
|
|
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
const run = await heartbeat.getRun(runId);
|
|
const runtime = await db
|
|
.select({ lastError: agentRuntimeState.lastError })
|
|
.from(agentRuntimeState)
|
|
.where(eq(agentRuntimeState.agentId, agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
const recoveryRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
expect(run).toMatchObject({ status: "failed", error: "Adapter failed" });
|
|
expect(runtime?.lastError).toBe("Adapter failed");
|
|
expect(recoveryRun).toMatchObject({ retryOfRunId: runId, scheduledRetryAttempt: 1 });
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
const missingCommentWakeups = await db
|
|
.select({ id: agentWakeupRequests.id })
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
eq(agentWakeupRequests.reason, "missing_issue_comment"),
|
|
),
|
|
);
|
|
expect(missingCommentWakeups).toHaveLength(0);
|
|
});
|
|
|
|
it.each([
|
|
"continuation_task_ownership_changed",
|
|
] as const)("cancels obsolete continuation setup: %s", async (code) => {
|
|
const { agentId, runId, wakeupRequestId } = await seedQueuedIssueRunFixture();
|
|
const build = vi.spyOn(executionContinuation, "buildExecutionContinuation")
|
|
.mockRejectedValueOnce(new executionContinuation.StaleExecutionContinuationError(code));
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
expect(build).toHaveBeenCalled();
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "cancelled", errorCode: code });
|
|
const [wakeup] = await db.select().from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
expect(wakeup.status).toBe("cancelled");
|
|
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
|
|
expect(agent.status).not.toBe("error");
|
|
expect(mockAdapterExecute.mock.calls.some(
|
|
([input]) => (input as { runId?: string } | undefined)?.runId === runId,
|
|
)).toBe(false);
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
} finally {
|
|
build.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
"continuation_source_context_missing",
|
|
"continuation_user_authorization_missing",
|
|
"continuation_task_ownership_changed",
|
|
])("retains untyped continuation setup failures: %s", async (message) => {
|
|
const { runId, wakeupRequestId } = await seedQueuedIssueRunFixture();
|
|
const error = new Error(message, { cause: Object.assign(new Error("upstream setup failed"), { code: "ECONNRESET" }) });
|
|
const build = vi.spyOn(executionContinuation, "buildExecutionContinuation")
|
|
.mockRejectedValueOnce(error);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
expect(build).toHaveBeenCalled();
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "failed", errorCode: "setup_failed", error: message,
|
|
});
|
|
const report = await waitForValue(async () => mockCaptureRunFailure.mock.calls.find(([event]) => event.runId === runId)?.[0]);
|
|
expect(report?.diagnostics).toMatchObject({
|
|
execution: { failurePhase: "setup" },
|
|
exceptions: [{ message, stack: expect.stringContaining("heartbeat-process-recovery.test.ts") }, { code: "ECONNRESET" }],
|
|
});
|
|
const [wakeup] = await db.select().from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
expect(wakeup.status).toBe("failed");
|
|
expect(mockAdapterExecute.mock.calls.some(
|
|
([input]) => (input as { runId?: string } | undefined)?.runId === runId,
|
|
)).toBe(false);
|
|
} finally {
|
|
build.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("does not immediately continue a low-trust preflight setup failure", async () => {
|
|
const { agentId, runId, issueId, companyId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const reviewPreset = {
|
|
id: "low_trust_review",
|
|
version: 1,
|
|
rawOutputDisposition: "quarantine",
|
|
} as const;
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
sourceTrust: {
|
|
preset: "low_trust_review",
|
|
disposition: "quarantined",
|
|
sourceIssueId: issueId,
|
|
},
|
|
executionPolicy: {
|
|
mode: "normal",
|
|
commentRequired: true,
|
|
stages: [],
|
|
reviewPreset,
|
|
authorizationPolicy: {
|
|
trustPreset: "low_trust_review",
|
|
reviewPreset,
|
|
trustBoundary: {
|
|
mode: "low_trust_review",
|
|
companyId,
|
|
rootIssueId: issueId,
|
|
issueIds: [issueId],
|
|
allowedAgentIds: [agentId],
|
|
allowedToolClasses: ["git.read", "github.pr.read", "tests.local"],
|
|
},
|
|
},
|
|
},
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "low_trust_isolation_unavailable",
|
|
});
|
|
expect(
|
|
mockAdapterExecute.mock.calls.some(
|
|
([input]) => (input as { runId?: string } | undefined)?.runId === runId,
|
|
),
|
|
).toBe(false);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]?.status),
|
|
).toBe("blocked");
|
|
await expect(
|
|
db
|
|
.select({ status: agents.status, errorReason: agents.errorReason })
|
|
.from(agents)
|
|
.where(eq(agents.id, agentId))
|
|
.then((rows) => rows[0] ?? null),
|
|
).resolves.toEqual({ status: "idle", errorReason: null });
|
|
});
|
|
|
|
it("retries a continuation whose controller lease is lost before dispatch instead of blocking the issue", async () => {
|
|
const { agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const originalWatch = controllerLeases.watchLegacyControllerLease;
|
|
// Expire the claimed lease before workspace preparation renews it, so the
|
|
// real renewal is rejected and the watchdog stops setup before dispatch.
|
|
const watcher = vi.spyOn(controllerLeases, "watchLegacyControllerLease").mockImplementation((...args) => {
|
|
const lease = originalWatch(...args);
|
|
if (args[1].id !== runId) return lease;
|
|
return { ...lease, async assertOwned(stage?: "dispatching") {
|
|
if (stage === undefined) {
|
|
await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() - 60_000) })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
}
|
|
return lease.assertOwned(stage);
|
|
} };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "controller_lease_lost",
|
|
resultJson: {
|
|
cancellation: { source: "controller_lease", reason: "Legacy controller lease lost (renewal_rejected)" },
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
});
|
|
expect(
|
|
mockAdapterExecute.mock.calls.some(
|
|
([input]) => (input as { runId?: string } | undefined)?.runId === runId,
|
|
),
|
|
).toBe(false);
|
|
const retries = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(retries).toHaveLength(1);
|
|
// One bounded transient retry, instead of escalating `setup_failed`.
|
|
expect(retries[0]).toMatchObject({ scheduledRetryReason: "transient_failure", scheduledRetryAttempt: 1 });
|
|
expect(
|
|
await db.select({ status: issues.status }).from(issues).where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]?.status),
|
|
).toBe("in_progress");
|
|
expect(
|
|
await db.select({ status: agents.status }).from(agents).where(eq(agents.id, agentId))
|
|
.then((rows) => rows[0]?.status),
|
|
).not.toBe("error");
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions().catch(() => undefined);
|
|
watcher.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("retries an accepted interaction continuation whose controller lease is lost before dispatch", async () => {
|
|
const { companyId, agentId, runId, wakeupRequestId, issueId } = await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: { type: "issue_document", issueId, key: "plan", revisionId: randomUUID() },
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
const interactionContext = {
|
|
issueId,
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
mutation: "interaction",
|
|
};
|
|
await db.update(agentWakeupRequests)
|
|
.set({ source: "automation", reason: "issue_commented", payload: interactionContext })
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db.update(heartbeatRuns)
|
|
.set({
|
|
invocationSource: "automation",
|
|
contextSnapshot: { ...interactionContext, taskId: issueId, wakeReason: "issue_commented" },
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, issueId));
|
|
|
|
const originalWatch = controllerLeases.watchLegacyControllerLease;
|
|
const watcher = vi.spyOn(controllerLeases, "watchLegacyControllerLease").mockImplementation((...args) => {
|
|
const lease = originalWatch(...args);
|
|
if (args[1].id !== runId) return lease;
|
|
return { ...lease, async assertOwned(stage?: "dispatching") {
|
|
if (stage === undefined) {
|
|
await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() - 60_000) })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
}
|
|
return lease.assertOwned(stage);
|
|
} };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "controller_lease_lost",
|
|
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } },
|
|
});
|
|
expect(
|
|
mockAdapterExecute.mock.calls.some(
|
|
([input]) => (input as { runId?: string } | undefined)?.runId === runId,
|
|
),
|
|
).toBe(false);
|
|
const retries = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(retries).toHaveLength(1);
|
|
expect(retries[0]).toMatchObject({
|
|
scheduledRetryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
expect(
|
|
await db.select({ status: issues.status }).from(issues).where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]?.status),
|
|
).toBe("in_progress");
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions().catch(() => undefined);
|
|
watcher.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("does not queue immediate recovery when the failed run's issue is hidden", async () => {
|
|
mockAdapterExecute.mockResolvedValueOnce({
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
provider: "test",
|
|
model: "test-model",
|
|
});
|
|
|
|
const { runId, issueId } = await seedQueuedIssueRunFixture();
|
|
await db
|
|
.update(issues)
|
|
.set({ hiddenAt: new Date("2026-03-19T00:05:00.000Z") })
|
|
.where(eq(issues.id, issueId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
const run = await heartbeat.getRun(runId);
|
|
const recoveryRuns = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
|
|
expect(run).toMatchObject({ status: "failed" });
|
|
expect(recoveryRuns).toHaveLength(0);
|
|
});
|
|
|
|
it("does not relabel a lost process run when its agent changes to a conversation adapter", async () => {
|
|
const { companyId, agentId, runId } = await seedRunFixture({ adapterType: "process", processPid: 99999999 });
|
|
await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, agentId));
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(run.status).toBe("failed");
|
|
expect(run.resultJson?.conversationContinuation).toBeUndefined();
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
|
});
|
|
|
|
it.each([false, true])("waits for a live terminal predecessor before a new turn (historical hold: %s)", async withHold => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
const { runId, issueId, companyId } = await seedRunFixture({
|
|
agentStatus: "idle", runStatus: "interrupted", runErrorCode: "server_shutdown_interrupted", processPid: child.pid!,
|
|
});
|
|
await db.update(heartbeatRuns).set({ resultJson: { conversationContinuation: "continue_conversation_v1" } }).where(eq(heartbeatRuns.id, runId));
|
|
if (withHold) await db.insert(issueRecoveryActions).values({
|
|
companyId, sourceIssueId: issueId, kind: "active_run_watchdog", status: "active", ownerType: "board",
|
|
cause: "legacy_execution_requires_reconciliation", fingerprint: runId,
|
|
evidence: { runId, automaticRecovery: { replay: "blocked" } }, nextAction: "Wait for the previous execution to stop.",
|
|
});
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId, cause: "execution_owner_active" });
|
|
// Scheduling itself has no execution authority. Actual queued admission
|
|
// must still block while the predecessor owns a process or lease.
|
|
const queuedId = randomUUID();
|
|
const previous = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
|
|
await db.insert(heartbeatRuns).values({ id: queuedId, companyId, agentId: previous.agentId,
|
|
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } });
|
|
const { createPostgresRunDispatchAdapter } = await import("../modules/run-dispatch/adapters/postgres.js");
|
|
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
|
|
expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
|
|
const { settleUnrecoverableExecutions } = await import("../services/execution-recovery-resolution.js");
|
|
await settleUnrecoverableExecutions(db);
|
|
if (withHold) expect((await selectRecoveryActionsForIssue(issueId))[0].status).toBe("active");
|
|
expect(isPidAlive(child.pid!)).toBe(true);
|
|
child.kill("SIGTERM");
|
|
await waitForPidExit(child.pid!);
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
});
|
|
|
|
it("waits for a terminal predecessor's environment lease to be released", async () => {
|
|
const { companyId, issueId, runId } = await seedRunFixture({ agentStatus: "idle", runStatus: "interrupted" });
|
|
await db.update(heartbeatRuns).set({ resultJson: { conversationContinuation: "continue_conversation_v1" } }).where(eq(heartbeatRuns.id, runId));
|
|
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId, status: "active" }).returning();
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId, cause: "execution_owner_active" });
|
|
// Scheduling itself has no execution authority. Actual queued admission
|
|
// must still block while the predecessor owns a process or lease.
|
|
const queuedId = randomUUID();
|
|
const previous = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
|
|
await db.insert(heartbeatRuns).values({ id: queuedId, companyId, agentId: previous.agentId,
|
|
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } });
|
|
const { createPostgresRunDispatchAdapter } = await import("../modules/run-dispatch/adapters/postgres.js");
|
|
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
|
|
expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
|
|
await db.update(environmentLeases).set({ releasedAt: new Date(), status: "released" }).where(eq(environmentLeases.id, lease!.id));
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
});
|
|
|
|
it("keeps an unsafe Stop blocked when recovery sees a deferred human comment", async () => {
|
|
const { companyId, agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress", runStatus: "cancelled",
|
|
resultJson: { executionCancellation: { state: "acknowledged" } },
|
|
});
|
|
await db.update(agents).set({ adapterType: "process" }).where(eq(agents.id, agentId));
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
await terminalizeLegacyExecution({ db, run, status: "cancelled" });
|
|
const wakeId = randomUUID();
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeId, companyId, agentId, source: "on_demand", triggerDetail: "manual",
|
|
reason: "issue_commented", payload: { issueId }, status: "deferred_issue_execution",
|
|
});
|
|
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId });
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId });
|
|
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId));
|
|
expect(wake.status).toBe("deferred_issue_execution");
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
|
});
|
|
|
|
it("leaves hidden issues out of stranded-issue reconciliation", async () => {
|
|
const { issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({ hiddenAt: new Date("2026-03-19T00:05:00.000Z") })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.issueIds).not.toContain(issueId);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
});
|
|
|
|
async function seedPendingNativeFinalization(accept = true) {
|
|
const fixture = await seedRunFixture({ runtimeMode: "native", adapterType: "paperclip_runner", processPid: 2_000_000_000 });
|
|
const { companyId, agentId, issueId, runId } = fixture;
|
|
const contractId = randomUUID(), runnerInstanceId = randomUUID();
|
|
const contractSha = `finalization-contract-${runId}`;
|
|
await db.insert(completionContracts).values({
|
|
id: contractId, companyId, issueId, revision: 1,
|
|
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v1",
|
|
risk: "low", completionAuthority: "agent_claim_policy", incompleteCriteriaPolicy: "preserve_non_terminal",
|
|
contractJson: { revision: CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim.contractRevision,
|
|
objective: "Keep completed work", criteria: [{ id: "objective", requirement: "Keep completed work" }] },
|
|
canonicalSha256: contractSha, createdByActorType: "system", createdByActorId: "test",
|
|
});
|
|
await db.update(heartbeatRuns).set({ nativeIssueId: issueId, nativeSessionId: runId,
|
|
runnerInstanceId, completionContractId: contractId, completionContractSha256: contractSha,
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
const makePort = (targetDb = db) => new PaperclipControlPlanePort(targetDb, { companyId, issueId, runId, agentId, sessionId: runId,
|
|
completionContractId: contractId, completionContractSha256: contractSha,
|
|
sourceInstanceId: runnerInstanceId, controlPlaneSourceInstanceId: `finalization-control-${runId}`,
|
|
});
|
|
const port = makePort();
|
|
await port.openRun({ ...CONTROL_PLANE_CONFORMANCE_OPEN,
|
|
identity: { companyId, issueId, runId, agentId, sessionId: runId }, sourceInstanceId: runnerInstanceId });
|
|
const complete = (targetDb = db) => makePort(targetDb).completeRun({ result: CONTROL_PLANE_CONFORMANCE_RESULT,
|
|
terminal: CONTROL_PLANE_CONFORMANCE_TERMINAL, callerResultId: `finalization-result-${runId}` });
|
|
if (accept) await complete();
|
|
const [local] = await db.select().from(environments).where(eq(environments.driver, "local"));
|
|
const lease = local
|
|
? { environmentId: local.id, leaseId: (await db.insert(environmentLeases).values({
|
|
companyId, issueId, heartbeatRunId: runId, environmentId: local.id,
|
|
status: "active", leasePolicy: "ephemeral", provider: "local", metadata: { driver: "local" },
|
|
updatedAt: new Date(0),
|
|
}).returning())[0].id }
|
|
: await seedEnvironmentLeaseFixture(fixture);
|
|
await persistHeartbeatRunProcessMetadata(db, runId, { pid: 2_000_000_000, processGroupId: null,
|
|
startedAt: new Date(0).toISOString(), targetKind: "local" });
|
|
return { ...fixture, ...lease, complete };
|
|
}
|
|
|
|
it.each(["foreign", "malformed", "expired_controller"] as const)(
|
|
"preserves native finalization source and board hold after restart with %s owner",
|
|
async (kind) => {
|
|
const f = await seedPendingNativeFinalization();
|
|
const owner = kind === "malformed" ? { unknown: true } : {
|
|
token: randomUUID(), controllerBootId: randomUUID(),
|
|
hostname: kind === "foreign" ? "previous-controller.invalid" : os.hostname(),
|
|
pid: 2_000_000_000, processStartedAt: new Date(0).toISOString(),
|
|
};
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceFinalizationOwner: owner } })
|
|
.where(eq(heartbeatRuns.id, f.runId));
|
|
await db.update(nativeRunFinalizations).set({ leaseOwner: null, leaseExpiresAt: new Date(0),
|
|
controllerPid: 2_000_000_000, controllerProcessStartedAt: new Date(0),
|
|
}).where(eq(nativeRunFinalizations.runId, f.runId));
|
|
const accepted = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId));
|
|
const runtime = environmentRuntimeService(db);
|
|
const release = vi.spyOn(runtime, "releaseRunLeases");
|
|
const destroy = vi.spyOn(runtime, "destroyRunLease");
|
|
const heartbeat = heartbeatService(db, { environmentRuntime: runtime });
|
|
await heartbeat.recoverNativeRunsAfterRestart();
|
|
const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
|
|
expect(hold).toMatchObject({ status: "active", cause: "native_workspace_finalization_owner_unverified", ownerType: "board", wakePolicy: null });
|
|
for (let tick = 0; tick < 2; tick += 1) {
|
|
expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
|
|
// The held run itself is an execution path; it does not settle copyback.
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
|
|
expect(actions).toHaveLength(1);
|
|
expect(actions[0]).toMatchObject({ id: hold.id });
|
|
expect(["active", "escalated"]).toContain(actions[0].status);
|
|
}
|
|
expect((await heartbeat.getRun(f.runId))).toMatchObject({ status: "running", nativePhase: "workspace_finalizing", errorCode: null,
|
|
runnerProfileJson: { nativeWorkspaceFinalizationOwner: owner } });
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId)))[0])
|
|
.toMatchObject({ status: "active", releasedAt: null });
|
|
expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId))).toEqual(accepted);
|
|
expect(await db.select().from(workspaceOperations).where(eq(workspaceOperations.heartbeatRunId, f.runId))).toEqual([]);
|
|
expect(release).not.toHaveBeenCalled();
|
|
expect(destroy).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
await waitForPendingRunFailureReports();
|
|
expect(mockCaptureRunFailure).not.toHaveBeenCalled();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
},
|
|
);
|
|
|
|
it("rejects a stale orphan candidate when native finalization commits before owner acquisition", async () => {
|
|
const f = await seedPendingNativeFinalization(false);
|
|
// Avoid the unrelated observed-owner gate while the old enumeration still
|
|
// lacks a result. Publish through the real result transaction just before
|
|
// generic orphan recovery reaches its conditional status write.
|
|
await db.update(nativeRunFinalizations).set({ phase: "workspace_finalizing" }).where(eq(nativeRunFinalizations.runId, f.runId));
|
|
const usedConversation = vi.spyOn(conversationContinuation, "runUsedConversationAdapter").mockImplementationOnce(async () => {
|
|
await f.complete();
|
|
return false;
|
|
});
|
|
const runtime = environmentRuntimeService(db);
|
|
const release = vi.spyOn(runtime, "releaseRunLeases");
|
|
try {
|
|
expect(await heartbeatService(db, { environmentRuntime: runtime }).reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
|
|
expect(usedConversation).toHaveBeenCalledOnce();
|
|
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0])
|
|
.toMatchObject({ status: "running", nativePhase: "workspace_finalizing", errorCode: null });
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId)))[0].status).toBe("active");
|
|
expect(release).not.toHaveBeenCalled();
|
|
} finally { usedConversation.mockRestore(); }
|
|
});
|
|
|
|
it("fences a native finalization publisher that commits while the orphan UPDATE waits on its row lock", async () => {
|
|
const f = await seedPendingNativeFinalization(false);
|
|
await db.update(nativeRunFinalizations).set({ phase: "workspace_finalizing" }).where(eq(nativeRunFinalizations.runId, f.runId));
|
|
let release!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
let entered!: () => void;
|
|
const writerEntered = new Promise<void>(resolve => { entered = resolve; });
|
|
let publisherPid = 0;
|
|
let publisher: Promise<void> | undefined;
|
|
const usedConversation = vi.spyOn(conversationContinuation, "runUsedConversationAdapter").mockImplementationOnce(async () => {
|
|
publisher = db.transaction(async tx => {
|
|
const rows = await tx.execute(sql`select pg_backend_pid() as pid`);
|
|
publisherPid = Number(rows[0].pid);
|
|
// This is the real publication protocol, not a synthetic version bump:
|
|
// completeRun locks heartbeat, accepts the result, and writes its phase.
|
|
await f.complete(tx as unknown as typeof db);
|
|
entered();
|
|
await gate;
|
|
});
|
|
await writerEntered;
|
|
return false;
|
|
});
|
|
const runtime = environmentRuntimeService(db);
|
|
const releaseLease = vi.spyOn(runtime, "releaseRunLeases");
|
|
const heartbeat = heartbeatService(db, { environmentRuntime: runtime });
|
|
const reaping = heartbeat.reapOrphanedRuns();
|
|
try {
|
|
await writerEntered;
|
|
await vi.waitFor(async () => {
|
|
const waiting = await db.execute(sql`select pid from pg_stat_activity
|
|
where ${publisherPid} = any(pg_blocking_pids(pid)) and wait_event_type = 'Lock'`);
|
|
expect(waiting.length).toBeGreaterThan(0);
|
|
}, { timeout: 5_000 });
|
|
release();
|
|
await publisher;
|
|
expect(await reaping).toEqual({ reaped: 0, runIds: [] });
|
|
expect((await heartbeat.getRun(f.runId))).toMatchObject({ status: "running", errorCode: null, nativePhase: "workspace_finalizing" });
|
|
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId)))).toHaveLength(1);
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId)))[0].status).toBe("active");
|
|
expect(releaseLease).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
await waitForPendingRunFailureReports();
|
|
expect(mockCaptureRunFailure).not.toHaveBeenCalled();
|
|
} finally {
|
|
release();
|
|
await publisher?.catch(() => undefined);
|
|
await reaping.catch(() => undefined);
|
|
usedConversation.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each(["phase_only", "rejected_result", "terminal_failure", "unknown_phase"] as const)(
|
|
"does not invent native finalization authority from %s",
|
|
async (kind) => {
|
|
const f = await seedPendingNativeFinalization(kind !== "phase_only");
|
|
await db.update(heartbeatRuns).set({ nativePhase: "workspace_finalizing",
|
|
runnerProfileJson: { nativeWorkspaceFinalizationOwner: { unknown: true } },
|
|
}).where(eq(heartbeatRuns.id, f.runId));
|
|
await db.update(nativeRunFinalizations).set({ phase: kind === "terminal_failure" ? "terminal_failure"
|
|
: kind === "unknown_phase" ? "unknown_phase" : "workspace_finalizing",
|
|
// Prevent the finalizer from changing this negative control first.
|
|
leaseOwner: "unverified-old-owner", leaseExpiresAt: new Date(Date.now() + 60_000),
|
|
}).where(eq(nativeRunFinalizations.runId, f.runId));
|
|
if (kind === "rejected_result") await db.update(nativeRunResults).set({ schemaStatus: "rejected" }).where(eq(nativeRunResults.runId, f.runId));
|
|
const result = await heartbeatService(db).reapOrphanedRuns();
|
|
expect(result.runIds).toContain(f.runId);
|
|
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0])
|
|
.toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
},
|
|
);
|
|
|
|
it("resolves the exact native finalization hold after verified workspace settlement without replay", async () => {
|
|
const f = await seedPendingNativeFinalization();
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceFinalizationOwner: {
|
|
token: randomUUID(), hostname: "previous-controller.invalid", pid: 2_000_000_000, processStartedAt: new Date(0).toISOString(),
|
|
} } }).where(eq(heartbeatRuns.id, f.runId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.recoverNativeRunsAfterRestart();
|
|
const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
|
|
const accepted = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId));
|
|
// Model exact operator stop verification and a completed copyback receipt;
|
|
// no test or product path infers these facts from a dead provider PID.
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: {} }).where(eq(heartbeatRuns.id, f.runId));
|
|
await db.insert(workspaceOperations).values({ companyId: f.companyId, issueId: f.issueId,
|
|
heartbeatRunId: f.runId, phase: "workspace_finalize", status: "succeeded" });
|
|
await heartbeat.reapOrphanedRuns();
|
|
expect((await heartbeat.getRun(f.runId))).toMatchObject({ status: "succeeded", nativePhase: "committed" });
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)))[0])
|
|
.toMatchObject({ status: "resolved", outcome: "restored" });
|
|
expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId))).toEqual(accepted);
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
});
|
|
|
|
it("rejects foreign result, company, and issue bindings for native finalization", async () => {
|
|
const source = await seedPendingNativeFinalization();
|
|
const other = await seedPendingNativeFinalization();
|
|
const [otherResult] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, other.runId));
|
|
for (const patch of [{ resultId: otherResult.id }, { companyId: other.companyId }, { issueId: other.issueId }]) {
|
|
await expect(db.update(nativeRunFinalizations).set(patch).where(eq(nativeRunFinalizations.runId, source.runId)))
|
|
.rejects.toMatchObject({ cause: { code: "23503" } });
|
|
}
|
|
// The composite foreign keys are part of the guard's durable authority;
|
|
// invalid foreign bindings never become a candidate through a valid write.
|
|
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, source.runId)))[0])
|
|
.toMatchObject({ companyId: source.companyId, issueId: source.issueId, phase: "workspace_finalizing" });
|
|
});
|
|
|
|
it("does not extend native finalization authority to a legacy runtime", async () => {
|
|
const f = await seedPendingNativeFinalization();
|
|
await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, f.runId));
|
|
expect((await heartbeatService(db).reapOrphanedRuns()).runIds).toContain(f.runId);
|
|
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0])
|
|
.toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
});
|
|
|
|
it("does not clear another run's native finalization hold on the same task", async () => {
|
|
const f = await seedPendingNativeFinalization();
|
|
const [otherHold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId,
|
|
sourceIssueId: f.issueId, kind: "active_run_watchdog", status: "active", ownerType: "board",
|
|
cause: "native_workspace_finalization_owner_unverified", fingerprint: randomUUID(),
|
|
evidence: { runId: randomUUID() }, nextAction: "Verify the other physical owner has stopped.",
|
|
}).returning();
|
|
await db.insert(workspaceOperations).values({ companyId: f.companyId, issueId: f.issueId,
|
|
heartbeatRunId: f.runId, phase: "workspace_finalize", status: "succeeded" });
|
|
await expect(finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }))
|
|
.resolves.toMatchObject({ phase: "committed" });
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, otherHold.id)))[0])
|
|
.toMatchObject({ status: "active", resolvedAt: null });
|
|
});
|
|
|
|
it("retains the exact native owner hold without changing a terminal task's disposition", async () => {
|
|
const f = await seedPendingNativeFinalization();
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceFinalizationOwner: { unknown: true } } })
|
|
.where(eq(heartbeatRuns.id, f.runId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.recoverNativeRunsAfterRestart();
|
|
const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId));
|
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)))[0])
|
|
.toEqual(hold);
|
|
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].status).toBe("done");
|
|
}
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: {} }).where(eq(heartbeatRuns.id, f.runId));
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)))[0])
|
|
.toMatchObject({ status: "resolved", resolutionNote: "source_terminal" });
|
|
await heartbeat.drainActiveRunExecutions();
|
|
});
|
|
|
|
it("resolves stale recovery on terminal tasks unless system recovery is still in flight", async () => {
|
|
const f = await seedRunFixture({ runStatus: "failed" });
|
|
const seedTerminalAction = async (action: Partial<typeof issueRecoveryActions.$inferInsert>) => {
|
|
const [issue] = await db.insert(issues).values({ companyId: f.companyId, title: "Closed recovery source",
|
|
status: "done", completedAt: new Date(), assigneeAgentId: f.agentId }).returning();
|
|
const [row] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: issue.id,
|
|
kind: "active_run_watchdog", status: "active", ownerType: "agent", ownerAgentId: f.agentId,
|
|
cause: "native_finalization_error", fingerprint: randomUUID(), evidence: { runId: f.runId },
|
|
nextAction: "Resume the native run.", ...action }).returning();
|
|
return row;
|
|
};
|
|
const agentNative = await seedTerminalAction({ wakePolicy: { kind: "resume_native_run", runId: f.runId } });
|
|
const systemEscalated = await seedTerminalAction({ status: "escalated", ownerType: "system", ownerAgentId: null });
|
|
const systemInFlight = await seedTerminalAction({ ownerType: "system", ownerAgentId: null,
|
|
evidence: { runId: f.runId, systemRecovery: createSystemRecovery(f.runId) } });
|
|
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
for (const action of [agentNative, systemEscalated]) {
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id)))[0])
|
|
.toMatchObject({ status: "resolved", outcome: "restored", resolutionNote: "source_terminal" });
|
|
}
|
|
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, systemInFlight.id)))[0])
|
|
.toMatchObject({ status: "active", resolvedAt: null });
|
|
});
|
|
|
|
it.each(["settled", "rejected", "late_callback", "provider_transport_failed"] as const)(
|
|
"joins startup and reap retained cleanup, keeps recovery live, and drains its %s operation",
|
|
async (outcome) => {
|
|
await withTempPaperclipHome(async () => {
|
|
const fixture = await seedRunFixture({ runtimeMode: "native" });
|
|
const { companyId, agentId, issueId, runId } = fixture;
|
|
const contractId = randomUUID();
|
|
const runnerInstanceId = randomUUID();
|
|
const contractSha = `maintenance-contract-${runId}`;
|
|
await db.insert(completionContracts).values({
|
|
id: contractId,
|
|
companyId,
|
|
issueId,
|
|
revision: 1,
|
|
schemaVersion: "paperclip.completion-contract.v1",
|
|
policyVersion: "phase6-v1",
|
|
risk: "low",
|
|
completionAuthority: "agent_claim_policy",
|
|
incompleteCriteriaPolicy: "preserve_non_terminal",
|
|
contractJson: {
|
|
revision: CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim.contractRevision,
|
|
objective: "Retained cleanup lifecycle",
|
|
criteria: [{ id: "objective", requirement: "Keep cleanup joined" }],
|
|
},
|
|
canonicalSha256: contractSha,
|
|
createdByActorType: "system",
|
|
createdByActorId: "test",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
nativeIssueId: issueId,
|
|
nativeSessionId: runId,
|
|
runnerInstanceId,
|
|
completionContractId: contractId,
|
|
completionContractSha256: contractSha,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
// Use the real accepted-result/finalization path. Only physical cleanup
|
|
// is held below; startup, candidate discovery, reaping and drain are real.
|
|
const port = new PaperclipControlPlanePort(db, {
|
|
companyId,
|
|
issueId,
|
|
runId,
|
|
agentId,
|
|
sessionId: runId,
|
|
completionContractId: contractId,
|
|
completionContractSha256: contractSha,
|
|
sourceInstanceId: runnerInstanceId,
|
|
controlPlaneSourceInstanceId: `maintenance-control-${runId}`,
|
|
});
|
|
await port.openRun({
|
|
...CONTROL_PLANE_CONFORMANCE_OPEN,
|
|
identity: { companyId, issueId, runId, agentId, sessionId: runId },
|
|
sourceInstanceId: runnerInstanceId,
|
|
});
|
|
await port.completeRun({
|
|
result: CONTROL_PLANE_CONFORMANCE_RESULT,
|
|
terminal: CONTROL_PLANE_CONFORMANCE_TERMINAL,
|
|
callerResultId: `maintenance-result-${runId}`,
|
|
});
|
|
await db.insert(workspaceOperations).values({
|
|
companyId,
|
|
heartbeatRunId: runId,
|
|
issueId,
|
|
phase: "workspace_finalize",
|
|
status: "succeeded",
|
|
});
|
|
await expect(
|
|
finalizeNativeRun({
|
|
db,
|
|
runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
}),
|
|
).resolves.toMatchObject({ phase: "committed" });
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.status).toBe("done");
|
|
// The visible successful result was already repaired. This private
|
|
// diagnostic is what permits the separate control-only maintenance lane.
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
resultJson: sql`${heartbeatRuns.resultJson} || ${JSON.stringify({
|
|
recoveredExecutionFailure: {
|
|
errorCode: outcome === "provider_transport_failed" ? "provider_transport_failed" : "adapter_failed",
|
|
error:
|
|
"provider_transport_failed: runner did not durably suspend before checkpoint",
|
|
},
|
|
})}::jsonb`,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const beforeRuns = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, companyId));
|
|
const beforeWakes = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, companyId));
|
|
const beforeResults = await db
|
|
.select()
|
|
.from(nativeRunResults)
|
|
.where(eq(nativeRunResults.runId, runId));
|
|
expect(beforeRuns).toEqual([
|
|
expect.objectContaining({
|
|
status: "succeeded",
|
|
nativePhase: "committed",
|
|
error: null,
|
|
errorCode: null,
|
|
}),
|
|
]);
|
|
expect(beforeResults).toEqual([
|
|
expect.objectContaining({ schemaStatus: "accepted" }),
|
|
]);
|
|
|
|
let release!: () => void;
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
let releaseLateCallback!: () => void;
|
|
const lateCallback = new Promise<void>((resolve) => {
|
|
releaseLateCallback = resolve;
|
|
});
|
|
let physicalCleanupFinished = false;
|
|
mockRetainedNativeCleanup.mockImplementationOnce(
|
|
async (cleanupDb, input) => {
|
|
expect(cleanupDb).toBe(db);
|
|
expect(input).toEqual({ companyId, runId });
|
|
await held;
|
|
physicalCleanupFinished = true;
|
|
|
|
|
|
if (outcome === "late_callback") await lateCallback;
|
|
if (outcome === "rejected")
|
|
throw new Error("maintenance-test-closed-failure");
|
|
return {
|
|
runId,
|
|
status:
|
|
outcome === "late_callback" ? "operator_required" : "settled",
|
|
};
|
|
},
|
|
);
|
|
const heartbeat = heartbeatService(db);
|
|
let startupFinished = false;
|
|
const startup = heartbeat
|
|
.recoverNativeRunsAfterRestart()
|
|
.then((result) => {
|
|
startupFinished = true;
|
|
return result;
|
|
});
|
|
let drain: Promise<void> | undefined;
|
|
try {
|
|
await vi.waitFor(
|
|
() => {
|
|
expect(mockRetainedNativeCleanup).toHaveBeenCalledTimes(1);
|
|
expect(startupFinished).toBe(true);
|
|
},
|
|
{ timeout: 2_000 },
|
|
);
|
|
expect((await startup).claims).toEqual([]);
|
|
expect(physicalCleanupFinished).toBe(false);
|
|
|
|
const unrelated = await seedRunFixture({
|
|
adapterType: "process",
|
|
includeIssue: false,
|
|
});
|
|
let reapFinished = false;
|
|
const reap = heartbeat.reapOrphanedRuns().then((result) => {
|
|
reapFinished = true;
|
|
return result;
|
|
});
|
|
await vi.waitFor(() => expect(reapFinished).toBe(true), {
|
|
timeout: 2_000,
|
|
});
|
|
expect((await reap).reaped).toBe(1);
|
|
expect(await heartbeat.getRun(unrelated.runId)).toMatchObject({
|
|
status: "failed",
|
|
});
|
|
expect(mockRetainedNativeCleanup).toHaveBeenCalledTimes(1);
|
|
expect(physicalCleanupFinished).toBe(false);
|
|
|
|
let drainFinished = false;
|
|
drain = heartbeat.drainActiveRunExecutions().then(() => {
|
|
drainFinished = true;
|
|
});
|
|
// A completed unrelated DB read is a deterministic scheduling barrier:
|
|
// drain has entered its await while the physical cleanup is still held.
|
|
await heartbeat.getRun(runId);
|
|
expect(drainFinished).toBe(false);
|
|
expect(heartbeat.getTaskDrainStatus()).toMatchObject({
|
|
pendingWakes: 0,
|
|
quiescent: false,
|
|
});
|
|
expect(heartbeat.getTaskDrainStatus().activeRuns).toBeGreaterThan(0);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
release();
|
|
if (outcome === "late_callback") {
|
|
await vi.waitFor(() => expect(physicalCleanupFinished).toBe(true));
|
|
expect(physicalCleanupFinished).toBe(true);
|
|
expect(drainFinished).toBe(false);
|
|
expect(heartbeat.getTaskDrainStatus().quiescent).toBe(false);
|
|
}
|
|
releaseLateCallback();
|
|
await drain;
|
|
expect(physicalCleanupFinished).toBe(true);
|
|
expect(heartbeat.getTaskDrainStatus()).toMatchObject({
|
|
activeRuns: 0,
|
|
pendingWakes: 0,
|
|
quiescent: true,
|
|
});
|
|
expect(mockRetainedNativeCleanup).toHaveBeenCalledTimes(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, companyId)),
|
|
).toEqual(beforeRuns);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, companyId)),
|
|
).toEqual(beforeWakes);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(nativeRunResults)
|
|
.where(eq(nativeRunResults.runId, runId)),
|
|
).toEqual(beforeResults);
|
|
} finally {
|
|
release();
|
|
releaseLateCallback();
|
|
await startup;
|
|
await drain;
|
|
await heartbeat.drainActiveRunExecutions();
|
|
}
|
|
});
|
|
},
|
|
);
|
|
|
|
it("keeps a local run active when the recorded pid is still alive", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeTypeOf("number");
|
|
|
|
const { runId, wakeupRequestId } = await seedRunFixture({
|
|
processPid: child.pid ?? null,
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(0);
|
|
|
|
const run = await heartbeat.getRun(runId);
|
|
expect(run?.status).toBe("running");
|
|
expect(run?.errorCode).toBe("process_detached");
|
|
expect(run?.error).toContain(String(child.pid));
|
|
|
|
const wakeup = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(wakeup?.status).toBe("claimed");
|
|
});
|
|
|
|
it.each(["running", "failed"] as const)("holds a remote %s native PID despite a colliding live host child", async status => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeTypeOf("number");
|
|
const { companyId, agentId, runId, issueId } = await seedRunFixture({ adapterType: "process",
|
|
runtimeMode: "native", runStatus: status,
|
|
runErrorCode: status === "failed" ? "native_session_interrupted" : null,
|
|
runError: status === "failed" ? "native session timed out after 120000ms" : null });
|
|
if (status === "failed") {
|
|
await db.update(heartbeatRuns).set({ nativeIssueId: issueId, nativePhase: "retryable_failure", finishedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId,
|
|
phase: "retryable_failure", nextAttemptAt: new Date(0) });
|
|
}
|
|
await persistHeartbeatRunProcessMetadata(db, runId, { pid: child.pid!, processGroupId: null,
|
|
startedAt: new Date().toISOString(), targetKind: "remote" });
|
|
const heartbeat = heartbeatService(db);
|
|
const before = await heartbeat.getRun(runId);
|
|
expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status, processPid: child.pid,
|
|
processStartedAt: before!.processStartedAt, errorCode: before!.errorCode, error: before!.error });
|
|
expect(isPidAlive(child.pid!)).toBe(true);
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
child.kill("SIGTERM");
|
|
await waitForPidExit(child.pid!);
|
|
expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status, processPid: child.pid,
|
|
processStartedAt: before!.processStartedAt, errorCode: before!.errorCode, error: before!.error });
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps a native run active without granting legacy retry or signal authority", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeTypeOf("number");
|
|
|
|
const { agentId, runId, wakeupRequestId } = await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
runtimeMode: "native",
|
|
processPid: child.pid ?? null,
|
|
includeIssue: false,
|
|
});
|
|
await persistHeartbeatRunProcessMetadata(db, runId, { pid: child.pid!, processGroupId: null,
|
|
startedAt: new Date().toISOString(), targetKind: "local" });
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result).toEqual({ reaped: 0, runIds: [] });
|
|
expect(isPidAlive(child.pid!)).toBe(true);
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
|
|
const run = await heartbeat.getRun(runId);
|
|
expect(run).toMatchObject({
|
|
status: "running",
|
|
errorCode: "native_execution_ownership_unverified",
|
|
processPid: child.pid,
|
|
});
|
|
const retries = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
),
|
|
);
|
|
expect(retries).toHaveLength(0);
|
|
|
|
const wakeup = await db
|
|
.select({ status: agentWakeupRequests.status })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(wakeup?.status).toBe("claimed");
|
|
});
|
|
|
|
it.each(["terminal_failure", "retryable_failure"])(
|
|
"retains authentication-blocked ownership after restart with coordinator phase %s",
|
|
async (coordinatorPhase) => {
|
|
const { companyId, agentId, runId, issueId, wakeupRequestId } =
|
|
await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
runtimeMode: "native",
|
|
runErrorCode: "native_execution_ownership_unverified",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ nativeIssueId: issueId, nativePhase: "terminal_failure" })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_review" })
|
|
.where(eq(issues.id, issueId));
|
|
const { leaseId } = await seedEnvironmentLeaseFixture({
|
|
companyId,
|
|
runId,
|
|
issueId,
|
|
driver: "ownership-test",
|
|
});
|
|
const interactionId = randomUUID();
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "pending",
|
|
sourceRunId: runId,
|
|
createdByUserId: "responsible-user",
|
|
payload: { version: 1, prompt: "Review the task" },
|
|
});
|
|
await db.insert(nativeRunFinalizations).values({
|
|
runId,
|
|
companyId,
|
|
issueId,
|
|
phase: coordinatorPhase,
|
|
attempt: 1,
|
|
recoveryState: "blocked",
|
|
failureCode: "native_adopted_runner_authentication_timeout",
|
|
leaseExpiresAt: new Date(0),
|
|
nextAttemptAt:
|
|
coordinatorPhase === "retryable_failure" ? new Date(0) : null,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
const enqueueWakeup = vi.fn();
|
|
const recovery = recoveryService(db, { enqueueWakeup });
|
|
expect(await heartbeat.reapOrphanedRuns()).toEqual({
|
|
reaped: 0,
|
|
runIds: [],
|
|
});
|
|
expect(
|
|
await claimNativeSessionResumptions({
|
|
db,
|
|
runnerInstanceId: "new-controller",
|
|
runIds: [runId],
|
|
}),
|
|
).toEqual([]);
|
|
const claims = await claimNativeRestartRecoveries({
|
|
db,
|
|
restartKind: "hard",
|
|
runIds: [runId],
|
|
});
|
|
expect(claims.every((claim) => claim.kind === "blocked")).toBe(true);
|
|
expect(
|
|
await heartbeat.drainRunningRunsForShutdown("SIGTERM", new Date(), [
|
|
runId,
|
|
]),
|
|
).toMatchObject({
|
|
interrupted: 0,
|
|
interruptedRunIds: [],
|
|
retryRunIds: [],
|
|
restartSuspendedRunIds: [],
|
|
});
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(nativeRunFinalizations)
|
|
.where(eq(nativeRunFinalizations.runId, runId)),
|
|
).toMatchObject([
|
|
{
|
|
phase: coordinatorPhase,
|
|
recoveryState: "blocked",
|
|
recoveryHistory: [],
|
|
},
|
|
]);
|
|
const gracefulClaims = await claimNativeRestartRecoveries({
|
|
db,
|
|
restartKind: "graceful",
|
|
runIds: [runId],
|
|
});
|
|
expect(gracefulClaims.every((claim) => claim.kind === "blocked")).toBe(
|
|
true,
|
|
);
|
|
expect(
|
|
(await recovery.sweepStaleIssueLocks()).terminalizedRunIds,
|
|
).toEqual([]);
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "running",
|
|
nativePhase: "terminal_failure",
|
|
finishedAt: null,
|
|
});
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toMatchObject([
|
|
{
|
|
status: "in_review",
|
|
executionRunId: runId,
|
|
checkoutRunId: runId,
|
|
},
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(environmentLeases)
|
|
.where(eq(environmentLeases.id, leaseId)),
|
|
).toMatchObject([{ status: "active" }]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId)),
|
|
).toMatchObject([{ status: "pending" }]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId)),
|
|
).toMatchObject([{ status: "claimed" }]);
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toHaveLength(1);
|
|
expect(enqueueWakeup).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
// Even a later Board task-status change cannot prove this process stopped.
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "done" })
|
|
.where(eq(issues.id, issueId));
|
|
expect(
|
|
(await recovery.sweepStaleIssueLocks()).terminalizedRunIds,
|
|
).toEqual([]);
|
|
expect((await heartbeat.getRun(runId))?.status).toBe("running");
|
|
},
|
|
);
|
|
|
|
it("keeps a live native run owned by the current controller out of ambiguous recovery", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeTypeOf("number");
|
|
|
|
const { companyId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
runtimeMode: "native",
|
|
processPid: child.pid ?? null,
|
|
});
|
|
const controller = await currentNativeControllerIdentity();
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ nativeIssueId: issueId, nativePhase: "observed" })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(nativeRunFinalizations).values({
|
|
runId,
|
|
companyId,
|
|
issueId,
|
|
phase: "observed",
|
|
attempt: 1,
|
|
leaseOwner: "current-controller:test",
|
|
leaseExpiresAt: new Date(Date.now() + 60_000),
|
|
controllerBootId: controller.bootId,
|
|
controllerPid: controller.pid,
|
|
controllerProcessStartedAt: controller.processStartedAt,
|
|
controllerGeneration: 1,
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
|
|
expect(result).toEqual({ reaped: 0, runIds: [] });
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "running",
|
|
error: null,
|
|
errorCode: null,
|
|
processPid: child.pid,
|
|
});
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not reap a retryable native run while its same-run recovery path owns it", async () => {
|
|
const { companyId, agentId, runId, issueId, wakeupRequestId } =
|
|
await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
runtimeMode: "native",
|
|
});
|
|
const nextAttemptAt = new Date(Date.now() + 60_000);
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ nativeIssueId: issueId, nativePhase: "retryable_failure" })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(nativeRunFinalizations).values({
|
|
runId,
|
|
companyId,
|
|
issueId,
|
|
phase: "retryable_failure",
|
|
attempt: 1,
|
|
nextAttemptAt,
|
|
recoveryState: "resuming_session",
|
|
});
|
|
|
|
const result = await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
expect(result).toEqual({ reaped: 0, runIds: [] });
|
|
expect(await heartbeatService(db).getRun(runId)).toMatchObject({
|
|
status: "running",
|
|
nativePhase: "retryable_failure",
|
|
});
|
|
await expect(
|
|
db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
),
|
|
),
|
|
).resolves.toHaveLength(0);
|
|
await expect(
|
|
db
|
|
.select({ status: agentWakeupRequests.status })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId)),
|
|
).resolves.toEqual([{ status: "claimed" }]);
|
|
});
|
|
|
|
it("does not grant a dead native run legacy retry authority after adapter reassignment", async () => {
|
|
const { agentId, runId } = await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
runtimeMode: "native",
|
|
processPid: 999_999_999,
|
|
includeIssue: false,
|
|
});
|
|
await persistHeartbeatRunProcessMetadata(db, runId, { pid: 999_999_999, processGroupId: null,
|
|
startedAt: new Date().toISOString(), targetKind: "local" });
|
|
// The persisted run remains native even after the agent's current adapter
|
|
// changes to one that normally owns a legacy local child.
|
|
await db
|
|
.update(agents)
|
|
.set({ adapterType: "codex_local", updatedAt: new Date() })
|
|
.where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result).toEqual({ reaped: 1, runIds: [runId] });
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]).toMatchObject({
|
|
id: runId,
|
|
status: "failed",
|
|
errorCode: "process_lost",
|
|
runtimeMode: "native",
|
|
});
|
|
expect(runs[0]?.retryOfRunId).toBeNull();
|
|
});
|
|
|
|
it("skips generic timer wakes without invoking an adapter when no assigned work is actionable", async () => {
|
|
const { companyId, agentId } = await seedIdleTimerAgentFixture();
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const run = await heartbeat.wakeup(agentId, {
|
|
source: "timer",
|
|
triggerDetail: "system",
|
|
reason: "heartbeat_timer",
|
|
requestedByActorType: "system",
|
|
requestedByActorId: "heartbeat_scheduler",
|
|
contextSnapshot: {
|
|
source: "scheduler",
|
|
reason: "interval_elapsed",
|
|
now: "2026-03-19T00:00:00.000Z",
|
|
},
|
|
});
|
|
|
|
expect(run).toBeNull();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const requests = await selectRecoveryWakesByAgent(agentId);
|
|
expect(requests).toHaveLength(1);
|
|
expect(requests[0]).toMatchObject({
|
|
companyId,
|
|
source: "timer",
|
|
reason: "heartbeat.timer.no_actionable_work",
|
|
status: "skipped",
|
|
error: null,
|
|
});
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(0);
|
|
});
|
|
|
|
it("recovers legacy startup before adapter.invoke using the claimed adapter identity", async () => {
|
|
const f = await seedRunFixture({ agentStatus: "idle", adapterType: "claude_local" });
|
|
await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, f.runId));
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: {
|
|
adapterDispatch: { adapterType: "claude_local" },
|
|
} }).where(eq(heartbeatRuns.id, f.runId));
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(source.resultJson).toMatchObject({ conversationContinuation: "continue_conversation_v1" });
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
|
|
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agentId));
|
|
expect(runs.filter(run => run.retryOfRunId === f.runId)).toHaveLength(1);
|
|
});
|
|
|
|
it("schedules one conversation continuation after losing the provider", async () => {
|
|
const { agentId, runId, issueId } = await seedRunFixture({
|
|
agentStatus: "idle",
|
|
processPid: 999_999_999,
|
|
contextSnapshot: {
|
|
modelProfile: "cheap",
|
|
allowDeliverableWork: false,
|
|
allowDocumentUpdates: false,
|
|
resumeRequiresNormalModel: true,
|
|
},
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(1);
|
|
expect(result.runIds).toEqual([runId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const failedRun = runs.find((row) => row.id === runId);
|
|
const retryRuns = runs.filter((row) => row.retryOfRunId === runId);
|
|
expect(retryRuns).toHaveLength(1);
|
|
const retryRun = retryRuns[0];
|
|
expect(failedRun?.status).toBe("failed");
|
|
expect(failedRun?.errorCode).toBe("process_lost");
|
|
expect(failedRun?.livenessState).toBe("failed");
|
|
expect(failedRun?.livenessReason).toContain("process_lost");
|
|
expect(failedRun?.resultJson).toMatchObject({
|
|
stopReason: "process_lost",
|
|
timeoutConfigured: false,
|
|
timeoutFired: false,
|
|
processLossDiagnostic: {
|
|
pidRecorded: true, groupRecorded: false, localCheck: "not_observed_alive", retryEligible: true,
|
|
observerUptimeMs: expect.any(Number), runPredatesObserver: true,
|
|
},
|
|
});
|
|
// The legacy engine writes this terminal status through the same
|
|
// guarded emitter that reports a genuine failed transition to Sentry.
|
|
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
|
|
expect(mockCaptureRunFailure).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
runId,
|
|
errorCode: "process_lost",
|
|
runStatus: "failed",
|
|
diagnostics: expect.objectContaining({ execution: expect.objectContaining({
|
|
processLossPidRecorded: true, processLossGroupRecorded: false, processLossLocalCheck: "not_observed_alive",
|
|
processLossRetryEligible: true, processLossRunPredatesObserver: true,
|
|
}) }),
|
|
}),
|
|
);
|
|
const [action] = await selectRecoveryActionsForIssue(issueId);
|
|
expect(action).toBeUndefined();
|
|
expect(retryRun).toMatchObject({ status: "scheduled_retry", scheduledRetryAttempt: 1 });
|
|
await heartbeat.reapOrphanedRuns();
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toHaveLength(2);
|
|
// A replay over the same already-failed run must not report a second
|
|
// Sentry event for one terminal failure.
|
|
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
|
|
|
|
const issue = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row?.checkoutRunId === null ? row : null;
|
|
}),
|
|
);
|
|
expect([retryRun?.id ?? null, null]).toContain(
|
|
issue?.executionRunId ?? null,
|
|
);
|
|
|
|
const checkoutReleasedIssue = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row?.checkoutRunId === null ? row : null;
|
|
}),
|
|
);
|
|
// Terminal run cleanup releases the checkout lock so future checkout 409s only mean a live owner exists.
|
|
expect(checkoutReleasedIssue?.checkoutRunId).toBeNull();
|
|
});
|
|
|
|
it("requires reconciliation for a lost monitor whose provider outcomes are unknown", async () => {
|
|
const { agentId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "openclaw_gateway",
|
|
agentStatus: "idle",
|
|
processPid: null,
|
|
processGroupId: null,
|
|
contextSnapshot: { wakeReason: "issue_monitor_due" },
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
expect(await heartbeat.reapOrphanedRuns()).toEqual({
|
|
reaped: 1,
|
|
runIds: [runId],
|
|
});
|
|
await heartbeat.reapOrphanedRuns();
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toHaveLength(1);
|
|
const actions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(actions).toEqual([
|
|
expect.objectContaining({
|
|
ownerType: "board",
|
|
returnOwnerAgentId: agentId,
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("does not retry a lost monitor dispatch while another monitor wake remains scheduled", async () => {
|
|
const { companyId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "openclaw_gateway",
|
|
agentStatus: "idle",
|
|
processPid: null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
wakeReason: "issue_monitor_due",
|
|
},
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({ monitorNextCheckAt: new Date("2099-03-19T00:00:00.000Z") })
|
|
.where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
|
|
expect(result).toEqual({ reaped: 1, runIds: [runId] });
|
|
const retries = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
),
|
|
);
|
|
expect(retries).toHaveLength(0);
|
|
});
|
|
|
|
// A hard restart can kill the server after it claimed a legacy run but before
|
|
// the adapter dispatch renewal, leaving an expired lease from another boot.
|
|
async function seedRestartOrphanedLegacySetup(executionStage: "preparing" | "dispatching") {
|
|
const fixture = await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
agentStatus: "idle",
|
|
runtimeMode: "legacy",
|
|
});
|
|
await db.update(heartbeatRuns).set({
|
|
controllerBootId: randomUUID(),
|
|
controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`,
|
|
executionStage,
|
|
}).where(eq(heartbeatRuns.id, fixture.runId));
|
|
return fixture;
|
|
}
|
|
|
|
it("retries a legacy run that a restart stopped before adapter dispatch", async () => {
|
|
const { companyId, runId, issueId } = await seedRestartOrphanedLegacySetup("preparing");
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
|
|
expect(result).toEqual({ reaped: 1, runIds: [runId] });
|
|
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(reaped).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "process_lost",
|
|
error: "Process lost -- server may have restarted; retrying once",
|
|
});
|
|
expect(reaped?.resultJson).toMatchObject({
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true, runPredatesObserver: true },
|
|
});
|
|
const retries = await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
));
|
|
expect(retries).toEqual([expect.objectContaining({ status: "scheduled_retry" })]);
|
|
expect(await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
["an assignment", {}],
|
|
["a due monitor", { wakeReason: "issue_monitor_due" }],
|
|
] as const)("retries %s run whose lease this process lost before adapter dispatch", async (_label, contextSnapshot) => {
|
|
const { companyId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy", contextSnapshot,
|
|
});
|
|
await db.update(heartbeatRuns).set({
|
|
controllerBootId: controllerLeases.legacyControllerBootId,
|
|
controllerProcess: currentControllerProcessStamp(),
|
|
controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`,
|
|
executionStage: "preparing",
|
|
runnerProfileJson: {
|
|
adapterDispatch: { adapterType: "paperclip_runner" },
|
|
remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", epoch: 6, state: "prepared",
|
|
leaseId: randomUUID(), providerLeaseId: randomUUID(), workspaceId: randomUUID(),
|
|
remoteCwd: "/home/daytona/paperclip-workspace", snapshotId: randomUUID() },
|
|
},
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 1, runIds: [runId] });
|
|
|
|
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost",
|
|
error: "Process lost -- server may have restarted; retrying once" });
|
|
expect(reaped?.resultJson).toMatchObject({
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true },
|
|
});
|
|
expect(await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId),
|
|
))).toEqual([expect.objectContaining({ status: "scheduled_retry" })]);
|
|
await heartbeat.reapOrphanedRuns();
|
|
expect(await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps a run this process dispatched held for reconciliation after its lease lapses", async () => {
|
|
const { companyId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy",
|
|
});
|
|
await db.update(heartbeatRuns).set({
|
|
controllerBootId: controllerLeases.legacyControllerBootId,
|
|
controllerProcess: currentControllerProcessStamp(),
|
|
controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`,
|
|
executionStage: "dispatching",
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
expect(reaped?.resultJson).not.toHaveProperty("executionRecovery");
|
|
expect(await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId),
|
|
))).toEqual([]);
|
|
expect(await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([
|
|
expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }),
|
|
]);
|
|
});
|
|
|
|
it("keeps a lost preparation from an older build without a controller stamp in the charged lane", async () => {
|
|
const { companyId, runId } = await seedRestartOrphanedLegacySetup("preparing");
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId)))).toEqual([expect.objectContaining({
|
|
status: "scheduled_retry", scheduledRetryReason: "transient_failure", scheduledRetryAttempt: 1 })]);
|
|
});
|
|
|
|
it("continues a chain whose preparations were killed twice and then interrupted again, without a Retry", async () => {
|
|
const { companyId, agentId, runId: firstRunId } = await seedRunFixture({ adapterType: "paperclip_runner",
|
|
agentStatus: "idle", runtimeMode: "legacy" });
|
|
const preparing = async (runId: string, owner: "killed" | "current") => {
|
|
const live = currentControllerProcessStamp();
|
|
const bootId = owner === "current" ? controllerLeases.legacyControllerBootId : randomUUID();
|
|
const pid = Number(spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"],
|
|
{ encoding: "utf8" }).stdout);
|
|
await db.update(heartbeatRuns).set({ status: "running", startedAt: new Date(), executionStage: "preparing",
|
|
runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } }, controllerBootId: bootId,
|
|
controllerProcess: owner === "current" ? live
|
|
: { bootId, pid, hostHash: live.hostHash, processStartedAt: new Date(Date.now() - 120_000).toISOString() },
|
|
controllerLeaseExpiresAt: sql`clock_timestamp() + interval '45 seconds'` }).where(eq(heartbeatRuns.id, runId));
|
|
await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId));
|
|
};
|
|
const successorOf = async (runId: string) => (await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId))))[0];
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await preparing(firstRunId, "killed");
|
|
await heartbeat.reapOrphanedRuns();
|
|
const second = await successorOf(firstRunId);
|
|
expect(second).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: "interrupted_preparation",
|
|
scheduledRetryAttempt: 1 });
|
|
|
|
await preparing(second!.id, "killed");
|
|
await heartbeat.reapOrphanedRuns();
|
|
const third = await successorOf(second!.id);
|
|
expect(third).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: "interrupted_preparation",
|
|
scheduledRetryAttempt: 2 });
|
|
expect(third!.contextSnapshot?.executionRetryAccounting).toMatchObject({ failureRetries: 0, interruptedPreparations: 2 });
|
|
|
|
await preparing(third!.id, "current");
|
|
const drained = await heartbeat.drainRunningRunsForShutdown("SIGTERM");
|
|
expect(drained.interruptedRunIds).toEqual([third!.id]);
|
|
const exited = randomUUID();
|
|
await db.update(heartbeatRuns).set({ controllerBootId: exited, controllerProcess: { bootId: exited,
|
|
pid: Number(spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"], { encoding: "utf8" }).stdout),
|
|
hostHash: currentControllerProcessStamp().hostHash, processStartedAt: new Date(Date.now() - 120_000).toISOString() } })
|
|
.where(eq(heartbeatRuns.id, third!.id));
|
|
await settleUnrecoverableExecutions(db);
|
|
await runOwnershipReconciliationPass(db, { state: createOwnershipReportState(), record: true });
|
|
expect(await successorOf(third!.id)).toMatchObject({ agentId, status: "scheduled_retry",
|
|
scheduledRetryReason: "interrupted_preparation", scheduledRetryAttempt: 3 });
|
|
});
|
|
|
|
it("retries within the failure budget even when a legacy process-loss counter is set", async () => {
|
|
const { companyId, runId } = await seedRestartOrphanedLegacySetup("preparing");
|
|
// Earlier releases wrote this counter; nothing writes it now.
|
|
await db.update(heartbeatRuns).set({ processLossRetryCount: 1 }).where(eq(heartbeatRuns.id, runId));
|
|
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
const retries = await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
));
|
|
expect(retries).toEqual([expect.objectContaining({ status: "scheduled_retry" })]);
|
|
});
|
|
|
|
it("does not promise a process-loss retry once the failure budget is spent", async () => {
|
|
const { companyId, runId } = await seedRestartOrphanedLegacySetup("preparing");
|
|
const [seeded] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
await db.update(heartbeatRuns).set({
|
|
contextSnapshot: { ...(seeded!.contextSnapshot ?? {}), executionRetryAccounting: spentFailureRetryAccounting },
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost",
|
|
error: "Process lost -- server may have restarted" });
|
|
expect(reaped?.resultJson).toMatchObject({ processLossDiagnostic: { retryEligible: false } });
|
|
expect(await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
))).toEqual([]);
|
|
});
|
|
|
|
// A routine deploy replaces the server: the old one drains its runs at
|
|
// SIGTERM (server_shutdown_interrupted), and a run whose owner died without a
|
|
// drain is found by the new one (process_lost). Neither is a failed attempt.
|
|
describe("runs ended by a server restart or replacement", () => {
|
|
const successorsOf = (companyId: string, runId: string) => db.select().from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId)));
|
|
|
|
/** A conversation-adapter run in progress. `alreadyRetried` makes it the
|
|
* second automatic retry of a chain whose real failures spent the budget. */
|
|
async function seedInterruptibleRun(input: { alreadyRetried: boolean; owner: "this_server" | "replaced_server";
|
|
accounting?: Record<string, unknown>; adapterType?: string; executionStage?: "preparing" | "dispatching";
|
|
controllerBootId?: string; controllerProcess?: Record<string, unknown>; leaseExpiredSeconds?: number }) {
|
|
const fixture = await seedRunFixture({ adapterType: input.adapterType ?? "codex_local", agentStatus: "running",
|
|
runtimeMode: "legacy", contextSnapshot: { wakeReason: "issue_monitor_due" } });
|
|
const [seeded] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
await db.update(heartbeatRuns).set({
|
|
controllerBootId: input.owner === "this_server" ? controllerLeases.legacyControllerBootId
|
|
: input.controllerBootId ?? randomUUID(),
|
|
...(input.controllerProcess ? { controllerProcess: input.controllerProcess } : {}),
|
|
controllerLeaseExpiresAt: input.owner === "this_server"
|
|
? sql`clock_timestamp() + interval '1 minute'`
|
|
: sql`clock_timestamp() - make_interval(secs => ${input.leaseExpiredSeconds ?? 1})`,
|
|
executionStage: input.executionStage ?? "dispatching",
|
|
...(input.alreadyRetried ? { scheduledRetryReason: "transient_failure", scheduledRetryAttempt: 2 } : {}),
|
|
contextSnapshot: {
|
|
...(seeded!.contextSnapshot ?? {}),
|
|
...(input.alreadyRetried || input.accounting ? { executionRetryAccounting: {
|
|
version: 1, failureRetries: input.alreadyRetried ? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS : 0,
|
|
maxTurnContinuations: 0, ...input.accounting } } : {}),
|
|
},
|
|
}).where(eq(heartbeatRuns.id, fixture.runId));
|
|
return fixture;
|
|
}
|
|
|
|
async function expectOneRestartContinuation(fixture: { companyId: string; agentId: string; runId: string; issueId: string },
|
|
failureRetries: number) {
|
|
const successors = await successorsOf(fixture.companyId, fixture.runId);
|
|
expect(successors).toEqual([expect.objectContaining({ status: "scheduled_retry", scheduledRetryReason: "server_restart",
|
|
scheduledRetryAttempt: 1, agentId: fixture.agentId })]);
|
|
const [successor] = successors;
|
|
// Started at once, and the failure budget is carried, never spent.
|
|
expect(successor!.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now());
|
|
expect(successor!.contextSnapshot?.executionRetryAccounting).toMatchObject({ failureRetries, serverRestarts: 1 });
|
|
// The continuation still serves the original wake (a monitor check).
|
|
const continuation = await executionContinuation.buildExecutionContinuation({ db, companyId: fixture.companyId,
|
|
issueId: fixture.issueId, agentId: fixture.agentId, context: successor!.contextSnapshot ?? {}, runId: successor!.id,
|
|
summary: null, exposeLowTrustRaw: false });
|
|
expect(continuation.trigger.retriedReason).toBe("issue_monitor_due");
|
|
expect(await selectRecoveryActionsForIssue(fixture.issueId)).toEqual([]);
|
|
return successor!;
|
|
}
|
|
|
|
it.each([
|
|
{ name: "a first attempt", alreadyRetried: false },
|
|
{ name: "a run that was already the last automatic retry", alreadyRetried: true },
|
|
])("continues $name that a graceful shutdown interrupted, once, on a second server too", async ({ alreadyRetried }) => {
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried, owner: "this_server" });
|
|
|
|
const drained = await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM");
|
|
|
|
expect(drained.interruptedRunIds).toEqual([fixture.runId]);
|
|
const successor = await expectOneRestartContinuation(fixture, alreadyRetried ? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS : 0);
|
|
expect(drained.retryRunIds).toEqual([successor.id]);
|
|
// The replacement server is alive at the same time and runs its own
|
|
// recovery passes: they reuse the one continuation.
|
|
const replacement = heartbeatService(db);
|
|
await Promise.all([replacement.reapOrphanedRuns(), replacement.reconcileStrandedAssignedIssues(),
|
|
heartbeatService(db).reconcileStrandedAssignedIssues()]);
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toEqual([expect.objectContaining({ id: successor.id })]);
|
|
});
|
|
|
|
it.each([
|
|
{ name: "a first attempt", alreadyRetried: false },
|
|
{ name: "a run that was already the last automatic retry", alreadyRetried: true },
|
|
])("continues $name that a new server found without its owner, once, when two servers recover it", async ({ alreadyRetried }) => {
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried, owner: "replaced_server" });
|
|
|
|
// Two servers are alive during a replacement; both run the boot sweep.
|
|
await Promise.all([heartbeatService(db).reapOrphanedRuns(), heartbeatService(db).reapOrphanedRuns()]);
|
|
|
|
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
await expectOneRestartContinuation(fixture, alreadyRetried ? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS : 0);
|
|
expect(lost!.resultJson).toMatchObject({ processLossDiagnostic: { controllerReplaced: true, retryEligible: true } });
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toHaveLength(1);
|
|
});
|
|
|
|
it.each([
|
|
{ name: "a first attempt", alreadyRetried: false },
|
|
{ name: "a run that was already the last automatic retry", alreadyRetried: true },
|
|
])("continues $name whose old server exited before it scheduled the continuation", async ({ alreadyRetried }) => {
|
|
// The old server committed the interruption, then exited while it waited
|
|
// for the adapter to settle: the task still names the interrupted run.
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried, owner: "replaced_server" });
|
|
await db.update(heartbeatRuns).set({
|
|
status: "interrupted", errorCode: "server_shutdown_interrupted", signal: "SIGTERM",
|
|
error: "Interrupted by graceful server shutdown (SIGTERM)", finishedAt: new Date(), controllerLeaseExpiresAt: null,
|
|
resultJson: { stopReason: "interrupted", conversationContinuation: "continue_conversation_v1" },
|
|
}).where(eq(heartbeatRuns.id, fixture.runId));
|
|
|
|
const replacement = heartbeatService(db);
|
|
await replacement.reapOrphanedRuns();
|
|
await replacement.reconcileStrandedAssignedIssues();
|
|
|
|
await expectOneRestartContinuation(fixture, alreadyRetried ? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS : 0);
|
|
});
|
|
|
|
it("continues a task that an older release left without a continuation after a restart", async () => {
|
|
// Saved by the previous release: the process-loss verdict has no
|
|
// controllerReplaced field, the failure budget is spent, and nothing
|
|
// was scheduled. The new server picks it up on its stranded-task sweep.
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried: true, owner: "replaced_server" });
|
|
await db.update(heartbeatRuns).set({
|
|
status: "failed", errorCode: "process_lost", error: "Process lost -- server may have restarted",
|
|
finishedAt: new Date(), controllerLeaseExpiresAt: null,
|
|
resultJson: { stopReason: "process_lost", conversationContinuation: "continue_conversation_v1",
|
|
processLossDiagnostic: { pidRecorded: false, groupRecorded: false, localCheck: "no_identifiers", retryEligible: false } },
|
|
}).where(eq(heartbeatRuns.id, fixture.runId));
|
|
await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, fixture.issueId));
|
|
|
|
const reconciled = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
expect(reconciled.escalated).toBe(0);
|
|
await expectOneRestartContinuation(fixture, BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS);
|
|
expect((await selectRecoveryIssueById(fixture.issueId))?.status).toBe("in_progress");
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toHaveLength(1);
|
|
});
|
|
|
|
it("stops after the restart bound in one window, says so on the run, and starts a new window later", async () => {
|
|
const recent = new Date(Date.now() - 10 * 60_000).toISOString();
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried: false, owner: "this_server",
|
|
accounting: { serverRestarts: SERVER_RESTART_RETRY_MAX_ATTEMPTS, serverRestartWindowStartedAt: recent } });
|
|
|
|
const drained = await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM");
|
|
|
|
expect(drained.retryRunIds).toEqual([]);
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toEqual([]);
|
|
const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, fixture.runId));
|
|
expect(events).toEqual(expect.arrayContaining([expect.objectContaining({
|
|
payload: expect.objectContaining({ retryReason: "server_restart",
|
|
scheduledRetryAttempt: SERVER_RESTART_RETRY_MAX_ATTEMPTS, maxAttempts: SERVER_RESTART_RETRY_MAX_ATTEMPTS }),
|
|
})]));
|
|
// The sweeper makes the stop visible instead of retrying again.
|
|
const reconciled = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(reconciled.escalated).toBe(1);
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toEqual([]);
|
|
|
|
// The same count in a window that has closed is not a loop.
|
|
const old = await seedInterruptibleRun({ alreadyRetried: false, owner: "this_server",
|
|
accounting: { serverRestarts: SERVER_RESTART_RETRY_MAX_ATTEMPTS,
|
|
serverRestartWindowStartedAt: new Date(Date.now() - SERVER_RESTART_RETRY_WINDOW_MS - 60_000).toISOString() } });
|
|
await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM", new Date(), [old.runId]);
|
|
expect(await successorsOf(old.companyId, old.runId)).toEqual([expect.objectContaining({
|
|
scheduledRetryReason: "server_restart", scheduledRetryAttempt: 1 })]);
|
|
});
|
|
|
|
// Production shape (staging, 2026-11-12): every run the replacement server
|
|
// reaped was a Runner run still preparing (no process recorded), so the
|
|
// reaper marked it bootstrap/providerWorkStarted=false. Those successors
|
|
// went to the charged transient_failure lane instead of server_restart.
|
|
it.each([
|
|
{ name: "a first attempt", alreadyRetried: false },
|
|
{ name: "a run that was already the last automatic retry", alreadyRetried: true },
|
|
])("continues $name that a replaced server left preparing, in the restart lane", async ({ alreadyRetried }) => {
|
|
// The replaced server stamped its process on the claim. It is in another
|
|
// container and has no live server lease, so it is not proven alive.
|
|
const bootId = randomUUID();
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried, owner: "replaced_server",
|
|
adapterType: "paperclip_runner", executionStage: "preparing", controllerBootId: bootId,
|
|
controllerProcess: { bootId, pid: 3, hostHash: "replaced-server-container",
|
|
processStartedAt: new Date(Date.now() - 60 * 60_000).toISOString() } });
|
|
|
|
await Promise.all([heartbeatService(db).reapOrphanedRuns(), heartbeatService(db).reapOrphanedRuns()]);
|
|
|
|
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
expect(lost!.resultJson).toMatchObject({ executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
processLossDiagnostic: { controllerReplaced: true, retryEligible: true } });
|
|
await expectOneRestartContinuation(fixture, alreadyRetried ? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS : 0);
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toHaveLength(1);
|
|
});
|
|
|
|
describe("while the server that owns the run is still serving", () => {
|
|
const oldBootId = randomUUID();
|
|
const oldServer = { bootId: oldBootId, pid: 3, hostHash: "old-server-container",
|
|
processStartedAt: new Date(Date.now() - 60 * 60_000).toISOString() };
|
|
|
|
beforeEach(async () => {
|
|
// The old server's own process lease is live: it is alive and serving.
|
|
await db.insert(controllerInstances).values({ bootId: oldBootId, processSpace: oldServer.hostHash, pid: oldServer.pid,
|
|
leaseExpiresAt: new Date(Date.now() + 60_000) });
|
|
registerControllerInstanceDb(db);
|
|
});
|
|
afterEach(async () => {
|
|
resetControllerInstanceLeaseForTests();
|
|
await db.delete(controllerInstances);
|
|
});
|
|
|
|
it.each(["preparing", "dispatching"] as const)(
|
|
"leaves a %s run whose lease lapsed with its owner, then recovers it once the owner stops", async (executionStage) => {
|
|
// A slow database held the owner's renewal past the 60 s lease while
|
|
// the new server was already running its recovery sweeps.
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried: false, owner: "replaced_server",
|
|
adapterType: "paperclip_runner", executionStage, controllerBootId: oldBootId, controllerProcess: oldServer });
|
|
|
|
await Promise.all([heartbeatService(db).reapOrphanedRuns(), heartbeatService(db).reapOrphanedRuns()]);
|
|
|
|
const [kept] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
expect(kept).toMatchObject({ status: "running", controllerBootId: oldBootId, errorCode: null });
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toEqual([]);
|
|
|
|
// The old server shut down: its process lease is stopped, so the run is lost now.
|
|
await db.update(controllerInstances).set({ stoppedAt: new Date() }).where(eq(controllerInstances.bootId, oldBootId));
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
if (executionStage === "preparing") await expectOneRestartContinuation(fixture, 0);
|
|
});
|
|
|
|
it("recovers the run when its live owner has not settled it within the grace", async () => {
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried: false, owner: "replaced_server",
|
|
adapterType: "paperclip_runner", executionStage: "preparing", controllerBootId: oldBootId,
|
|
controllerProcess: oldServer, leaseExpiredSeconds: controllerLeases.LEGACY_LIVE_OWNER_SETTLE_GRACE_MS / 1000 + 1 });
|
|
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
|
|
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
|
await expectOneRestartContinuation(fixture, 0);
|
|
});
|
|
});
|
|
|
|
it("keeps the failure budget for a run that failed on its own", async () => {
|
|
const fixture = await seedInterruptibleRun({ alreadyRetried: true, owner: "this_server" });
|
|
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "adapter_failed", error: "Adapter failed",
|
|
finishedAt: new Date(), resultJson: { conversationContinuation: "continue_conversation_v1" } })
|
|
.where(eq(heartbeatRuns.id, fixture.runId));
|
|
await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, fixture.issueId));
|
|
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
expect(await successorsOf(fixture.companyId, fixture.runId)).toEqual([]);
|
|
});
|
|
});
|
|
|
|
it("keeps an orphaned legacy run that reached adapter dispatch held for reconciliation", async () => {
|
|
const { companyId, runId, issueId } = await seedRestartOrphanedLegacySetup("dispatching");
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.reapOrphanedRuns();
|
|
|
|
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(reaped).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "process_lost",
|
|
error: "Process lost -- server may have restarted",
|
|
});
|
|
expect(reaped?.resultJson).not.toHaveProperty("executionRecovery");
|
|
expect(await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId),
|
|
))).toEqual([]);
|
|
expect(await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([
|
|
expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }),
|
|
]);
|
|
});
|
|
|
|
async function withTempPaperclipHome<T>(
|
|
fn: (home: string) => Promise<T>,
|
|
): Promise<T> {
|
|
const home = await fs.mkdtemp(
|
|
path.join(os.tmpdir(), "paperclip-hot-restart-"),
|
|
);
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
process.env.PAPERCLIP_HOME = home;
|
|
try {
|
|
return await fn(home);
|
|
} finally {
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
|
|
else process.env.PAPERCLIP_HOME = previousHome;
|
|
// Native dispatch materializes read-only runtime bundles in this owned
|
|
// temporary home. Restore directory permissions solely for test cleanup.
|
|
const makeDirectoriesWritable = async (
|
|
directory: string,
|
|
): Promise<void> => {
|
|
const stat = await fs.lstat(directory);
|
|
if (!stat.isDirectory() || stat.isSymbolicLink()) return;
|
|
await fs.chmod(directory, 0o700);
|
|
for (const entry of await fs.readdir(directory, {
|
|
withFileTypes: true,
|
|
})) {
|
|
if (entry.isDirectory())
|
|
await makeDirectoriesWritable(path.join(directory, entry.name));
|
|
}
|
|
};
|
|
await makeDirectoriesWritable(home);
|
|
await fs.rm(home, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
it.each([false, true])("settles a failed saved native descriptor without inventing files when workspace access is disabled: %s", async withoutWorkspace => {
|
|
await withTempPaperclipHome(async () => {
|
|
const f = await seedQueuedIssueRunFixture();
|
|
await db.update(agents).set({ adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
}).where(eq(agents.id, f.agentId));
|
|
const originalFactory = environmentOrchestrator.environmentRunOrchestrator;
|
|
const release = vi.fn(async () => ({ released: [], errors: [] }));
|
|
const factory = vi.spyOn(environmentOrchestrator, "environmentRunOrchestrator").mockImplementation((...args) => ({
|
|
...originalFactory(...args), releaseForRun: release,
|
|
}));
|
|
const provider = vi.fn(() => { throw new Error("provider must not start"); });
|
|
let leaseId: string | undefined;
|
|
try {
|
|
const heartbeat = heartbeatService(db, {
|
|
nativeSessionBackendFactory: provider,
|
|
beforeNativeRuntimeSelection: async runId => {
|
|
const [lease] = await db.insert(environmentLeases).values({ companyId: f.companyId, issueId: f.issueId,
|
|
heartbeatRunId: runId, provider: "daytona", providerLeaseId: randomUUID(), status: "active", leasePolicy: "ephemeral",
|
|
metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" },
|
|
}).returning();
|
|
leaseId = lease!.id;
|
|
const reference = { schema: "paperclip.native-workspace-sync/v3" as const, state: "prepared" as const,
|
|
descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null,
|
|
workspaceId: randomUUID(), leaseId: lease!.id, providerLeaseId: lease!.providerLeaseId!, remoteCwd: "/work", resourceDisposition: "destroy" as const };
|
|
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: f.issueId, nativePhase: "observed",
|
|
driverKind: withoutWorkspace ? "grok_bot_mcp" : null,
|
|
runnerProfileJson: { nativeWorkspaceSync: reference, ...(withoutWorkspace ? { nativeExecutionInput: {
|
|
schema: "paperclip.native-execution-input.v6", provider: { kind: "grok_bot" },
|
|
binding: { companyId: f.companyId, agentId: f.agentId, runId, issueId: f.issueId },
|
|
workspace: { access: "none", cwd: null, repoUrl: null, repoRef: null, branchName: null },
|
|
} } : {}) },
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(nativeRunFinalizations).values({ runId, companyId: f.companyId, issueId: f.issueId, phase: "observed" });
|
|
await nativeWorkspaceSyncInternals.readDescriptor({ runId, reference });
|
|
},
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(leaseId).toBeDefined();
|
|
const failed = await heartbeat.getRun(f.runId, { includeExecutionEvidence: true });
|
|
expect(failed).toMatchObject({ status: "failed", runtimeMode: "native", nativePhase: "terminal_failure" });
|
|
if (withoutWorkspace) {
|
|
expect(failed?.resultJson?.workspaceRestoreFailure ?? null).toBeNull();
|
|
expect(failed?.resultJson?.workspaceRestoreRecovery ?? null).toBeNull();
|
|
expect((await getExecutionBlocker(db, f.companyId, f.issueId))?.workspaceRepairRequired).not.toBe(true);
|
|
expect(release).toHaveBeenCalled();
|
|
expect(release).not.toHaveBeenCalledWith(expect.objectContaining({ providerResourceDisposition: "stop_and_retain" }));
|
|
} else {
|
|
expect(failed?.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { leaseIds: [leaseId] } });
|
|
expect(await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId!)))
|
|
.toMatchObject([{ status: "pending_cleanup", leasePolicy: "retain_on_failure" }]);
|
|
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ workspaceRepairRequired: true, canRetry: false });
|
|
expect(release).toHaveBeenCalledWith(expect.objectContaining({ providerResourceDisposition: "stop_and_retain" }));
|
|
}
|
|
expect(provider).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
} finally { factory.mockRestore(); }
|
|
});
|
|
});
|
|
|
|
it("fences native selection when cancellation wins during preparation", async () => {
|
|
await withTempPaperclipHome(async () => {
|
|
const { agentId, issueId, runId } = await seedQueuedIssueRunFixture();
|
|
await db.update(agents).set({ adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
}).where(eq(agents.id, agentId));
|
|
const factory = vi.fn(() => { throw new Error("provider must not start"); });
|
|
let reachedSelection = false;
|
|
const heartbeat = heartbeatService(db, {
|
|
nativeSessionBackendFactory: factory,
|
|
beforeNativeRuntimeSelection: async id => {
|
|
reachedSelection = true;
|
|
await heartbeat.cancelRun(id);
|
|
},
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(reachedSelection).toBe(true);
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "cancelled", runtimeMode: "legacy",
|
|
runtimeModeResolvedAt: null, nativeSessionId: null,
|
|
resultJson: { startupCancellation: { beforeNativeSelection: true },
|
|
startupPreparationSettledAt: expect.any(String) },
|
|
});
|
|
expect(await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId))).toHaveLength(0);
|
|
expect(factory).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(task.executionRunId).toBeNull();
|
|
});
|
|
});
|
|
|
|
it("does not dispatch when cancellation wins after native selection", async () => {
|
|
await withTempPaperclipHome(async () => {
|
|
const { agentId, issueId, runId } = await seedQueuedIssueRunFixture();
|
|
await db.update(agents).set({ adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
}).where(eq(agents.id, agentId));
|
|
await db.update(heartbeatRuns).set({ invocationSource: "automation" }).where(eq(heartbeatRuns.id, runId));
|
|
const factory = vi.fn(() => { throw new Error("provider must not start"); });
|
|
let reachedDispatch = false;
|
|
const heartbeat = heartbeatService(db, {
|
|
nativeSessionBackendFactory: factory,
|
|
beforeChatControlRecoveryCheck: async ({ stage, runId: id }) => {
|
|
if (stage !== "dispatch") return;
|
|
reachedDispatch = true;
|
|
expect((await heartbeat.getRun(id))?.runtimeMode).toBe("native");
|
|
await heartbeat.cancelRun(id);
|
|
},
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(reachedDispatch).toBe(true);
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "cancelled", runtimeMode: "native",
|
|
resultJson: { startupPreparationSettledAt: expect.any(String) },
|
|
});
|
|
expect(factory).not.toHaveBeenCalled();
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
|
|
expect(coordinator).toMatchObject({ attempt: 0, leaseOwner: null });
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(task.executionRunId).toBeNull();
|
|
});
|
|
});
|
|
|
|
it.each(["projectless", "organization_only", "empty_source"] as const)("dispatches local native external chat inside the server-selected task root: %s", async placement => {
|
|
await withTempPaperclipHome(async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedQueuedIssueRunFixture();
|
|
await fs.mkdir(resolvePaperclipInstanceRoot(), { recursive: true });
|
|
const projectId = placement === "projectless" ? null : randomUUID();
|
|
if (projectId) {
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Chat channel project default" });
|
|
if (placement === "empty_source") {
|
|
await db.insert(projectWorkspaces).values({ companyId, projectId, name: "Unconfigured source", cwd: " ", repoUrl: null });
|
|
}
|
|
}
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
})
|
|
.where(eq(agents.id, agentId));
|
|
await db
|
|
.update(issues)
|
|
.set({ originKind: "chat_channel", projectId })
|
|
.where(eq(issues.id, issueId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runtimeMode: "native",
|
|
runtimeModeResolvedAt: new Date(),
|
|
nativeIssueId: issueId,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const nativeSessionBackendFactory = vi.fn(
|
|
(_execution: NativeExecutionInput) => {
|
|
// Stop at the real provider boundary, without spawning a provider.
|
|
throw new NativeRunnerOwnershipUnverifiedError();
|
|
},
|
|
);
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForValue(
|
|
async () =>
|
|
nativeSessionBackendFactory.mock.calls.length > 0 ||
|
|
Boolean((await heartbeat.getRun(runId))?.errorCode),
|
|
8_000,
|
|
);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
expect(nativeSessionBackendFactory).toHaveBeenCalledTimes(1);
|
|
const input = nativeSessionBackendFactory.mock.calls[0]![0];
|
|
expect(input.workspace.cwd).toBe(
|
|
path.join(
|
|
await fs.realpath(resolvePaperclipInstanceRoot()),
|
|
"isolated-workspaces",
|
|
companyId,
|
|
issueId,
|
|
),
|
|
);
|
|
expect(input.workspace.cwd).not.toBe(
|
|
resolveDefaultAgentWorkspaceDir(agentId),
|
|
);
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, task.executionWorkspaceId!));
|
|
expect(task.projectId).toBe(projectId);
|
|
expect(workspace).toMatchObject({ sourceIssueId: issueId, projectId: null, projectWorkspaceId: null, cwd: input.workspace.cwd });
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
it.each(["managed_isolated", "shared"] as const)("prepares a fresh native chat configured source safely: %s", async (mode) => {
|
|
await withTempPaperclipHome(async () => {
|
|
const { companyId, agentId, issueId, runId } = await seedQueuedIssueRunFixture();
|
|
const instanceRoot = resolvePaperclipInstanceRoot();
|
|
await fs.mkdir(instanceRoot, { recursive: true });
|
|
const cwd = path.join(instanceRoot, "source-repository");
|
|
await fs.mkdir(cwd, { recursive: true });
|
|
execFileSync("git", ["init", "-b", "main"], { cwd, stdio: "ignore" });
|
|
await fs.writeFile(path.join(cwd, "report.txt"), "source bytes");
|
|
execFileSync("git", ["add", "report.txt"], { cwd, stdio: "ignore" });
|
|
execFileSync("git", ["-c", "user.name=Test", "-c", "user.email=test@example.test", "commit", "-m", "Source"], { cwd, stdio: "ignore" });
|
|
const [project] = await db.insert(projects).values({ companyId, name: "Chat source" }).returning();
|
|
const [source] = await db.insert(projectWorkspaces).values({ companyId, projectId: project.id, name: "Source", cwd, isPrimary: true }).returning();
|
|
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-5.6-luna" } }).where(eq(agents.id, agentId));
|
|
await db.update(issues).set({ originKind: "chat_channel", projectWorkspaceId: source.id,
|
|
workspaceSelection: { version: 1, source: "channel", selection: { kind: "configured_source", projectWorkspaceId: source.id, mode } },
|
|
executionWorkspaceSettings: { mode: mode === "managed_isolated" ? "isolated_workspace" : "shared_workspace" },
|
|
}).where(eq(issues.id, issueId));
|
|
await db.update(heartbeatRuns).set({ runtimeMode: "native", runtimeModeResolvedAt: new Date(), nativeIssueId: issueId }).where(eq(heartbeatRuns.id, runId));
|
|
const nativeSessionBackendFactory = vi.fn((_execution: NativeExecutionInput) => { throw new NativeRunnerOwnershipUnverifiedError(); });
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForValue(async () => nativeSessionBackendFactory.mock.calls.length > 0 || Boolean((await heartbeat.getRun(runId))?.errorCode), 15_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
if (mode === "shared") {
|
|
expect(nativeSessionBackendFactory).not.toHaveBeenCalled();
|
|
expect((await heartbeat.getRun(runId))?.error).toContain("External chat requires a task-owned isolated workspace");
|
|
} else {
|
|
expect(nativeSessionBackendFactory).toHaveBeenCalledTimes(1);
|
|
const input = nativeSessionBackendFactory.mock.calls[0]![0];
|
|
expect(await fs.realpath(input.workspace.cwd!)).not.toBe(await fs.realpath(cwd));
|
|
expect(await fs.readFile(path.join(input.workspace.cwd!, "report.txt"), "utf8")).toBe("source bytes");
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, task.executionWorkspaceId!));
|
|
expect(workspace).toMatchObject({ sourceIssueId: issueId, projectId: project.id, mode: "isolated_workspace", strategyType: "git_worktree", cwd: input.workspace.cwd, providerRef: input.workspace.cwd });
|
|
}
|
|
expect(await fs.readFile(path.join(cwd, "report.txt"), "utf8")).toBe("source bytes");
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
it("carries the ordinary initial description provenance through native heartbeat assembly", async () => {
|
|
await withTempPaperclipHome(async () => {
|
|
const { agentId, issueId, runId } = await seedQueuedIssueRunFixture();
|
|
await db.update(agents).set({
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
}).where(eq(agents.id, agentId));
|
|
const nativeSessionBackendFactory = vi.fn(
|
|
(_execution: NativeExecutionInput) => {
|
|
throw new NativeRunnerOwnershipUnverifiedError();
|
|
},
|
|
);
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForValue(
|
|
async () => nativeSessionBackendFactory.mock.calls.length > 0 ||
|
|
Boolean((await heartbeat.getRun(runId))?.errorCode),
|
|
8_000,
|
|
);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
expect(nativeSessionBackendFactory).toHaveBeenCalledTimes(1);
|
|
const input = nativeSessionBackendFactory.mock.calls[0]![0] as ReturnType<typeof buildNativeExecutionInput>;
|
|
const description = "Verify the successful-run handoff and choose an honest disposition.";
|
|
const source = nativeCompletionSource("description", issueId, description);
|
|
expect(input.completionContract.contract.criteria).toEqual([{
|
|
id: "objective",
|
|
requirement: description,
|
|
}]);
|
|
expect(input.completionSources).toMatchObject({
|
|
criteria: [{ id: "objective", source }],
|
|
});
|
|
expect(input.task.prompt).toContain(description);
|
|
expect(input.task.prompt.split(description)).toHaveLength(2);
|
|
const modelEnvelope = buildNativeModelEnvelope(input);
|
|
expect(modelEnvelope.schema).toBe("paperclip.native-model-envelope.v3");
|
|
expect(modelEnvelope.task).not.toHaveProperty("description");
|
|
expect(modelEnvelope.task.prompt.split(description)).toHaveLength(2);
|
|
expect(modelEnvelope.completionContract.criteria).toEqual([{
|
|
id: "objective",
|
|
source: { ...source, location: "task.prompt" },
|
|
}]);
|
|
});
|
|
});
|
|
|
|
it("holds admitted native chat with a legacy shared cwd without replacing input or releasing ownership", async () => {
|
|
await withTempPaperclipHome(async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const legacyCwd = resolveDefaultAgentWorkspaceDir(agentId);
|
|
await fs.mkdir(legacyCwd, { recursive: true });
|
|
const nativeExecutionInput = buildNativeExecutionInput({
|
|
companyId,
|
|
runId,
|
|
agentId,
|
|
issue: {
|
|
id: issueId,
|
|
identifier: "CHAT-1",
|
|
title: "Legacy chat",
|
|
description: null,
|
|
workMode: "standard",
|
|
},
|
|
taskPrompt: "Keep the admitted session intact",
|
|
workspace: {
|
|
id: runId,
|
|
cwd: legacyCwd,
|
|
repoUrl: null,
|
|
repoRef: null,
|
|
branchName: null,
|
|
},
|
|
normalizedSessionId: randomUUID(),
|
|
provider: "codex",
|
|
completionContract: {
|
|
id: randomUUID(),
|
|
sha256: `sha256:${"a".repeat(64)}`,
|
|
schemaVersion: "paperclip.run-result.v1",
|
|
contract: {
|
|
revision: "1",
|
|
objective: "Retain ownership",
|
|
criteria: [
|
|
{
|
|
id: "objective",
|
|
requirement: "Do not replace a shared-root session",
|
|
},
|
|
],
|
|
},
|
|
},
|
|
runtimeContext: nativeRuntimeContextFixture(),
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
})
|
|
.where(eq(agents.id, agentId));
|
|
await db
|
|
.update(issues)
|
|
.set({ originKind: "chat_channel" })
|
|
.where(eq(issues.id, issueId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runtimeMode: "native",
|
|
runtimeModeResolvedAt: new Date(),
|
|
nativeIssueId: issueId,
|
|
runnerProfileJson: { nativeExecutionInput },
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const { leaseId } = await seedEnvironmentLeaseFixture({
|
|
companyId,
|
|
runId,
|
|
issueId,
|
|
driver: "ownership-test",
|
|
});
|
|
const nativeSessionBackendFactory = vi.fn(() => {
|
|
throw new Error("Provider must not be opened");
|
|
});
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForValue(
|
|
async () => (await heartbeat.getRun(runId))?.errorCode,
|
|
8_000,
|
|
);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({
|
|
status: "running",
|
|
nativePhase: "terminal_failure",
|
|
errorCode: "native_execution_ownership_unverified",
|
|
runnerProfileJson: { nativeExecutionInput },
|
|
});
|
|
expect(
|
|
await db
|
|
.select({ executionRunId: issues.executionRunId })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId)),
|
|
).toEqual([{ executionRunId: runId }]);
|
|
expect(
|
|
await db
|
|
.select({ releasedAt: environmentLeases.releasedAt })
|
|
.from(environmentLeases)
|
|
.where(eq(environmentLeases.id, leaseId)),
|
|
).toEqual([{ releasedAt: null }]);
|
|
const events = await heartbeat.listEvents(runId);
|
|
expect(events).toContainEqual(
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
reason: "native_chat_workspace_scope_mismatch",
|
|
}),
|
|
}),
|
|
);
|
|
expect(nativeSessionBackendFactory).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
await expect(
|
|
fs.stat(path.join(resolvePaperclipInstanceRoot(), "chat-workspaces")),
|
|
).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(
|
|
await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId)),
|
|
).toEqual([]);
|
|
});
|
|
});
|
|
|
|
it("checkpoints idle warm sessions even when no hot restart was requested", async () => {
|
|
await withTempPaperclipHome(async () => {
|
|
mockCloseIdleWarmNativeSessionsForRestart.mockClear();
|
|
const heartbeat = heartbeatService(db);
|
|
await expect(heartbeat.prepareHotRestartShutdown("SIGTERM")).resolves.toMatchObject({ mode: "not_requested" });
|
|
expect(mockCloseIdleWarmNativeSessionsForRestart).toHaveBeenCalledOnce();
|
|
});
|
|
});
|
|
|
|
it("captures a hot-restart shutdown snapshot without interrupting running runs", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeGreaterThan(0);
|
|
const { runId, wakeupRequestId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: child.pid ?? null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "cli",
|
|
processTopology: "detached",
|
|
},
|
|
});
|
|
|
|
await withTempPaperclipHome(async () => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-version",
|
|
requestedAt: new Date("2026-03-19T00:05:00.000Z"),
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
mockCloseIdleWarmNativeSessionsForRestart.mockClear();
|
|
const result = await heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-03-19T00:06:00.000Z"),
|
|
);
|
|
|
|
expect(result).toEqual({
|
|
mode: "hot_restart",
|
|
skipDrain: true,
|
|
activeRunIds: [runId],
|
|
});
|
|
expect(mockCloseIdleWarmNativeSessionsForRestart).toHaveBeenCalledOnce();
|
|
expect(isPidAlive(child.pid)).toBe(true);
|
|
const run = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(run).toMatchObject({
|
|
status: "running",
|
|
errorCode: null,
|
|
});
|
|
const wakeup = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(wakeup?.status).toBe("claimed");
|
|
const intent = await readHotRestartIntent();
|
|
expect(intent?.shutdownSnapshot).toMatchObject({
|
|
capturedAt: "2026-03-19T00:06:00.000Z",
|
|
signal: "SIGTERM",
|
|
activeRuns: [
|
|
{
|
|
runId,
|
|
adapterType: "codex_local",
|
|
status: "running",
|
|
processPid: child.pid,
|
|
},
|
|
],
|
|
});
|
|
});
|
|
});
|
|
|
|
it("snapshots and drains a server-stdio ACP run before embedded database shutdown", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeGreaterThan(0);
|
|
const { agentId, runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: child.pid ?? null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "acp",
|
|
processTopology: "server_stdio",
|
|
},
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-acp-version",
|
|
requestedAt: new Date("2026-08-04T00:05:00.000Z"),
|
|
preflightActiveRunIds: [runId],
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await expect(
|
|
heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-08-04T00:06:00.000Z"),
|
|
),
|
|
).resolves.toEqual({
|
|
mode: "acp_drain_required",
|
|
skipDrain: false,
|
|
activeRunIds: [runId],
|
|
activeAcpRunIds: [runId],
|
|
drainRunIds: [runId],
|
|
drainReason: "active_acp_run",
|
|
});
|
|
await expect(readHotRestartIntent()).resolves.toMatchObject({
|
|
drainRequired: true,
|
|
drainReason: "active_acp_run",
|
|
drainRunIds: [runId],
|
|
shutdownSnapshot: {
|
|
activeRuns: [
|
|
expect.objectContaining({ runId, processPid: child.pid }),
|
|
],
|
|
},
|
|
});
|
|
|
|
const drain = await heartbeat.drainRunningRunsForShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-08-04T00:06:01.000Z"),
|
|
[runId],
|
|
);
|
|
expect(drain.interruptedRunIds).toEqual([runId]);
|
|
expect(drain.retryRunIds).toHaveLength(1);
|
|
await waitForPidExit(child.pid!);
|
|
|
|
const reconciliation = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-08-04T00:07:00.000Z"),
|
|
);
|
|
expect(reconciliation).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [],
|
|
finalizedWhileDownRunIds: [runId],
|
|
lostRunIds: [],
|
|
skippedRunIds: [],
|
|
});
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs.find((run) => run.id === runId)).toMatchObject({
|
|
status: "interrupted",
|
|
errorCode: "server_shutdown_interrupted",
|
|
});
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as Record<string, unknown>;
|
|
expect(report).toMatchObject({
|
|
drainRequired: true,
|
|
drainReason: "active_acp_run",
|
|
adoptedRunIds: [],
|
|
finalizedWhileDownRunIds: [runId],
|
|
lostRunIds: [],
|
|
});
|
|
});
|
|
});
|
|
|
|
it("drains late legacy settlement before releasing its source and scheduling one continuation", async () => {
|
|
const f = await seedRunFixture({ runtimeMode: "legacy", adapterType: "codex_local", agentStatus: "running" });
|
|
await db.update(heartbeatRuns).set({ scopeKind: "issue", issueId: f.issueId }).where(eq(heartbeatRuns.id, f.runId));
|
|
const { leaseId } = await seedEnvironmentLeaseFixture({ ...f, provider: "daytona", driver: "sandbox" });
|
|
await db.update(environmentLeases).set({ providerLeaseId: randomUUID(), metadata: { driver: "sandbox" } })
|
|
.where(eq(environmentLeases.id, leaseId));
|
|
const release = vi.fn(async () => {
|
|
const [saved] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(saved.resultJson).toMatchObject({ workspaceRestored: true });
|
|
return (await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date() })
|
|
.where(eq(environmentLeases.id, leaseId)).returning())[0] as EnvironmentLease;
|
|
});
|
|
const runtime = environmentRuntimeService(db, { drivers: [{ driver: "sandbox",
|
|
resolveCapabilities: async () => classifyEnvironmentCapabilities({}),
|
|
acquireRunLease: async () => { throw new Error("Unexpected acquire"); }, releaseRunLease: release }] });
|
|
const heartbeat = heartbeatService(db, { environmentRuntime: runtime });
|
|
const control = createAdapterExecutionControl();
|
|
adapterExecutionControls.set(f.runId, control);
|
|
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
const shutdown = heartbeat.drainRunningRunsForShutdown("SIGTERM", new Date(), [f.runId]);
|
|
let drained = false;
|
|
let finalizers: Promise<void> | undefined;
|
|
try {
|
|
await vi.waitFor(() => expect(control.controller.signal.aborted).toBe(true));
|
|
await vi.advanceTimersByTimeAsync(30_000);
|
|
expect(await shutdown).toMatchObject({ interruptedRunIds: [f.runId], retryRunIds: [] });
|
|
finalizers = heartbeat.drainActiveRunExecutions().then(() => { drained = true; });
|
|
await Promise.resolve();
|
|
expect(drained).toBe(false);
|
|
expect(release).not.toHaveBeenCalled();
|
|
expect(await selectRecoveryRunsByAgent(f.agentId)).toHaveLength(1);
|
|
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toHaveLength(0);
|
|
await db.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || '{"workspaceRestored":true}'::jsonb` })
|
|
.where(eq(heartbeatRuns.id, f.runId));
|
|
control.finish();
|
|
await finalizers;
|
|
expect(release).toHaveBeenCalledOnce();
|
|
const runs = await selectRecoveryRunsByAgent(f.agentId);
|
|
expect(runs).toHaveLength(2);
|
|
expect(runs.find(run => run.id !== f.runId)).toMatchObject({ status: "scheduled_retry", scheduledRetryAttempt: 1,
|
|
scopeKind: "issue", issueId: f.issueId });
|
|
const reloaded = heartbeatService(db, { environmentRuntime: runtime });
|
|
await reloaded.drainRunningRunsForShutdown("SIGTERM", new Date(), [f.runId]);
|
|
expect(await selectRecoveryRunsByAgent(f.agentId)).toHaveLength(2);
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0])
|
|
.toMatchObject({ status: "released", cleanupStatus: "success", metadata: { legacyShutdownWorkspaceSettlement: { state: "settled" } } });
|
|
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toHaveLength(0);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
control.finish();
|
|
adapterExecutionControls.delete(f.runId);
|
|
await shutdown;
|
|
await finalizers;
|
|
}
|
|
});
|
|
|
|
it("reports a selectively drained ACP run as lost when terminal persistence fails", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeGreaterThan(0);
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: child.pid ?? null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "acp",
|
|
processTopology: "server_stdio",
|
|
},
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-acp-persistence-failure-version",
|
|
requestedAt: new Date("2026-08-04T00:15:00.000Z"),
|
|
preflightActiveRunIds: [runId],
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-08-04T00:16:00.000Z"),
|
|
);
|
|
|
|
// Model the failure boundary precisely: termination succeeded, but the
|
|
// interrupted status write never landed, so the durable row is running.
|
|
process.kill(child.pid!, "SIGKILL");
|
|
await waitForPidExit(child.pid!);
|
|
|
|
const reconciliation = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-08-04T00:17:00.000Z"),
|
|
);
|
|
expect(reconciliation).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [runId],
|
|
skippedRunIds: [],
|
|
});
|
|
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as {
|
|
runs: Array<{ runId: string; classification: string; reason: string }>;
|
|
};
|
|
expect(report.runs).toContainEqual(
|
|
expect.objectContaining({
|
|
runId,
|
|
classification: "lost",
|
|
reason: "selective_drain_not_finalized",
|
|
}),
|
|
);
|
|
});
|
|
});
|
|
|
|
it("drains only server-stdio runs and preserves detached CLI adoption in a mixed restart", async () => {
|
|
const acpChild = spawnAliveProcess();
|
|
const cliChild = spawnAliveProcess();
|
|
childProcesses.add(acpChild);
|
|
childProcesses.add(cliChild);
|
|
expect(acpChild.pid).toBeGreaterThan(0);
|
|
expect(cliChild.pid).toBeGreaterThan(0);
|
|
|
|
const acp = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: acpChild.pid ?? null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "acp",
|
|
processTopology: "server_stdio",
|
|
},
|
|
});
|
|
const cli = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: cliChild.pid ?? null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "cli",
|
|
processTopology: "detached",
|
|
},
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-mixed-version",
|
|
requestedAt: new Date("2026-08-04T01:05:00.000Z"),
|
|
preflightActiveRunIds: [acp.runId, cli.runId],
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const preparation = await heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-08-04T01:06:00.000Z"),
|
|
);
|
|
expect(preparation).toMatchObject({
|
|
mode: "acp_drain_required",
|
|
skipDrain: false,
|
|
activeAcpRunIds: [acp.runId],
|
|
drainRunIds: [acp.runId],
|
|
drainReason: "active_acp_run",
|
|
});
|
|
if (preparation.mode !== "acp_drain_required") {
|
|
throw new Error(
|
|
`Expected selective ACP drain, received ${preparation.mode}`,
|
|
);
|
|
}
|
|
expect(new Set(preparation.activeRunIds)).toEqual(
|
|
new Set([acp.runId, cli.runId]),
|
|
);
|
|
|
|
const drain = await heartbeat.drainRunningRunsForShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-08-04T01:06:01.000Z"),
|
|
preparation.drainRunIds,
|
|
);
|
|
expect(drain.interruptedRunIds).toEqual([acp.runId]);
|
|
await waitForPidExit(acpChild.pid!);
|
|
expect(isPidAlive(cliChild.pid)).toBe(true);
|
|
|
|
const reconciliation = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-08-04T01:07:00.000Z"),
|
|
);
|
|
expect(reconciliation).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [cli.runId],
|
|
finalizedWhileDownRunIds: [acp.runId],
|
|
lostRunIds: [],
|
|
skippedRunIds: [],
|
|
});
|
|
|
|
const originalRuns = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(inArray(heartbeatRuns.id, [acp.runId, cli.runId]));
|
|
expect(originalRuns.find((run) => run.id === acp.runId)).toMatchObject({
|
|
status: "interrupted",
|
|
errorCode: "server_shutdown_interrupted",
|
|
});
|
|
expect(originalRuns.find((run) => run.id === cli.runId)).toMatchObject({
|
|
status: "running",
|
|
});
|
|
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as Record<string, unknown>;
|
|
expect(report).toMatchObject({
|
|
drainRequired: true,
|
|
drainReason: "active_acp_run",
|
|
adoptedRunIds: [cli.runId],
|
|
finalizedWhileDownRunIds: [acp.runId],
|
|
lostRunIds: [],
|
|
});
|
|
});
|
|
});
|
|
|
|
it("adopts an old-server legacy snapshot written for a new instance-scoped marker", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeGreaterThan(0);
|
|
const { companyId, agentId, issueId, runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: child.pid ?? null,
|
|
processGroupId: null,
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-home-root-version",
|
|
requestedAt: new Date("2026-08-01T00:05:00.000Z"),
|
|
requestedByRunId: "deploy-run",
|
|
preflightActiveRunIds: [runId],
|
|
});
|
|
|
|
// Simulate the previous binary: it reads and rewrites only the legacy
|
|
// home-root marker, and its parser drops fields introduced by the new binary.
|
|
const legacyPath = resolveLegacyHotRestartIntentPath(home);
|
|
const legacyIntent = JSON.parse(
|
|
await fs.readFile(legacyPath, "utf8"),
|
|
) as Record<string, unknown>;
|
|
delete legacyIntent.preflightActiveRunIds;
|
|
legacyIntent.shutdownSnapshot = {
|
|
capturedAt: "2026-08-01T00:06:00.000Z",
|
|
signal: "SIGTERM",
|
|
activeRuns: [
|
|
{
|
|
runId,
|
|
companyId,
|
|
agentId,
|
|
adapterType: "codex_local",
|
|
status: "running",
|
|
processPid: child.pid,
|
|
processGroupId: null,
|
|
issueId,
|
|
},
|
|
],
|
|
};
|
|
await fs.writeFile(
|
|
legacyPath,
|
|
`${JSON.stringify(legacyIntent, null, 2)}\n`,
|
|
"utf8",
|
|
);
|
|
|
|
const mergedIntent = await readHotRestartIntent();
|
|
expect(mergedIntent).toMatchObject({
|
|
preflightActiveRunIds: [runId],
|
|
shutdownSnapshot: {
|
|
activeRuns: [
|
|
expect.objectContaining({ runId, processPid: child.pid }),
|
|
],
|
|
},
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const adoption = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-08-01T00:07:00.000Z"),
|
|
);
|
|
expect(adoption).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [runId],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [],
|
|
});
|
|
});
|
|
});
|
|
|
|
it("reports preflight live runs as lost when the shutdown snapshot is missing", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: process.pid,
|
|
processGroupId: null,
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "missing-snapshot-version",
|
|
requestedAt: new Date("2026-08-01T01:05:00.000Z"),
|
|
preflightActiveRunIds: [runId],
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const adoption = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-08-01T01:07:00.000Z"),
|
|
);
|
|
expect(adoption).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [runId],
|
|
});
|
|
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as Record<string, unknown>;
|
|
expect(report).toMatchObject({
|
|
adoptedRunIds: [],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [runId],
|
|
});
|
|
});
|
|
});
|
|
|
|
it("reports a preflight run that finished before snapshot capture as finalized", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: process.pid,
|
|
processGroupId: null,
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "preflight-race-version",
|
|
requestedAt: new Date("2026-08-01T01:08:00.000Z"),
|
|
preflightActiveRunIds: [runId],
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "succeeded",
|
|
finishedAt: new Date("2026-08-01T01:08:01.000Z"),
|
|
updatedAt: new Date("2026-08-01T01:08:01.000Z"),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const adoption = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-08-01T01:09:00.000Z"),
|
|
);
|
|
expect(adoption).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [],
|
|
finalizedWhileDownRunIds: [runId],
|
|
lostRunIds: [],
|
|
});
|
|
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as { runs?: Array<Record<string, unknown>> };
|
|
expect(report.runs).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
runId,
|
|
classification: "finalized_while_down",
|
|
reason: "run_status_succeeded",
|
|
}),
|
|
]),
|
|
);
|
|
});
|
|
});
|
|
|
|
it("persists codex_local spawn identity before hot restart and never loses the live run for missing metadata", async () => {
|
|
let releaseAdapter!: () => void;
|
|
const adapterRelease = new Promise<void>(resolve => { releaseAdapter = resolve; });
|
|
let spawnedPid: number | null = null;
|
|
const adapterStarted = new Promise<void>((resolve) => {
|
|
mockAdapterExecute.mockImplementationOnce(async (rawInput?: unknown) => {
|
|
const input = rawInput as {
|
|
onSpawn?: (meta: {
|
|
pid: number;
|
|
processGroupId: number | null;
|
|
startedAt: string;
|
|
}) => Promise<void>;
|
|
};
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
if (!child.pid)
|
|
throw new Error("Test codex_local child did not expose a pid");
|
|
spawnedPid = child.pid;
|
|
await input.onSpawn?.({
|
|
pid: child.pid,
|
|
processGroupId: null,
|
|
startedAt: new Date("2026-07-30T07:00:00.000Z").toISOString(),
|
|
});
|
|
resolve();
|
|
await adapterRelease;
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Codex run completed after hot restart adoption.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
});
|
|
});
|
|
const { runId } = await seedRunFixture({
|
|
adapterType: "codex_local",
|
|
agentStatus: "idle",
|
|
runStatus: "queued",
|
|
processPid: null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "cli",
|
|
processTopology: "detached",
|
|
},
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await Promise.race([
|
|
adapterStarted,
|
|
new Promise<never>((_, reject) => {
|
|
setTimeout(
|
|
() =>
|
|
reject(
|
|
new Error("Timed out waiting for codex_local spawn identity"),
|
|
),
|
|
3_000,
|
|
);
|
|
}),
|
|
]);
|
|
|
|
const running = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row?.status === "running" && row.processPid ? row : null;
|
|
}),
|
|
);
|
|
const observedProcessStartedAt = await readProcessStartedAt(spawnedPid!);
|
|
expect(observedProcessStartedAt).not.toBeNull();
|
|
expect(running).toMatchObject({
|
|
id: runId,
|
|
status: "running",
|
|
processPid: spawnedPid,
|
|
processGroupId: null,
|
|
processStartedAt: new Date(observedProcessStartedAt!),
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-version",
|
|
requestedAt: new Date("2026-07-30T07:01:00.000Z"),
|
|
});
|
|
await heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-07-30T07:02:00.000Z"),
|
|
);
|
|
|
|
const adoption = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-07-30T07:03:00.000Z"),
|
|
);
|
|
expect(adoption).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [runId],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [],
|
|
});
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as { runs?: Array<Record<string, unknown>> };
|
|
expect(report.runs).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
runId,
|
|
classification: "adopted",
|
|
reason: "process_pid_alive",
|
|
}),
|
|
]),
|
|
);
|
|
expect(report.runs).not.toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
runId,
|
|
reason: "missing_process_metadata",
|
|
}),
|
|
]),
|
|
);
|
|
});
|
|
|
|
releaseAdapter();
|
|
const settled = await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
expect(settled?.status).toBe("succeeded");
|
|
} finally {
|
|
releaseAdapter();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
}
|
|
});
|
|
|
|
it("reports adopted hot-restart runs before startup reap can mark them process_lost", async () => {
|
|
const child = spawnAliveProcess();
|
|
childProcesses.add(child);
|
|
expect(child.pid).toBeGreaterThan(0);
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: child.pid ?? null,
|
|
processGroupId: null,
|
|
contextSnapshot: {
|
|
executionEngine: "cli",
|
|
processTopology: "detached",
|
|
},
|
|
});
|
|
|
|
await withTempPaperclipHome(async (home) => {
|
|
const heartbeat = heartbeatService(db);
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-version",
|
|
requestedAt: new Date("2026-03-19T00:05:00.000Z"),
|
|
});
|
|
await heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-03-19T00:06:00.000Z"),
|
|
);
|
|
|
|
const adoption = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-03-19T00:07:00.000Z"),
|
|
);
|
|
expect(adoption).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [runId],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [],
|
|
skippedRunIds: [],
|
|
});
|
|
|
|
const report = JSON.parse(
|
|
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
|
) as Record<string, unknown>;
|
|
expect(report).toMatchObject({
|
|
previousServerPid: process.pid,
|
|
newServerPid: process.pid,
|
|
previousServerVersion: "old-version",
|
|
adoptedRunIds: [runId],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [],
|
|
});
|
|
expect(typeof report.newServerVersion).toBe("string");
|
|
|
|
const reap = await heartbeat.reapOrphanedRuns();
|
|
expect(reap).toEqual({ reaped: 0, runIds: [] });
|
|
const adopted = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(adopted?.status).toBe("running");
|
|
expect(adopted?.errorCode).not.toBe("process_lost");
|
|
expect(adopted?.resultJson).toMatchObject({
|
|
hotRestart: {
|
|
adopted: true,
|
|
adoptedAt: "2026-03-19T00:07:00.000Z",
|
|
previousServerPid: process.pid,
|
|
newServerPid: process.pid,
|
|
previousServerVersion: "old-version",
|
|
processPid: child.pid,
|
|
},
|
|
});
|
|
});
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"keeps process-group-only hot-restart adoptions out of process_lost reaping",
|
|
async () => {
|
|
const orphan = await spawnOrphanedProcessGroup();
|
|
cleanupPids.add(orphan.descendantPid);
|
|
expect(isPidAlive(orphan.descendantPid)).toBe(true);
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
processPid: orphan.processPid,
|
|
processGroupId: orphan.processGroupId,
|
|
contextSnapshot: {
|
|
executionEngine: "cli",
|
|
processTopology: "detached",
|
|
},
|
|
});
|
|
|
|
await withTempPaperclipHome(async () => {
|
|
const heartbeat = heartbeatService(db);
|
|
await writeHotRestartIntent({
|
|
previousServerPid: process.pid,
|
|
previousServerVersion: "old-version",
|
|
requestedAt: new Date("2026-03-19T00:05:00.000Z"),
|
|
});
|
|
await heartbeat.prepareHotRestartShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-03-19T00:06:00.000Z"),
|
|
);
|
|
|
|
const adoption = await heartbeat.reconcileHotRestartAdoption(
|
|
new Date("2026-03-19T00:07:00.000Z"),
|
|
);
|
|
expect(adoption).toMatchObject({
|
|
mode: "reported",
|
|
adoptedRunIds: [runId],
|
|
finalizedWhileDownRunIds: [],
|
|
lostRunIds: [],
|
|
skippedRunIds: [],
|
|
});
|
|
|
|
const reap = await heartbeat.reapOrphanedRuns();
|
|
expect(reap).toEqual({ reaped: 0, runIds: [] });
|
|
expect(isPidAlive(orphan.descendantPid)).toBe(true);
|
|
const adopted = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(adopted?.status).toBe("running");
|
|
expect(adopted?.errorCode).not.toBe("process_lost");
|
|
expect(adopted?.resultJson).toMatchObject({
|
|
hotRestart: {
|
|
adopted: true,
|
|
processPid: orphan.processPid,
|
|
processGroupId: orphan.processGroupId,
|
|
},
|
|
});
|
|
});
|
|
},
|
|
);
|
|
|
|
it("terminalizes an unsupported legacy session on shutdown without speculative replay", async () => {
|
|
const { agentId, runId, issueId, wakeupRequestId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "running",
|
|
});
|
|
const result = await heartbeatService(db).drainRunningRunsForShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-03-19T00:06:00.000Z"),
|
|
);
|
|
expect(result.interruptedRunIds).toEqual([runId]);
|
|
expect(result.retryRunIds).toEqual([]);
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
id: runId,
|
|
status: "interrupted",
|
|
errorCode: "server_shutdown_interrupted",
|
|
signal: "SIGTERM",
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId)),
|
|
).toEqual([expect.objectContaining({ status: "cancelled" })]);
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
assigneeAgentId: agentId,
|
|
executionRunId: null,
|
|
checkoutRunId: null,
|
|
}),
|
|
]);
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
ownerType: "board",
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("hands off the same portable task lease during in-flight workspace preparation on graceful shutdown", async () => {
|
|
const f = await seedRunFixture({ adapterType: "paperclip_runner", agentStatus: "idle", runStatus: "queued", runtimeMode: "legacy" });
|
|
await db.update(heartbeatRuns).set({ scopeKind: "issue", issueId: f.issueId }).where(eq(heartbeatRuns.id, f.runId));
|
|
await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, f.runId));
|
|
const { leaseId } = await seedEnvironmentLeaseFixture({ ...f, driver: "plugin", provider: "plugin:fixture:tasks" });
|
|
await db.update(environmentLeases).set({ providerLeaseId: "same-portable-task", metadata: {
|
|
driver: "plugin", agentId: f.agentId, runnerTaskLease: true, portableTaskPreviousLeaseId: randomUUID(),
|
|
} }).where(eq(environmentLeases.id, leaseId));
|
|
let finishPreparation!: () => void;
|
|
const providerReply = new Promise<void>(resolve => { finishPreparation = resolve; });
|
|
const reachedPreparation = vi.fn();
|
|
const preparation = vi.spyOn(workspacePreparation, "prepareHeartbeatWorkspace").mockImplementationOnce(async (_db, input) => {
|
|
await input.controllerLease.assertOwned();
|
|
reachedPreparation();
|
|
await providerReply;
|
|
await input.controllerLease.assertOwned();
|
|
throw new Error("Old controller unexpectedly kept preparation authority");
|
|
});
|
|
const runtime = environmentRuntimeService(db);
|
|
const release = vi.spyOn(runtime, "releaseRunLeases");
|
|
const heartbeat = heartbeatService(db, { environmentRuntime: runtime });
|
|
try {
|
|
await heartbeat.resumeQueuedRunsForAgent(f.companyId, f.agentId);
|
|
await vi.waitFor(() => expect(reachedPreparation).toHaveBeenCalledOnce(), { timeout: 10_000 });
|
|
expect(await heartbeat.drainRunningRunsForShutdown("SIGTERM", new Date(), [f.runId])).toMatchObject({
|
|
restartSuspendedRunIds: [f.runId], interruptedRunIds: [], retryRunIds: [],
|
|
});
|
|
finishPreparation();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(run).toMatchObject({ status: "running", runtimeMode: "legacy", executionStage: "preparing" });
|
|
expect(run.controllerLeaseExpiresAt!.getTime()).toBeLessThanOrEqual(Date.now());
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0])
|
|
.toMatchObject({ heartbeatRunId: f.runId, status: "active", providerLeaseId: "same-portable-task" });
|
|
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].executionRunId).toBe(f.runId);
|
|
expect(release).not.toHaveBeenCalled();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
} finally {
|
|
finishPreparation();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
preparation.mockRestore();
|
|
release.mockRestore();
|
|
}
|
|
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
|
|
|
it.each([
|
|
{ name: "still preparing", resumes: true },
|
|
{ name: "admitted to dispatch", stage: "dispatching", resumes: false },
|
|
{ name: "with a dispatch handoff receipt", handoff: true, resumes: false },
|
|
{ name: "with a process identity", processStarted: true, resumes: false },
|
|
{ name: "with an adapter.invoke event", invoked: true, resumes: false },
|
|
{ name: "with a workspace restore failure", restoreFailure: true, resumes: false },
|
|
] as Array<{ name: string; resumes: boolean; stage?: string; handoff?: boolean; processStarted?: boolean;
|
|
invoked?: boolean; restoreFailure?: boolean }>)("resumes a legacy run that a graceful shutdown stopped before adapter dispatch ($name)", async (variant) => {
|
|
const { resumes } = variant;
|
|
const { agentId, runId, issueId } = await seedRunFixture({ adapterType: "process", agentStatus: "running" });
|
|
await db.update(heartbeatRuns).set({
|
|
controllerBootId: controllerLeases.legacyControllerBootId,
|
|
controllerLeaseExpiresAt: new Date(Date.now() + 60_000),
|
|
executionStage: variant.stage ?? "preparing",
|
|
startedAt: new Date(),
|
|
...(variant.handoff ? { usageJson: { budgetDispatch: { reservationId: randomUUID(), recoveryLeaseOwner: null,
|
|
admittedAt: new Date().toISOString(), handedOffAt: new Date().toISOString() } } } : {}),
|
|
...(variant.processStarted ? { processStartedAt: new Date() } : {}),
|
|
...(variant.restoreFailure ? { resultJson: { workspaceRestoreFailure: "restore_unsafe_archive" } } : {}),
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
// Setup had not reached the adapter: no adapter.invoke was recorded.
|
|
if (!variant.invoked) await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId));
|
|
|
|
const result = await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM");
|
|
|
|
expect(result.interruptedRunIds).toEqual([runId]);
|
|
const [interrupted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(interrupted).toMatchObject({ status: "interrupted", errorCode: "server_shutdown_interrupted" });
|
|
if (resumes) {
|
|
expect(interrupted!.resultJson?.executionRecovery).toEqual({ kind: "bootstrap", providerWorkStarted: false });
|
|
expect(result.retryRunIds).toHaveLength(1);
|
|
expect(await selectRecoveryActionsForIssue(issueId)).toEqual([]);
|
|
expect(await getExecutionBlocker(db, interrupted!.companyId, issueId)).toBeNull();
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({ id: result.retryRunIds[0], retryOfRunId: runId, status: "scheduled_retry" }),
|
|
]));
|
|
} else {
|
|
expect(interrupted!.resultJson?.executionRecovery).toBeUndefined();
|
|
expect(result.retryRunIds).toEqual([]);
|
|
expect(await selectRecoveryActionsForIssue(issueId)).toEqual([
|
|
expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }),
|
|
]);
|
|
expect(await getExecutionBlocker(db, interrupted!.companyId, issueId)).toMatchObject({ runId });
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
{ name: "before dispatch", startedWork: false },
|
|
{ name: "after an adapter.invoke event", startedWork: true },
|
|
])("lets Retry start a run only for a pre-dispatch shutdown hold saved by an older server ($name)", async ({ startedWork }) => {
|
|
const { companyId, agentId, runId, issueId } = await seedRunFixture({ adapterType: "process", agentStatus: "idle" });
|
|
// The older server committed the interruption and its no-replay hold
|
|
// without the bootstrap certificate.
|
|
await db.update(heartbeatRuns).set({
|
|
status: "interrupted", errorCode: "server_shutdown_interrupted", error: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
finishedAt: new Date(), startedAt: new Date(Date.now() - 1_000),
|
|
controllerBootId: randomUUID(), controllerLeaseExpiresAt: null, executionStage: "preparing",
|
|
resultJson: { stopReason: "interrupted", timeoutFired: false, timeoutSource: "default", timeoutConfigured: false, effectiveTimeoutSec: 0 },
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
if (!startedWork) await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId));
|
|
await db.update(issues).set({ status: "blocked", executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId));
|
|
await db.insert(issueRecoveryActions).values({
|
|
companyId, sourceIssueId: issueId, kind: "active_run_watchdog", ownerType: "board", returnOwnerAgentId: agentId,
|
|
cause: "legacy_execution_requires_reconciliation", fingerprint: `legacy-execution:${runId}`, status: "active",
|
|
evidence: { runId, originalFailureCode: "server_shutdown_interrupted", adapterRecovery: "unsupported_or_unknown", attempt: 1 },
|
|
nextAction: "Inspect the stopped provider and recorded actions, then reconcile their outcomes before continuing.",
|
|
attemptCount: 1, maxAttempts: 3,
|
|
});
|
|
|
|
if (startedWork) {
|
|
// The adapter may have acted: the hold stays and no replay is admitted.
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId });
|
|
return;
|
|
}
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
const heartbeat = heartbeatService(db);
|
|
const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "responsible-user",
|
|
idempotencyKey: randomUUID(), observedRunId: runId });
|
|
expect(receipt.accepted).toBe(true);
|
|
await heartbeat.resumeTaskRetry(companyId, receipt.requestId!);
|
|
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!));
|
|
expect(wake?.payload?.executionWait).toBeUndefined();
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs.filter(run => run.id !== runId)).toHaveLength(1);
|
|
await heartbeat.drainActiveRunExecutions();
|
|
});
|
|
|
|
it("suspends native Paperclip Runner ownership on graceful restart without cancelling or creating a retry run", async () => {
|
|
const { agentId, runId, issueId, wakeupRequestId } = await seedRunFixture({
|
|
adapterType: "paperclip_runner",
|
|
agentStatus: "running",
|
|
runtimeMode: "native",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ nativeIssueId: issueId })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(nativeRunFinalizations).values({
|
|
runId,
|
|
companyId: (await heartbeatService(db).getRun(runId))!.companyId,
|
|
issueId,
|
|
phase: "observed",
|
|
});
|
|
|
|
const result = await heartbeatService(db).drainRunningRunsForShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-09-04T12:00:00.000Z"),
|
|
);
|
|
|
|
expect(result).toMatchObject({
|
|
interrupted: 0,
|
|
interruptedRunIds: [],
|
|
retryRunIds: [],
|
|
restartSuspendedRunIds: [runId],
|
|
});
|
|
expect(mockDetachNativeSessionsForRestart).toHaveBeenCalledWith([runId]);
|
|
await expect(
|
|
selectRecoveryRunsByAgent(agentId),
|
|
).resolves.toEqual([
|
|
expect.objectContaining({
|
|
id: runId,
|
|
status: "running",
|
|
retryOfRunId: null,
|
|
}),
|
|
]);
|
|
await expect(
|
|
db
|
|
.select({ recoveryState: nativeRunFinalizations.recoveryState })
|
|
.from(nativeRunFinalizations)
|
|
.where(eq(nativeRunFinalizations.runId, runId)),
|
|
).resolves.toEqual([{ recoveryState: "awaiting_runner_reattach" }]);
|
|
await expect(
|
|
db
|
|
.select({ status: agentWakeupRequests.status })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId)),
|
|
).resolves.toEqual([{ status: "claimed" }]);
|
|
await expect(
|
|
db
|
|
.select({ executionRunId: issues.executionRunId })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId)),
|
|
).resolves.toEqual([{ executionRunId: runId }]);
|
|
});
|
|
|
|
it("does not overwrite a run that is no longer running during graceful shutdown drain", async () => {
|
|
const { runId, wakeupRequestId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "succeeded",
|
|
finishedAt: new Date("2026-03-19T00:05:30.000Z"),
|
|
updatedAt: new Date("2026-03-19T00:05:30.000Z"),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const result = await heartbeat.drainRunningRunsForShutdown(
|
|
"SIGTERM",
|
|
new Date("2026-03-19T00:06:00.000Z"),
|
|
);
|
|
|
|
expect(result).toMatchObject({
|
|
interrupted: 0,
|
|
interruptedRunIds: [],
|
|
retryRunIds: [],
|
|
});
|
|
const run = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(run).toMatchObject({
|
|
status: "succeeded",
|
|
errorCode: null,
|
|
signal: null,
|
|
});
|
|
const wakeup = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(wakeup?.status).toBe("claimed");
|
|
});
|
|
|
|
it("does not duplicate a legacy reconciliation action across repeated shutdowns", async () => {
|
|
const { agentId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "running",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.drainRunningRunsForShutdown("SIGTERM");
|
|
await heartbeat.drainRunningRunsForShutdown("SIGTERM");
|
|
await heartbeatService(db).reapOrphanedRuns();
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toEqual([expect.objectContaining({ id: runId, status: "interrupted" })]);
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it("preserves a settled no-replay decision across repeated terminalization while holding a new source run", async () => {
|
|
const { companyId, agentId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "idle",
|
|
runStatus: "failed",
|
|
});
|
|
const { settleUnrecoverableExecutions } = await import("../services/execution-recovery-resolution.js");
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
await terminalizeLegacyExecution({ db, run: run!, status: "failed" });
|
|
await settleUnrecoverableExecutions(db);
|
|
const [settled] = await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
|
expect(settled).toMatchObject({
|
|
status: "resolved",
|
|
outcome: "blocked",
|
|
evidence: { runId, automaticRecovery: { replay: "blocked" } },
|
|
});
|
|
|
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
await terminalizeLegacyExecution({ db, run: current!, status: "failed" });
|
|
await settleUnrecoverableExecutions(db);
|
|
}
|
|
expect(await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([settled]);
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId });
|
|
|
|
const [newSource] = await db.insert(heartbeatRuns).values({
|
|
companyId, agentId, status: "failed", contextSnapshot: { issueId },
|
|
}).returning();
|
|
await terminalizeLegacyExecution({ db, run: newSource!, status: "failed" });
|
|
const actions = await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
|
expect(actions).toHaveLength(2);
|
|
expect(actions.find((action) => action.id === settled!.id)).toEqual(settled);
|
|
expect(actions.find((action) => action.id !== settled!.id)).toMatchObject({
|
|
status: "active",
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
fingerprint: `legacy-execution:${newSource!.id}`,
|
|
evidence: { runId: newSource!.id },
|
|
});
|
|
});
|
|
|
|
it("does not reset an exhausted incident budget on server restart", async () => {
|
|
// A restart continues a run without spending failures, so the exhausted
|
|
// budget here is the server-restart bound of the open window.
|
|
const { agentId, runId, issueId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
contextSnapshot: { executionRetryAccounting: spentRestartRetryAccounting() },
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
scheduledRetryAttempt: 2,
|
|
resultJson: {
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM");
|
|
const reconciled = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
// The budget stays spent across the restart: no successor run is
|
|
// queued, by the process-loss retry or by the sweeper.
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toHaveLength(1);
|
|
// A spent budget is no longer left to sit: the sweeper escalates the
|
|
// issue to a board-owned recovery action instead of skipping it on
|
|
// every tick with no live path. The action spawns no run of its own.
|
|
expect(reconciled.escalated).toBe(1);
|
|
const recoveryActions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(recoveryActions).toHaveLength(1);
|
|
expect(recoveryActions[0]).toMatchObject({ status: "active", ownerType: "board", ownerAgentId: null });
|
|
const escalatedIssue = await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(escalatedIssue?.status).toBe("blocked");
|
|
// And the escalation is idempotent across further sweeps.
|
|
const again = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(again.escalated).toBe(0);
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it("releases active environment leases when an orphaned run is reaped", async () => {
|
|
const { runId, issueId, companyId } = await seedRunFixture({
|
|
processPid: 999_999_999,
|
|
});
|
|
const { leaseId } = await seedEnvironmentLeaseFixture({
|
|
companyId,
|
|
runId,
|
|
issueId,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(1);
|
|
expect(result.runIds).toEqual([runId]);
|
|
|
|
const lease = await db
|
|
.select()
|
|
.from(environmentLeases)
|
|
.where(eq(environmentLeases.id, leaseId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(lease?.status).toBe("failed");
|
|
expect(lease?.releasedAt).toBeTruthy();
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"does not signal an unowned persisted process group after the tracked parent exits",
|
|
async () => {
|
|
const orphan = await spawnOrphanedProcessGroup();
|
|
cleanupPids.add(orphan.descendantPid);
|
|
expect(isPidAlive(orphan.descendantPid)).toBe(true);
|
|
|
|
const { agentId, runId } = await seedRunFixture({
|
|
agentStatus: "idle",
|
|
processPid: orphan.processPid,
|
|
processGroupId: orphan.processGroupId,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(0);
|
|
expect(result.runIds).toEqual([]);
|
|
|
|
expect(isPidAlive(orphan.descendantPid)).toBe(true);
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]).toMatchObject({
|
|
id: runId,
|
|
status: "running",
|
|
errorCode: "process_detached",
|
|
});
|
|
expect(runs[0]?.error).toContain(
|
|
`persisted process group ${orphan.processGroupId}`,
|
|
);
|
|
},
|
|
);
|
|
|
|
it("does not bypass unknown process outcomes through immediate continuation recovery", async () => {
|
|
const { agentId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "idle",
|
|
processPid: 999_999_999,
|
|
failureRetryBudgetSpent: true,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.reapOrphanedRuns();
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toEqual([expect.objectContaining({ id: runId, status: "failed" })]);
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
returnOwnerAgentId: agentId,
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("blocks failed recovery work in place during immediate terminal-run cleanup", async () => {
|
|
const sourceIssueId = randomUUID();
|
|
const { companyId, agentId, runId, issueId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "idle",
|
|
processPid: 999_999_999,
|
|
failureRetryBudgetSpent: true,
|
|
runErrorCode: "process_lost",
|
|
runError: "Authorization: Bearer sk-test-recovery-secret",
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
title: "Recover stalled issue PAP-1",
|
|
originKind: "stranded_issue_recovery",
|
|
originId: sourceIssueId,
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
await db.insert(issues).values({
|
|
id: sourceIssueId,
|
|
companyId,
|
|
title: "Original stranded source",
|
|
status: "blocked",
|
|
priority: "medium",
|
|
issueNumber: 2,
|
|
identifier: `${issuePrefix}-2`,
|
|
});
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId,
|
|
relatedIssueId: sourceIssueId,
|
|
type: "blocks",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(1);
|
|
expect(result.runIds).toEqual([runId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]?.status).toBe("failed");
|
|
|
|
const [recoveryIssue] = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId));
|
|
expect(recoveryIssue).toMatchObject({
|
|
assigneeAgentId: agentId,
|
|
originKind: "stranded_issue_recovery",
|
|
originId: sourceIssueId,
|
|
executionRunId: null,
|
|
checkoutRunId: null,
|
|
});
|
|
const actions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(actions).toEqual([
|
|
expect.objectContaining({
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
ownerType: "board",
|
|
}),
|
|
]);
|
|
expect(JSON.stringify(actions)).not.toContain("sk-test-recovery-secret");
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.originKind, "stranded_issue_recovery"),
|
|
eq(issues.originId, issueId),
|
|
),
|
|
),
|
|
).toHaveLength(0);
|
|
await expect(
|
|
sourceBlockerIssueIds(companyId, sourceIssueId),
|
|
).resolves.toEqual([issueId]);
|
|
});
|
|
|
|
it("does not block paused-tree work when immediate continuation recovery is suppressed by the hold", async () => {
|
|
const { companyId, agentId, runId, issueId } = await seedRunFixture({
|
|
agentStatus: "idle",
|
|
processPid: 999_999_999,
|
|
failureRetryBudgetSpent: true,
|
|
});
|
|
await db.insert(issueTreeHolds).values({
|
|
companyId,
|
|
rootIssueId: issueId,
|
|
mode: "pause",
|
|
status: "active",
|
|
reason: "pause immediate recovery subtree",
|
|
releasePolicy: { strategy: "manual" },
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(1);
|
|
expect(result.runIds).toEqual([runId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]?.status).toBe("failed");
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_progress");
|
|
expect(issue?.executionRunId).toBeNull();
|
|
// Terminal run cleanup releases the checkout lock even when paused-tree recovery is suppressed.
|
|
expect(issue?.checkoutRunId).toBeNull();
|
|
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(0);
|
|
});
|
|
|
|
it("allows conversation continuation after a transient remote-compaction failure", async () => {
|
|
mockAdapterExecute.mockResolvedValueOnce({
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorCode: "adapter_failed",
|
|
errorFamily: "transient_upstream",
|
|
errorMessage:
|
|
"Error running remote compact task: We're currently experiencing high demand, which may cause temporary errors.",
|
|
provider: "openai",
|
|
model: "gpt-5.4",
|
|
resultJson: {
|
|
errorFamily: "transient_upstream",
|
|
},
|
|
});
|
|
|
|
const { agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
expect(runs.find(run => run.id === runId)).toMatchObject({
|
|
status: "failed", errorCode: "adapter_failed", resultJson: { errorFamily: "transient_upstream" },
|
|
});
|
|
expect(runs.find(run => run.retryOfRunId === runId)).toMatchObject({
|
|
status: "scheduled_retry", scheduledRetryAttempt: 1,
|
|
});
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toEqual([]);
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("schedules bounded retries for failed accepted interaction continuation wakes", async () => {
|
|
const { companyId, agentId, runId, wakeupRequestId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: {
|
|
type: "issue_document",
|
|
issueId,
|
|
key: "plan",
|
|
revisionId: randomUUID(),
|
|
},
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
payload: {
|
|
issueId,
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
mutation: "interaction",
|
|
},
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
invocationSource: "automation",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_progress" })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
mockAdapterExecute.mockResolvedValueOnce({
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorCode: "adapter_failed",
|
|
errorMessage:
|
|
'Failed to start command "codex" in "/workspace". Verify adapter command, working directory, and PATH.',
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
|
|
const runs = await waitForValue(async () => {
|
|
const rows = await selectRecoveryRunsByAgent(agentId);
|
|
if (rows.length < 2) return null;
|
|
// Gate on the *terminal* write of the background recovery, not the
|
|
// intermediate retry-run commit. recordPlanApprovalResumeFailureRetry
|
|
// writes the system comment first and updates the interaction
|
|
// result.resumeFailure last (heartbeat.ts:5627 then :5632), so once
|
|
// resumeFailure.status is observed the comment + issue update are also
|
|
// committed and every assertion below is race-free.
|
|
const interactionRow = await db
|
|
.select({ result: issueThreadInteractions.result })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId))
|
|
.then((interactionRows) => interactionRows[0] ?? null);
|
|
const result = interactionRow?.result ?? null;
|
|
const resumeFailure =
|
|
result && "resumeFailure" in result ? result.resumeFailure : null;
|
|
return resumeFailure?.status === "retrying" ? rows : null;
|
|
});
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const failedRun = runs?.find((row) => row.id === runId);
|
|
const retryRun = runs?.find((row) => row.id !== runId);
|
|
expect(failedRun).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "adapter_failed",
|
|
});
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
retryOfRunId: runId,
|
|
scheduledRetryAttempt: 1,
|
|
scheduledRetryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
});
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
interactionId,
|
|
interactionStatus: "accepted",
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
|
|
const wakeups = await db
|
|
.select({
|
|
id: agentWakeupRequests.id,
|
|
status: agentWakeupRequests.status,
|
|
reason: agentWakeupRequests.reason,
|
|
runId: agentWakeupRequests.runId,
|
|
payload: agentWakeupRequests.payload,
|
|
})
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.agentId, agentId));
|
|
expect(wakeups.find((row) => row.id === wakeupRequestId)).toMatchObject({
|
|
status: "failed",
|
|
reason: "issue_commented",
|
|
runId,
|
|
});
|
|
expect(wakeups.find((row) => row.runId === retryRun?.id)).toMatchObject({
|
|
status: "queued",
|
|
reason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
payload: expect.objectContaining({
|
|
issueId,
|
|
interactionId,
|
|
retryOfRunId: runId,
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
scheduledRetryAttempt: 1,
|
|
}),
|
|
});
|
|
|
|
const issue = await db
|
|
.select({ status: issues.status, executionRunId: issues.executionRunId })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(issue).toEqual({
|
|
status: "in_progress",
|
|
executionRunId: retryRun?.id ?? null,
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]).toMatchObject({
|
|
authorType: "system",
|
|
createdByRunId: runId,
|
|
body: "Agent failed to resume after approval: `adapter_failed` — retrying (attempt 1/2)",
|
|
});
|
|
|
|
const interaction = await db
|
|
.select({ result: issueThreadInteractions.result })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(interaction?.result).toMatchObject({
|
|
version: 1,
|
|
outcome: "accepted",
|
|
resumeFailure: {
|
|
status: "retrying",
|
|
errorCode: "adapter_failed",
|
|
attempt: 1,
|
|
maxAttempts: 2,
|
|
runId,
|
|
retryRunId: retryRun?.id ?? null,
|
|
},
|
|
});
|
|
mockAdapterExecute.mockClear();
|
|
});
|
|
|
|
it("schedules an infra retry for a setup failure caused by a transient sandbox provider worker restart", async () => {
|
|
// Model a configured plugin manager whose worker is mid-restart when
|
|
// a run tries to acquire a lease. A missing manager is a wiring error,
|
|
// not a worker restart. The lease
|
|
// acquisition fails BEFORE the adapter is ever dispatched (no call to
|
|
// mockAdapterExecute), so this hits the setup-failure catch (errorCode
|
|
// "setup_failed") rather than the adapter-failure catch. The condition is
|
|
// transient and self-healing, so it must be classified retryable
|
|
// infrastructure, not a terminal setup failure.
|
|
const { companyId, agentId, runId, wakeupRequestId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
const pluginId = randomUUID();
|
|
const environmentId = randomUUID();
|
|
|
|
await db.insert(plugins).values({
|
|
id: pluginId,
|
|
pluginKey: "paperclip.kubernetes-sandbox-provider",
|
|
packageName: "@paperclipai/kubernetes-sandbox-provider",
|
|
version: "1.0.0",
|
|
apiVersion: 1,
|
|
categories: ["automation"],
|
|
manifestJson: {
|
|
id: "paperclip.kubernetes-sandbox-provider",
|
|
apiVersion: 1,
|
|
version: "1.0.0",
|
|
displayName: "Kubernetes Sandbox Provider",
|
|
description:
|
|
"Test Kubernetes sandbox provider whose worker is mid-restart",
|
|
author: "Paperclip",
|
|
categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"],
|
|
entrypoints: { worker: "dist/worker.js" },
|
|
environmentDrivers: [
|
|
{
|
|
driverKey: "kubernetes",
|
|
kind: "sandbox_provider",
|
|
displayName: "Kubernetes Sandbox",
|
|
configSchema: { type: "object" },
|
|
},
|
|
],
|
|
},
|
|
status: "ready",
|
|
installOrder: 1,
|
|
updatedAt: new Date(),
|
|
} as any);
|
|
await db.insert(environments).values({
|
|
id: environmentId,
|
|
name: "Kubernetes Sandbox",
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "kubernetes",
|
|
image: "fake:test",
|
|
timeoutMs: 1234,
|
|
reuseLease: false,
|
|
},
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({ defaultEnvironmentId: environmentId })
|
|
.where(eq(agents.id, agentId));
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: {
|
|
type: "issue_document",
|
|
issueId,
|
|
key: "plan",
|
|
revisionId: randomUUID(),
|
|
},
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
payload: {
|
|
issueId,
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
mutation: "interaction",
|
|
},
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
invocationSource: "automation",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_progress" })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const heartbeat = heartbeatService(db, {
|
|
pluginWorkerManager: {
|
|
isRunning: () => false,
|
|
call: vi.fn(),
|
|
} as unknown as PluginWorkerManager,
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
|
|
// The real manager waits up to five seconds for worker readiness before
|
|
// lease acquisition fails and the heartbeat can schedule its retry.
|
|
const runs = await waitForValue(async () => {
|
|
const rows = await selectRecoveryRunsByAgent(agentId);
|
|
return rows.length >= 2 ? rows : null;
|
|
}, 10_000);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const failedRun = runs?.find((row) => row.id === runId);
|
|
const retryRun = runs?.find((row) => row.id !== runId);
|
|
expect(failedRun?.status).toBe("failed");
|
|
expect(failedRun?.errorCode).toBe("plugin_worker_unavailable");
|
|
expect(failedRun?.error).toContain("worker is not running");
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
retryOfRunId: runId,
|
|
scheduledRetryAttempt: 1,
|
|
scheduledRetryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
});
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
interactionId,
|
|
interactionStatus: "accepted",
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
|
|
// The lease never succeeded, so the adapter was never dispatched.
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const issue = await db
|
|
.select({ status: issues.status, executionRunId: issues.executionRunId })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(issue).toEqual({
|
|
status: "in_progress",
|
|
executionRunId: retryRun?.id ?? null,
|
|
});
|
|
|
|
mockAdapterExecute.mockClear();
|
|
});
|
|
|
|
describe("transient sandbox provider refusal during lease acquisition", () => {
|
|
// Daytona answered sandbox create with HTTP 502 and the provisional
|
|
// allocation's cleanup could not be confirmed, exactly as staging recorded.
|
|
const daytonaCreate502 = () => new JsonRpcCallError({ code: -32000,
|
|
message: "Daytona sandbox creation failed (HTTP 502); cleanup could not be confirmed for paperclip-create-05f81d77",
|
|
data: { schema: "paperclip/environment-acquire-error/v1", providerDiagnostic: { httpStatus: 502 } } });
|
|
|
|
// EP1: Daytona's own acquisition deadline expired while the provisional
|
|
// sandbox was still being created, as staging recorded at 14:00-14:45Z when
|
|
// concurrent runs rose from about 8 to about 20. The environment runtime
|
|
// records the validated acquisition diagnostic for this run before rethrowing.
|
|
// The chaos fault EP1 injects these same shapes (environment-lease-fault-injection.ts).
|
|
type LeaseFault = (input: { companyId: string; environment: { id: string }; heartbeatRunId?: string | null }) => Error;
|
|
const daytonaAcquisitionDeadline: LeaseFault = input => leaseFaultError("timeout",
|
|
{ companyId: input.companyId, environmentId: input.environment.id, heartbeatRunId: input.heartbeatRunId! });
|
|
// EP1 database: a control-plane query failed while the lease was being
|
|
// recorded (staging: "Database query failed (lease_acquire_failed)").
|
|
const leaseRecordQueryFailure: LeaseFault = input => leaseFaultError("database",
|
|
{ companyId: input.companyId, environmentId: input.environment.id, heartbeatRunId: input.heartbeatRunId! });
|
|
|
|
function failLeaseAcquisition(times: number, fault: LeaseFault = daytonaCreate502) {
|
|
let remaining = times;
|
|
const acquisitions = { refused: 0, delegated: 0 };
|
|
const originalFactory = environmentOrchestrator.environmentRunOrchestrator;
|
|
const factory = vi.spyOn(environmentOrchestrator, "environmentRunOrchestrator").mockImplementation((database, options = {}) => {
|
|
const runtime = originalFactory(database, options).runtime;
|
|
return originalFactory(database, { ...options, environmentRuntime: { ...runtime, acquireRunLease: async (input) => {
|
|
if (remaining > 0) {
|
|
remaining -= 1;
|
|
acquisitions.refused += 1;
|
|
throw fault(input);
|
|
}
|
|
acquisitions.delegated += 1;
|
|
return runtime.acquireRunLease(input);
|
|
} } });
|
|
});
|
|
return { acquisitions, restore: () => factory.mockRestore() };
|
|
}
|
|
|
|
async function runsFor(agentId: string) {
|
|
return (await selectRecoveryRunsByAgent(agentId)).sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime());
|
|
}
|
|
|
|
async function promoteLatestScheduledRetry(heartbeat: ReturnType<typeof heartbeatService>, agentId: string) {
|
|
const scheduled = (await runsFor(agentId)).filter(run => run.status === "scheduled_retry");
|
|
expect(scheduled).toHaveLength(1);
|
|
// Let the backoff elapse, as it would in real time, before promotion.
|
|
const due = new Date();
|
|
await db.update(heartbeatRuns).set({ scheduledRetryAt: due }).where(eq(heartbeatRuns.id, scheduled[0]!.id));
|
|
await heartbeat.promoteDueScheduledRetries(due);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
return scheduled[0]!;
|
|
}
|
|
|
|
it("retries automatically and runs exactly one successful successor without user action", async () => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const lease = failLeaseAcquisition(1);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
|
|
const afterFailure = await runsFor(agentId);
|
|
expect(afterFailure.map(run => run.status)).toEqual(["failed", "scheduled_retry"]);
|
|
expect(afterFailure[0]).toMatchObject({ id: runId, errorCode: "environment_provider_unavailable" });
|
|
expect(afterFailure[0]!.resultJson).toMatchObject({ providerFailure: { provider: "local", httpStatus: 502,
|
|
phase: "startup", retryability: "transient" } });
|
|
expect(afterFailure[1]).toMatchObject({ retryOfRunId: runId, scheduledRetryAttempt: 1 });
|
|
// The task is retrying, not blocked: no hold, and the task explains the wait.
|
|
const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(waiting).toMatchObject({ status: "in_progress", executionRunId: afterFailure[1]!.id });
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
expect(await taskInterruptionPresentation(db, waiting!)).toMatchObject({ state: "retry_scheduled", responsibility: "system",
|
|
providerFailure: { httpStatus: 502, phase: "startup", retryability: "transient" } });
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
await promoteLatestScheduledRetry(heartbeat, agentId);
|
|
const settled = await runsFor(agentId);
|
|
// Exactly one successor of the refused run, and it did the work. Later
|
|
// runs (for example disposition repair) are ordinary follow-up wakes.
|
|
const successors = settled.filter(run => run.retryOfRunId === runId);
|
|
expect(successors).toHaveLength(1);
|
|
expect(successors[0]).toMatchObject({ id: afterFailure[1]!.id, status: "succeeded" });
|
|
expect(settled.filter(run => run.errorCode === "environment_provider_unavailable").map(run => run.id)).toEqual([runId]);
|
|
expect(mockAdapterExecute).toHaveBeenCalled();
|
|
expect(lease.acquisitions.refused).toBe(1);
|
|
const [done] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(done!.status).not.toBe("blocked");
|
|
} finally {
|
|
lease.restore();
|
|
mockAdapterExecute.mockClear();
|
|
}
|
|
}, 60_000);
|
|
|
|
it("explains the block with a working Retry once automatic retries are used up", async () => {
|
|
const { companyId, agentId, issueId } = await seedQueuedIssueRunFixture();
|
|
const lease = failLeaseAcquisition(3);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await promoteLatestScheduledRetry(heartbeat, agentId);
|
|
await promoteLatestScheduledRetry(heartbeat, agentId);
|
|
|
|
const exhausted = await runsFor(agentId);
|
|
expect(exhausted.map(run => [run.status, run.errorCode])).toEqual([
|
|
["failed", "environment_provider_unavailable"],
|
|
["failed", "environment_provider_unavailable"],
|
|
["failed", "environment_provider_unavailable"],
|
|
]);
|
|
expect(lease.acquisitions.refused).toBe(3);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const blocked = await waitForValue(async () => {
|
|
const [row] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
return row?.status === "blocked" ? row : null;
|
|
});
|
|
expect(blocked).not.toBeNull();
|
|
// The blocked task names its cause, its next action, and a Retry.
|
|
const presentation = await taskInterruptionPresentation(db, blocked!);
|
|
expect(presentation).toMatchObject({ state: "failed", responsibility: "system", canRetry: true,
|
|
observedRunId: exhausted[2]!.id,
|
|
providerFailure: { httpStatus: 502, phase: "startup", retryability: "transient" } });
|
|
expect(presentation?.providerFailure?.message).toContain("temporarily unavailable");
|
|
const notices = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
|
|
expect(notices.map(comment => (comment.presentation as { title?: string } | null)?.title))
|
|
.toContain("Environment provider was temporarily unavailable");
|
|
// No no-replay hold: provider work never started.
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
|
|
const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "responsible-user",
|
|
idempotencyKey: randomUUID(), observedRunId: presentation!.observedRunId });
|
|
expect(receipt.accepted).toBe(true);
|
|
await heartbeat.resumeTaskRetry(companyId, receipt.requestId!);
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const retried = await waitForValue(async () => (await runsFor(agentId)).find(run => run.status === "succeeded") ?? null, 10_000);
|
|
expect(retried).not.toBeNull();
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
expect(lease.acquisitions.delegated).toBe(1);
|
|
} finally {
|
|
lease.restore();
|
|
mockAdapterExecute.mockClear();
|
|
}
|
|
}, 90_000);
|
|
it.each([
|
|
["a provider acquisition deadline", daytonaAcquisitionDeadline, "timeout"],
|
|
["a database error while recording the lease", leaseRecordQueryFailure, "overloaded"],
|
|
] as const)("retries %s before provider work with a bounded, visible backoff", async (_label, fault, category) => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const lease = failLeaseAcquisition(1, fault);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
|
|
const afterFailure = await runsFor(agentId);
|
|
expect(afterFailure.map(run => [run.status, run.errorCode])).toEqual([
|
|
["failed", "environment_provider_unavailable"], ["scheduled_retry", null]]);
|
|
expect(afterFailure[0]!.resultJson).toMatchObject({ providerFailure: { phase: "startup", category, retryability: "transient" },
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false } });
|
|
expect(afterFailure[1]).toMatchObject({ retryOfRunId: runId, scheduledRetryAttempt: 1, scheduledRetryReason: "transient_failure" });
|
|
const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(waiting).toMatchObject({ status: "in_progress", executionRunId: afterFailure[1]!.id });
|
|
expect(await taskInterruptionPresentation(db, waiting!)).toMatchObject({ state: "retry_scheduled", responsibility: "system" });
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
|
|
await promoteLatestScheduledRetry(heartbeat, agentId);
|
|
const successors = (await runsFor(agentId)).filter(run => run.retryOfRunId === runId);
|
|
expect(successors).toHaveLength(1);
|
|
expect(successors[0]).toMatchObject({ status: "succeeded" });
|
|
expect(lease.acquisitions.refused).toBe(1);
|
|
// The mock adapter's later disposition repair is unrelated; no setup failure reached recovery.
|
|
expect((await selectRecoveryActionsForIssue(issueId)).filter(action => action.kind === "stranded_assigned_issue")).toEqual([]);
|
|
} finally {
|
|
lease.restore();
|
|
mockAdapterExecute.mockClear();
|
|
}
|
|
}, 60_000);
|
|
|
|
it("rests a provider deadline that never clears on a working Retry, never on a board recovery action", async () => {
|
|
const { companyId, agentId, issueId } = await seedQueuedIssueRunFixture();
|
|
const lease = failLeaseAcquisition(BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS + 1, daytonaAcquisitionDeadline);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
for (let attempt = 0; attempt < BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS; attempt += 1) {
|
|
await promoteLatestScheduledRetry(heartbeat, agentId);
|
|
}
|
|
const exhausted = await runsFor(agentId);
|
|
expect(exhausted.map(run => run.errorCode)).toEqual(
|
|
Array(BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS + 1).fill("environment_provider_unavailable"));
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const blocked = await waitForValue(async () => {
|
|
const [row] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
return row?.status === "blocked" ? row : null;
|
|
});
|
|
const presentation = await taskInterruptionPresentation(db, blocked!);
|
|
expect(presentation).toMatchObject({ state: "failed", responsibility: "system", canRetry: true,
|
|
observedRunId: exhausted.at(-1)!.id, providerFailure: { category: "timeout", retryability: "transient" } });
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
|
// The task rests on a system-owned action and Retry; nothing waits on the board.
|
|
expect((await selectRecoveryActionsForIssue(issueId)).map(action => [action.ownerType, action.cause]))
|
|
.toEqual([["system", "environment_provider_unavailable"]]);
|
|
|
|
const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "responsible-user",
|
|
idempotencyKey: randomUUID(), observedRunId: presentation!.observedRunId });
|
|
expect(receipt.accepted).toBe(true);
|
|
await heartbeat.resumeTaskRetry(companyId, receipt.requestId!);
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(await waitForValue(async () => (await runsFor(agentId)).find(run => run.status === "succeeded") ?? null, 10_000))
|
|
.not.toBeNull();
|
|
expect(lease.acquisitions.delegated).toBe(1);
|
|
} finally {
|
|
lease.restore();
|
|
mockAdapterExecute.mockClear();
|
|
}
|
|
}, 90_000);
|
|
});
|
|
|
|
it("classifies only the installed-but-not-ready sandbox provider plugin message as a configuration gap", () => {
|
|
expect(
|
|
parseSandboxProviderPluginNotReadyFailureMessage(
|
|
'Sandbox provider "kubernetes" is installed via plugin "paperclip.kubernetes-sandbox-provider", but that plugin is currently error.',
|
|
),
|
|
).toEqual({
|
|
provider: "kubernetes",
|
|
pluginKey: "paperclip.kubernetes-sandbox-provider",
|
|
pluginStatus: "error",
|
|
});
|
|
expect(
|
|
parseSandboxProviderPluginNotReadyFailureMessage(
|
|
'Failed to acquire lease: Sandbox provider "daytona" is installed via plugin "paperclip.daytona-sandbox-provider", but that plugin is currently upgrade_pending.',
|
|
),
|
|
).toMatchObject({ pluginStatus: "upgrade_pending" });
|
|
expect(
|
|
parseSandboxProviderPluginNotReadyFailureMessage(
|
|
'Sandbox provider "kubernetes" is installed via plugin "x", but that plugin is currently disabled.',
|
|
),
|
|
).toMatchObject({ pluginStatus: "disabled" });
|
|
// The transient worker-restart message keeps its retryable classification.
|
|
expect(
|
|
parseSandboxProviderPluginNotReadyFailureMessage(
|
|
'Sandbox provider "kubernetes" is installed via plugin "paperclip.kubernetes-sandbox-provider", but its worker is not running.',
|
|
),
|
|
).toBeNull();
|
|
// The permanent "not installed" message is a different condition.
|
|
expect(
|
|
parseSandboxProviderPluginNotReadyFailureMessage(
|
|
'Sandbox provider "kubernetes" is not installed or its plugin worker is not running.',
|
|
),
|
|
).toBeNull();
|
|
expect(parseSandboxProviderPluginNotReadyFailureMessage(null)).toBeNull();
|
|
});
|
|
|
|
it("blocks the issue instead of re-dispatching when the sandbox provider plugin is stuck in error", async () => {
|
|
// Reproduces a production incident: the bundled Kubernetes sandbox
|
|
// provider plugin was marked `error` after one failed activation and
|
|
// nothing ever cleared it. Every run for every agent on that provider
|
|
// failed lease acquisition before dispatch with "that plugin is currently
|
|
// error", and because that message matched neither retry classifier the
|
|
// scheduler re-dispatched the same failing run every tick for days. The
|
|
// condition needs an operator, so the setup catch must record it as a
|
|
// `configuration_incomplete` gap that routes the issue to `blocked` with
|
|
// one recovery action, not as a retryable `setup_failed`.
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const pluginId = randomUUID();
|
|
const environmentId = randomUUID();
|
|
|
|
await db.insert(plugins).values({
|
|
id: pluginId,
|
|
pluginKey: "paperclip.kubernetes-sandbox-provider",
|
|
packageName: "@paperclipai/kubernetes-sandbox-provider",
|
|
version: "1.0.0",
|
|
apiVersion: 1,
|
|
categories: ["automation"],
|
|
manifestJson: {
|
|
id: "paperclip.kubernetes-sandbox-provider",
|
|
apiVersion: 1,
|
|
version: "1.0.0",
|
|
displayName: "Kubernetes Sandbox Provider",
|
|
description: "Test Kubernetes sandbox provider stuck in error",
|
|
author: "Paperclip",
|
|
categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"],
|
|
entrypoints: { worker: "dist/worker.js" },
|
|
environmentDrivers: [
|
|
{
|
|
driverKey: "kubernetes",
|
|
kind: "sandbox_provider",
|
|
displayName: "Kubernetes Sandbox",
|
|
configSchema: { type: "object" },
|
|
},
|
|
],
|
|
},
|
|
status: "error",
|
|
lastError: 'RPC call "initialize" timed out after 15000ms',
|
|
installOrder: 1,
|
|
updatedAt: new Date(),
|
|
} as any);
|
|
await db.insert(environments).values({
|
|
id: environmentId,
|
|
name: "Kubernetes Sandbox",
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "kubernetes",
|
|
image: "fake:test",
|
|
timeoutMs: 1234,
|
|
reuseLease: false,
|
|
},
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({ defaultEnvironmentId: environmentId })
|
|
.where(eq(agents.id, agentId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
|
|
// The lease never succeeded, so the adapter was never dispatched.
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const failedRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(failedRun).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "configuration_incomplete",
|
|
});
|
|
expect(failedRun?.error).toContain("that plugin is currently error");
|
|
expect(failedRun?.resultJson).toMatchObject({
|
|
configurationIncomplete: {
|
|
reason: "sandbox_provider_plugin_not_ready",
|
|
sandboxProvider: "kubernetes",
|
|
pluginKey: "paperclip.kubernetes-sandbox-provider",
|
|
pluginStatus: "error",
|
|
fingerprint:
|
|
"sandbox_provider_plugin:paperclip.kubernetes-sandbox-provider:error",
|
|
},
|
|
});
|
|
|
|
const issue = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row?.status === "blocked" ? row : null;
|
|
}),
|
|
);
|
|
expect(issue?.executionRunId).toBeNull();
|
|
|
|
// No scheduled retry and no fresh dispatch: the failed run is the only
|
|
// run this agent has.
|
|
const agentRuns = await db
|
|
.select({ id: heartbeatRuns.id, status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId));
|
|
expect(agentRuns).toEqual([{ id: runId, status: "failed" }]);
|
|
|
|
const recoveryAction = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(recoveryAction).toMatchObject({
|
|
kind: "configuration_validation",
|
|
cause: "configuration_incomplete",
|
|
status: "active",
|
|
ownerType: "board",
|
|
});
|
|
expect(recoveryAction?.nextAction).toContain("plugin that starts this agent's sandbox is not running");
|
|
expect(recoveryAction?.nextAction).toContain("enable the plugin");
|
|
|
|
const notice = await waitForValue(async () => {
|
|
const rows = await selectRecoveryCommentsForIssue(issueId);
|
|
return (
|
|
rows.find((comment) =>
|
|
comment.body.includes("paperclip.kubernetes-sandbox-provider"),
|
|
) ?? null
|
|
);
|
|
});
|
|
expect(notice?.body).toContain("is in status `error`");
|
|
expect(notice?.body).not.toContain("secret/env bindings");
|
|
});
|
|
|
|
it("escalates (does not retry) an accepted-interaction-continuation setup failure whose message matches neither retryable pattern", async () => {
|
|
// Negative-case counterpart to "schedules an infra retry for a setup
|
|
// failure caused by a transient sandbox provider worker restart" above.
|
|
// The injected failure message is the real *permanent* "provider not
|
|
// installed" message plugin-environment-driver.ts throws (see :135 and
|
|
// :233): "... is not installed or its plugin worker is not running."
|
|
// That phrase is NOT the transient lease-failure phrasing this heartbeat
|
|
// classifier is meant to catch (environment-runtime.ts:808's "is
|
|
// installed via plugin ... but its worker is not running"), so a
|
|
// correctly narrow classifier must not treat it as retryable
|
|
// infrastructure: it must escalate straight to needs-attention at
|
|
// attempt 1, not schedule a retry. If the classifier's sandbox-worker
|
|
// regex over-matches on the coincidental "worker is not running"
|
|
// substring, this test fails by finding a scheduled_retry row instead.
|
|
const { companyId, agentId, runId, wakeupRequestId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: {
|
|
type: "issue_document",
|
|
issueId,
|
|
key: "plan",
|
|
revisionId: randomUUID(),
|
|
},
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
payload: {
|
|
issueId,
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
mutation: "interaction",
|
|
},
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
invocationSource: "automation",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_progress" })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
mockAdapterExecute.mockRejectedValueOnce(
|
|
new Error(
|
|
'Sandbox provider "kubernetes" is not installed or its plugin worker is not running.',
|
|
),
|
|
);
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
|
|
const failedRun = await waitForValue(async () => {
|
|
const row = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
return row?.status === "failed" ? row : null;
|
|
});
|
|
expect(failedRun?.errorCode).toBe("adapter_failed");
|
|
expect(failedRun?.error).toContain(
|
|
"is not installed or its plugin worker is not running",
|
|
);
|
|
const report = await waitForValue(async () => mockCaptureRunFailure.mock.calls.find(([event]) => event.runId === runId)?.[0]);
|
|
expect(report?.diagnostics).toMatchObject({
|
|
execution: { failurePhase: "execute" },
|
|
exceptions: [{ stack: expect.stringContaining("heartbeat-process-recovery.test.ts") }],
|
|
});
|
|
|
|
const interaction = await waitForValue(async () => {
|
|
const row = await db
|
|
.select({ result: issueThreadInteractions.result })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId))
|
|
.then((rows) => rows[0] ?? null);
|
|
const result = row?.result ?? null;
|
|
const resumeFailure =
|
|
result && "resumeFailure" in result ? result.resumeFailure : null;
|
|
return resumeFailure?.status === "needs_attention" ? row : null;
|
|
});
|
|
expect(interaction?.result).toMatchObject({
|
|
version: 1,
|
|
outcome: "accepted",
|
|
resumeFailure: {
|
|
status: "needs_attention",
|
|
errorCode: "adapter_failed",
|
|
runId,
|
|
},
|
|
});
|
|
|
|
// No scheduled retry: the classifier's FALSE branch must not schedule
|
|
// one for this run. (A downstream, unrelated recovery reassignment run
|
|
// may still exist for the issue once it's escalated and rerouted; the
|
|
// test only cares that *this* run's failure was not classified as
|
|
// retryable infrastructure.)
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs.some((row) => row.retryOfRunId === runId)).toBe(false);
|
|
expect(
|
|
runs.some(
|
|
(row) =>
|
|
row.status === "scheduled_retry" &&
|
|
row.scheduledRetryReason ===
|
|
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
),
|
|
).toBe(false);
|
|
|
|
// Instead it escalates straight to needs-attention, same as the
|
|
// retry-exhausted path.
|
|
const issue = await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
const recoveryAction = await db
|
|
.select({
|
|
status: issueRecoveryActions.status,
|
|
sourceIssueId: issueRecoveryActions.sourceIssueId,
|
|
})
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(recoveryAction).toMatchObject({
|
|
status: "active",
|
|
sourceIssueId: issueId,
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]).toMatchObject({
|
|
authorType: "system",
|
|
body: expect.stringContaining(
|
|
"Agent failed to resume after approval: `adapter_failed` — needs attention",
|
|
),
|
|
});
|
|
|
|
mockAdapterExecute.mockClear();
|
|
});
|
|
|
|
it("escalates exhausted plan approval resume failures with a system comment and recovery action", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: {
|
|
type: "issue_document",
|
|
issueId,
|
|
key: "plan",
|
|
revisionId: randomUUID(),
|
|
},
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "failed",
|
|
error: "Failed to start command",
|
|
errorCode: "adapter_failed",
|
|
scheduledRetryAttempt: 5,
|
|
scheduledRetryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
},
|
|
finishedAt: new Date("2026-03-19T00:10:00.000Z"),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_review", executionRunId: runId })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.scheduleBoundedRetry(runId, {
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
maxAttempts: 5,
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
outcome: "retry_exhausted",
|
|
maxAttempts: 5,
|
|
});
|
|
|
|
const issue = await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
const recoveryAction = await db
|
|
.select({
|
|
id: issueRecoveryActions.id,
|
|
status: issueRecoveryActions.status,
|
|
sourceIssueId: issueRecoveryActions.sourceIssueId,
|
|
})
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(recoveryAction).toMatchObject({
|
|
status: "active",
|
|
sourceIssueId: issueId,
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]).toMatchObject({
|
|
authorType: "system",
|
|
body: expect.stringContaining(
|
|
"Agent failed to resume after approval: `adapter_failed` — needs attention",
|
|
),
|
|
});
|
|
expect(
|
|
commentMetadataRows(comments[0]).some(
|
|
(row) => row.label === "Recovery action",
|
|
),
|
|
).toBe(true);
|
|
|
|
const interaction = await db
|
|
.select({ result: issueThreadInteractions.result })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(interaction?.result).toMatchObject({
|
|
version: 1,
|
|
outcome: "accepted",
|
|
resumeFailure: {
|
|
status: "needs_attention",
|
|
errorCode: "adapter_failed",
|
|
attempt: 5,
|
|
maxAttempts: 5,
|
|
runId,
|
|
recoveryActionId: recoveryAction?.id ?? null,
|
|
},
|
|
});
|
|
});
|
|
|
|
// Positive dispatch evidence proves provider work never began. Absence of a
|
|
// PID or output alone is insufficient to authorize this bootstrap retry.
|
|
it("retries a plan-approval continuation lost as process_lost before agent start as an infrastructure failure", async () => {
|
|
const { companyId, agentId, runId, wakeupRequestId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: {
|
|
type: "issue_document",
|
|
issueId,
|
|
key: "plan",
|
|
revisionId: randomUUID(),
|
|
},
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
|
|
// The continuation wake was claimed and a run spawned, but the process was lost before
|
|
// the agent produced any output — no pid/process-group was ever recorded.
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
status: "claimed",
|
|
payload: {
|
|
issueId,
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
mutation: "interaction",
|
|
},
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "running",
|
|
invocationSource: "automation",
|
|
processPid: null,
|
|
processGroupId: null,
|
|
// Explicit dispatch evidence, not absence of output, establishes safe bootstrap.
|
|
resultJson: {
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
},
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
updatedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_review" })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reapOrphanedRuns();
|
|
expect(result.reaped).toBe(1);
|
|
expect(result.runIds).toEqual([runId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const failedRun = runs.find((row) => row.id === runId);
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(failedRun).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "process_lost",
|
|
});
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
retryOfRunId: runId,
|
|
scheduledRetryAttempt: 1,
|
|
scheduledRetryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
});
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
interactionId,
|
|
interactionStatus: "accepted",
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
|
|
const retryWakeup = await db
|
|
.select({
|
|
reason: agentWakeupRequests.reason,
|
|
status: agentWakeupRequests.status,
|
|
})
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.runId, retryRun?.id ?? ""))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(retryWakeup?.reason).toBe(
|
|
INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]).toMatchObject({
|
|
authorType: "system",
|
|
body: "Agent failed to resume after approval: `process_lost` — retrying (attempt 1/2)",
|
|
});
|
|
|
|
const interaction = await db
|
|
.select({ result: issueThreadInteractions.result })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(interaction?.result).toMatchObject({
|
|
version: 1,
|
|
outcome: "accepted",
|
|
resumeFailure: {
|
|
status: "retrying",
|
|
errorCode: "process_lost",
|
|
attempt: 1,
|
|
maxAttempts: 2,
|
|
runId,
|
|
retryRunId: retryRun?.id ?? null,
|
|
},
|
|
});
|
|
mockAdapterExecute.mockClear();
|
|
});
|
|
|
|
it("blocks a projectless task before launch when its configured source directory is unavailable", async () => {
|
|
mockAdapterExecute.mockClear();
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const projectId = randomUUID();
|
|
const projectWorkspaceId = randomUUID();
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await db.insert(projects).values({
|
|
id: projectId,
|
|
companyId,
|
|
name: "Paperclip App",
|
|
status: "in_progress",
|
|
});
|
|
await db.insert(projectWorkspaces).values({
|
|
id: projectWorkspaceId,
|
|
companyId,
|
|
projectId,
|
|
name: "Primary workspace",
|
|
sourceType: "local_path",
|
|
cwd: `/tmp/paperclip-missing-workspace-${randomUUID()}`,
|
|
isPrimary: true,
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
title: "Launch from linked workspace without project id",
|
|
identifier: `${issuePrefix}-1`,
|
|
projectId: null,
|
|
projectWorkspaceId,
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const failedRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(failedRun).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "workspace_validation_failed",
|
|
});
|
|
expect(failedRun?.error).toContain(
|
|
"Configured project workspace is unavailable",
|
|
);
|
|
// The adapter process never started, so no agent could post an issue
|
|
// comment. The comment policy is not_applicable and no missing-comment
|
|
// retry is queued, which stops a pre-adapter setup failure from looping.
|
|
expect(failedRun?.processStartedAt).toBeNull();
|
|
expect(failedRun?.issueCommentStatus).toBe("not_applicable");
|
|
const missingCommentWakeups = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
eq(agentWakeupRequests.reason, "missing_issue_comment"),
|
|
),
|
|
);
|
|
expect(missingCommentWakeups).toHaveLength(0);
|
|
expect(failedRun?.resultJson).toMatchObject({
|
|
workspaceValidation: {
|
|
reason: "configured_workspace_unavailable",
|
|
issueId,
|
|
issueProjectId: null,
|
|
issueProjectWorkspaceId: projectWorkspaceId,
|
|
},
|
|
});
|
|
|
|
const issue = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row?.status === "blocked" ? row : null;
|
|
}),
|
|
);
|
|
expect(issue?.executionRunId).toBeNull();
|
|
|
|
const recoveryAction = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(recoveryAction).toMatchObject({
|
|
kind: "workspace_validation",
|
|
cause: "workspace_validation_failed",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
recoveryIssueId: null,
|
|
});
|
|
expect(recoveryAction?.evidence).toMatchObject({
|
|
sourceIssueId: issueId,
|
|
latestRunId: runId,
|
|
latestRunErrorCode: "workspace_validation_failed",
|
|
recoveryCause: "workspace_validation_failed",
|
|
});
|
|
expect(recoveryAction?.nextAction).toContain(
|
|
"The task's workspace could not be used",
|
|
);
|
|
|
|
const validationComment = await waitForValue(async () => {
|
|
const rows = await selectRecoveryCommentsForIssue(issueId);
|
|
return (
|
|
rows.find((comment) =>
|
|
comment.body.includes("workspace could not be used"),
|
|
) ?? null
|
|
);
|
|
});
|
|
expect(validationComment).toBeTruthy();
|
|
});
|
|
|
|
it("keeps an explicit local-path/worktree conflict blocked with a board action and no Sentry event", async () => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-local-workspace-policy-"));
|
|
const projectId = randomUUID();
|
|
const workspaceId = randomUUID();
|
|
const heartbeat = heartbeatService(db);
|
|
const previousSettings = await instanceSettingsService(db).getExperimental();
|
|
try {
|
|
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Local documents", status: "in_progress" });
|
|
await db.insert(projectWorkspaces).values({
|
|
id: workspaceId, companyId, projectId, name: "Documents", sourceType: "local_path", cwd, isPrimary: true,
|
|
});
|
|
await db.update(issues).set({
|
|
projectId, projectWorkspaceId: workspaceId, executionWorkspaceSettings: { mode: "isolated_workspace" },
|
|
}).where(eq(issues.id, issueId));
|
|
await db.update(agents).set({ adapterConfig: { workspaceStrategy: { type: "git_worktree" } } }).where(eq(agents.id, agentId));
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await waitForPendingRunFailureReports();
|
|
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(run).toMatchObject({
|
|
status: "failed", errorCode: "workspace_validation_failed", processStartedAt: null,
|
|
resultJson: {
|
|
workspaceValidation: { reason: "git_worktree_base_not_git_checkout", configurationReason: "local_path_requires_git_checkout" },
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
});
|
|
expect(run.error).toContain("is not a git checkout");
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(issue).toMatchObject({ status: "blocked", executionRunId: null, projectId, projectWorkspaceId: workspaceId });
|
|
const [action] = await db.select().from(issueRecoveryActions).where(and(
|
|
eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
));
|
|
expect(action).toMatchObject({ status: "active", kind: "workspace_validation", ownerType: "board" });
|
|
expect(action.nextAction).toContain("workspace");
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments.some((comment) => comment.body.includes("workspace could not be used"))).toBe(true);
|
|
expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toEqual([]);
|
|
} finally {
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: previousSettings.enableIsolatedWorkspaces });
|
|
await fs.rm(cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
{ name: "HTTPS authentication", failures: ["auth"], report: false },
|
|
{ name: "SSH alias DNS", failures: ["dns"], report: false },
|
|
{ name: "mixed recognized and unknown candidates", failures: ["auth", "unknown"], report: true },
|
|
{ name: "mixed local and authentication diagnostics", failures: ["mixed"], report: true },
|
|
{ name: "unknown clone failure", failures: ["unknown"], report: true },
|
|
])("preserves failed workspace recovery while classifying managed Git connections: $name", async ({ failures, report }) => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const home = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-git-connection-lifecycle-"));
|
|
const bin = path.join(home, "bin");
|
|
const callsPath = path.join(home, "git-calls.jsonl");
|
|
const projectId = randomUUID();
|
|
const workspaceIds = failures.map(() => randomUUID());
|
|
const remotes = failures.map((failure, index) => failure === "dns"
|
|
? `git@clone-alias.example.test:team/repository-${index}.git`
|
|
: `https://clone.example.test/team/repository-${index}.git`);
|
|
const diagnostics = failures.map((failure) => failure === "dns"
|
|
? "ssh: Could not resolve hostname clone-alias.example.test: Name or service not known\nfatal: Could not read from remote repository."
|
|
: failure === "unknown" ? "fatal: unexpected internal clone failure"
|
|
: "fatal: Authentication failed for 'https://clone.example.test/'" +
|
|
(failure === "mixed" ? "\nfatal: No space left on device" : ""));
|
|
await fs.mkdir(bin);
|
|
// A real child process supplies execFile's numeric exit/stderr evidence.
|
|
// Every command is intercepted, so no fixture can reach a remote Git host.
|
|
await fs.writeFile(path.join(bin, "git"), `#!${process.execPath}\n` +
|
|
`const fs = require('node:fs');\n` +
|
|
`const args = process.argv.slice(2);\n` +
|
|
`fs.appendFileSync(${JSON.stringify(callsPath)}, JSON.stringify(args) + '\\n');\n` +
|
|
`const remotes = ${JSON.stringify(remotes)};\n` +
|
|
`const diagnostics = ${JSON.stringify(diagnostics)};\n` +
|
|
`const index = remotes.indexOf(args.at(-2));\n` +
|
|
`if (!args.includes('clone') || index < 0) { process.stderr.write('Unexpected fixture Git command\\n'); process.exit(2); }\n` +
|
|
`process.stderr.write(diagnostics[index] + '\\n'); process.exitCode = 128;\n`, { mode: 0o755 });
|
|
const heartbeat = heartbeatService(db);
|
|
const previousSettings = await instanceSettingsService(db).getExperimental();
|
|
const previousPath = process.env.PATH;
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
try {
|
|
process.env.PATH = `${bin}${path.delimiter}${previousPath ?? ""}`;
|
|
process.env.PAPERCLIP_HOME = home;
|
|
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Git connection fixture", status: "in_progress" });
|
|
await db.insert(projectWorkspaces).values(workspaceIds.map((id, index) => ({
|
|
id, companyId, projectId, name: `Repository ${index}`, sourceType: "git_repo",
|
|
repoUrl: remotes[index], cwd: null, isPrimary: index === 0,
|
|
})));
|
|
await db.update(issues).set({
|
|
projectId, projectWorkspaceId: workspaceIds[0], executionWorkspaceSettings: { mode: "isolated_workspace" },
|
|
}).where(eq(issues.id, issueId));
|
|
await db.update(agents).set({ adapterConfig: { workspaceStrategy: { type: "git_worktree" } } }).where(eq(agents.id, agentId));
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await waitForPendingRunFailureReports();
|
|
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(run).toMatchObject({
|
|
status: "failed", errorCode: "workspace_validation_failed", processStartedAt: null,
|
|
resultJson: {
|
|
workspaceValidation: { reason: "git_worktree_base_materialization_failed" },
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
});
|
|
expect(run.error).toContain("Configured project workspace is unavailable");
|
|
expect(run.error).toContain("Repair the configured path or repository access");
|
|
const validation = run.resultJson!.workspaceValidation as Record<string, unknown>;
|
|
expect(validation.baseCwdFallback).toBe(false);
|
|
const materializations = validation.materializationFailures as Array<Record<string, unknown>>;
|
|
expect(materializations).toHaveLength(failures.length);
|
|
expect(materializations.map((failure) => failure.connectionFailure)).toEqual(failures.map((failure) =>
|
|
failure === "auth" || failure === "dns" ? {
|
|
schemaVersion: 1, provider: "git", operation: "clone",
|
|
reason: failure === "auth" ? "authentication_failed" : "dns_failure",
|
|
} : undefined));
|
|
expect(run.resultJson!.connectionFailure).toEqual(report ? undefined : materializations[0].connectionFailure);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(issue).toMatchObject({ status: "blocked", executionRunId: null, projectId, projectWorkspaceId: workspaceIds[0] });
|
|
const [action] = await db.select().from(issueRecoveryActions).where(and(
|
|
eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
));
|
|
expect(action).toMatchObject({ status: "active", kind: "workspace_validation", ownerType: "board" });
|
|
expect(action.nextAction).toContain("workspace");
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments.some((comment) => comment.body.includes("workspace could not be used"))).toBe(true);
|
|
expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toHaveLength(report ? 1 : 0);
|
|
const calls = (await fs.readFile(callsPath, "utf8")).trim().split("\n").map((line) => JSON.parse(line) as string[]);
|
|
expect(calls).toHaveLength(failures.length);
|
|
expect(calls.every((args) => args.includes("clone"))).toBe(true);
|
|
} finally {
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
if (previousPath === undefined) delete process.env.PATH; else process.env.PATH = previousPath;
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
|
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: previousSettings.enableIsolatedWorkspaces });
|
|
await fs.rm(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("keeps a direct additional-repository connection failure visible without reporting it to Sentry", async () => {
|
|
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const home = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-additional-git-connection-"));
|
|
const cwd = path.join(home, "primary");
|
|
const bin = path.join(home, "bin");
|
|
const cloneCalls = path.join(home, "clone-calls.jsonl");
|
|
const projectId = randomUUID();
|
|
const workspaceId = randomUUID();
|
|
const repoUrl = "git@clone-alias.example.test:team/additional.git";
|
|
const previousPath = process.env.PATH;
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
const heartbeat = heartbeatService(db);
|
|
await fs.mkdir(cwd);
|
|
await fs.mkdir(bin);
|
|
execFileSync("git", ["init", "-b", "main"], { cwd, stdio: "ignore" });
|
|
await fs.writeFile(path.join(cwd, "README.md"), "Keep this local repository intact.\n");
|
|
execFileSync("git", ["add", "README.md"], { cwd, stdio: "ignore" });
|
|
execFileSync("git", ["-c", "user.name=Test", "-c", "user.email=test@example.test", "commit", "-m", "Fixture"], { cwd, stdio: "ignore" });
|
|
await fs.writeFile(path.join(bin, "git"), `#!${process.execPath}\n` +
|
|
`const fs = require('node:fs'); const { spawnSync } = require('node:child_process');\n` +
|
|
`const args = process.argv.slice(2);\n` +
|
|
`if (args.includes('clone')) {\n` +
|
|
` fs.appendFileSync(${JSON.stringify(cloneCalls)}, JSON.stringify(args) + '\\n');\n` +
|
|
` if (args.at(-2) !== ${JSON.stringify(repoUrl)}) process.exit(2);\n` +
|
|
` process.stderr.write('ssh: Could not resolve hostname clone-alias.example.test: Name or service not known\\nfatal: Could not read from remote repository.\\n'); process.exit(128);\n` +
|
|
`}\n` +
|
|
`if (args.some(arg => ['fetch', 'pull', 'push', 'ls-remote', 'submodule'].includes(arg))) process.exit(2);\n` +
|
|
`const result = spawnSync('git', args, { stdio: 'inherit', env: { ...process.env, PATH: ${JSON.stringify(previousPath)} } });\n` +
|
|
`process.exit(result.status ?? 2);\n`, { mode: 0o755 });
|
|
try {
|
|
process.env.PATH = `${bin}${path.delimiter}${previousPath ?? ""}`;
|
|
process.env.PAPERCLIP_HOME = home;
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Additional repository fixture", status: "in_progress" });
|
|
await db.insert(projectWorkspaces).values([
|
|
{ id: workspaceId, companyId, projectId, name: "Primary", sourceType: "local_path", cwd, isPrimary: true },
|
|
{ id: randomUUID(), companyId, projectId, name: "Additional", sourceType: "git_repo", repoUrl, cwd: null, isPrimary: false },
|
|
]);
|
|
await db.update(issues).set({ projectId, projectWorkspaceId: workspaceId,
|
|
executionWorkspaceSettings: { mode: "shared_workspace" },
|
|
}).where(eq(issues.id, issueId));
|
|
await db.update(agents).set({ adapterConfig: { cwd } }).where(eq(agents.id, agentId));
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await waitForPendingRunFailureReports();
|
|
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(run).toMatchObject({ status: "failed", errorCode: "setup_failed", executionStage: "preparing", processStartedAt: null,
|
|
resultJson: {
|
|
connectionFailure: { schemaVersion: 1, provider: "git", operation: "clone", reason: "dns_failure" },
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
});
|
|
expect(run.resultJson?.workspaceValidation).toBeUndefined();
|
|
expect(run.error).toContain("Could not resolve hostname");
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(issue).toMatchObject({ status: "blocked", executionRunId: null, projectId, projectWorkspaceId: workspaceId });
|
|
const [action] = await db.select().from(issueRecoveryActions).where(and(
|
|
eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
));
|
|
expect(action).toMatchObject({ status: "active", ownerType: "board" });
|
|
expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toHaveLength(0);
|
|
const calls = (await fs.readFile(cloneCalls, "utf8")).trim().split("\n").map((line) => JSON.parse(line) as string[]);
|
|
expect(calls).toHaveLength(1);
|
|
expect(calls[0].at(-2)).toBe(repoUrl);
|
|
expect(await fs.readFile(path.join(cwd, "README.md"), "utf8")).toBe("Keep this local repository intact.\n");
|
|
} finally {
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
if (previousPath === undefined) delete process.env.PATH; else process.env.PATH = previousPath;
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
|
await fs.rm(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it.each(["throw", "result"])("redacts opaque environment-bound credentials from Sentry diagnostics: %s", async (mode) => {
|
|
const { companyId, agentId, runId } = await seedQueuedIssueRunFixture();
|
|
const svc = secretService(db);
|
|
const value = "opaque-runtime-credential-fixture";
|
|
const secret = await svc.create(companyId, {
|
|
name: `sentry-redaction-${randomUUID()}`, provider: "local_encrypted", value,
|
|
});
|
|
const env = { CUSTOM_BINDING: { type: "secret_ref", secretId: secret.id, version: "latest" } };
|
|
await svc.syncEnvBindingsForTarget(companyId, { targetType: "agent", targetId: agentId }, env);
|
|
await db.update(agents).set({ adapterConfig: { env } }).where(eq(agents.id, agentId));
|
|
mockAdapterExecute.mockImplementationOnce(async (input) => {
|
|
expect((input.config.env as Record<string, unknown>).CUSTOM_BINDING).toBe(value);
|
|
const message = `upstream rejected ${value}`;
|
|
if (mode === "throw") throw new Error(message, { cause: new Error(message) });
|
|
return {
|
|
exitCode: 1, signal: null, timedOut: false, errorMessage: message, errorCode: "adapter_failed",
|
|
errorMeta: { causeMessage: message },
|
|
resultJson: { terminalSessionFailure: { category: "service", details: message } },
|
|
};
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
const report = await waitForValue(async () => mockCaptureRunFailure.mock.calls.find(([event]) => event.runId === runId)?.[0]);
|
|
expect(report).toBeDefined();
|
|
expect(report.errorMessage).toContain("upstream rejected");
|
|
expect(JSON.stringify(report)).not.toContain(value);
|
|
if (mode === "throw") expect(report.diagnostics.exceptions).toHaveLength(2);
|
|
else expect(report.diagnostics.provider.category).toBe("service");
|
|
});
|
|
|
|
it("blocks before dispatch when a declared secret ref has no binding instead of emitting an opaque setup failure", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const svc = secretService(db);
|
|
const secretName = `unbound-runtime-${randomUUID()}`;
|
|
const secret = await svc.create(companyId, {
|
|
name: secretName,
|
|
provider: "local_encrypted",
|
|
value: "never-resolved",
|
|
});
|
|
// Declare the secret ref on the agent env WITHOUT creating a binding so the
|
|
// pre-dispatch gate short-circuits to a configuration-incomplete blocker.
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterConfig: {
|
|
env: {
|
|
UNBOUND_API_KEY: {
|
|
type: "secret_ref",
|
|
secretId: secret.id,
|
|
version: "latest",
|
|
},
|
|
},
|
|
},
|
|
})
|
|
.where(eq(agents.id, agentId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
const failedRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(failedRun).toMatchObject({
|
|
status: "failed",
|
|
errorCode: "configuration_incomplete",
|
|
});
|
|
expect(failedRun?.error).toContain("configuration incomplete");
|
|
expect(failedRun?.error).toContain(secretName);
|
|
expect(failedRun?.error).toContain("env.UNBOUND_API_KEY");
|
|
expect(failedRun?.resultJson).toMatchObject({
|
|
configurationIncomplete: {
|
|
reason: "secret_binding_missing",
|
|
missingBindings: [
|
|
{
|
|
consumerType: "agent",
|
|
consumerId: agentId,
|
|
configPath: "env.UNBOUND_API_KEY",
|
|
envKey: "UNBOUND_API_KEY",
|
|
secretId: secret.id,
|
|
secretName,
|
|
},
|
|
],
|
|
},
|
|
});
|
|
// The run's terminal write precedes the agent-status settlement. Wait for
|
|
// this exact configuration error instead of observing the intermediate idle state.
|
|
const failedAgent = await waitForValue(async () => {
|
|
const row = await db
|
|
.select({ status: agents.status, errorReason: agents.errorReason })
|
|
.from(agents)
|
|
.where(eq(agents.id, agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
return row?.status === "error" &&
|
|
row.errorReason?.includes("configuration incomplete")
|
|
? row
|
|
: null;
|
|
});
|
|
expect(failedAgent).toMatchObject({
|
|
status: "error",
|
|
errorReason: expect.stringContaining("configuration incomplete"),
|
|
});
|
|
// Value-free gate: no secret access events were recorded.
|
|
expect(await svc.listAccessEvents(companyId, secret.id)).toHaveLength(0);
|
|
|
|
const issue = await waitForValue(async () =>
|
|
db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row?.status === "blocked" ? row : null;
|
|
}),
|
|
);
|
|
expect(issue?.executionRunId).toBeNull();
|
|
|
|
const recoveryAction = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(recoveryAction).toMatchObject({
|
|
kind: "configuration_validation",
|
|
cause: "configuration_incomplete",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
recoveryIssueId: null,
|
|
});
|
|
expect(recoveryAction?.nextAction).toContain("A secret this agent needs is not set");
|
|
|
|
const configurationComment = await waitForValue(async () => {
|
|
const rows = await selectRecoveryCommentsForIssue(issueId);
|
|
return (
|
|
rows.find((comment) =>
|
|
comment.body.includes("a secret it needs is not set"),
|
|
) ?? null
|
|
);
|
|
});
|
|
expect(configurationComment).toBeTruthy();
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
await waitForPendingRunFailureReports();
|
|
expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toEqual([]);
|
|
});
|
|
|
|
it("queues one finish-handoff wake when a successful run leaves in-progress work without a next action", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
mockAdapterExecute.mockImplementationOnce(
|
|
async (ctx: { runId: string }) => {
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
createdByRunId: ctx.runId,
|
|
body: "Implemented the backend detector, but did not choose a final issue state.",
|
|
});
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary:
|
|
"Implemented the backend detector, but did not choose a final issue state.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
},
|
|
);
|
|
// The repair agent records completion through state, not its final text.
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "I will inspect optional next steps.", provider: "test", model: "test-model" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const wakes = await selectRecoveryWakesByAgent(agentId);
|
|
const repairs = wakes.filter(w => w.reason === "issue_disposition_repair");
|
|
expect(repairs).toHaveLength(1);
|
|
const repair = await heartbeat.getRun(repairs[0].runId!);
|
|
expect(repair?.contextSnapshot).toMatchObject({
|
|
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
|
|
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
|
|
});
|
|
expect({ status: repair?.status, errorCode: repair?.errorCode, error: repair?.error })
|
|
.toEqual({ status: "succeeded", errorCode: null, error: null });
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(2);
|
|
expect(await selectRecoveryCommentsForIssue(issueId)).not.toEqual(expect.arrayContaining([expect.objectContaining({body: SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY})]));
|
|
expect(repairs[0].idempotencyKey).toBe(`issue_disposition_repair:${issueId}:${legacyDispositionFingerprint(companyId, issueId, agentId, runId)}:1`);
|
|
});
|
|
|
|
it("requeues a missing-disposition handoff when the previous corrective wake was cancelled", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const idempotencyKey = `finish_successful_run_handoff:${issueId}:${runId}:1`;
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
agentId,
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "finish_successful_run_handoff",
|
|
payload: {
|
|
issueId,
|
|
sourceRunId: runId,
|
|
handoffRequired: true,
|
|
handoffReason: SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
},
|
|
status: "cancelled",
|
|
idempotencyKey,
|
|
requestedAt: new Date("2026-03-19T00:00:01.000Z"),
|
|
finishedAt: new Date("2026-03-19T00:00:02.000Z"),
|
|
updatedAt: new Date("2026-03-19T00:00:02.000Z"),
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce(
|
|
async (ctx: { runId: string }) => {
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
createdByRunId: ctx.runId,
|
|
body: "Implemented recovery handling, but did not choose a final issue state.",
|
|
});
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary:
|
|
"Implemented recovery handling, but did not choose a final issue state.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
},
|
|
);
|
|
// The repair agent records completion through state, not its final text.
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "I will inspect optional next steps.", provider: "test", model: "test-model" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const wakes = await selectRecoveryWakesByAgent(agentId);
|
|
const repairs = wakes.filter(w => w.reason === "issue_disposition_repair");
|
|
expect(repairs).toHaveLength(1);
|
|
const repair = await heartbeat.getRun(repairs[0].runId!);
|
|
expect(repair?.contextSnapshot).toMatchObject({
|
|
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
|
|
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
|
|
});
|
|
expect(repair?.status).toBe("succeeded");
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(2);
|
|
expect(await selectRecoveryCommentsForIssue(issueId)).not.toEqual(expect.arrayContaining([expect.objectContaining({body: SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY})]));
|
|
expect(repairs[0].idempotencyKey).toBe(`issue_disposition_repair:${issueId}:${legacyDispositionFingerprint(companyId, issueId, agentId, runId)}:1`);
|
|
expect(wakes.filter(w => w.reason === "finish_successful_run_handoff")).toHaveLength(1);
|
|
expect(wakes.find(w => w.reason === "finish_successful_run_handoff")?.status).toBe("cancelled");
|
|
});
|
|
|
|
it("queues one missing-disposition handoff for artifact-producing successful runs left in progress", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
mockAdapterExecute.mockImplementationOnce(
|
|
async (ctx: { runId: string }) => {
|
|
const documentId = randomUUID();
|
|
const revisionId = randomUUID();
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
createdByRunId: ctx.runId,
|
|
body: "Drafted the Phase 3 test plan but did not choose a final issue disposition.",
|
|
});
|
|
await db.insert(documents).values({
|
|
id: documentId,
|
|
companyId,
|
|
title: "Regression test plan",
|
|
format: "markdown",
|
|
latestBody:
|
|
"# Regression test plan\n\n- Cover artifact-producing successful runs",
|
|
latestRevisionId: revisionId,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: agentId,
|
|
updatedByAgentId: agentId,
|
|
});
|
|
await db.insert(documentRevisions).values({
|
|
id: revisionId,
|
|
companyId,
|
|
documentId,
|
|
revisionNumber: 1,
|
|
title: "Regression test plan",
|
|
format: "markdown",
|
|
body: "# Regression test plan\n\n- Cover artifact-producing successful runs",
|
|
createdByAgentId: agentId,
|
|
createdByRunId: ctx.runId,
|
|
});
|
|
await db.insert(issueDocuments).values({
|
|
companyId,
|
|
issueId,
|
|
documentId,
|
|
key: "plan",
|
|
});
|
|
await db.insert(issueWorkProducts).values({
|
|
companyId,
|
|
issueId,
|
|
type: "report",
|
|
provider: "test",
|
|
externalId: "phase-3-report",
|
|
title: "Phase 3 regression notes",
|
|
status: "ready",
|
|
summary: "Successful run produced a visible artifact.",
|
|
createdByRunId: ctx.runId,
|
|
});
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary:
|
|
"Created comments, a plan document, and a work product without choosing a disposition.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
},
|
|
);
|
|
// The repair agent records completion through state, not its final text.
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "I will inspect optional next steps.", provider: "test", model: "test-model" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const wakes = await selectRecoveryWakesByAgent(agentId);
|
|
const repairs = wakes.filter(w => w.reason === "issue_disposition_repair");
|
|
expect(repairs).toHaveLength(1);
|
|
const repair = await heartbeat.getRun(repairs[0].runId!);
|
|
expect(repair?.contextSnapshot).toMatchObject({
|
|
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
|
|
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
|
|
});
|
|
expect(repair?.status).toBe("succeeded");
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(2);
|
|
expect(await selectRecoveryCommentsForIssue(issueId)).not.toEqual(expect.arrayContaining([expect.objectContaining({body: SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY})]));
|
|
expect(repairs[0].idempotencyKey).toBe(`issue_disposition_repair:${issueId}:${legacyDispositionFingerprint(companyId, issueId, agentId, runId)}:1`);
|
|
expect(await db.select().from(issueWorkProducts).where(eq(issueWorkProducts.issueId, issueId))).toHaveLength(1);
|
|
});
|
|
|
|
it("redacts secret-bearing successful-run detected progress before handoff disclosure", async () => {
|
|
const { agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
|
const bearerSecret = "live-bearer-token-value";
|
|
const apiKeySecret = "sk-testsuccessfulhandoffsecret";
|
|
const redactedDetectedSummary =
|
|
redactDetectedSuccessfulRunProgressSummaryForBoard(
|
|
`Next action noted: Authorization: Bearer ${bearerSecret} OPENAI_API_KEY=${apiKeySecret}`,
|
|
{ enabled: false },
|
|
);
|
|
expect(redactedDetectedSummary).toContain("***REDACTED***");
|
|
expect(redactedDetectedSummary).not.toContain(bearerSecret);
|
|
expect(redactedDetectedSummary).not.toContain(apiKeySecret);
|
|
expect(
|
|
redactSuccessfulRunHandoffEvidence(
|
|
`Authorization: Bearer ${bearerSecret} OPENAI_API_KEY=${apiKeySecret}`,
|
|
{ enabled: false },
|
|
),
|
|
).toBe("Authorization: ***REDACTED*** OPENAI_API_KEY=***REDACTED***");
|
|
|
|
mockAdapterExecute.mockResolvedValueOnce({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: `Made progress but left the issue open. Authorization: Bearer ${bearerSecret} OPENAI_API_KEY=${apiKeySecret}`,
|
|
resultJson: {
|
|
message: `Next action: Authorization: Bearer ${bearerSecret} OPENAI_API_KEY=${apiKeySecret}`,
|
|
},
|
|
provider: "test",
|
|
model: "test-model",
|
|
});
|
|
// The repair agent records completion through state, not its final text.
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "I will inspect optional next steps.", provider: "test", model: "test-model" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const wakes = await selectRecoveryWakesByAgent(agentId);
|
|
const repairs = wakes.filter(w => w.reason === "issue_disposition_repair");
|
|
expect(repairs).toHaveLength(1);
|
|
const repair = await heartbeat.getRun(repairs[0].runId!);
|
|
expect(repair?.contextSnapshot).toMatchObject({
|
|
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
|
|
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
|
|
});
|
|
expect(repair?.status).toBe("succeeded");
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(2);
|
|
expect(await selectRecoveryCommentsForIssue(issueId)).not.toEqual(expect.arrayContaining([expect.objectContaining({body: SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY})]));
|
|
expect(JSON.stringify(repairs[0].payload)).not.toContain(bearerSecret);
|
|
expect(JSON.stringify(repairs[0].payload)).not.toContain(apiKeySecret);
|
|
expect(JSON.stringify(repair?.contextSnapshot?.dispositionRepairInstruction)).not.toContain(bearerSecret);
|
|
});
|
|
|
|
it("escalates an exhausted failed successful-run handoff without using generic continuation recovery first", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "adapter_failed",
|
|
runError: "Authorization: Bearer sk-test-successful-handoff-secret",
|
|
});
|
|
const sourceRunId = randomUUID();
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "finish_successful_run_handoff",
|
|
sourceRunId,
|
|
resumeFromRunId: sourceRunId,
|
|
handoffRequired: true,
|
|
handoffReason: "successful_run_missing_state",
|
|
missingDisposition: "clear_next_step",
|
|
handoffAttempt: 1,
|
|
maxHandoffAttempts: 1,
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.successfulRunHandoffEscalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: null,
|
|
cause: SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
kind: "missing_disposition",
|
|
});
|
|
expect(recoveryAction.evidence).toMatchObject({
|
|
sourceRunId,
|
|
missingDisposition: "clear_next_step",
|
|
latestRunStatus: "failed",
|
|
latestRunErrorCode: "adapter_failed",
|
|
recoveryCause: SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
});
|
|
expect(JSON.stringify(recoveryAction.evidence)).not.toContain(
|
|
"sk-test-successful-handoff-secret",
|
|
);
|
|
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue?.status).toBe("blocked");
|
|
await expect(sourceBlockerIssueIds(companyId, issueId)).resolves.toEqual(
|
|
[],
|
|
);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments[0]?.body).toBe(
|
|
SUCCESSFUL_RUN_HANDOFF_EXHAUSTED_NOTICE_BODY,
|
|
);
|
|
expect(comments[0]?.authorType).toBe("system");
|
|
expect(comments[0]?.presentation).toMatchObject({
|
|
kind: "system_notice",
|
|
tone: "danger",
|
|
detailsDefaultOpen: false,
|
|
});
|
|
expect(comments[0]?.presentation).not.toHaveProperty("density");
|
|
expect(comments[0]?.metadata).toMatchObject({
|
|
version: 1,
|
|
sections: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
title: "Recovery",
|
|
rows: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
type: "key_value",
|
|
label: "Recovery action",
|
|
value: recoveryAction.id,
|
|
}),
|
|
expect.objectContaining({
|
|
type: "key_value",
|
|
label: "Recovery owner",
|
|
value: "Waiting for you",
|
|
}),
|
|
]),
|
|
}),
|
|
expect.objectContaining({
|
|
title: "Run evidence",
|
|
rows: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
type: "key_value",
|
|
label: "Normalized cause",
|
|
value: SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
}),
|
|
expect.objectContaining({
|
|
type: "key_value",
|
|
label: "Missing disposition",
|
|
value: "clear_next_step",
|
|
}),
|
|
]),
|
|
}),
|
|
]),
|
|
});
|
|
expect(comments[0]?.body).not.toContain(
|
|
"sk-test-successful-handoff-secret",
|
|
);
|
|
expect(JSON.stringify(comments[0]?.metadata ?? {})).not.toContain(
|
|
"sk-test-successful-handoff-secret",
|
|
);
|
|
|
|
const activity = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.entityId, issueId));
|
|
expect(
|
|
activity.some(
|
|
(event) => event.action === "issue.successful_run_handoff_escalated",
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("retries an interrupted corrective successful-run handoff instead of escalating it", async () => {
|
|
// A graceful server shutdown (a deploy restart) interrupted the single
|
|
// corrective run before the agent could choose a disposition. That is
|
|
// not a finished attempt, so the sweeper must give it the bounded
|
|
// transient retry any interrupted run gets, not a board escalation.
|
|
const { agentId, runId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "server_shutdown_interrupted",
|
|
runError: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
});
|
|
const sourceRunId = randomUUID();
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "finish_successful_run_handoff",
|
|
sourceRunId,
|
|
resumeFromRunId: sourceRunId,
|
|
handoffRequired: true,
|
|
handoffReason: "successful_run_missing_state",
|
|
missingDisposition: "clear_next_step",
|
|
handoffAttempt: 1,
|
|
maxHandoffAttempts: 1,
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.successfulRunHandoffRetried).toBe(1);
|
|
expect(result.successfulRunHandoffEscalated).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const retryRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(retryRun).toMatchObject({
|
|
agentId,
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 1,
|
|
scheduledRetryReason: "interrupted_preparation",
|
|
});
|
|
// The retry keeps the handoff contract: it is still the corrective run,
|
|
// so a finished attempt that leaves no disposition still escalates.
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
retryOfRunId: runId,
|
|
handoffRequired: true,
|
|
handoffReason: "successful_run_missing_state",
|
|
missingDisposition: "clear_next_step",
|
|
handoffAttempt: 1,
|
|
maxHandoffAttempts: 1,
|
|
});
|
|
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue?.status).toBe("in_progress");
|
|
expect(sourceIssue?.assigneeAgentId).toBe(agentId);
|
|
const recoveryActions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(recoveryActions).toHaveLength(0);
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(0);
|
|
|
|
// A second sweep sees the scheduled retry as the live path and leaves
|
|
// the issue alone rather than escalating or double-scheduling.
|
|
const again = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(again.successfulRunHandoffRetried).toBe(0);
|
|
expect(again.successfulRunHandoffEscalated).toBe(0);
|
|
const retryRuns = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(retryRuns).toHaveLength(1);
|
|
});
|
|
|
|
it("escalates an interrupted corrective successful-run handoff once its transient retry budget is spent", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "server_shutdown_interrupted",
|
|
runError: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
// The real interrupted run carries the conversation-continuation
|
|
// marker the shutdown path writes; it also keeps a spent retry chain
|
|
// out of legacy reconciliation so the sweeper reaches the handoff
|
|
// branch with an exhausted budget.
|
|
resultJson: {
|
|
stopReason: "interrupted",
|
|
conversationContinuation: "continue_conversation_v1",
|
|
},
|
|
});
|
|
const sourceRunId = randomUUID();
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "transient_failure_retry",
|
|
sourceRunId,
|
|
resumeFromRunId: sourceRunId,
|
|
handoffRequired: true,
|
|
handoffReason: "successful_run_missing_state",
|
|
missingDisposition: "clear_next_step",
|
|
handoffAttempt: 1,
|
|
maxHandoffAttempts: 1,
|
|
// A restart-ended run is bounded by the server-restart window.
|
|
executionRetryAccounting: spentRestartRetryAccounting(),
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.successfulRunHandoffRetried).toBe(0);
|
|
expect(result.successfulRunHandoffEscalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
const retryRuns = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(retryRuns).toHaveLength(0);
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: null,
|
|
cause: SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
kind: "missing_disposition",
|
|
});
|
|
expect(recoveryAction.evidence).toMatchObject({
|
|
sourceRunId,
|
|
missingDisposition: "clear_next_step",
|
|
latestRunStatus: "interrupted",
|
|
latestRunErrorCode: "server_shutdown_interrupted",
|
|
recoveryCause: SUCCESSFUL_RUN_MISSING_STATE_REASON,
|
|
});
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue?.status).toBe("blocked");
|
|
});
|
|
|
|
it("escalates an in_progress issue whose interrupted run has spent its transient retry budget", async () => {
|
|
// Restarts in a row interrupted a run until its server-restart bound for
|
|
// the window was spent. The retry scheduler then reports the budget
|
|
// exhausted and queues nothing, and the sweeper used to skip the issue
|
|
// on every tick: in_progress, no run, no path, no notice.
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "server_shutdown_interrupted",
|
|
runError: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
// A conversation adapter's interrupted run keeps its session for
|
|
// continuation, so legacy reconciliation does not terminalize it;
|
|
// the sweeper reaches the retry lane with a spent budget.
|
|
resultJson: {
|
|
stopReason: "interrupted",
|
|
conversationContinuation: "continue_conversation_v1",
|
|
},
|
|
});
|
|
const originalRunId = randomUUID();
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "transient_failure_retry",
|
|
retryOfRunId: originalRunId,
|
|
executionRetryAccounting: spentRestartRetryAccounting(),
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.skipped).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
const successors = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(successors).toHaveLength(0);
|
|
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue?.status).toBe("blocked");
|
|
expect(sourceIssue?.assigneeAgentId).toBe(agentId);
|
|
const recoveryActions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(recoveryActions).toHaveLength(1);
|
|
expect(recoveryActions[0]).toMatchObject({
|
|
companyId,
|
|
status: "active",
|
|
previousOwnerAgentId: agentId,
|
|
});
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain("Paperclip tried to continue this task again, but it still could not continue");
|
|
expect(comments[0]?.body).toContain("Press Retry");
|
|
expect(comments[0]?.authorType).toBe("system");
|
|
expect(comments[0]?.presentation).toMatchObject({
|
|
kind: "system_notice",
|
|
tone: "danger",
|
|
});
|
|
|
|
// The escalated issue is board-owned now: a second sweep leaves it alone.
|
|
const again = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(again.escalated).toBe(0);
|
|
expect(again.continuationRequeued).toBe(0);
|
|
});
|
|
|
|
it("keeps retrying an interrupted run while its transient retry budget remains", async () => {
|
|
const { agentId, runId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "server_shutdown_interrupted",
|
|
runError: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
scheduledRetryAttempt: 1,
|
|
scheduledRetryReason: "transient_failure",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "transient_failure_retry",
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
const successor = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId))
|
|
.then((rows) => rows[0] ?? null);
|
|
// The interrupted preparation spent no provider work: it starts its own
|
|
// lane and keeps the one transient failure already spent (section F).
|
|
expect(successor).toMatchObject({
|
|
agentId,
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 1,
|
|
scheduledRetryReason: "interrupted_preparation",
|
|
contextSnapshot: expect.objectContaining({
|
|
executionRetryAccounting: expect.objectContaining({ failureRetries: 1 }),
|
|
}),
|
|
});
|
|
const sourceIssue = await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(sourceIssue?.status).toBe("in_progress");
|
|
});
|
|
|
|
it("escalates an assigned todo issue whose lost dispatch has spent its transient retry budget", async () => {
|
|
const { agentId, runId, issueId } = await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "failed",
|
|
runErrorCode: "server_shutdown_interrupted",
|
|
runError: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
resultJson: {
|
|
stopReason: "interrupted",
|
|
conversationContinuation: "continue_conversation_v1",
|
|
},
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "transient_failure_retry",
|
|
executionRetryAccounting: spentRestartRetryAccounting(),
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue?.status).toBe("blocked");
|
|
expect(sourceIssue?.assigneeAgentId).toBe(agentId);
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments[0]?.body).toContain("Paperclip tried to start this task again, but it still could not start. Press Retry");
|
|
});
|
|
|
|
it("escalates an exhausted successful handoff run that still leaves no disposition", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
});
|
|
const sourceRunId = randomUUID();
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "finish_successful_run_handoff",
|
|
sourceRunId,
|
|
resumeFromRunId: sourceRunId,
|
|
handoffRequired: true,
|
|
handoffReason: "successful_run_missing_state",
|
|
missingDisposition: "clear_next_step",
|
|
handoffAttempt: 1,
|
|
maxHandoffAttempts: 1,
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.successfulContinuationObserved).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
const [action] = await selectRecoveryActionsForIssue(issueId);
|
|
expect(action).toMatchObject({ kind: "deliberate_wait_without_target", ownerType: "board", attemptCount: 1 });
|
|
expect(action.evidence).toMatchObject({ latestRunId: runId, sourceMaxAttempts: 1 });
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked", assigneeAgentId: agentId });
|
|
});
|
|
|
|
it.each([false, "receipt", "launch", "provider", "cleanup"])("converts a continuation parked for review into a dependency wait on its open sub-tasks (dispatch receipt: %s)", async dispatchReceipt => {
|
|
const { companyId, agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
runError: "Continuation parked: issue is waiting on review/approval",
|
|
});
|
|
if (dispatchReceipt) {
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
|
|
await db.update(heartbeatRuns).set({ startedAt: null,
|
|
resultJson: { stopReason: "issue_continuation_waiting_on_review", timeoutSource: "stale_queued_run_gate" },
|
|
}).where(eq(heartbeatRuns.id, run.id));
|
|
}
|
|
if (dispatchReceipt === "launch" || dispatchReceipt === "provider") {
|
|
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1,
|
|
eventType: dispatchReceipt === "launch" ? "native.process_start_requested" : "provider.event",
|
|
stream: "system", level: "info", message: "Contradictory execution evidence" });
|
|
} else if (dispatchReceipt === "cleanup") {
|
|
await db.insert(environmentLeases).values({ companyId, heartbeatRunId: runId,
|
|
provider: "local", status: "pending_cleanup", cleanupStatus: "failed" });
|
|
}
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
const openChildTodoId = randomUUID();
|
|
const openChildInProgressId = randomUUID();
|
|
const doneChildId = randomUUID();
|
|
|
|
await db.insert(issues).values([
|
|
{
|
|
id: openChildTodoId,
|
|
companyId,
|
|
parentId: issueId,
|
|
title: "Sub-task still to do",
|
|
status: "todo",
|
|
priority: "medium",
|
|
issueNumber: 10,
|
|
identifier: `${issuePrefix}-10`,
|
|
},
|
|
{
|
|
id: openChildInProgressId,
|
|
companyId,
|
|
parentId: issueId,
|
|
title: "Sub-task in progress",
|
|
status: "in_progress",
|
|
priority: "medium",
|
|
issueNumber: 11,
|
|
identifier: `${issuePrefix}-11`,
|
|
},
|
|
{
|
|
id: doneChildId,
|
|
companyId,
|
|
parentId: issueId,
|
|
title: "Sub-task already finished",
|
|
status: "done",
|
|
priority: "medium",
|
|
issueNumber: 12,
|
|
identifier: `${issuePrefix}-12`,
|
|
},
|
|
]);
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
if (dispatchReceipt && dispatchReceipt !== "receipt") {
|
|
expect(result.waitingOnReviewResolved).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({
|
|
cause: "legacy_execution_requires_reconciliation", runId, canRetry: false,
|
|
});
|
|
return;
|
|
}
|
|
expect(result.waitingOnReviewResolved).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const umbrella = await selectRecoveryIssueById(issueId);
|
|
expect(umbrella?.status).toBe("blocked");
|
|
// Original assignee is preserved — no reassignment to a recovery owner.
|
|
expect(umbrella?.assigneeAgentId).toBe(agentId);
|
|
|
|
// Only the open children become first-class blockers; the done child is excluded.
|
|
const blockers = await sourceBlockerIssueIds(companyId, issueId);
|
|
expect(blockers.sort()).toEqual(
|
|
[openChildTodoId, openChildInProgressId].sort(),
|
|
);
|
|
|
|
// No stranded-recovery action/issue is opened for a deliberate wait.
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.authorType).toBe("system");
|
|
expect(comments[0]?.body).toContain("This task is waiting on");
|
|
expect(comments[0]?.body).toContain("continue automatically");
|
|
expect(comments[0]?.body).toContain(`${issuePrefix}-10`);
|
|
expect(comments[0]?.body).toContain(`${issuePrefix}-11`);
|
|
expect(comments[0]?.body).not.toContain(`${issuePrefix}-12`);
|
|
// Plain language — the raw machine error code never leaks into the thread.
|
|
expect(comments[0]?.body).not.toContain(
|
|
"issue_continuation_waiting_on_review",
|
|
);
|
|
expect(comments[0]?.presentation).toMatchObject({
|
|
kind: "system_notice",
|
|
tone: "warning",
|
|
title: "Recovery: waiting on dependencies — moved to blocked",
|
|
density: "compact",
|
|
});
|
|
expect(comments[0]?.metadata).toMatchObject({
|
|
version: 1,
|
|
sections: [
|
|
expect.objectContaining({
|
|
rows: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
type: "key_value",
|
|
label: "Cause",
|
|
value: "continuation_waiting_on_review",
|
|
}),
|
|
]),
|
|
}),
|
|
],
|
|
});
|
|
|
|
const activity = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.entityId, issueId));
|
|
expect(
|
|
activity.some(
|
|
(event) =>
|
|
event.action === "issue.updated" &&
|
|
(event.details as { source?: string } | null)?.source ===
|
|
"recovery.reconcile_continuation_waiting_on_review",
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("converts a continuation parked for review into a dependency wait on its existing blockers", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
runError: "Continuation parked: issue is waiting on review/approval",
|
|
});
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
const openBlockerId = randomUUID();
|
|
const doneBlockerId = randomUUID();
|
|
|
|
await db.insert(issues).values([
|
|
{
|
|
id: openBlockerId,
|
|
companyId,
|
|
title: "Blocking issue still open",
|
|
status: "in_progress",
|
|
priority: "medium",
|
|
issueNumber: 20,
|
|
identifier: `${issuePrefix}-20`,
|
|
},
|
|
{
|
|
id: doneBlockerId,
|
|
companyId,
|
|
title: "Blocking issue already finished",
|
|
status: "done",
|
|
priority: "medium",
|
|
issueNumber: 21,
|
|
identifier: `${issuePrefix}-21`,
|
|
},
|
|
]);
|
|
await db.insert(issueRelations).values([
|
|
{
|
|
companyId,
|
|
issueId: openBlockerId,
|
|
relatedIssueId: issueId,
|
|
type: "blocks",
|
|
},
|
|
{
|
|
companyId,
|
|
issueId: doneBlockerId,
|
|
relatedIssueId: issueId,
|
|
type: "blocks",
|
|
},
|
|
]);
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.waitingOnReviewResolved).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const blocked = await selectRecoveryIssueById(issueId);
|
|
expect(blocked?.status).toBe("blocked");
|
|
expect(blocked?.assigneeAgentId).toBe(agentId);
|
|
|
|
// Only the still-open blocker is carried over; the resolved one is excluded.
|
|
const blockers = await sourceBlockerIssueIds(companyId, issueId);
|
|
expect(blockers).toEqual([openBlockerId]);
|
|
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.authorType).toBe("system");
|
|
expect(comments[0]?.body).toContain("This task is waiting on");
|
|
expect(comments[0]?.body).toContain("continue automatically");
|
|
// The blocker's real identifier is linked — not the "another open issue" fallback.
|
|
expect(comments[0]?.body).toContain(`${issuePrefix}-20`);
|
|
expect(comments[0]?.body).not.toContain("another open issue");
|
|
expect(comments[0]?.body).not.toContain(`${issuePrefix}-21`);
|
|
expect(comments[0]?.body).not.toContain(
|
|
"issue_continuation_waiting_on_review",
|
|
);
|
|
});
|
|
|
|
it("repairs the PAP-16986 deliberate wait through the original owner when no target exists", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
runError: "Continuation parked: issue is waiting on review/approval",
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.waitingOnReviewResolved).toBe(0);
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.dispositionRepairRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
await expect(sourceBlockerIssueIds(companyId, issueId)).resolves.toEqual(
|
|
[],
|
|
);
|
|
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue).toMatchObject({
|
|
status: "in_progress",
|
|
assigneeAgentId: agentId,
|
|
});
|
|
|
|
const action = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(action).toMatchObject({
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerAgentId: agentId,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
});
|
|
expect(action?.fingerprint).toMatch(/^disposition_repair:v1:/);
|
|
expect(action?.wakePolicy).toMatchObject({
|
|
type: "bounded_owner_disposition_repair",
|
|
retryAgentId: agentId,
|
|
attempt: 1,
|
|
maxAttempts: 5,
|
|
baseBackoffMs: 0,
|
|
jitterMs: 0,
|
|
});
|
|
|
|
const repairRun = await waitForValue(async () => {
|
|
const rows = await selectRecoveryRunsByAgent(agentId);
|
|
return (
|
|
rows.find(
|
|
(run) =>
|
|
(run.contextSnapshot as { retryReason?: string } | null)
|
|
?.retryReason === "issue_disposition_repair",
|
|
) ?? null
|
|
);
|
|
});
|
|
expect(repairRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
retryReason: "issue_disposition_repair",
|
|
dispositionRepairFingerprint: action?.fingerprint,
|
|
dispositionRepairAttempt: 1,
|
|
dispositionRepairMaxAttempts: 5,
|
|
});
|
|
expect(repairRun?.contextSnapshot).not.toHaveProperty("modelProfile");
|
|
expect(repairRun?.contextSnapshot).not.toHaveProperty(
|
|
"allowDeliverableWork",
|
|
);
|
|
});
|
|
|
|
it("folds a persisted disposition-repair action when a current typed wait appears", async () => {
|
|
const { companyId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
await db.delete(activityLog);
|
|
await db.delete(heartbeatRunEvents);
|
|
await db.delete(heartbeatRuns);
|
|
await db.delete(agentWakeupRequests);
|
|
const sourceIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]!);
|
|
const sourceState = await collectDispositionRepairSourceState(db, {
|
|
issue: sourceIssue,
|
|
});
|
|
const action = await db
|
|
.insert(issueRecoveryActions)
|
|
.values({
|
|
companyId,
|
|
sourceIssueId: issueId,
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "agent",
|
|
ownerAgentId: sourceIssue.assigneeAgentId,
|
|
previousOwnerAgentId: sourceIssue.assigneeAgentId,
|
|
returnOwnerAgentId: sourceIssue.assigneeAgentId,
|
|
cause: "deliberate_wait_without_target",
|
|
fingerprint: sourceState.fingerprint,
|
|
evidence: { sourceStateFingerprint: sourceState.fingerprint },
|
|
nextAction: "Record a durable disposition.",
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
attempt: 1,
|
|
maxAttempts: 5,
|
|
},
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
timeoutAt: new Date(Date.now() - 60_000),
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_review" })
|
|
.where(eq(issues.id, issueId));
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "pending",
|
|
continuationPolicy: "wake_assignee",
|
|
payload: { version: 1, prompt: "Confirm the current disposition." },
|
|
});
|
|
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
const folded = await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.id, action.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(folded).toMatchObject({
|
|
status: "resolved",
|
|
outcome: "restored",
|
|
resolutionNote: "durable_path_restored:interaction",
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
});
|
|
});
|
|
|
|
it("reschedules an expired persisted disposition repair without duplicating the retry", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
await db.delete(activityLog);
|
|
await db.delete(heartbeatRunEvents);
|
|
await db.delete(heartbeatRuns);
|
|
await db.delete(agentWakeupRequests);
|
|
const sourceIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]!);
|
|
const sourceState = await collectDispositionRepairSourceState(db, {
|
|
issue: sourceIssue,
|
|
});
|
|
const action = await db
|
|
.insert(issueRecoveryActions)
|
|
.values({
|
|
companyId,
|
|
sourceIssueId: issueId,
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "agent",
|
|
ownerAgentId: agentId,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
cause: "deliberate_wait_without_target",
|
|
fingerprint: sourceState.fingerprint,
|
|
evidence: { sourceStateFingerprint: sourceState.fingerprint },
|
|
nextAction: "Record a durable disposition.",
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
attempt: 1,
|
|
maxAttempts: 5,
|
|
},
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
timeoutAt: new Date(Date.now() - 60_000),
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
|
|
const restartedHeartbeat = heartbeatService(db);
|
|
await restartedHeartbeat.reconcileStrandedAssignedIssues();
|
|
await restartedHeartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
const [rescheduledAction, retries] = await Promise.all([
|
|
db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.id, action.id))
|
|
.then((rows) => rows[0] ?? null),
|
|
db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'recoveryActionId' = ${action.id}`,
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'dispositionRepairAttempt' = '2'`,
|
|
),
|
|
),
|
|
]);
|
|
expect(rescheduledAction).toMatchObject({
|
|
status: "active",
|
|
attemptCount: 2,
|
|
maxAttempts: 5,
|
|
});
|
|
expect(rescheduledAction?.wakePolicy).toMatchObject({
|
|
type: "bounded_owner_disposition_repair",
|
|
attempt: 2,
|
|
maxAttempts: 5,
|
|
});
|
|
expect(retries).toHaveLength(1);
|
|
expect(retries[0]).toMatchObject({
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "issue_disposition_repair",
|
|
});
|
|
});
|
|
|
|
it("atomically deduplicates concurrent disposition-repair reconciliation", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
await db.delete(activityLog);
|
|
await db.delete(heartbeatRunEvents);
|
|
await db.delete(heartbeatRuns);
|
|
await db.delete(agentWakeupRequests);
|
|
const sourceIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]!);
|
|
const sourceState = await collectDispositionRepairSourceState(db, {
|
|
issue: sourceIssue,
|
|
});
|
|
const action = await db
|
|
.insert(issueRecoveryActions)
|
|
.values({
|
|
companyId,
|
|
sourceIssueId: issueId,
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "agent",
|
|
ownerAgentId: agentId,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
cause: "deliberate_wait_without_target",
|
|
fingerprint: sourceState.fingerprint,
|
|
evidence: { sourceStateFingerprint: sourceState.fingerprint },
|
|
nextAction: "Record a durable disposition.",
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
attempt: 1,
|
|
maxAttempts: 5,
|
|
},
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
timeoutAt: new Date(Date.now() - 60_000),
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
|
|
await Promise.all([
|
|
heartbeatService(db).reconcileStrandedAssignedIssues(),
|
|
heartbeatService(db).reconcileStrandedAssignedIssues(),
|
|
]);
|
|
|
|
const [requests, retries, scheduledActivities] = await Promise.all([
|
|
db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
sql`${agentWakeupRequests.idempotencyKey} LIKE 'issue_disposition_repair:%'`,
|
|
sql`${agentWakeupRequests.status} <> 'skipped'`,
|
|
),
|
|
),
|
|
db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'recoveryActionId' = ${action.id}`,
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'dispositionRepairAttempt' = '2'`,
|
|
),
|
|
),
|
|
db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(
|
|
and(
|
|
eq(activityLog.companyId, companyId),
|
|
eq(activityLog.action, "issue.disposition_repair_scheduled"),
|
|
eq(activityLog.entityId, action.id),
|
|
),
|
|
),
|
|
]);
|
|
expect(requests).toHaveLength(1);
|
|
expect(retries).toHaveLength(1);
|
|
expect(scheduledActivities).toHaveLength(1);
|
|
});
|
|
|
|
it("does not reset disposition repair for prose but does reset for durable source state", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
const sourceIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]!);
|
|
const initial = await collectDispositionRepairSourceState(db, {
|
|
issue: sourceIssue,
|
|
});
|
|
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
body: "Parked summary: waiting for review, with no typed target.",
|
|
});
|
|
const afterProse = await collectDispositionRepairSourceState(db, {
|
|
issue: sourceIssue,
|
|
});
|
|
expect(afterProse.fingerprint).toBe(initial.fingerprint);
|
|
|
|
await db
|
|
.update(issues)
|
|
.set({ executionPolicy: { mode: "auto" } })
|
|
.where(eq(issues.id, issueId));
|
|
const changedIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]!);
|
|
const afterDurableChange = await collectDispositionRepairSourceState(db, {
|
|
issue: changedIssue,
|
|
});
|
|
expect(afterDurableChange.fingerprint).not.toBe(initial.fingerprint);
|
|
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_disposition_repair",
|
|
retryReason: "issue_disposition_repair",
|
|
dispositionRepairFingerprint: initial.fingerprint,
|
|
dispositionRepairAttempt: 5,
|
|
dispositionRepairMaxAttempts: 5,
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.dispositionRepairRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
|
|
const action = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(action).toMatchObject({
|
|
fingerprint: afterDurableChange.fingerprint,
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
status: "active",
|
|
});
|
|
});
|
|
|
|
it("escalates exhausted source-owner repair to the board without a substitute wake", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
const managerId = randomUUID();
|
|
await db.insert(agents).values(recoveryAgentRow(managerId, companyId, "Recovery CTO", "cto", "idle"));
|
|
await db
|
|
.update(agents)
|
|
.set({ reportsTo: managerId })
|
|
.where(eq(agents.id, agentId));
|
|
|
|
const sourceIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0]!);
|
|
const state = await collectDispositionRepairSourceState(db, {
|
|
issue: sourceIssue,
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_disposition_repair",
|
|
retryReason: "issue_disposition_repair",
|
|
dispositionRepairFingerprint: state.fingerprint,
|
|
dispositionRepairAttempt: 5,
|
|
dispositionRepairMaxAttempts: 5,
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result).toMatchObject({
|
|
dispositionRepairRequeued: 0,
|
|
escalated: 1,
|
|
});
|
|
|
|
const [sourceAfter, action, substituteWakes, sourceAttemptSix] =
|
|
await Promise.all([
|
|
selectRecoveryIssueById(issueId),
|
|
selectRecoveryActionForIssue(companyId, issueId),
|
|
db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
eq(agentWakeupRequests.agentId, managerId),
|
|
),
|
|
),
|
|
db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'dispositionRepairAttempt' = '6'`,
|
|
),
|
|
),
|
|
]);
|
|
expect(sourceAfter).toMatchObject({
|
|
status: "blocked",
|
|
assigneeAgentId: agentId,
|
|
});
|
|
expect(action).toMatchObject({
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
maxAttempts: null,
|
|
resolutionNote: "unchanged_source_state_exhausted",
|
|
wakePolicy: expect.objectContaining({
|
|
type: "board_escalation",
|
|
reason: "unchanged_source_state_exhausted",
|
|
preservesSourceAssignee: true,
|
|
}),
|
|
evidence: expect.objectContaining({
|
|
routingPolicy: "board_escalation_no_takeover_v1",
|
|
sourceAttemptCount: 5,
|
|
sourceMaxAttempts: 5,
|
|
}),
|
|
});
|
|
const notices = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(notices.some(comment => comment.metadata?.recovery?.kind === "disposition_repair_escalated")).toBe(true);
|
|
const snapshot = notices.find(comment => comment.metadata?.recovery?.kind === "disposition_repair_escalated")!.metadata!.recovery;
|
|
expect(snapshot).toEqual({ kind: "disposition_repair_escalated", actionId: action!.id, assigneeAgentId: agentId, attemptCount: 5, maxAttempts: 5, reason: "unchanged_source_state_exhausted" });
|
|
expect(substituteWakes).toHaveLength(0);
|
|
expect(sourceAttemptSix).toHaveLength(0);
|
|
});
|
|
|
|
it("routes a non-invokable source owner to recovery without reassigning the source", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({ status: "paused" })
|
|
.where(eq(agents.id, agentId));
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue).toMatchObject({
|
|
status: "blocked",
|
|
assigneeAgentId: agentId,
|
|
});
|
|
|
|
const action = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(action).toMatchObject({
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
attemptCount: 0,
|
|
maxAttempts: null,
|
|
resolutionNote: "owner_not_invokable",
|
|
});
|
|
});
|
|
|
|
it("keeps a legacy agent-owned recovery action readable without scheduling another takeover wake", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
const legacyOwnerId = randomUUID();
|
|
await db.insert(agents).values(recoveryAgentRow(legacyOwnerId, companyId, "Legacy recovery owner", "cto", "idle"));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "blocked" })
|
|
.where(eq(issues.id, issueId));
|
|
const [legacyAction] = await db
|
|
.insert(issueRecoveryActions)
|
|
.values({
|
|
companyId,
|
|
sourceIssueId: issueId,
|
|
kind: "stranded_assigned_issue",
|
|
status: "active",
|
|
ownerType: "agent",
|
|
ownerAgentId: legacyOwnerId,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
cause: "process_lost",
|
|
fingerprint: `legacy:${issueId}`,
|
|
evidence: { latestRunId: null },
|
|
nextAction: "Legacy recovery action",
|
|
wakePolicy: {
|
|
type: "bounded_recovery_owner",
|
|
ownerAgentId: legacyOwnerId,
|
|
attempt: 1,
|
|
maxAttempts: 5,
|
|
},
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
})
|
|
.returning();
|
|
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
const [persisted, takeoverWakes] = await Promise.all([
|
|
db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.id, legacyAction!.id))
|
|
.then((rows) => rows[0]),
|
|
selectRecoveryWakesByAgent(legacyOwnerId),
|
|
]);
|
|
expect(persisted).toMatchObject({
|
|
status: "active",
|
|
ownerType: "agent",
|
|
ownerAgentId: legacyOwnerId,
|
|
attemptCount: 1,
|
|
maxAttempts: 5,
|
|
});
|
|
expect(takeoverWakes).toHaveLength(0);
|
|
});
|
|
|
|
it("does not consume a disposition-repair attempt when on-demand wakes are disabled", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "issue_continuation_waiting_on_review",
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } })
|
|
.where(eq(agents.id, agentId));
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.dispositionRepairRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
|
|
const [action, repairWakeups] = await Promise.all([
|
|
selectRecoveryActionForIssue(companyId, issueId),
|
|
db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
eq(agentWakeupRequests.agentId, agentId),
|
|
sql`${agentWakeupRequests.idempotencyKey} LIKE 'issue_disposition_repair:%'`,
|
|
),
|
|
),
|
|
]);
|
|
expect(action).toMatchObject({
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
attemptCount: 0,
|
|
maxAttempts: null,
|
|
resolutionNote: "owner_not_invokable",
|
|
});
|
|
expect(repairWakeups).toHaveLength(0);
|
|
});
|
|
|
|
it.each([
|
|
{ providerOutcome: "succeeded", cleanupAt: "inner", warningFails: false },
|
|
{ providerOutcome: "failed", cleanupAt: "inner", warningFails: false },
|
|
{ providerOutcome: "throws", cleanupAt: "inner", warningFails: false },
|
|
{ providerOutcome: "succeeded", cleanupAt: "outer", warningFails: false },
|
|
{ providerOutcome: "succeeded", cleanupAt: "inner", warningFails: true },
|
|
] as const)("preserves a $providerOutcome provider outcome when instruction cleanup times out ($cleanupAt, warning failure: $warningFails)", async ({ providerOutcome, cleanupAt, warningFails }) => {
|
|
const { companyId, agentId, runId, issueId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });
|
|
const interactionId = randomUUID();
|
|
const release = vi.fn().mockRejectedValue(Object.assign(new Error("Timed out waiting for workspace restore lock at /private/agent-files.lock"), {
|
|
code: "ERR_WORKSPACE_RESTORE_LOCK_TIMEOUT",
|
|
}));
|
|
if (cleanupAt === "outer") release.mockResolvedValueOnce(undefined);
|
|
const originalFactory = instructionWorkingCopies.agentInstructionWorkingCopyService;
|
|
const factory = vi.spyOn(instructionWorkingCopies, "agentInstructionWorkingCopyService").mockImplementation((...args) => ({
|
|
...originalFactory(...args), release,
|
|
}));
|
|
const originalAppend = runEvents.appendHeartbeatRunEvent;
|
|
const append = vi.spyOn(runEvents, "appendHeartbeatRunEvent").mockImplementation((db, event) => {
|
|
if (warningFails && event.eventType === "instruction_cleanup") throw new Error("Fixture warning persistence failed");
|
|
return originalAppend(db, event);
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId, issueId, sourceRunId: runId,
|
|
kind: "request_confirmation", title: "Approve the saved plan", payload: { version: 1, prompt: "Accept the plan?" } });
|
|
await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, issueId));
|
|
await db.insert(issueComments).values({ companyId, issueId, authorAgentId: agentId, createdByRunId: runId, body: "Plan saved; awaiting approval." });
|
|
if (providerOutcome === "throws") throw new Error("Original provider failure");
|
|
return { exitCode: providerOutcome === "succeeded" ? 0 : 1, signal: null, timedOut: false,
|
|
errorCode: providerOutcome === "succeeded" ? null : "provider_failed",
|
|
errorMessage: providerOutcome === "succeeded" ? null : "Original provider failure",
|
|
summary: "Plan saved; awaiting approval.", provider: "test", model: "test-model",
|
|
usage: { inputTokens: 100, outputTokens: 25 }, costUsd: 0.05 };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const settled = await heartbeat.getRun(runId);
|
|
expect(settled).toMatchObject({ status: providerOutcome === "succeeded" ? "succeeded" : "failed",
|
|
error: providerOutcome === "succeeded" ? null : "Original provider failure" });
|
|
if (providerOutcome !== "throws") {
|
|
expect(settled?.resultJson?.summary).toBe("Plan saved; awaiting approval.");
|
|
expect(settled?.usageJson).toMatchObject({ inputTokens: 100, outputTokens: 25 });
|
|
const costs = await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId));
|
|
expect(costs).toHaveLength(1);
|
|
expect(costs[0]?.costCents).toBe(5);
|
|
}
|
|
expect(release).toHaveBeenCalledTimes(cleanupAt === "outer" ? 2 : 1);
|
|
expect(adapterExecutionControls.has(runId)).toBe(false);
|
|
const warnings = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId), eq(heartbeatRunEvents.eventType, "instruction_cleanup")));
|
|
expect(warnings).toHaveLength(warningFails ? 0 : 1);
|
|
if (!warningFails) expect(warnings[0]).toMatchObject({ level: "warn", payload: { state: "deferred" } });
|
|
expect(JSON.stringify(warnings)).not.toContain("/private/");
|
|
expect(await selectRecoveryCommentsForIssue(issueId)).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({ body: "Plan saved; awaiting approval." }),
|
|
]));
|
|
expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId)))[0]?.status).toBe("pending");
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]?.status).toBe("in_review");
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
|
} finally {
|
|
factory.mockRestore();
|
|
append.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("persists a failed capture before heartbeat failure finalization settles an older receipt", async () => {
|
|
const { companyId, agentId, runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });
|
|
await db.insert(budgetPolicies).values({ companyId, scopeType: "company", scopeId: companyId,
|
|
metric: "billed_cents", windowKind: "calendar_month_utc", amount: 100, reservationCents: "10.0000000", isActive: true });
|
|
mockAdapterExecute.mockImplementationOnce(async (raw?: unknown) => {
|
|
const input = raw as { onUsage: (receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => Promise<void> };
|
|
await input.onUsage({ costUsd: 0, complete: true });
|
|
const transaction = vi.spyOn(db, "transaction").mockRejectedValueOnce(new Error("Database temporarily unavailable"));
|
|
const rename = vi.spyOn(fs, "rename").mockRejectedValueOnce(new Error("Receipt disk full"));
|
|
try {
|
|
// A paid capture and the first database fence write both fail. The
|
|
// heartbeat catch must retry the fence before terminalizing.
|
|
await input.onUsage({ costUsd: 0.25, usage: { inputTokens: 10, outputTokens: 2 }, complete: true });
|
|
throw new Error("Expected capture to reject");
|
|
} finally { transaction.mockRestore(); rename.mockRestore(); }
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", costAccountedAt: null,
|
|
costAccountingPending: true, accountingLastError: "usage_capture_failed",
|
|
usageJson: { accountingReceiptReady: false, accountingCaptureFailed: true } });
|
|
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
|
|
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]?.state).toBe("held");
|
|
expect(Number((await db.select().from(agentRuntimeState).where(eq(agentRuntimeState.agentId, agentId)))[0]?.totalCostCents ?? 0)).toBe(0);
|
|
});
|
|
|
|
it("stops controller renewal and releases execution controls when teardown deadline cleanup throws", async () => {
|
|
const { runId, issueId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done", completedAt: new Date() }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "Completed the turn.", provider: "test", model: "test-model" };
|
|
});
|
|
const originalWatch = controllerLeases.watchLegacyControllerLease;
|
|
const stopped = vi.fn();
|
|
const watcher = vi.spyOn(controllerLeases, "watchLegacyControllerLease").mockImplementation((...args) => {
|
|
const lease = originalWatch(...args);
|
|
return { ...lease, stop() { stopped(); lease.stop(); } };
|
|
});
|
|
const originalTransaction = db.transaction.bind(db);
|
|
const cleanupFailure = vi.fn(() => { throw new Error("fixture_deadline_cleanup_failure"); });
|
|
const transaction = vi.spyOn(db, "transaction").mockImplementation((operation, config) =>
|
|
originalTransaction(async tx => {
|
|
const originalUpdate = tx.update.bind(tx);
|
|
const update = vi.spyOn(tx, "update").mockImplementation(((table: typeof heartbeatRuns) => {
|
|
const builder = originalUpdate(table);
|
|
const originalSet = builder.set.bind(builder);
|
|
builder.set = ((values: Record<string, unknown>) => {
|
|
if (table === heartbeatRuns && Object.keys(values).length === 1 && values.executionControlDeadlineAt === null) {
|
|
return { where: async () => cleanupFailure() };
|
|
}
|
|
return originalSet(values);
|
|
}) as typeof builder.set;
|
|
return builder;
|
|
}) as typeof tx.update);
|
|
try {
|
|
return await operation(tx);
|
|
} finally {
|
|
update.mockRestore();
|
|
}
|
|
}, config));
|
|
const heartbeat = heartbeatService(db);
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions().catch(() => undefined);
|
|
expect(cleanupFailure).toHaveBeenCalledTimes(1);
|
|
expect(stopped).toHaveBeenCalledTimes(1);
|
|
expect(adapterExecutionControls.has(runId)).toBe(false);
|
|
expect((await heartbeat.getRun(runId))?.status).not.toBe("running");
|
|
} finally {
|
|
transaction.mockRestore();
|
|
watcher.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each([false, true])("dispatches interrupted CLI input and cleans up early fixture exits (%s)", async (earlyExit) => {
|
|
const actualProcess = await vi.importActual<typeof import("../adapters/process/execute.js")>("../adapters/process/execute.js");
|
|
const { companyId, agentId, issueId, runId } = await seedRunFixture({
|
|
runtimeMode: "legacy", adapterType: "codex_local", agentStatus: "idle", runStatus: "queued",
|
|
});
|
|
await db.update(agents).set({ adapterConfig: {
|
|
command: process.execPath, args: ["-e", "console.log('ready');setInterval(() => {}, 1000)"], graceSec: 1,
|
|
} }).where(eq(agents.id, agentId));
|
|
mockAdapterExecute.mockImplementationOnce((async (input: unknown) =>
|
|
actualProcess.execute(input as Parameters<typeof actualProcess.execute>[0])) as typeof mockAdapterExecute);
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
expect(await waitForValue(async () => runningProcesses.get(runId))).toBeTruthy();
|
|
if (earlyExit) return; // Exercise afterEach while the unbounded CLI child is still live.
|
|
const [comment] = await db.insert(issueComments).values({ companyId, issueId, authorUserId: "responsible-user", body: "continue" }).returning();
|
|
const [wake] = await db.insert(agentWakeupRequests).values({
|
|
companyId, agentId, source: "automation", reason: "issue_commented", status: "deferred_issue_execution",
|
|
requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
payload: { issueId, commentId: comment!.id, _paperclipWakeContext: { issueId, wakeReason: "issue_commented", wakeCommentIds: [comment!.id] } },
|
|
}).returning();
|
|
await heartbeat.cancelRun(runId, "Interrupt queued input", {
|
|
errorCode: "operator_interrupted", suppressImmediateRecovery: true,
|
|
resultJson: { operatorInterrupted: true, queuedCommentInterruptQueueId: wake!.id },
|
|
});
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const [updated] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake!.id));
|
|
expect(updated!.runId).toBeTruthy();
|
|
expect(updated!.runId).not.toBe(runId);
|
|
expect((await heartbeat.getRun(updated!.runId!))!.contextSnapshot?.wakeCommentIds).toEqual([comment!.id]);
|
|
});
|
|
|
|
it("retries durable queue interruption after a promotion failure on a fresh service", async () => {
|
|
const { companyId, agentId, issueId, runId } = await seedRunFixture({
|
|
runtimeMode: "legacy", adapterType: "codex_local", agentStatus: "idle", runStatus: "cancelled",
|
|
});
|
|
mockAdapterExecute.mockImplementation(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "Recorded completion", provider: "test", model: "test-model" };
|
|
});
|
|
const [comment] = await db.insert(issueComments).values({ companyId, issueId, authorUserId: "responsible-user", body: "retry this input" }).returning();
|
|
const [wake] = await db.insert(agentWakeupRequests).values({
|
|
companyId, agentId, source: "automation", reason: "issue_commented", status: "deferred_issue_execution",
|
|
requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
payload: { issueId, commentId: comment!.id, _paperclipWakeContext: { issueId, wakeReason: "issue_commented", wakeCommentIds: [comment!.id] } },
|
|
}).returning();
|
|
await db.update(heartbeatRuns).set({ resultJson: {
|
|
queuedCommentInterruptQueueId: wake!.id,
|
|
executionCancellation: { state: "acknowledged" },
|
|
conversationContinuation: "continue_conversation_v1",
|
|
} }).where(eq(heartbeatRuns.id, runId));
|
|
const failedPromotion = vi.spyOn(db, "transaction").mockRejectedValueOnce(new Error("temporary queue promotion outage"));
|
|
try {
|
|
await heartbeatService(db).resumeQueuedRuns();
|
|
expect(failedPromotion).toHaveBeenCalled();
|
|
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake!.id)))[0]!.status).toBe("deferred_issue_execution");
|
|
} finally {
|
|
failedPromotion.mockRestore();
|
|
}
|
|
const restarted = heartbeatService(db);
|
|
await restarted.resumeQueuedRuns();
|
|
await restarted.drainActiveRunExecutions();
|
|
const [updated] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake!.id));
|
|
expect(updated!.runId).toBeTruthy();
|
|
expect((await restarted.getRun(updated!.runId!))!.contextSnapshot?.wakeCommentIds).toEqual([comment!.id]);
|
|
await restarted.resumeQueuedRuns();
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(2);
|
|
});
|
|
|
|
it.each(["pending", "discarded", "wrong queue"] as const)(
|
|
"resumes only the authorized %s queue after an acknowledged legacy interrupt",
|
|
async (state) => {
|
|
const { companyId, agentId, issueId, runId } = await seedRunFixture({
|
|
runtimeMode: "legacy", adapterType: "codex_local", agentStatus: "running",
|
|
});
|
|
mockAdapterExecute.mockImplementation(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "Recorded completion", provider: "test", model: "test-model" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
const comments = await db.insert(issueComments).values([
|
|
{ companyId, issueId, authorUserId: "responsible-user", body: "First, edited" },
|
|
{ companyId, issueId, authorUserId: "responsible-user", body: "Deleted" },
|
|
{ companyId, issueId, authorUserId: "responsible-user", body: "Third, moved first" },
|
|
]).returning();
|
|
const commentIds = [comments[2]!.id, comments[0]!.id];
|
|
const [deferred] = await db.insert(agentWakeupRequests).values({
|
|
companyId, agentId, source: "automation", reason: "issue_commented",
|
|
status: state === "discarded" ? "cancelled" : "deferred_issue_execution",
|
|
requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
payload: { issueId, commentId: commentIds[0], _paperclipWakeContext: {
|
|
issueId, wakeReason: "issue_commented", wakeCommentIds: commentIds,
|
|
} },
|
|
}).returning();
|
|
// A different actor's older queue must not consume this interrupt.
|
|
const [otherComment] = await db.insert(issueComments).values({
|
|
companyId, issueId, authorUserId: "other-user", body: "Other actor's input",
|
|
}).returning();
|
|
await db.insert(agentWakeupRequests).values({
|
|
companyId, agentId, source: "automation", reason: "issue_commented",
|
|
status: "deferred_issue_execution", requestedAt: new Date(0),
|
|
requestedByActorType: "user", requestedByActorId: "other-user",
|
|
payload: { issueId, commentId: otherComment!.id, _paperclipWakeContext: {
|
|
issueId, wakeReason: "issue_commented", wakeCommentIds: [otherComment!.id],
|
|
} },
|
|
});
|
|
await heartbeat.cancelRun(runId, "Interrupt queued messages", {
|
|
suppressImmediateRecovery: true, errorCode: "operator_interrupted",
|
|
resultJson: {
|
|
operatorInterrupted: true,
|
|
queuedCommentInterruptQueueId: state === "wrong queue" ? randomUUID() : deferred!.id,
|
|
executionCancellation: { state: "acknowledged" },
|
|
executionRecovery: { kind: "interrupted", providerStopped: true, sessionPreserved: true, actionOutcomes: "settled" },
|
|
},
|
|
});
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
const successors = runs.filter((run) => run.id !== runId)
|
|
.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime());
|
|
expect(successors).toHaveLength(state === "pending" ? 2 : 0);
|
|
if (state === "pending") {
|
|
expect(successors[0]!.contextSnapshot?.wakeCommentIds).toEqual(commentIds);
|
|
// Only the requested turn's normal completion can drain the other queue.
|
|
expect(successors[1]!.contextSnapshot?.wakeCommentIds).toEqual([otherComment!.id]);
|
|
await heartbeat.cancelRun(runId, "Duplicate interrupt");
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(3);
|
|
}
|
|
},
|
|
);
|
|
|
|
it("preserves deferred input on a clean Stop and adopts it once on the next explicit comment", async () => {
|
|
const { companyId, agentId, issueId, runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "running" });
|
|
const heartbeat = heartbeatService(db);
|
|
const [pending] = await db.insert(issueComments).values({ companyId, issueId, authorUserId: "responsible-user", body: "List recent Drive files" }).returning();
|
|
const [deferred] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", reason: "issue_execution_deferred", status: "deferred_issue_execution",
|
|
payload: { issueId, commentId: pending!.id, _paperclipWakeContext: { issueId, wakeReason: "issue_commented", wakeCommentIds: [pending!.id] } },
|
|
}).returning();
|
|
await heartbeat.cancelRun(runId, "Operator Stop", { resultJson: {
|
|
executionCancellation: { state: "acknowledged" },
|
|
executionRecovery: { kind: "interrupted", providerStopped: true, sessionPreserved: true, actionOutcomes: "settled" },
|
|
} });
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(1);
|
|
expect(await selectRecoveryActionsForIssue(issueId)).toHaveLength(0);
|
|
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, deferred!.id)))[0]?.status).toBe("deferred_issue_execution");
|
|
const [go] = await db.insert(issueComments).values({ companyId, issueId, authorUserId: "responsible-user", body: "go" }).returning();
|
|
const next = await heartbeat.wakeup(agentId, { source: "automation", reason: "issue_commented", requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
payload: { issueId, commentId: go!.id }, contextSnapshot: { issueId, commentId: go!.id, wakeReason: "issue_commented" },
|
|
});
|
|
expect(next?.contextSnapshot?.wakeCommentIds).toEqual([pending!.id, go!.id]);
|
|
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, deferred!.id)))[0]).toMatchObject({ status: "coalesced", runId: next!.id });
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect((await heartbeat.getRun(next!.id))?.status).not.toBe("running");
|
|
});
|
|
|
|
it.each(["dedicated deferred donor", "non-coalescing recipient", "persistent agent conversation"] as const)(
|
|
"does not adopt unrelated queued comments for a %s after Stop",
|
|
async (direction) => {
|
|
const { companyId, agentId, issueId, runId } = await seedRunFixture({
|
|
runtimeMode: "legacy",
|
|
agentStatus: "running",
|
|
});
|
|
const persistentConversation = direction === "persistent agent conversation";
|
|
if (persistentConversation) {
|
|
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true });
|
|
await db.update(issues).set({
|
|
conversationAgentId: agentId, conversationUserId: "responsible-user", conversationState: "active",
|
|
}).where(eq(issues.id, issueId));
|
|
}
|
|
const heartbeat = heartbeatService(db);
|
|
const [pending, go] = await db
|
|
.insert(issueComments)
|
|
.values([
|
|
{
|
|
companyId,
|
|
issueId,
|
|
authorUserId: "responsible-user",
|
|
body: "Earlier input",
|
|
},
|
|
{
|
|
companyId,
|
|
issueId,
|
|
authorUserId: "responsible-user",
|
|
body: "Fresh input",
|
|
},
|
|
])
|
|
.returning();
|
|
const interaction = {
|
|
interactionId: randomUUID(),
|
|
interactionKind: "question",
|
|
interactionStatus: "answered",
|
|
source: "chat:telegram",
|
|
forceFreshSession: true,
|
|
};
|
|
const dedicatedDonor = direction === "dedicated deferred donor";
|
|
// This is the deferred envelope produced by the chat interaction wake:
|
|
// mutation belongs to payload, not the retained context snapshot.
|
|
const deferredPayload = {
|
|
issueId,
|
|
commentId: pending!.id,
|
|
...(dedicatedDonor ? { mutation: "interaction", ...interaction } : {}),
|
|
_paperclipWakeContext: {
|
|
issueId,
|
|
wakeReason: "issue_commented",
|
|
wakeCommentIds: [pending!.id],
|
|
...(dedicatedDonor ? interaction : {}),
|
|
},
|
|
};
|
|
const [deferred] = await db
|
|
.insert(agentWakeupRequests)
|
|
.values({
|
|
companyId,
|
|
agentId,
|
|
source: "automation",
|
|
reason: "issue_execution_deferred",
|
|
status: "deferred_issue_execution",
|
|
payload: deferredPayload,
|
|
})
|
|
.returning();
|
|
await heartbeat.cancelRun(runId, "Operator Stop", {
|
|
resultJson: {
|
|
executionCancellation: { state: "acknowledged" },
|
|
executionRecovery: {
|
|
kind: "interrupted",
|
|
providerStopped: true,
|
|
sessionPreserved: true,
|
|
actionOutcomes: "settled",
|
|
},
|
|
},
|
|
});
|
|
let release!: () => void;
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await held;
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Completed fresh input",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
});
|
|
let next: Awaited<ReturnType<typeof heartbeat.wakeup>>;
|
|
try {
|
|
next = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
...(direction === "non-coalescing recipient" ? { allowRunCoalescing: false } : {}),
|
|
payload: {
|
|
issueId,
|
|
commentId: go!.id,
|
|
...(dedicatedDonor || persistentConversation
|
|
? {}
|
|
: { mutation: "interaction", ...interaction }),
|
|
},
|
|
contextSnapshot: {
|
|
issueId,
|
|
commentId: go!.id,
|
|
wakeReason: "issue_commented",
|
|
...(dedicatedDonor || persistentConversation ? {} : interaction),
|
|
},
|
|
});
|
|
expect(next).not.toBeNull();
|
|
expect(next?.contextSnapshot?.wakeCommentIds).toEqual([go!.id]);
|
|
if (!dedicatedDonor && !persistentConversation)
|
|
expect(next?.contextSnapshot).toMatchObject(interaction);
|
|
const [retained] = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, deferred!.id));
|
|
expect(retained).toMatchObject({
|
|
status: "deferred_issue_execution",
|
|
runId: null,
|
|
});
|
|
expect(retained?.payload).toEqual(deferredPayload);
|
|
} finally {
|
|
if (persistentConversation) await instanceSettingsService(db).updateExperimental({ enableAgentChat: false });
|
|
// Keep this fixture's parked donor from being scheduled during teardown.
|
|
await db
|
|
.update(agents)
|
|
.set({ status: "paused" })
|
|
.where(eq(agents.id, agentId));
|
|
release();
|
|
// Wait for the released executor and its cleanup, not the default
|
|
// one-second polling window. The next case must not inherit live work.
|
|
await heartbeat.drainActiveRunExecutions();
|
|
if (next!) expect((await heartbeat.getRun(next!.id))?.status).not.toBe("running");
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each([{}, { command: "/nonexistent-paperclip-bootstrap-command" }])("releases holds for real process bootstrap failures: %j", async (config) => {
|
|
const { execute } = await import("../adapters/process/execute.js");
|
|
mockAdapterExecute.mockImplementationOnce(execute);
|
|
const { runId, agentId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued", includeIssue: false });
|
|
await db.update(agents).set({ adapterType: "process", adapterConfig: config }).where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", costAccountingPending: false, costAccountedAt: expect.any(Date) });
|
|
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]?.state).toBe("released");
|
|
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
|
|
});
|
|
|
|
it("releases the dispatch reservation after a proven pre-provider adapter failure", async () => {
|
|
mockAdapterExecute.mockResolvedValueOnce({
|
|
exitCode: 1, signal: null, timedOut: false,
|
|
errorMessage: "Provider startup failed", provider: "test", model: "test-model",
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
});
|
|
const { runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued", includeIssue: false });
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const run = await heartbeat.getRun(runId);
|
|
expect(run).toMatchObject({ status: "failed", costAccountingPending: false });
|
|
expect(run?.costAccountedAt).not.toBeNull();
|
|
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]).toMatchObject({ state: "released" });
|
|
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
|
|
});
|
|
|
|
it.each(["single Stop", "agent pause"] as const)(
|
|
"fences adapter registration while an earlier no-owner %s waits to commit",
|
|
async (operation) => {
|
|
let context!: {
|
|
onCancellationReady?: () => Promise<void>;
|
|
signal?: AbortSignal;
|
|
};
|
|
let releaseRegistration!: () => void;
|
|
const registrationGate = new Promise<void>((resolve) => {
|
|
releaseRegistration = resolve;
|
|
});
|
|
let releaseAdapter!: () => void;
|
|
const adapterGate = new Promise<void>((resolve) => {
|
|
releaseAdapter = resolve;
|
|
});
|
|
let registered = false;
|
|
let registrationAttempted = false;
|
|
let providerStarts = 0;
|
|
mockAdapterExecute.mockImplementationOnce(async (input) => {
|
|
context = input as typeof context;
|
|
await registrationGate;
|
|
registrationAttempted = true;
|
|
await context.onCancellationReady?.();
|
|
registered = true;
|
|
// This is the real engine's next permission check, before buildRuntime.
|
|
if (!context.signal?.aborted) providerStarts += 1;
|
|
await adapterGate;
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Stopped before provider startup",
|
|
provider: "test",
|
|
model: "test-model",
|
|
...(context.signal?.aborted
|
|
? {
|
|
executionRecovery: {
|
|
kind: "bootstrap",
|
|
providerWorkStarted: false,
|
|
},
|
|
resultJson: {
|
|
executionCancellation: { state: "acknowledged", forced: false },
|
|
},
|
|
}
|
|
: {}),
|
|
};
|
|
});
|
|
const { runId, agentId } = await seedRunFixture({
|
|
runtimeMode: "legacy",
|
|
agentStatus: "idle",
|
|
runStatus: "queued",
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForValue(async () => context);
|
|
expect(adapterExecutionControls.has(runId)).toBe(false);
|
|
let releaseRow!: () => void;
|
|
const rowGate = new Promise<void>((resolve) => {
|
|
releaseRow = resolve;
|
|
});
|
|
let reportRow!: (pid: number) => void;
|
|
const rowReady = new Promise<number>((resolve) => {
|
|
reportRow = resolve;
|
|
});
|
|
const lock = db.transaction(async (tx) => {
|
|
await tx
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
.for("update");
|
|
const [row] = await tx.execute<{ pid: number }>(
|
|
sql`select pg_backend_pid() as pid`,
|
|
);
|
|
reportRow(row!.pid);
|
|
await rowGate;
|
|
});
|
|
const pid = await rowReady;
|
|
let stopReturned = false;
|
|
const requestStop =
|
|
operation === "single Stop"
|
|
? heartbeat.cancelRun(runId)
|
|
: heartbeat
|
|
.cancelActiveForAgent(agentId)
|
|
.then(() => heartbeat.getRun(runId));
|
|
const stopping = requestStop.then(
|
|
(run) => {
|
|
stopReturned = true;
|
|
return { run, error: null };
|
|
},
|
|
(error: unknown) => {
|
|
stopReturned = true;
|
|
return { run: null, error };
|
|
},
|
|
);
|
|
try {
|
|
await vi.waitFor(async () => {
|
|
const [row] = await db.execute<{ count: number }>(sql`
|
|
select count(*)::int as count from pg_stat_activity activity
|
|
where datname = current_database() and ${pid} = any(pg_blocking_pids(activity.pid))
|
|
and wait_event_type = 'Lock'
|
|
and exists (select 1 from pg_locks locks where locks.pid = activity.pid
|
|
and locks.relation = 'heartbeat_runs'::regclass)
|
|
`);
|
|
expect(row!.count).toBeGreaterThan(0);
|
|
});
|
|
releaseRegistration();
|
|
await vi.waitFor(() => expect(registrationAttempted).toBe(true));
|
|
// Readiness must remain behind the earlier Stop, without publishing a
|
|
// joinable owner that would deadlock a duplicate Stop on this barrier.
|
|
expect(adapterExecutionControls.has(runId)).toBe(false);
|
|
expect(registered).toBe(false);
|
|
expect(providerStarts).toBe(0);
|
|
expect(stopReturned).toBe(false);
|
|
releaseRow();
|
|
await lock;
|
|
const result = await stopping;
|
|
expect(result.error).toBeNull();
|
|
expect(result.run).toMatchObject({ status: "cancelled" });
|
|
await vi.waitFor(() => expect(registered).toBe(true));
|
|
expect(context.signal?.aborted).toBe(true);
|
|
expect(providerStarts).toBe(0);
|
|
releaseAdapter();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const settledRun = await heartbeat.getRun(runId);
|
|
expect(settledRun?.costAccountingPending).toBe(false);
|
|
expect(settledRun?.costAccountedAt).not.toBeNull();
|
|
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]).toMatchObject({ state: "released" });
|
|
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
|
|
expect({
|
|
status: settledRun?.status,
|
|
errorCode: settledRun?.errorCode,
|
|
resultJson: settledRun?.resultJson,
|
|
finishedAt: settledRun?.finishedAt,
|
|
}).toEqual({
|
|
status: result.run!.status,
|
|
errorCode: result.run!.errorCode,
|
|
resultJson: result.run!.resultJson,
|
|
finishedAt: result.run!.finishedAt,
|
|
});
|
|
} finally {
|
|
releaseRow();
|
|
releaseRegistration();
|
|
releaseAdapter();
|
|
await lock;
|
|
await stopping;
|
|
await heartbeat.drainActiveRunExecutions();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("signals an embedded adapter and waits for its cleanup before returning Stop", async () => {
|
|
const { runId } = await seedRunFixture({ runtimeMode: "legacy", includeIssue: false });
|
|
const control = createAdapterExecutionControl();
|
|
adapterExecutionControls.set(runId, control);
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
let returned = false;
|
|
const stopping = heartbeat.cancelRun(runId).then((run) => { returned = true; return run; });
|
|
await vi.waitFor(() => expect(control.controller.signal.aborted).toBe(true));
|
|
const repeatedStop = heartbeat.cancelRun(runId);
|
|
// Let the duplicate request observe the still-running execution.
|
|
await new Promise(resolve => setTimeout(resolve, 25));
|
|
expect(returned).toBe(false);
|
|
expect((await heartbeat.getRun(runId))?.status).toBe("running");
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", resultJson: {
|
|
executionCancellation: { state: "acknowledged" },
|
|
} }).where(eq(heartbeatRuns.id, runId));
|
|
control.finish();
|
|
expect(await stopping).toMatchObject({ status: "cancelled", resultJson: { executionCancellation: { state: "acknowledged" } } });
|
|
expect(await repeatedStop).toMatchObject({ status: "cancelled", resultJson: { executionCancellation: { state: "acknowledged" } } });
|
|
} finally {
|
|
control.finish();
|
|
adapterExecutionControls.delete(runId);
|
|
}
|
|
});
|
|
|
|
it("preserves a copy-back obligation recorded after Stop reads the running adapter", async () => {
|
|
const { runId, companyId, issueId } = await seedRunFixture({ runtimeMode: "legacy", adapterType: "codex_local" });
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
const [environment] = await db.insert(environments).values({ name: `Stop restore race ${runId}`, driver: "sandbox" }).returning();
|
|
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId,
|
|
environmentId: environment.id, provider: "daytona", providerLeaseId: randomUUID(), status: "active",
|
|
leasePolicy: "ephemeral", metadata: { driver: "sandbox" },
|
|
}).returning();
|
|
const control = createAdapterExecutionControl();
|
|
adapterExecutionControls.set(runId, control);
|
|
let releaseWrite!: () => void;
|
|
const writeGate = new Promise<void>(resolve => { releaseWrite = resolve; });
|
|
let reportWrite!: () => void;
|
|
const writeCaptured = new Promise<void>(resolve => { reportWrite = resolve; });
|
|
const originalUpdate = db.update.bind(db);
|
|
const writeSpy = vi.spyOn(db, "update").mockImplementationOnce((table) => {
|
|
const update = originalUpdate(table);
|
|
const originalSet = update.set.bind(update);
|
|
vi.spyOn(update, "set").mockImplementationOnce((value) => {
|
|
const query = originalSet(value);
|
|
const originalWhere = query.where.bind(query);
|
|
vi.spyOn(query, "where").mockImplementationOnce((condition) => {
|
|
reportWrite();
|
|
return writeGate.then(() => originalWhere(condition)) as unknown as ReturnType<typeof query.where>;
|
|
});
|
|
return query;
|
|
});
|
|
return update;
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
const stopping = heartbeat.cancelRun(runId);
|
|
try {
|
|
await writeCaptured;
|
|
// This commits after Stop captured its old result, before Stop's write.
|
|
await recordLegacyWorkspaceRestoreFailure(db, run, { workspaceRestoreFailure: "restore_failed" });
|
|
releaseWrite();
|
|
await vi.waitFor(() => expect(control.controller.signal.aborted).toBe(true));
|
|
const [requested] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(requested.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_failed",
|
|
workspaceRestoreRecovery: { leaseIds: [lease.id] }, executionCancellation: { state: "requested" } });
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0])
|
|
.toMatchObject({ leasePolicy: "retain_on_failure", status: "pending_cleanup" });
|
|
const cancelled = await terminalizeLegacyExecution({ db, run: requested, status: "cancelled", reconcileIfNeeded: true,
|
|
patch: { resultJson: { executionCancellation: { state: "acknowledged" } } } });
|
|
control.finish();
|
|
await expect(stopping).resolves.toMatchObject({ status: "cancelled" });
|
|
expect(cancelled?.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { leaseIds: [lease.id] } });
|
|
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId!))).toHaveLength(1);
|
|
} finally {
|
|
releaseWrite();
|
|
writeSpy.mockRestore();
|
|
control.finish();
|
|
adapterExecutionControls.delete(runId);
|
|
await stopping.catch(() => undefined);
|
|
}
|
|
});
|
|
|
|
it("clears the detached warning when the run reports activity again", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
includeIssue: false,
|
|
runErrorCode: "process_detached",
|
|
runError:
|
|
"Lost in-memory process handle, but child pid 123 is still alive",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const updated = await heartbeat.reportRunActivity(runId);
|
|
expect(updated?.errorCode).toBeNull();
|
|
expect(updated?.error).toBeNull();
|
|
|
|
const run = await heartbeat.getRun(runId);
|
|
expect(run?.errorCode).toBeNull();
|
|
expect(run?.error).toBeNull();
|
|
});
|
|
|
|
it("tracks the first heartbeat with the agent role instead of adapter type", async () => {
|
|
const { agentId, runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.cancelRun(runId);
|
|
|
|
expect(mockTrackAgentFirstHeartbeat).toHaveBeenCalledWith(
|
|
mockTelemetryClient,
|
|
expect.objectContaining({
|
|
agentRole: "engineer",
|
|
agentId,
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("preserves first-heartbeat telemetry after a timer interval claim", async () => {
|
|
const { agentId, runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
contextSnapshot: { timerClaimWasFirstHeartbeat: true },
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({ lastHeartbeatAt: new Date("2026-03-19T00:00:00.000Z") })
|
|
.where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.cancelRun(runId);
|
|
|
|
expect(mockTrackAgentFirstHeartbeat).toHaveBeenCalledWith(
|
|
mockTelemetryClient,
|
|
expect.objectContaining({
|
|
agentRole: "engineer",
|
|
agentId,
|
|
}),
|
|
);
|
|
});
|
|
|
|
it.each(([
|
|
{ mode: "signal", graceful: false, failure: null },
|
|
{ mode: "graceful exit", graceful: true, failure: null },
|
|
{ mode: "adapter exception", graceful: false, failure: null },
|
|
{ mode: "termination error", graceful: false, failure: "termination" },
|
|
{ mode: "cancellation write error", graceful: false, failure: "write" },
|
|
{
|
|
mode: "graceful termination error",
|
|
graceful: true,
|
|
failure: "termination",
|
|
},
|
|
{
|
|
mode: "graceful cancellation write error",
|
|
graceful: true,
|
|
failure: "write",
|
|
},
|
|
{
|
|
mode: "late graceful cancellation write error",
|
|
graceful: true,
|
|
failure: "write",
|
|
},
|
|
] as const).flatMap((scenario) =>
|
|
(["process", "codex_local"] as const).map((adapterType) => ({ ...scenario, adapterType })),
|
|
))(
|
|
"settles an owned $adapterType Stop before classifying its $mode",
|
|
async ({ mode, graceful, failure, adapterType }) => {
|
|
const stopSignal = adapterType === "codex_local" ? "SIGINT" : "SIGTERM";
|
|
const actualProcess = await vi.importActual<
|
|
typeof import("../adapters/process/execute.js")
|
|
>("../adapters/process/execute.js");
|
|
const actualSupervisor = await vi.importActual<
|
|
typeof import("../services/local-service-supervisor.js")
|
|
>("../services/local-service-supervisor.js");
|
|
let releaseTermination!: () => void;
|
|
const terminationRelease = new Promise<void>((resolve) => {
|
|
releaseTermination = resolve;
|
|
});
|
|
let reportTerminated!: () => void;
|
|
const terminated = new Promise<void>((resolve) => {
|
|
reportTerminated = resolve;
|
|
});
|
|
let releaseResult!: () => void;
|
|
const resultRelease = new Promise<void>((resolve) => {
|
|
releaseResult = resolve;
|
|
});
|
|
let observedResult:
|
|
Awaited<ReturnType<typeof actualProcess.execute>> | undefined;
|
|
let reportReady!: () => void;
|
|
const ready = new Promise<void>((resolve) => {
|
|
reportReady = resolve;
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce((async (input: unknown) => {
|
|
const context = input as Parameters<typeof actualProcess.execute>[0];
|
|
observedResult = await actualProcess.execute({
|
|
...context,
|
|
onLog: async (stream, text) => {
|
|
await context.onLog(stream, text);
|
|
if (text.includes("stop ready")) reportReady();
|
|
},
|
|
});
|
|
if (mode === "adapter exception")
|
|
throw new Error(
|
|
"process adapter reported its signal as an exception",
|
|
);
|
|
if (mode === "late graceful cancellation write error")
|
|
await resultRelease;
|
|
return observedResult;
|
|
}) as typeof mockAdapterExecute);
|
|
mockTerminateLocalService.mockImplementationOnce(async (...args: Parameters<typeof actualSupervisor.terminateLocalService>) => {
|
|
await actualSupervisor.terminateLocalService(...args);
|
|
reportTerminated();
|
|
await terminationRelease;
|
|
if (failure === "termination")
|
|
throw new Error("owned termination unconfirmed");
|
|
});
|
|
const { runId, agentId } = await seedRunFixture({
|
|
adapterType,
|
|
agentStatus: "idle",
|
|
runStatus: "queued",
|
|
includeIssue: false,
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterConfig: {
|
|
command: process.execPath,
|
|
args: [
|
|
"-e",
|
|
`${graceful ? `process.on('${stopSignal}', () => process.exit(0));` : ""} console.log('stop ready'); setInterval(() => {}, 1000)`,
|
|
],
|
|
graceSec: 1,
|
|
},
|
|
})
|
|
.where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
const running = await waitForValue(async () =>
|
|
runningProcesses.get(runId),
|
|
);
|
|
expect(running?.child.pid).toBeTruthy();
|
|
await ready;
|
|
const cancellation = heartbeat
|
|
.cancelRun(runId, "Stopped by test operator")
|
|
.then(
|
|
(run) => ({ run, error: null as Error | null }),
|
|
(error: Error) => ({ run: null, error }),
|
|
);
|
|
let duplicate: typeof cancellation | undefined;
|
|
let duplicateSettled = false;
|
|
let writeSpy: ReturnType<typeof vi.spyOn> | undefined;
|
|
let first!: Awaited<typeof cancellation>;
|
|
let second: Awaited<typeof cancellation> | undefined;
|
|
try {
|
|
await terminated;
|
|
expect(await waitForValue(async () => observedResult)).toMatchObject(
|
|
graceful
|
|
? { exitCode: 0, signal: null }
|
|
: { exitCode: null, signal: stopSignal },
|
|
);
|
|
// The process utility already removed its child record on close. A new
|
|
// service instance must still join the original cancellation owner.
|
|
expect(runningProcesses.has(runId)).toBe(false);
|
|
duplicate = heartbeatService(db)
|
|
.cancelRun(runId, "Duplicate Stop")
|
|
.then(
|
|
(run) => {
|
|
duplicateSettled = true;
|
|
return { run, error: null as Error | null };
|
|
},
|
|
(error: Error) => {
|
|
duplicateSettled = true;
|
|
return { run: null, error };
|
|
},
|
|
);
|
|
// The child is gone, but the owned shutdown operation has not settled.
|
|
// Its signal cannot be classified as successful task completion.
|
|
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
expect((await heartbeat.getRun(runId))?.status).toBe("running");
|
|
expect(duplicateSettled).toBe(false);
|
|
if (failure === "write") {
|
|
const error = new Error("owned cancellation write unavailable");
|
|
// Both conversation and process cancellation now finalize under the
|
|
// task/run transaction. Fail that write before either owner resolves.
|
|
writeSpy = vi.spyOn(db, "transaction").mockRejectedValueOnce(error);
|
|
}
|
|
} finally {
|
|
releaseTermination();
|
|
[first, second] = await Promise.all([cancellation, duplicate]);
|
|
writeSpy?.mockRestore();
|
|
releaseResult();
|
|
}
|
|
if (failure) {
|
|
expect(first.error?.message).toContain(
|
|
failure === "write"
|
|
? "cancellation write unavailable"
|
|
: "termination unconfirmed",
|
|
);
|
|
expect(second?.error).toBe(first.error);
|
|
expect((await waitForRunToSettle(heartbeat, runId))?.status).toBe(
|
|
"failed",
|
|
);
|
|
// The failed owner did not leave an unresolved barrier behind.
|
|
expect((await heartbeat.cancelRun(runId))?.status).toBe("failed");
|
|
} else {
|
|
expect(first.error).toBeNull();
|
|
expect(second?.error).toBeNull();
|
|
expect(first.run?.status).toBe("cancelled");
|
|
expect(second?.run?.status).toBe("cancelled");
|
|
}
|
|
expect(mockTerminateLocalService).toHaveBeenCalledTimes(1);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRunEvents)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRunEvents.runId, runId),
|
|
eq(heartbeatRunEvents.message, "run succeeded"),
|
|
),
|
|
),
|
|
).toEqual([]);
|
|
},
|
|
);
|
|
|
|
it("preserves exact restore sources through late process Stop metadata with an oversized result", async () => {
|
|
const actualProcess = await vi.importActual<typeof import("../adapters/process/execute.js")>("../adapters/process/execute.js");
|
|
const actualSupervisor = await vi.importActual<typeof import("../services/local-service-supervisor.js")>("../services/local-service-supervisor.js");
|
|
let reportReady!: () => void;
|
|
const ready = new Promise<void>(resolve => { reportReady = resolve; });
|
|
let releaseTermination!: () => void;
|
|
const terminationGate = new Promise<void>(resolve => { releaseTermination = resolve; });
|
|
mockAdapterExecute.mockImplementationOnce(async (context) => {
|
|
const result = await actualProcess.execute({ ...context, onLog: async (stream, text) => {
|
|
await context.onLog(stream, text);
|
|
if (text.includes("restore stop ready")) reportReady();
|
|
} });
|
|
return { ...result, resultJson: { ...result.resultJson, lateAdapterReceipt: true } };
|
|
});
|
|
mockTerminateLocalService.mockImplementationOnce(async (...args: Parameters<typeof actualSupervisor.terminateLocalService>) => {
|
|
await actualSupervisor.terminateLocalService(...args);
|
|
await terminationGate;
|
|
});
|
|
const { runId, agentId, companyId, issueId } = await seedRunFixture({
|
|
adapterType: "process", runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued",
|
|
});
|
|
await db.update(agents).set({ adapterConfig: { command: process.execPath,
|
|
args: ["-e", "console.log('restore stop ready'); setInterval(() => {}, 1000)"], graceSec: 1,
|
|
} }).where(eq(agents.id, agentId));
|
|
const originalFactory = instructionWorkingCopies.agentInstructionWorkingCopyService;
|
|
let completionReached = false;
|
|
const factory = vi.spyOn(instructionWorkingCopies, "agentInstructionWorkingCopyService").mockImplementation((...args) => {
|
|
const service = originalFactory(...args);
|
|
return { ...service, release: async (...releaseArgs) => {
|
|
await service.release(...releaseArgs);
|
|
if (releaseArgs[1] === runId && !completionReached) {
|
|
completionReached = true;
|
|
// Host completion reaches its owned-Stop await in microtasks after
|
|
// instruction cleanup. Settle Stop on the next turn, without a delay.
|
|
setImmediate(releaseTermination);
|
|
}
|
|
} };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
let stopping: ReturnType<typeof heartbeat.cancelRun> | undefined;
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await ready;
|
|
expect(runningProcesses.get(runId)?.child.pid).toBeTruthy();
|
|
expect(adapterExecutionControls.has(runId)).toBe(false);
|
|
const [environment] = await db.insert(environments).values({ name: `Late restore Stop ${runId}`, driver: "sandbox" }).returning();
|
|
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId,
|
|
environmentId: environment.id, provider: "daytona", providerLeaseId: randomUUID(), status: "active",
|
|
leasePolicy: "ephemeral", metadata: { driver: "sandbox" },
|
|
}).returning();
|
|
// Incompressible fixture data exercises the database-size projection,
|
|
// which keeps the recovery schema but omits its internal source IDs.
|
|
const payload = Array.from({ length: 8192 }, () => randomUUID()).join("");
|
|
const [run] = await db.update(heartbeatRuns).set({ resultJson: { payload } }).where(eq(heartbeatRuns.id, runId)).returning();
|
|
await recordLegacyWorkspaceRestoreFailure(db, run, { workspaceRestoreFailure: "restore_failed" });
|
|
expect((await heartbeat.getRun(runId))?.resultJson?.workspaceRestoreRecovery).toEqual({ schema: "paperclip.workspace-restore-recovery.v1" });
|
|
stopping = heartbeat.cancelRun(runId, "Stopped by test operator");
|
|
await expect(stopping).resolves.toMatchObject({ status: "cancelled" });
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
const [finished] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(completionReached).toBe(true);
|
|
expect(finished).toMatchObject({ status: "cancelled", resultJson: {
|
|
lateAdapterReceipt: true,
|
|
workspaceRestoreFailure: "restore_failed",
|
|
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [lease.id] },
|
|
cancellation: { expected: true },
|
|
} });
|
|
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0])
|
|
.toMatchObject({ leasePolicy: "retain_on_failure", status: "pending_cleanup" });
|
|
expect(await selectRecoveryActionsForIssue(issueId)).toHaveLength(1);
|
|
} finally {
|
|
releaseTermination();
|
|
await stopping?.catch(() => undefined);
|
|
if (runningProcesses.has(runId)) await heartbeat.cancelRun(runId).catch(() => undefined);
|
|
await heartbeat.waitForRunExecutionDrain(runId);
|
|
factory.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
{
|
|
mode: "clean exit",
|
|
script: "console.log('complete')",
|
|
status: "succeeded",
|
|
},
|
|
{
|
|
mode: "unrequested signal",
|
|
script: "process.kill(process.pid, 'SIGTERM')",
|
|
status: "failed",
|
|
},
|
|
])(
|
|
"keeps an independent process $mode distinct from Stop",
|
|
async ({ script, status }) => {
|
|
const actualProcess = await vi.importActual<
|
|
typeof import("../adapters/process/execute.js")
|
|
>("../adapters/process/execute.js");
|
|
mockAdapterExecute.mockImplementationOnce((async (input: unknown) =>
|
|
actualProcess.execute(
|
|
input as Parameters<typeof actualProcess.execute>[0],
|
|
)) as typeof mockAdapterExecute);
|
|
const { runId, agentId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "idle",
|
|
runStatus: "queued",
|
|
includeIssue: false,
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterConfig: { command: process.execPath, args: ["-e", script] },
|
|
})
|
|
.where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
const finished = await waitForRunToSettle(heartbeat, runId, 5_000);
|
|
expect(finished?.status).toBe(status);
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
if (status === "succeeded") {
|
|
expect(finished).toMatchObject({ exitCode: 0, signal: null });
|
|
expect((await heartbeat.cancelRun(runId))?.status).toBe("succeeded");
|
|
} else {
|
|
expect(finished).toMatchObject({
|
|
exitCode: null,
|
|
signal: "SIGTERM",
|
|
errorCode: "adapter_failed",
|
|
});
|
|
}
|
|
},
|
|
);
|
|
|
|
it("retries a settled failed Stop while its exact active process remains alive", async () => {
|
|
const actualProcess = await vi.importActual<
|
|
typeof import("../adapters/process/execute.js")
|
|
>("../adapters/process/execute.js");
|
|
const actualSupervisor = await vi.importActual<
|
|
typeof import("../services/local-service-supervisor.js")
|
|
>("../services/local-service-supervisor.js");
|
|
let reportReady!: () => void;
|
|
const ready = new Promise<void>((resolve) => {
|
|
reportReady = resolve;
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce((async (input: unknown) => {
|
|
const context = input as Parameters<typeof actualProcess.execute>[0];
|
|
return actualProcess.execute({
|
|
...context,
|
|
onLog: async (stream, text) => {
|
|
await context.onLog(stream, text);
|
|
if (text.includes("retry stop ready")) reportReady();
|
|
},
|
|
});
|
|
}) as typeof mockAdapterExecute);
|
|
const { runId, agentId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "idle",
|
|
runStatus: "queued",
|
|
includeIssue: false,
|
|
});
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterConfig: {
|
|
command: process.execPath,
|
|
args: [
|
|
"-e",
|
|
"console.log('retry stop ready'); setInterval(() => {}, 1000)",
|
|
],
|
|
graceSec: 1,
|
|
},
|
|
})
|
|
.where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await ready;
|
|
const owned = runningProcesses.get(runId);
|
|
expect(owned?.child.pid).toBeTruthy();
|
|
mockTerminateLocalService.mockRejectedValueOnce(
|
|
new Error("first Stop did not terminate"),
|
|
);
|
|
try {
|
|
await expect(heartbeat.cancelRun(runId)).rejects.toThrow(
|
|
"first Stop did not terminate",
|
|
);
|
|
expect(runningProcesses.get(runId)).toBe(owned);
|
|
expect((await heartbeat.getRun(runId))?.status).toBe("running");
|
|
expect(owned?.child.exitCode).toBeNull();
|
|
mockTerminateLocalService.mockImplementationOnce(
|
|
actualSupervisor.terminateLocalService,
|
|
);
|
|
expect((await heartbeatService(db).cancelRun(runId))?.status).toBe(
|
|
"cancelled",
|
|
);
|
|
expect((await waitForRunToSettle(heartbeat, runId))?.status).toBe(
|
|
"cancelled",
|
|
);
|
|
expect(mockTerminateLocalService).toHaveBeenCalledTimes(2);
|
|
} finally {
|
|
// A failing assertion must not strand the real fixture child or executor.
|
|
mockTerminateLocalService.mockImplementation(
|
|
actualSupervisor.terminateLocalService,
|
|
);
|
|
await heartbeat.cancelRun(runId).catch(() => undefined);
|
|
}
|
|
});
|
|
|
|
it("retains the exact owned child when process Stop cannot verify termination", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
adapterType: "process",
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
const owned = {
|
|
child: { pid: 12_348 } as ChildProcess,
|
|
graceSec: 1,
|
|
processGroupId: null,
|
|
};
|
|
runningProcesses.set(runId, owned);
|
|
mockTerminateLocalService.mockRejectedValueOnce(
|
|
new Error("owned process remains alive"),
|
|
);
|
|
const heartbeat = heartbeatService(db);
|
|
await expect(heartbeat.cancelRun(runId)).rejects.toThrow(
|
|
"owned process remains alive",
|
|
);
|
|
expect(runningProcesses.get(runId)).toBe(owned);
|
|
expect((await heartbeat.getRun(runId))?.status).toBe("running");
|
|
mockTerminateLocalService.mockResolvedValueOnce(undefined);
|
|
expect((await heartbeat.cancelRun(runId))?.status).toBe("cancelled");
|
|
expect(runningProcesses.has(runId)).toBe(false);
|
|
});
|
|
|
|
it("terminates the in-memory process before persisting cancellation status", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
runningProcesses.set(runId, {
|
|
child: { pid: 12345 } as ChildProcess,
|
|
graceSec: 1,
|
|
processGroupId: null,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValueOnce(undefined);
|
|
|
|
|
|
await db.execute(sql.raw(
|
|
`create function test_process_cancellation_fault() returns trigger language plpgsql as $$
|
|
begin
|
|
if new.id = '${runId}'::uuid and new.status = 'cancelled' then
|
|
raise exception 'db update unavailable';
|
|
end if;
|
|
return new;
|
|
end $$`,
|
|
));
|
|
await db.execute(sql`create trigger test_process_cancellation_fault before update on heartbeat_runs
|
|
for each row execute function test_process_cancellation_fault()`);
|
|
try {
|
|
await expect(heartbeat.cancelRun(runId)).rejects.toMatchObject({
|
|
cause: expect.objectContaining({ message: "db update unavailable" }),
|
|
});
|
|
expect(mockTerminateLocalService).toHaveBeenCalledWith(
|
|
expect.objectContaining({ pid: 12345, processGroupId: null }),
|
|
{ forceAfterMs: 1000, signal: "SIGINT" },
|
|
);
|
|
expect(runningProcesses.has(runId)).toBe(false);
|
|
expect((await heartbeat.getRun(runId))?.status).toBe("running");
|
|
} finally {
|
|
await db.execute(sql`drop trigger test_process_cancellation_fault on heartbeat_runs`);
|
|
await db.execute(sql`drop function test_process_cancellation_fault()`);
|
|
}
|
|
});
|
|
|
|
it("uses a bounded per-cancel process grace for an external-chat successor", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
runningProcesses.set(runId, {
|
|
child: { pid: 12_346 } as ChildProcess,
|
|
graceSec: 30,
|
|
processGroupId: null,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValueOnce(undefined);
|
|
|
|
await heartbeat.cancelRun(
|
|
runId,
|
|
"Superseded by external-chat continuation",
|
|
{
|
|
errorCode: "external_chat_continuation",
|
|
terminationGraceMs: 2_000,
|
|
suppressImmediateRecovery: true,
|
|
},
|
|
);
|
|
|
|
expect(mockTerminateLocalService).toHaveBeenCalledWith(
|
|
expect.objectContaining({ pid: 12_346, processGroupId: null }),
|
|
{ forceAfterMs: 2_000, signal: "SIGINT" },
|
|
);
|
|
expect(runningProcesses.has(runId)).toBe(false);
|
|
});
|
|
|
|
it("does not overwrite a run that finishes while cancellation is stopping its process", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
runningProcesses.set(runId, {
|
|
child: { pid: 12_347 } as ChildProcess,
|
|
graceSec: 30,
|
|
processGroupId: null,
|
|
});
|
|
mockTerminateLocalService.mockImplementationOnce(async () => {
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "succeeded", finishedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
});
|
|
|
|
const outcome = await heartbeat.cancelRun(
|
|
runId,
|
|
"Superseded by external-chat continuation",
|
|
{
|
|
errorCode: "external_chat_continuation",
|
|
terminationGraceMs: 2_000,
|
|
suppressImmediateRecovery: true,
|
|
},
|
|
);
|
|
|
|
expect(outcome).toMatchObject({ status: "succeeded", errorCode: null });
|
|
expect(mockTerminateLocalService).toHaveBeenCalledWith(
|
|
expect.objectContaining({ pid: 12_347, processGroupId: null }),
|
|
{ forceAfterMs: 2_000, signal: "SIGINT" },
|
|
);
|
|
await expect(heartbeat.getRun(runId)).resolves.toMatchObject({
|
|
status: "succeeded",
|
|
errorCode: null,
|
|
});
|
|
});
|
|
|
|
it("does not signal an unowned persisted process during manual cancellation", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
processPid: 81_101,
|
|
processGroupId: 81_102,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValue(undefined);
|
|
|
|
await heartbeatService(db).cancelRun(runId);
|
|
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not signal an unowned persisted process during graceful shutdown", async () => {
|
|
await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
processPid: 81_201,
|
|
processGroupId: 81_202,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValue(undefined);
|
|
|
|
await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM");
|
|
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not signal an unowned persisted process during agent-wide cancellation", async () => {
|
|
const { agentId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
processPid: 81_301,
|
|
processGroupId: 81_302,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValue(undefined);
|
|
|
|
await heartbeatService(db).cancelActiveForAgent(agentId);
|
|
|
|
expect(mockTerminateLocalService).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("signals and clears an owned process during graceful shutdown", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
runningProcesses.set(runId, {
|
|
child: { pid: 81_401 } as ChildProcess,
|
|
graceSec: 2,
|
|
processGroupId: 81_402,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValue(undefined);
|
|
|
|
await heartbeatService(db).drainRunningRunsForShutdown("SIGTERM");
|
|
|
|
expect(mockTerminateLocalService).toHaveBeenCalledWith(
|
|
expect.objectContaining({ pid: 81_401, processGroupId: 81_402 }),
|
|
{ forceAfterMs: 2000 },
|
|
);
|
|
expect(runningProcesses.has(runId)).toBe(false);
|
|
});
|
|
|
|
it("signals and clears an owned process during agent-wide cancellation", async () => {
|
|
const { agentId, runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
runningProcesses.set(runId, {
|
|
child: { pid: 81_501 } as ChildProcess,
|
|
graceSec: 3,
|
|
processGroupId: 81_502,
|
|
});
|
|
mockTerminateLocalService.mockResolvedValue(undefined);
|
|
|
|
await heartbeatService(db).cancelActiveForAgent(agentId);
|
|
|
|
expect(mockTerminateLocalService).toHaveBeenCalledWith(
|
|
expect.objectContaining({ pid: 81_501, processGroupId: 81_502 }),
|
|
{ forceAfterMs: 3000, signal: "SIGINT" },
|
|
);
|
|
expect(runningProcesses.has(runId)).toBe(false);
|
|
});
|
|
|
|
it("records manual cancellation stop metadata", async () => {
|
|
const { runId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: false,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const cancelled = await heartbeat.cancelRun(runId);
|
|
expect(cancelled?.status).toBe("cancelled");
|
|
expect(cancelled?.resultJson).toMatchObject({
|
|
stopReason: "cancelled",
|
|
effectiveTimeoutSec: 0,
|
|
timeoutConfigured: false,
|
|
timeoutFired: false,
|
|
});
|
|
});
|
|
|
|
it("records operator interrupt cancellation metadata without changing terminal status", async () => {
|
|
const { runId, issueId } = await seedRunFixture({
|
|
agentStatus: "running",
|
|
includeIssue: true,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const cancelled = await heartbeat.cancelRun(
|
|
runId,
|
|
"Interrupted by board comment",
|
|
{
|
|
errorCode: "operator_interrupted",
|
|
resultJson: {
|
|
operatorInterrupted: true,
|
|
interruptionSource: "issue_comment_interrupt",
|
|
interruptedIssueId: issueId,
|
|
},
|
|
eventMessage: "run interrupted by board comment",
|
|
eventPayload: {
|
|
issueId,
|
|
source: "issue_comment_interrupt",
|
|
},
|
|
},
|
|
);
|
|
|
|
expect(cancelled?.status).toBe("cancelled");
|
|
expect(cancelled?.errorCode).toBe("operator_interrupted");
|
|
expect(cancelled?.error).toBe("Interrupted by board comment");
|
|
expect(cancelled?.resultJson).toMatchObject({
|
|
stopReason: "cancelled",
|
|
operatorInterrupted: true,
|
|
interruptionSource: "issue_comment_interrupt",
|
|
interruptedIssueId: issueId,
|
|
});
|
|
|
|
const events = await db
|
|
.select()
|
|
.from(heartbeatRunEvents)
|
|
.where(and(eq(heartbeatRunEvents.runId, runId), eq(heartbeatRunEvents.eventType, "lifecycle")));
|
|
expect(events).toHaveLength(1);
|
|
expect(events[0]).toMatchObject({
|
|
eventType: "lifecycle",
|
|
stream: "system",
|
|
level: "warn",
|
|
message: "run interrupted by board comment",
|
|
payload: expect.objectContaining({
|
|
issueId,
|
|
source: "issue_comment_interrupt",
|
|
}),
|
|
});
|
|
});
|
|
|
|
it("dispatches assigned todo work with no prior run as a normal assignment wake", async () => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(1);
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakeups).toHaveLength(1);
|
|
expect(wakeups[0]).toMatchObject({
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: expect.objectContaining({
|
|
issueId,
|
|
mutation: "assigned_todo_liveness_dispatch",
|
|
}),
|
|
});
|
|
expect(wakeups[0]?.payload as Record<string, unknown>).not.toHaveProperty(
|
|
"modelProfile",
|
|
);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]?.retryOfRunId).toBeNull();
|
|
expect(runs[0]?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_assigned",
|
|
source: "issue.assigned_todo_liveness_dispatch",
|
|
});
|
|
expect(
|
|
runs[0]?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
expect(
|
|
(runs[0]?.contextSnapshot as Record<string, unknown>)?.retryReason,
|
|
).toBeUndefined();
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("todo");
|
|
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
await expect(sourceBlockerIssueIds(companyId, issueId)).resolves.toEqual(
|
|
[],
|
|
);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(0);
|
|
|
|
if (runs[0]?.id) {
|
|
await waitForRunToSettle(heartbeat, runs[0].id);
|
|
}
|
|
});
|
|
|
|
it("leaves the onboarding first task idle until the user comments", async () => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
await db
|
|
.update(issues)
|
|
.set({ originKind: "onboarding_first_task" })
|
|
.where(eq(issues.id, issueId));
|
|
// The server-seeded greeting is agent-authored; it must not count as the
|
|
// user having typed.
|
|
await db.insert(issueComments).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
authorType: "agent",
|
|
body: "Welcome to Paperclip!",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.onboardingFirstTaskExempted).toBe(1);
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.issueIds).toEqual([]);
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakeups).toHaveLength(0);
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(0);
|
|
});
|
|
|
|
it("keeps the onboarding first task idle while the seeded opening card is unanswered", async () => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
await db
|
|
.update(issues)
|
|
.set({ originKind: "onboarding_first_task" })
|
|
.where(eq(issues.id, issueId));
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
issueId,
|
|
kind: "ask_user_questions",
|
|
status: "pending",
|
|
continuationPolicy: "wake_assignee",
|
|
createdByAgentId: agentId,
|
|
payload: {
|
|
version: 1,
|
|
questions: [
|
|
{
|
|
id: "first-task-opening",
|
|
prompt: "What would you like to do?",
|
|
selectionMode: "single",
|
|
options: [
|
|
{ id: "interview", label: "Interview me" },
|
|
{ id: "task", label: "I have a task in mind", freeText: true },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
// A pending wake-policy card is a durable wait path of its own, so the
|
|
// sweep skips the issue before it even reaches the onboarding exemption.
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.issueIds).toEqual([]);
|
|
expect(result.skipped).toBe(1);
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(0);
|
|
});
|
|
|
|
it("dispatches the onboarding first task once the user answered the opening card", async () => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
await db
|
|
.update(issues)
|
|
.set({ originKind: "onboarding_first_task" })
|
|
.where(eq(issues.id, issueId));
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
issueId,
|
|
kind: "ask_user_questions",
|
|
status: "answered",
|
|
continuationPolicy: "wake_assignee",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "local-board",
|
|
// Older than the accepted-interaction grace window: the answer-time
|
|
// wake has had time to appear, so a missing run is a lost continuation.
|
|
resolvedAt: new Date(Date.now() - 3 * 60_000),
|
|
payload: {
|
|
version: 1,
|
|
questions: [
|
|
{
|
|
id: "first-task-opening",
|
|
prompt: "What would you like to do?",
|
|
selectionMode: "single",
|
|
options: [
|
|
{ id: "interview", label: "Interview me" },
|
|
{ id: "task", label: "I have a task in mind", freeText: true },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
result: {
|
|
version: 1,
|
|
answers: [
|
|
{ questionId: "first-task-opening", optionIds: ["interview"] },
|
|
],
|
|
},
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
// The answered wake-policy card with no run after it is a lost
|
|
// continuation: the sweep re-queues the assignee rather than leaving the
|
|
// first task idle. The onboarding exemption must not swallow it.
|
|
expect(result.onboardingFirstTaskExempted).toBe(0);
|
|
expect(result.assignmentDispatched + result.continuationRequeued).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
if (runs[0]?.id) {
|
|
await waitForRunToSettle(heartbeat, runs[0].id);
|
|
}
|
|
});
|
|
|
|
it("dispatches the onboarding first task once a user comment exists", async () => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
await db
|
|
.update(issues)
|
|
.set({ originKind: "onboarding_first_task" })
|
|
.where(eq(issues.id, issueId));
|
|
await db.insert(issueComments).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
issueId,
|
|
authorUserId: "local-board",
|
|
authorType: "user",
|
|
body: "Let's start with a landing page.",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.onboardingFirstTaskExempted).toBe(0);
|
|
expect(result.assignmentDispatched).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
if (runs[0]?.id) {
|
|
await waitForRunToSettle(heartbeat, runs[0].id);
|
|
}
|
|
});
|
|
|
|
it("does not duplicate initial assigned todo dispatch when a queued wake already exists", async () => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
await db.insert(agentWakeupRequests).values({
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId, mutation: "assigned_todo_liveness_dispatch" },
|
|
status: "queued",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBe(1);
|
|
expect(result.issueIds).toEqual([]);
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakeups).toHaveLength(1);
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(0);
|
|
});
|
|
|
|
it.each(["preparing", "issued", "processing", "failed"])(
|
|
"does not bypass a %s durable inbound-chat wake intent with generic assignment recovery",
|
|
async (status) => {
|
|
const { companyId, agentId, issueId } =
|
|
await seedAssignedTodoNoRunFixture();
|
|
const { endpointId, conversationId } = await bindChatConversation({
|
|
agentId,
|
|
companyId,
|
|
issueId,
|
|
state: "active",
|
|
});
|
|
const actionId = randomUUID();
|
|
const [originalAction] = await db
|
|
.insert(chatActions)
|
|
.values({
|
|
id: actionId,
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
kind: "inbound_wakeup",
|
|
providerActionId: `inbound_wakeup:${randomUUID()}`,
|
|
status,
|
|
payload: {
|
|
version: 1,
|
|
issueId,
|
|
agentId,
|
|
commentId: randomUUID(),
|
|
sessionGeneration: 1,
|
|
requestedByActorType: "system",
|
|
requestedByActorId: randomUUID(),
|
|
},
|
|
})
|
|
.returning();
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result).toMatchObject({
|
|
assignmentDispatched: 0,
|
|
dispatchRequeued: 0,
|
|
continuationRequeued: 0,
|
|
escalated: 0,
|
|
skipped: 0,
|
|
issueIds: [],
|
|
});
|
|
// An explicit Board request must get an actionable conflict, not a
|
|
// silent skipped response or fresh authority for the denied input.
|
|
await expect(
|
|
heartbeat.wakeup(agentId, {
|
|
source: "on_demand",
|
|
triggerDetail: "manual",
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
payload: { issueId },
|
|
contextSnapshot: {
|
|
issueId,
|
|
triggeredBy: "board",
|
|
source: "issue.manual",
|
|
},
|
|
}),
|
|
).rejects.toMatchObject({
|
|
status: 409,
|
|
details: { code: "chat_inbound_wakeup_unadmitted", issueId },
|
|
});
|
|
expect(
|
|
await db
|
|
.select({ id: agentWakeupRequests.id })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, companyId)),
|
|
).toEqual([]);
|
|
expect(
|
|
await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, companyId)),
|
|
).toEqual([]);
|
|
expect(
|
|
await db.select().from(chatActions).where(eq(chatActions.id, actionId)),
|
|
).toEqual([originalAction]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it("creates a board recovery action for budget-blocked assigned work and continues the sweep", async () => {
|
|
const blocked = await seedAssignedTodoNoRunFixture();
|
|
const unblocked = await seedAssignedTodoNoRunFixture();
|
|
await db.insert(budgetPolicies).values({
|
|
companyId: blocked.companyId,
|
|
scopeType: "agent",
|
|
scopeId: blocked.agentId,
|
|
metric: "billed_cents",
|
|
windowKind: "calendar_month_utc",
|
|
amount: 1,
|
|
hardStopEnabled: true,
|
|
isActive: true,
|
|
});
|
|
await db.insert(costEvents).values({
|
|
companyId: blocked.companyId,
|
|
agentId: blocked.agentId,
|
|
issueId: blocked.issueId,
|
|
provider: "test",
|
|
biller: "test",
|
|
billingType: "tokens",
|
|
model: "test-model",
|
|
costCents: 1,
|
|
occurredAt: new Date(),
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(1);
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.skipped).toBe(0);
|
|
expect([...result.issueIds].sort()).toEqual(
|
|
[blocked.issueId, unblocked.issueId].sort(),
|
|
);
|
|
|
|
const blockedWakeups = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.agentId, blocked.agentId));
|
|
expect(blockedWakeups).toHaveLength(0);
|
|
const blockedRuns = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, blocked.agentId));
|
|
expect(blockedRuns).toHaveLength(0);
|
|
|
|
const blockedIssue = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, blocked.issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(blockedIssue).toMatchObject({
|
|
status: "blocked",
|
|
assigneeAgentId: blocked.agentId,
|
|
});
|
|
const blockedAction = await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, blocked.issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(blockedAction).toMatchObject({
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
returnOwnerAgentId: blocked.agentId,
|
|
evidence: expect.objectContaining({
|
|
routingPolicy: "board_escalation_no_takeover_v1",
|
|
}),
|
|
});
|
|
|
|
const unblockedWakeups = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.agentId, unblocked.agentId));
|
|
expect(unblockedWakeups).toHaveLength(1);
|
|
expect(unblockedWakeups[0]).toMatchObject({
|
|
reason: "issue_assigned",
|
|
payload: expect.objectContaining({
|
|
issueId: unblocked.issueId,
|
|
mutation: "assigned_todo_liveness_dispatch",
|
|
}),
|
|
});
|
|
expect(
|
|
unblockedWakeups[0]?.payload as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
const unblockedRuns = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, unblocked.agentId));
|
|
expect(unblockedRuns).toHaveLength(1);
|
|
if (unblockedRuns[0]?.id) {
|
|
await waitForRunToSettle(heartbeat, unblockedRuns[0].id);
|
|
}
|
|
});
|
|
|
|
it("routes paused assigned work to the board without waking available executives", async () => {
|
|
const { companyId, agentId, issueId } = await seedAssignedTodoNoRunFixture({
|
|
agentStatus: "paused",
|
|
});
|
|
const executiveIds = [randomUUID(), randomUUID()];
|
|
await db.insert(agents).values(
|
|
executiveIds.map((id, index) => ({
|
|
id,
|
|
companyId,
|
|
name: index === 0 ? "Available CTO" : "Available CEO",
|
|
role: index === 0 ? "cto" : "ceo",
|
|
status: "idle" as const,
|
|
adapterType: "codex_local" as const,
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
})),
|
|
);
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.skipped).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue).toMatchObject({
|
|
status: "blocked",
|
|
assigneeAgentId: agentId,
|
|
});
|
|
const action = await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(action).toMatchObject({
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
returnOwnerAgentId: agentId,
|
|
wakePolicy: expect.objectContaining({ type: "board_escalation" }),
|
|
});
|
|
const runs = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(inArray(heartbeatRuns.agentId, [agentId, ...executiveIds]));
|
|
expect(runs).toHaveLength(0);
|
|
const wakes = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(inArray(agentWakeupRequests.agentId, executiveIds));
|
|
expect(wakes).toHaveLength(0);
|
|
});
|
|
|
|
it("re-enqueues assigned todo work when the last issue run died and no wake remains", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "failed",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.dispatchRequeued).toBe(1);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(retryRun?.id).toBeTruthy();
|
|
expect(
|
|
(retryRun?.contextSnapshot as Record<string, unknown>)?.retryReason,
|
|
).toBe("transient_failure");
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
});
|
|
|
|
it("re-enqueues handed-back todo work when its resolving run succeeded but the wake was lost", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "succeeded",
|
|
});
|
|
const resolvedAt = new Date("2026-03-19T00:04:00.000Z");
|
|
await db.insert(issueRecoveryActions).values({
|
|
companyId,
|
|
sourceIssueId: issueId,
|
|
kind: "stranded_assigned_issue",
|
|
status: "resolved",
|
|
ownerType: "agent",
|
|
ownerAgentId: agentId,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
cause: "stranded_assigned_issue",
|
|
fingerprint: `handed-back:${issueId}`,
|
|
nextAction: "Resume source work",
|
|
outcome: "handed_back",
|
|
resolutionNote: "Returned source work to the original owner",
|
|
resolvedAt,
|
|
createdAt: new Date("2026-03-19T00:01:00.000Z"),
|
|
updatedAt: resolvedAt,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_disposition_repair",
|
|
retryReason: "issue_disposition_repair",
|
|
source: "issue.deliberate_wait_disposition_repair",
|
|
retryOfRunId: runId,
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
if (retryRun) {
|
|
await waitForRunToSettle(heartbeat, retryRun.id);
|
|
}
|
|
});
|
|
|
|
it("does not let an active chat conversation suppress stranded execution-review participant recovery", async () => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId, stageId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const finishedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "succeeded",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "execution_review_requested",
|
|
source: "chat:slack",
|
|
},
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
status: "completed",
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await bindChatConversation({
|
|
agentId,
|
|
companyId,
|
|
issueId,
|
|
state: "active",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.reviewParticipantRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(["queued", "running"]).toContain(retryRun?.status);
|
|
expect(retryRun).toMatchObject({
|
|
retryOfRunId: runId,
|
|
});
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "execution_review_participant_recovery",
|
|
retryReason: "execution_review_participant_recovery",
|
|
source: "issue.execution_review_recovery",
|
|
retryOfRunId: runId,
|
|
currentStageId: stageId,
|
|
currentStageType: "review",
|
|
reviewRecoveryInstruction: expect.stringContaining(
|
|
"Submit the review decision now",
|
|
),
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
});
|
|
|
|
it("escalates an execution-review participant whose interrupted run has spent its transient retry budget", async () => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const finishedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
errorCode: "server_shutdown_interrupted",
|
|
error: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure",
|
|
resultJson: {
|
|
stopReason: "interrupted",
|
|
conversationContinuation: "continue_conversation_v1",
|
|
},
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "transient_failure_retry",
|
|
executionRetryAccounting: spentRestartRetryAccounting(),
|
|
},
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ status: "cancelled", finishedAt, updatedAt: finishedAt })
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.reviewParticipantRequeued).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
const successors = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId));
|
|
expect(successors).toHaveLength(0);
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue?.status).toBe("blocked");
|
|
const recoveryActions = await selectRecoveryActionsForIssue(issueId);
|
|
expect(recoveryActions).toHaveLength(1);
|
|
expect(recoveryActions[0]).toMatchObject({
|
|
companyId,
|
|
status: "active",
|
|
cause: "execution_review_participant_recovery",
|
|
previousOwnerAgentId: agentId,
|
|
});
|
|
const again = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(again.escalated).toBe(0);
|
|
});
|
|
|
|
it("does not block an issue whose review participant spent its retry budget while another agent is still working it", async () => {
|
|
// `blocked` is issue-wide. The exhausted participant is a dead end for
|
|
// the review stage, but another agent with a live run on the same issue
|
|
// must not be blocked under it: the escalation re-reads the live path
|
|
// for ANY agent and stands down.
|
|
const { companyId, issueId, runId, wakeupRequestId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const finishedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "interrupted",
|
|
errorCode: "server_shutdown_interrupted",
|
|
error: "Interrupted by graceful server shutdown (SIGTERM)",
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: "transient_failure",
|
|
resultJson: {
|
|
stopReason: "interrupted",
|
|
conversationContinuation: "continue_conversation_v1",
|
|
},
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "transient_failure_retry",
|
|
executionRetryAccounting: spentRestartRetryAccounting(),
|
|
},
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ status: "cancelled", finishedAt, updatedAt: finishedAt })
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
const otherAgentId = randomUUID();
|
|
await db.insert(agents).values(recoveryAgentRow(otherAgentId, companyId, "CodexImplementor", "engineer", "running"));
|
|
await db.insert(heartbeatRuns).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
agentId: otherAgentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "running",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
},
|
|
startedAt: new Date("2026-03-19T00:10:00.000Z"),
|
|
createdAt: new Date(Date.now() + 1_000),
|
|
updatedAt: new Date("2026-03-19T00:10:00.000Z"),
|
|
});
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.reviewParticipantRequeued).toBe(0);
|
|
const sourceIssue = await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(sourceIssue?.status).toBe("in_review");
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toEqual([]);
|
|
});
|
|
|
|
it("re-enqueues a stranded execution-review participant when another agent has the latest issue run", async () => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId, stageId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const otherAgentId = randomUUID();
|
|
const otherRunId = randomUUID();
|
|
const finishedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "succeeded",
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
status: "completed",
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
|
|
await db.insert(agents).values(recoveryAgentRow(otherAgentId, companyId, "CodexImplementor", "engineer", "idle"));
|
|
await db.insert(heartbeatRuns).values({
|
|
id: otherRunId,
|
|
companyId,
|
|
agentId: otherAgentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "succeeded",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
},
|
|
startedAt: new Date("2026-03-19T00:10:00.000Z"),
|
|
finishedAt: new Date("2026-03-19T00:15:00.000Z"),
|
|
createdAt: new Date(Date.now() + 1_000),
|
|
updatedAt: new Date("2026-03-19T00:15:00.000Z"),
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.reviewParticipantRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const retryRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId))
|
|
.then(
|
|
(runs) =>
|
|
runs.find(
|
|
(row) =>
|
|
row.id !== runId &&
|
|
(row.contextSnapshot as Record<string, unknown> | null)
|
|
?.retryReason === "execution_review_participant_recovery",
|
|
) ?? null,
|
|
);
|
|
expect(retryRun).toMatchObject({
|
|
retryOfRunId: runId,
|
|
});
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
currentStageId: stageId,
|
|
currentStageType: "review",
|
|
});
|
|
});
|
|
|
|
it("re-enqueues a stranded execution-review participant when another agent has a queued issue wake", async () => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const otherAgentId = randomUUID();
|
|
const otherWakeId = randomUUID();
|
|
const finishedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "succeeded",
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
status: "completed",
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
|
|
await db.insert(agents).values(recoveryAgentRow(otherAgentId, companyId, "CodexImplementor", "engineer", "idle"));
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: otherWakeId,
|
|
companyId,
|
|
agentId: otherAgentId,
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_commented",
|
|
payload: { issueId },
|
|
status: "queued",
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.reviewParticipantRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(
|
|
wakeups.some(
|
|
(wakeup) =>
|
|
wakeup.reason === "execution_review_participant_recovery" &&
|
|
wakeup.status !== "skipped",
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("retries a pending execution-review participant when another agent has an active issue run", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const otherAgentId = randomUUID();
|
|
const otherRunId = randomUUID();
|
|
await db.insert(agents).values(recoveryAgentRow(otherAgentId, companyId, "CodexImplementor", "engineer", "idle"));
|
|
await db.insert(heartbeatRuns).values({
|
|
id: otherRunId,
|
|
companyId,
|
|
agentId: otherAgentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "running",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
},
|
|
startedAt: new Date("2026-03-19T00:01:00.000Z"),
|
|
updatedAt: new Date("2026-03-19T00:01:00.000Z"),
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
const reviewRecoveryRun = await waitForValue(async () => {
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
return (
|
|
runs.find(
|
|
(row) =>
|
|
(row.contextSnapshot as Record<string, unknown> | null)
|
|
?.retryReason === "execution_review_participant_recovery",
|
|
) ?? null
|
|
);
|
|
}, 8_000);
|
|
|
|
expect(reviewRecoveryRun).toMatchObject({
|
|
companyId,
|
|
agentId,
|
|
retryOfRunId: runId,
|
|
});
|
|
});
|
|
|
|
it("does not immediately recover a generic on-demand run used for an in-review agent API update", async () => {
|
|
const { agentId, issueId, runId } = await seedInReviewParticipantRunFixture(
|
|
{
|
|
wakeReason: "manual",
|
|
},
|
|
);
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
const settledRun = await waitForRunToSettle(heartbeat, runId, 8_000);
|
|
expect(settledRun?.status).toBe("succeeded");
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(
|
|
runs.some(
|
|
(row) =>
|
|
(row.contextSnapshot as Record<string, unknown> | null)
|
|
?.retryReason === "execution_review_participant_recovery",
|
|
),
|
|
).toBe(false);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_review");
|
|
expect(issue?.assigneeAgentId).toBe(agentId);
|
|
});
|
|
|
|
it("retries a pending execution-review participant once before blocking with a recovery action", async () => {
|
|
const { companyId, agentId, issueId, runId, stageId } =
|
|
await seedInReviewParticipantRunFixture();
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.resumeQueuedRuns();
|
|
const reviewRecoveryRun = await waitForValue(async () => {
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
return (
|
|
runs.find(
|
|
(row) =>
|
|
(row.contextSnapshot as Record<string, unknown> | null)
|
|
?.retryReason === "execution_review_participant_recovery" &&
|
|
row.status !== "queued" &&
|
|
row.status !== "running",
|
|
) ?? null
|
|
);
|
|
}, 8_000);
|
|
expect(reviewRecoveryRun).toBeTruthy();
|
|
expect(reviewRecoveryRun).toMatchObject({
|
|
companyId,
|
|
agentId,
|
|
retryOfRunId: runId,
|
|
status: "succeeded",
|
|
});
|
|
expect(reviewRecoveryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "execution_review_participant_recovery",
|
|
retryReason: "execution_review_participant_recovery",
|
|
source: "issue.execution_review_recovery",
|
|
retryOfRunId: runId,
|
|
currentStageId: stageId,
|
|
currentStageType: "review",
|
|
reviewRecoveryInstruction: expect.stringContaining(
|
|
"Submit the review decision now",
|
|
),
|
|
});
|
|
expect(
|
|
reviewRecoveryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
|
|
const sourceIssue = await waitForValue(async () => {
|
|
const row = await selectRecoveryIssueById(issueId);
|
|
return row?.status === "blocked" ? row : null;
|
|
}, 8_000);
|
|
expect(sourceIssue).toMatchObject({
|
|
status: "blocked",
|
|
assigneeAgentId: agentId,
|
|
executionRunId: null,
|
|
});
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId: reviewRecoveryRun!.id,
|
|
previousStatus: "in_review",
|
|
retryReason: "execution_review_participant_recovery",
|
|
cause: "execution_review_participant_recovery",
|
|
});
|
|
expect(recoveryAction.evidence).toMatchObject({
|
|
latestRunId: reviewRecoveryRun?.id,
|
|
latestRunStatus: "succeeded",
|
|
latestRunErrorCode: null,
|
|
recoveryCause: "execution_review_participant_recovery",
|
|
});
|
|
|
|
// The source issue flips to "blocked" before the recovery service posts
|
|
// its escalation comment and writes the activity-log event, so a read
|
|
// right after the status check can race an in-flight write. Poll for
|
|
// each row instead of reading once.
|
|
const recoveryComment = await waitForValue(async () => {
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
return (
|
|
comments.find(
|
|
(comment) =>
|
|
comment.body.includes(
|
|
"did not finish the review, even after Paperclip asked again",
|
|
) &&
|
|
noticeMetadataReferencesRecoveryAction(
|
|
comment.metadata,
|
|
recoveryAction.id,
|
|
),
|
|
) ?? null
|
|
);
|
|
});
|
|
expect(recoveryComment).toBeTruthy();
|
|
|
|
const recoveryActivityEvent = await waitForValue(async () => {
|
|
const activity = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.entityId, issueId));
|
|
return (
|
|
activity.find(
|
|
(event) =>
|
|
(event.details as Record<string, unknown> | null)?.source ===
|
|
"recovery.reconcile_execution_review_participant",
|
|
) ?? null
|
|
);
|
|
});
|
|
expect(recoveryActivityEvent).toBeTruthy();
|
|
});
|
|
|
|
it("blocks failed execution-review recovery under the reviewer when the source assignee differs", async () => {
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId, stageId } =
|
|
await seedInReviewParticipantRunFixture({
|
|
wakeReason: "execution_review_participant_recovery",
|
|
retryReason: "execution_review_participant_recovery",
|
|
});
|
|
const sourceAssigneeAgentId = randomUUID();
|
|
const finishedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
|
|
await db.insert(agents).values(recoveryAgentRow(sourceAssigneeAgentId, companyId, "CodexImplementor", "engineer", "idle"));
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
assigneeAgentId: sourceAssigneeAgentId,
|
|
executionState: {
|
|
status: "pending",
|
|
currentStageId: stageId,
|
|
currentStageIndex: 0,
|
|
currentStageType: "review",
|
|
currentParticipant: { type: "agent", agentId, userId: null },
|
|
returnAssignee: {
|
|
type: "agent",
|
|
agentId: sourceAssigneeAgentId,
|
|
userId: null,
|
|
},
|
|
reviewRequest: null,
|
|
completedStageIds: [],
|
|
lastDecisionId: null,
|
|
lastDecisionOutcome: null,
|
|
},
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "failed",
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
errorCode: "adapter_failed",
|
|
error: "review recovery failed before submitting a decision",
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
status: "failed",
|
|
claimedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
error: "review recovery failed before submitting a decision",
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.reviewParticipantRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const [sourceIssue] = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId));
|
|
expect(sourceIssue).toMatchObject({
|
|
status: "in_review",
|
|
assigneeAgentId: sourceAssigneeAgentId,
|
|
});
|
|
const [recoveryAction] = await selectRecoveryActionsForIssue(issueId);
|
|
expect(recoveryAction).toMatchObject({
|
|
ownerType: "board",
|
|
returnOwnerAgentId: sourceAssigneeAgentId,
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
evidence: {
|
|
runId,
|
|
reviewParticipantAgentId: agentId,
|
|
originalFailureCode: "adapter_failed",
|
|
},
|
|
});
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, runId)),
|
|
).toHaveLength(0);
|
|
});
|
|
|
|
it.each([
|
|
["failed", "adapter_failed"],
|
|
["failed", "process_lost"],
|
|
["timed_out", "adapter_timed_out"],
|
|
] as const)(
|
|
"re-enqueues stranded in-progress work after a %s/%s run before escalating",
|
|
async (runStatus, runErrorCode) => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus,
|
|
runErrorCode,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(retryRun?.id).toBeTruthy();
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown> | undefined,
|
|
).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
retryReason: "transient_failure",
|
|
retryOfRunId: runId,
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
|
|
const recoveries = await selectStrandedRecoveryIssuesForSource(companyId, issueId);
|
|
expect(recoveries).toHaveLength(0);
|
|
|
|
if (retryRun?.id) {
|
|
await waitForRunToSettle(heartbeat, retryRun.id);
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(["wake_assignee", "wake_assignee_on_accept"] as const)(
|
|
"skips stranded recovery when a pending %s interaction exists",
|
|
async (continuationPolicy) => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "pending",
|
|
continuationPolicy,
|
|
createdByAgentId: agentId,
|
|
payload: { version: 1, prompt: "Approve the plan?" },
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBeGreaterThanOrEqual(1);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_progress");
|
|
},
|
|
);
|
|
|
|
|
|
async function seedResolvedInteractionRecoveryFixture(input: {
|
|
title: string;
|
|
kind?: "request_confirmation" | "ask_user_questions";
|
|
issueStatus?: "in_review" | "in_progress";
|
|
agentName?: string;
|
|
}) {
|
|
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), interactionId = randomUUID();
|
|
const resolvedAt = new Date("2026-03-19T00:05:00.000Z");
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
await db.insert(agents).values({
|
|
id: agentId, companyId, name: input.agentName ?? "CodexCoder", role: "engineer", status: "idle", adapterType: "codex_local", adapterConfig: {},
|
|
runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } }, permissions: {},
|
|
});
|
|
await db.insert(issues).values({
|
|
id: issueId, companyId, title: input.title, status: input.issueStatus ?? "in_review", priority: "medium", assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user", issueNumber: 1, identifier: `${issuePrefix}-1`,
|
|
});
|
|
const kind = input.kind ?? "request_confirmation";
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId, companyId, issueId, kind, status: kind === "ask_user_questions" ? "answered" : "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept", createdByAgentId: agentId, resolvedByUserId: "responsible-user", resolvedAt, updatedAt: resolvedAt,
|
|
payload: kind === "ask_user_questions" ? { version: 1, questions: [{
|
|
id: "format", prompt: "Choose a format", selectionMode: "single", required: true, options: [{ id: "markdown", label: "Markdown" }],
|
|
}] } : { version: 1, prompt: "Approve the plan?" },
|
|
result: kind === "ask_user_questions" ? { version: 1, answers: [{ questionId: "format", optionIds: ["markdown"] }] } : { version: 1, outcome: "accepted" },
|
|
});
|
|
return { companyId, agentId, issueId, interactionId, resolvedAt };
|
|
}
|
|
|
|
it("recovers an answered question with its interaction-specific continuation context", async () => {
|
|
const { companyId, agentId, issueId, interactionId, resolvedAt } =
|
|
await seedResolvedInteractionRecoveryFixture({ title: "Answered question never resumed", kind: "ask_user_questions", issueStatus: "in_progress", agentName: "OpenCodeCoder" });
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(1);
|
|
const run = await db
|
|
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(run?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
interactionId,
|
|
interactionKind: "ask_user_questions",
|
|
interactionStatus: "answered",
|
|
interactionContinuationPolicy: "wake_assignee_on_accept",
|
|
source: "issue.interaction_continuation_recovery",
|
|
});
|
|
});
|
|
|
|
it("does not requeue an answered interaction after native recovery is board-owned", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "native_session_retry_exhausted",
|
|
runError: "native session recovery exhausted",
|
|
});
|
|
const interactionId = randomUUID();
|
|
const resolvedAt = new Date("2026-03-19T00:04:00.000Z");
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_review", checkoutRunId: null })
|
|
.where(eq(issues.id, issueId));
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "ask_user_questions",
|
|
status: "answered",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt,
|
|
updatedAt: resolvedAt,
|
|
payload: {
|
|
version: 1,
|
|
questions: [
|
|
{
|
|
id: "format",
|
|
prompt: "Choose a format",
|
|
selectionMode: "single",
|
|
required: true,
|
|
options: [{ id: "markdown", label: "Markdown" }],
|
|
},
|
|
],
|
|
},
|
|
result: {
|
|
version: 1,
|
|
answers: [{ questionId: "format", optionIds: ["markdown"] }],
|
|
},
|
|
});
|
|
const [action] = await db
|
|
.insert(issueRecoveryActions)
|
|
.values({
|
|
companyId,
|
|
sourceIssueId: issueId,
|
|
kind: "active_run_watchdog",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
returnOwnerAgentId: agentId,
|
|
cause: "native_session_retry_exhausted",
|
|
fingerprint: `native-exhausted:${runId}`,
|
|
evidence: { runId, coordinatorAttempt: 3 },
|
|
nextAction: "Inspect the trace and explicitly choose a retry.",
|
|
wakePolicy: null,
|
|
attemptCount: 3,
|
|
maxAttempts: 3,
|
|
})
|
|
.returning();
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
const [issue, runs, persistedAction] = await Promise.all([
|
|
selectRecoveryIssueById(issueId),
|
|
selectRecoveryRunsByAgent(agentId),
|
|
db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.id, action!.id))
|
|
.then((rows) => rows[0] ?? null),
|
|
]);
|
|
expect(issue?.status).toBe("in_review");
|
|
expect(runs).toHaveLength(1);
|
|
expect(persistedAction).toMatchObject({
|
|
status: "active",
|
|
ownerType: "board",
|
|
});
|
|
});
|
|
|
|
it("counts five historical review-park cancellations against the upgraded disposition-repair ceiling", async () => {
|
|
const { companyId, agentId, issueId, interactionId, resolvedAt } =
|
|
await seedResolvedInteractionRecoveryFixture({ title: "Accepted plan cancellation loop" });
|
|
for (let attempt = 1; attempt <= 5; attempt += 1) {
|
|
const finishedAt = new Date(resolvedAt.getTime() + attempt * 60_000);
|
|
await db.insert(heartbeatRuns).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "cancelled",
|
|
errorCode: "issue_continuation_waiting_on_review",
|
|
error: "Continuation summary still says to wait for review",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_continuation_needed",
|
|
retryReason: "issue_continuation_needed",
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionResolvedAt: resolvedAt.toISOString(),
|
|
},
|
|
createdAt: finishedAt,
|
|
startedAt: finishedAt,
|
|
finishedAt,
|
|
updatedAt: finishedAt,
|
|
});
|
|
}
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.waitingOnReviewResolved).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toContain(issueId);
|
|
|
|
const [issue, continuationRuns, comments] = await Promise.all([
|
|
selectRecoveryIssueById(issueId),
|
|
db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}`,
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'retryReason' = 'issue_continuation_needed'`,
|
|
),
|
|
),
|
|
db
|
|
.select({ body: issueComments.body })
|
|
.from(issueComments)
|
|
.where(eq(issueComments.issueId, issueId)),
|
|
]);
|
|
expect(issue?.status).toBe("blocked");
|
|
expect(continuationRuns).toHaveLength(5);
|
|
expect(
|
|
comments.some((comment) => comment.body.includes("Attempts: 5/5")),
|
|
).toBe(true);
|
|
const action = await selectRecoveryActionForIssue(companyId, issueId);
|
|
expect(action).toMatchObject({
|
|
kind: "deliberate_wait_without_target",
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
previousOwnerAgentId: agentId,
|
|
returnOwnerAgentId: agentId,
|
|
attemptCount: 5,
|
|
maxAttempts: null,
|
|
resolutionNote: "unchanged_source_state_exhausted",
|
|
});
|
|
expect(action?.evidence).toMatchObject({
|
|
sourceAttemptCount: 5,
|
|
sourceMaxAttempts: 5,
|
|
});
|
|
});
|
|
|
|
it("skips accepted interaction recovery after its continuation succeeds", async () => {
|
|
const { companyId, agentId, issueId, interactionId, resolvedAt } =
|
|
await seedResolvedInteractionRecoveryFixture({ title: "Accepted plan already resumed" });
|
|
const succeededAt = new Date("2026-03-19T00:06:00.000Z");
|
|
await db.insert(heartbeatRuns).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "succeeded",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_continuation_needed",
|
|
retryReason: "issue_continuation_needed",
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionResolvedAt: resolvedAt.toISOString(),
|
|
},
|
|
createdAt: succeededAt,
|
|
startedAt: succeededAt,
|
|
finishedAt: succeededAt,
|
|
updatedAt: succeededAt,
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBeGreaterThanOrEqual(1);
|
|
const runs = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId));
|
|
expect(runs).toHaveLength(1);
|
|
});
|
|
|
|
// BUG-03 (onboarding staging, ONB-1): the sweep read the plan approval
|
|
// ~500ms after it resolved, before its accept-time run existed, and queued
|
|
// a second continuation for the same approval. That redundant wake waited
|
|
// behind later runs for ~37 minutes and showed as an immutable
|
|
// "Accepted: <plan>" item in the composer queue.
|
|
async function seedJustAcceptedPlanApproval(title: string) {
|
|
const fixture = await seedResolvedInteractionRecoveryFixture({ title });
|
|
const resolvedAt = new Date(Date.now() - 500);
|
|
await db.update(issueThreadInteractions)
|
|
.set({ continuationPolicy: "wake_assignee", resolvedAt, updatedAt: resolvedAt })
|
|
.where(eq(issueThreadInteractions.id, fixture.interactionId));
|
|
return { ...fixture, resolvedAt };
|
|
}
|
|
|
|
async function interactionRecoveryRuns(agentId: string) {
|
|
return db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(and(
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
sql`${heartbeatRuns.contextSnapshot} ->> 'source' = 'issue.interaction_continuation_recovery'`,
|
|
));
|
|
}
|
|
|
|
it("does not race a just-accepted plan approval before its accept-time wake is visible", async () => {
|
|
const { agentId, interactionId, resolvedAt } = await seedJustAcceptedPlanApproval("Plan approved moments ago");
|
|
const deadlines: number[] = [];
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues({
|
|
onDeferredDeadline: (at) => deadlines.push(at),
|
|
});
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(await interactionRecoveryRuns(agentId)).toEqual([]);
|
|
// The skip registers a re-check, so a lost accept-time wake still recovers.
|
|
expect(deadlines).toContain(resolvedAt.getTime() + 2 * 60_000);
|
|
|
|
// After the grace window, with no other write, the next sweep requeues it.
|
|
const expiredAt = new Date(Date.now() - 2 * 60_000 - 1_000);
|
|
await db.update(issueThreadInteractions)
|
|
.set({ resolvedAt: expiredAt, updatedAt: expiredAt })
|
|
.where(eq(issueThreadInteractions.id, interactionId));
|
|
const later = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(later.continuationRequeued).toBe(1);
|
|
expect(await interactionRecoveryRuns(agentId)).toHaveLength(1);
|
|
});
|
|
|
|
it("does not requeue an accepted plan approval whose accept-time wake is deferred behind another run", async () => {
|
|
const { companyId, agentId, issueId, interactionId } =
|
|
await seedResolvedInteractionRecoveryFixture({ title: "Plan approval waiting for the active run" });
|
|
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, mutation: "interaction", interactionId, interactionStatus: "accepted" },
|
|
});
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(await interactionRecoveryRuns(agentId)).toEqual([]);
|
|
const wakes = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests)
|
|
.where(and(eq(agentWakeupRequests.agentId, agentId), eq(agentWakeupRequests.companyId, companyId)));
|
|
expect(wakes).toEqual([{ status: "deferred_issue_execution" }]);
|
|
});
|
|
|
|
it("requeues accepted interaction continuations even when a later successful run is unrelated", async () => {
|
|
const { companyId, agentId, issueId, interactionId, resolvedAt } =
|
|
await seedResolvedInteractionRecoveryFixture({ title: "Accepted plan masked by unrelated run" });
|
|
const unrelatedRunAt = new Date("2026-03-19T00:06:00.000Z");
|
|
await db.insert(heartbeatRuns).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
status: "succeeded",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_assigned",
|
|
source: "unrelated_followup",
|
|
},
|
|
startedAt: unrelatedRunAt,
|
|
finishedAt: unrelatedRunAt,
|
|
createdAt: unrelatedRunAt,
|
|
updatedAt: unrelatedRunAt,
|
|
});
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await db
|
|
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId));
|
|
const recoveryRun = runs.find(
|
|
(row) =>
|
|
(row.contextSnapshot as Record<string, unknown> | null)?.source ===
|
|
"issue.interaction_continuation_recovery",
|
|
);
|
|
expect(recoveryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
interactionId,
|
|
interactionStatus: "accepted",
|
|
source: "issue.interaction_continuation_recovery",
|
|
});
|
|
});
|
|
|
|
// Scenario 5: enqueue-failure at accept time is no longer a silent permanent
|
|
// stall. When the accept-time continuation wake is dropped (routes/issues.ts fire-and-forget
|
|
// enqueue swallowed the error), the issue is left in_review with an accepted interaction but
|
|
// *no* wake request and *no* run at all. Pre-P1 the recovery sweep skipped in_review issues
|
|
// lacking an execution policy, so this limbo persisted forever. The sweep now requeues it.
|
|
it("recovers a plan approval whose accept-time continuation wake enqueue was silently dropped", async () => {
|
|
const { companyId, agentId, issueId, interactionId, resolvedAt } =
|
|
await seedResolvedInteractionRecoveryFixture({ title: "Approved plan whose wake enqueue was dropped" });
|
|
|
|
// Precondition of the silent-enqueue-drop bug: the accept produced no wake and no run.
|
|
const priorWakeups = await db
|
|
.select({ id: agentWakeupRequests.id })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, companyId));
|
|
expect(priorWakeups).toHaveLength(0);
|
|
const priorRuns = await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, companyId));
|
|
expect(priorRuns).toHaveLength(0);
|
|
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const run = await db
|
|
.select({
|
|
agentId: heartbeatRuns.agentId,
|
|
contextSnapshot: heartbeatRuns.contextSnapshot,
|
|
retryOfRunId: heartbeatRuns.retryOfRunId,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(run?.agentId).toBe(agentId);
|
|
expect(run?.retryOfRunId).toBeNull();
|
|
expect(run?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_continuation_needed",
|
|
retryReason: "issue_continuation_needed",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
interactionContinuationPolicy: "wake_assignee_on_accept",
|
|
interactionResolvedAt: resolvedAt.toISOString(),
|
|
source: "issue.interaction_continuation_recovery",
|
|
});
|
|
|
|
const wakeup = await db
|
|
.select({ payload: agentWakeupRequests.payload })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.agentId, agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(wakeup).not.toBeNull();
|
|
expect((wakeup?.payload as Record<string, unknown> | null)?.issueId).toBe(
|
|
issueId,
|
|
);
|
|
});
|
|
|
|
// Scenario 3 (restart durability): a bounded continuation retry scheduled
|
|
// before a server restart survives it. Promotion is DB-driven (scheduled_retry rows +
|
|
// promoteDueScheduledRetries), not an in-memory setTimeout — so a brand-new heartbeat
|
|
// service instance with empty in-memory state still promotes the due retry.
|
|
it("promotes a scheduled plan-approval continuation retry after a simulated server restart", async () => {
|
|
const { companyId, agentId, runId, issueId } =
|
|
await seedQueuedIssueRunFixture();
|
|
const interactionId = randomUUID();
|
|
const now = new Date("2026-03-19T00:10:00.000Z");
|
|
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
continuationPolicy: "wake_assignee_on_accept",
|
|
createdByAgentId: agentId,
|
|
resolvedByUserId: "responsible-user",
|
|
resolvedAt: now,
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Approve the plan?",
|
|
target: {
|
|
type: "issue_document",
|
|
issueId,
|
|
key: "plan",
|
|
revisionId: randomUUID(),
|
|
},
|
|
},
|
|
result: { version: 1, outcome: "accepted" },
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "failed",
|
|
error: "workspace validation failed before dispatch",
|
|
errorCode: "workspace_validation_failed",
|
|
resultJson: {
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
finishedAt: now,
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
mutation: "interaction",
|
|
interactionId,
|
|
interactionKind: "request_confirmation",
|
|
interactionStatus: "accepted",
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "in_review", executionRunId: runId })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
// Service instance that scheduled the retry (pre-restart).
|
|
const preRestart = heartbeatService(db);
|
|
const scheduled = await preRestart.scheduleBoundedRetry(runId, {
|
|
now,
|
|
retryReason: INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
|
|
wakeReason: INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
|
|
maxAttempts: 3,
|
|
});
|
|
expect(scheduled.outcome).toBe("scheduled");
|
|
if (scheduled.outcome !== "scheduled") return;
|
|
|
|
const beforePromotion = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, scheduled.run.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(beforePromotion?.status).toBe("scheduled_retry");
|
|
|
|
// Simulate a server restart: no in-memory process/timer state carries over.
|
|
await stopRegisteredProcessesForCleanup();
|
|
const restarted = heartbeatService(db);
|
|
const promotion = await restarted.promoteDueScheduledRetries(
|
|
scheduled.dueAt,
|
|
);
|
|
expect(promotion).toEqual({ promoted: 1, runIds: [scheduled.run.id] });
|
|
|
|
const promoted = await db
|
|
.select({
|
|
status: heartbeatRuns.status,
|
|
retryOfRunId: heartbeatRuns.retryOfRunId,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, scheduled.run.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(promoted).toMatchObject({ status: "queued", retryOfRunId: runId });
|
|
});
|
|
|
|
it("still re-enqueues stranded assigned todo recovery when an old queued wake exists", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "failed",
|
|
});
|
|
await db.insert(agentWakeupRequests).values({
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId },
|
|
status: "queued",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.assignmentDispatched).toBe(0);
|
|
expect(result.dispatchRequeued).toBe(1);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(
|
|
(retryRun?.contextSnapshot as Record<string, unknown>)?.retryReason,
|
|
).toBe("transient_failure");
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
});
|
|
|
|
it("blocks assigned todo work after the one automatic dispatch recovery was already used", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "failed",
|
|
retryReason: "assignment_recovery",
|
|
runErrorCode: "process_lost",
|
|
runError: "Authorization: Bearer sk-test-recovery-secret",
|
|
});
|
|
const longRecoveryOwnerName = "R".repeat(161);
|
|
await db
|
|
.update(agents)
|
|
.set({ name: longRecoveryOwnerName })
|
|
.where(eq(agents.id, agentId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "todo",
|
|
retryReason: "assignment_recovery",
|
|
cause: "process_lost",
|
|
});
|
|
expect(JSON.stringify(recoveryAction.evidence)).not.toContain(
|
|
"sk-test-recovery-secret",
|
|
);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain("tried to start this task again");
|
|
expect(comments[0]?.body).not.toContain("sk-test-recovery-secret");
|
|
expect(JSON.stringify(comments[0]?.metadata)).not.toContain(
|
|
"sk-test-recovery-secret",
|
|
);
|
|
const failureSummary = commentMetadataRows(comments[0]).find(
|
|
(row) => row.type === "key_value" && row.label === "Failure summary",
|
|
);
|
|
expect(failureSummary).toMatchObject({
|
|
type: "key_value",
|
|
label: "Failure summary",
|
|
});
|
|
expect(
|
|
failureSummary?.type === "key_value" ? failureSummary.value : "",
|
|
).toContain("Authorization");
|
|
expect(comments[0]?.presentation).toMatchObject({
|
|
kind: "system_notice",
|
|
tone: "danger",
|
|
});
|
|
expect(
|
|
noticeMetadataReferencesRecoveryAction(
|
|
comments[0]?.metadata,
|
|
recoveryAction.id,
|
|
),
|
|
).toBe(true);
|
|
expect(
|
|
commentMetadataRows(comments[0]).some(
|
|
(row) =>
|
|
row.type === "key_value" &&
|
|
row.label === "Recovery owner" &&
|
|
row.value === "Waiting for you",
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("blocks an already stranded recovery issue without creating a recovery child", async () => {
|
|
const { companyId, issueId } = await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "failed",
|
|
retryReason: "assignment_recovery",
|
|
});
|
|
const sourceIssueId = randomUUID();
|
|
const sourceRunId = randomUUID();
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
|
|
await db.insert(issues).values({
|
|
id: sourceIssueId,
|
|
companyId,
|
|
title: "Original source issue",
|
|
status: "blocked",
|
|
priority: "medium",
|
|
issueNumber: 2,
|
|
identifier: `${issuePrefix}-2`,
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
title: "Recover stalled issue from previous adapter failure",
|
|
parentId: sourceIssueId,
|
|
originKind: "stranded_issue_recovery",
|
|
originId: sourceIssueId,
|
|
originRunId: sourceRunId,
|
|
originFingerprint: [
|
|
"stranded_issue_recovery",
|
|
companyId,
|
|
sourceIssueId,
|
|
sourceRunId,
|
|
].join(":"),
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(1);
|
|
expect(recoveryIssues[0]).toMatchObject({
|
|
id: issueId,
|
|
status: "blocked",
|
|
parentId: sourceIssueId,
|
|
originId: sourceIssueId,
|
|
originRunId: sourceRunId,
|
|
});
|
|
expect(recoveryIssues[0]?.checkoutRunId).toBeNull();
|
|
expect(recoveryIssues[0]?.executionRunId).toBeNull();
|
|
|
|
const blockerRelations = await db
|
|
.select()
|
|
.from(issueRelations)
|
|
.where(
|
|
and(
|
|
eq(issueRelations.companyId, companyId),
|
|
eq(issueRelations.relatedIssueId, issueId),
|
|
eq(issueRelations.type, "blocks"),
|
|
),
|
|
);
|
|
expect(blockerRelations).toHaveLength(0);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain(
|
|
"Paperclip stopped trying to recover this task automatically.",
|
|
);
|
|
expect(comments[0]?.body).toContain(
|
|
"This task was created to recover another task, so Paperclip does not create another recovery task for it.",
|
|
);
|
|
expect(comments[0]?.body).not.toMatch(/stranded_issue_recovery|Retry reason|assignment_recovery/);
|
|
expect(comments[0]?.body).toContain(
|
|
`Recovery task: [${recoveryIssues[0]?.identifier}]`,
|
|
);
|
|
expect(comments[0]?.body).toContain("Next action:");
|
|
expect(comments[0]?.presentation).toMatchObject({
|
|
kind: "system_notice",
|
|
tone: "warning",
|
|
title: "Recovery: recovery attempt failed — remains blocked",
|
|
density: "compact",
|
|
});
|
|
expect(comments[0]?.metadata).toMatchObject({ version: 1 });
|
|
});
|
|
|
|
it("assigns open unassigned blockers back to their creator agent", async () => {
|
|
const companyId = randomUUID();
|
|
const creatorAgentId = randomUUID();
|
|
const blockedAssigneeAgentId = randomUUID();
|
|
const blockerIssueId = randomUUID();
|
|
const blockedIssueId = randomUUID();
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
await db.insert(agents).values([
|
|
{
|
|
id: creatorAgentId,
|
|
companyId,
|
|
name: "SecurityEngineer",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
},
|
|
{
|
|
id: blockedAssigneeAgentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
},
|
|
]);
|
|
await db.insert(issues).values([
|
|
{
|
|
id: blockerIssueId,
|
|
companyId,
|
|
title: "Fix blocker",
|
|
status: "todo",
|
|
priority: "high",
|
|
createdByAgentId: creatorAgentId,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
},
|
|
{
|
|
id: blockedIssueId,
|
|
companyId,
|
|
title: "Blocked work",
|
|
status: "blocked",
|
|
priority: "high",
|
|
assigneeAgentId: blockedAssigneeAgentId,
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 2,
|
|
identifier: `${issuePrefix}-2`,
|
|
},
|
|
]);
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId: blockerIssueId,
|
|
relatedIssueId: blockedIssueId,
|
|
type: "blocks",
|
|
createdByAgentId: creatorAgentId,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.orphanBlockersAssigned).toBe(1);
|
|
expect(result.issueIds).toContain(blockerIssueId);
|
|
|
|
const blocker = await selectRecoveryIssueById(blockerIssueId);
|
|
expect(blocker?.assigneeAgentId).toBe(creatorAgentId);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(blockerIssueId);
|
|
expect(comments[0]?.body).toContain("Assigned Orphan Blocker");
|
|
expect(comments[0]?.body).toContain(
|
|
`[${issuePrefix}-2](/${issuePrefix}/issues/${issuePrefix}-2)`,
|
|
);
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(creatorAgentId);
|
|
expect(wakeups).toEqual([
|
|
expect.objectContaining({
|
|
reason: "issue_assigned",
|
|
payload: expect.objectContaining({
|
|
issueId: blockerIssueId,
|
|
mutation: "unassigned_blocker_recovery",
|
|
}),
|
|
}),
|
|
]);
|
|
|
|
const runId = wakeups[0]?.runId;
|
|
if (runId) {
|
|
await waitForRunToSettle(heartbeat, runId);
|
|
}
|
|
});
|
|
|
|
it("does not run generic continuation recovery for a paused unfinished session goal", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
await db.insert(agentTaskSessions).values({
|
|
companyId,
|
|
agentId,
|
|
adapterType: "paperclip_runner",
|
|
taskKey: issueId,
|
|
lastRunId: runId,
|
|
goalJson: {
|
|
objective: "Wait here until the user explicitly resumes me.",
|
|
status: "paused",
|
|
},
|
|
goalStatus: "paused",
|
|
goalDesiredState: "paused",
|
|
goalRevision: 2,
|
|
});
|
|
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBeGreaterThanOrEqual(1);
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakeups).toHaveLength(1);
|
|
expect(wakeups[0]?.runId).toBe(runId);
|
|
});
|
|
|
|
it("does not continue seeded in-progress work that has no run linkage", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
await seedRecoveryCompany(companyId, issuePrefix);
|
|
await db.insert(agents).values(recoveryAgentRow(agentId, companyId, "CodexCoder", "engineer", "idle"));
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
title: "Seeded in-flight work",
|
|
status: "in_progress",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
checkoutRunId: null,
|
|
executionRunId: null,
|
|
issueNumber: 1,
|
|
identifier: `${issuePrefix}-1`,
|
|
startedAt: new Date("2026-03-19T00:00:00.000Z"),
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBe(1);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(0);
|
|
const [issue] = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId));
|
|
expect(issue?.status).toBe("in_progress");
|
|
expect(issue?.executionRunId).toBeNull();
|
|
});
|
|
|
|
it.each([false, true])("enqueues one bounded plan-only continuation with legacy productivity review present: %s", async (withLegacyReview) => {
|
|
const { companyId, agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
const legacyReviewId = randomUUID();
|
|
if (withLegacyReview) {
|
|
await db.insert(issues).values({
|
|
id: legacyReviewId,
|
|
companyId,
|
|
title: "Historical productivity review",
|
|
description: "Keep this review and its existing ownership unchanged.",
|
|
status: "todo",
|
|
assigneeUserId: "responsible-user",
|
|
parentId: issueId,
|
|
originKind: "issue_productivity_review",
|
|
originId: issueId,
|
|
originFingerprint: `productivity-review:${issueId}`,
|
|
});
|
|
}
|
|
const legacyReviewBefore = withLegacyReview
|
|
? await db.select().from(issues).where(eq(issues.id, legacyReviewId))
|
|
: [];
|
|
let planOnlyRunId = "";
|
|
mockAdapterExecute.mockImplementationOnce(async (input?: unknown) => {
|
|
planOnlyRunId = (input as { runId: string }).runId;
|
|
if (withLegacyReview) {
|
|
// These pre-dispatch cancellations used to satisfy both the no-comment
|
|
// and churn thresholds and suppress an otherwise valid continuation.
|
|
await db.insert(heartbeatRuns).values(Array.from({ length: 10 }, (_, index) => ({
|
|
id: randomUUID(), companyId, agentId,
|
|
invocationSource: "automation", triggerDetail: "system", status: "cancelled",
|
|
errorCode: "execution_reconciliation_required",
|
|
contextSnapshot: { issueId, taskId: issueId },
|
|
createdAt: new Date(Date.now() - (index + 1) * 60_000),
|
|
finishedAt: new Date(),
|
|
})));
|
|
}
|
|
return {
|
|
exitCode: 0, signal: null, timedOut: false, errorMessage: null,
|
|
summary: "I will inspect the repo next and then implement the fix.",
|
|
provider: "test", model: "test-model",
|
|
};
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
const scheduledRun = (await selectRecoveryRunsByAgent(agentId))
|
|
.find((row) => row.status === "scheduled_retry");
|
|
expect(scheduledRun?.scheduledRetryAt).toBeInstanceOf(Date);
|
|
await heartbeat.promoteDueScheduledRetries(scheduledRun!.scheduledRetryAt!);
|
|
await heartbeat.resumeQueuedRuns();
|
|
// The continuation is produced by completion; wait for that durable boundary.
|
|
await heartbeat.drainActiveRunExecutions();
|
|
|
|
expect(planOnlyRunId).not.toBe("");
|
|
const livenessWakes = await waitForValue(async () => {
|
|
const rows = await selectRecoveryWakesByAgent(agentId);
|
|
// Follow-up repairs can already exist. Match this plan-only result,
|
|
// rather than relying on the database's unordered row order.
|
|
const matching = rows.filter((row) => row.reason === "issue_disposition_repair"
|
|
&& row.payload?.retryOfRunId === planOnlyRunId);
|
|
return matching.length > 0 ? matching : null;
|
|
});
|
|
expect(livenessWakes).toHaveLength(1);
|
|
const livenessWake = livenessWakes![0]!;
|
|
expect(livenessWake?.payload).toMatchObject({
|
|
issueId,
|
|
dispositionRepairAttempt: 1,
|
|
});
|
|
|
|
const sourceRunId = (
|
|
livenessWake?.payload as Record<string, unknown> | null
|
|
)?.retryOfRunId;
|
|
expect(sourceRunId).toBe(planOnlyRunId);
|
|
const sourceRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, String(sourceRunId)))
|
|
.then((rows) => rows[0] ?? null);
|
|
if (sourceRun?.id) {
|
|
await waitForRunToSettle(heartbeat, sourceRun.id, 5_000);
|
|
}
|
|
expect(sourceRun?.id).not.toBe(runId);
|
|
// Durable accounting is bookkeeping, not evidence that the agent acted
|
|
// on its plan. A receipt must not suppress plan-only recovery.
|
|
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, String(sourceRunId)))).toHaveLength(1);
|
|
expect(sourceRun?.livenessState).toBe("plan_only");
|
|
if (withLegacyReview) {
|
|
expect(await db.select().from(issues).where(eq(issues.id, legacyReviewId))).toEqual(legacyReviewBefore);
|
|
const source = (await issueService(db).list(companyId)).find((issue) => issue.id === issueId);
|
|
expect(source).toBeDefined();
|
|
expect(source).not.toHaveProperty("productivityReview");
|
|
}
|
|
});
|
|
|
|
it("treats a plan document update as progress and does not enqueue liveness continuation", async () => {
|
|
const { agentId, companyId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce(
|
|
async (ctx: { runId: string }) => {
|
|
const documentId = randomUUID();
|
|
const revisionId = randomUUID();
|
|
await db.insert(documents).values({
|
|
id: documentId,
|
|
companyId,
|
|
title: "Plan",
|
|
format: "markdown",
|
|
latestBody: "# Plan\n\n- Inspect files\n- Implement fix",
|
|
latestRevisionId: revisionId,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: agentId,
|
|
updatedByAgentId: agentId,
|
|
});
|
|
await db.insert(documentRevisions).values({
|
|
id: revisionId,
|
|
companyId,
|
|
documentId,
|
|
revisionNumber: 1,
|
|
title: "Plan",
|
|
format: "markdown",
|
|
body: "# Plan\n\n- Inspect files\n- Implement fix",
|
|
createdByAgentId: agentId,
|
|
createdByRunId: ctx.runId,
|
|
});
|
|
await db.insert(issueDocuments).values({
|
|
companyId,
|
|
issueId,
|
|
documentId,
|
|
key: "plan",
|
|
});
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Plan:\n- Inspect files\n- Implement fix",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
},
|
|
);
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
await heartbeat.reconcileStrandedAssignedIssues();
|
|
const scheduledRun = (await selectRecoveryRunsByAgent(agentId))
|
|
.find((row) => row.status === "scheduled_retry");
|
|
expect(scheduledRun?.scheduledRetryAt).toBeInstanceOf(Date);
|
|
await heartbeat.promoteDueScheduledRetries(scheduledRun!.scheduledRetryAt!);
|
|
await heartbeat.resumeQueuedRuns();
|
|
|
|
const retryRun = await waitForValue(async () => {
|
|
const rows = await selectRecoveryRunsByAgent(agentId);
|
|
return (
|
|
rows.find(
|
|
(row) => row.id !== runId && row.livenessState === "advanced",
|
|
) ?? null
|
|
);
|
|
}, 5_000);
|
|
if (retryRun?.id) {
|
|
await waitForRunToSettle(heartbeat, retryRun.id, 5_000);
|
|
}
|
|
expect(retryRun?.livenessState).toBe("advanced");
|
|
|
|
const wakes = await selectRecoveryWakesByAgent(agentId);
|
|
expect(
|
|
wakes.some((row) => row.reason === "run_liveness_continuation"),
|
|
).toBe(false);
|
|
});
|
|
it("blocks stranded in-progress work after the continuation retry was already used", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
retryReason: "issue_continuation_needed",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: "issue_continuation_needed",
|
|
cause: "process_lost",
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain("tried to continue this task again");
|
|
expect(comments[0]?.presentation).toMatchObject({
|
|
kind: "system_notice",
|
|
tone: "danger",
|
|
});
|
|
expect(
|
|
noticeMetadataReferencesRecoveryAction(
|
|
comments[0]?.metadata,
|
|
recoveryAction.id,
|
|
),
|
|
).toBe(true);
|
|
expect(
|
|
commentMetadataRows(comments[0]).some(
|
|
(row) =>
|
|
row.type === "key_value" &&
|
|
row.label === "Recovery owner" &&
|
|
row.value === "Waiting for you",
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("redacts error-code-only stranded recovery failures in issue copy", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "adapter_exit_code",
|
|
runError: null,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: "issue_continuation_needed",
|
|
});
|
|
expect(recoveryAction.evidence).toMatchObject({
|
|
latestRunErrorCode: "adapter_exit_code",
|
|
});
|
|
expect(JSON.stringify(recoveryAction.evidence)).not.toContain(
|
|
"- Failure: none recorded",
|
|
);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
// The short structured body carries no failure details; the normalized
|
|
// failure code surfaces only as a metadata row.
|
|
expect(comments[0]?.body).not.toContain("adapter_exit_code");
|
|
expect(comments[0]?.body).not.toContain("- Failure: none recorded");
|
|
expect(commentMetadataRows(comments[0])).toContainEqual({
|
|
type: "key_value",
|
|
label: "Failure code",
|
|
value: "adapter_exit_code",
|
|
});
|
|
});
|
|
|
|
it("keeps retrying transient adapter_failed continuation runs before the cap", async () => {
|
|
const { agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "adapter_failed",
|
|
runError: "ssh: connection reset",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_progress");
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(2);
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown> | undefined,
|
|
).toMatchObject({
|
|
issueId,
|
|
retryReason: "transient_failure",
|
|
});
|
|
expect(retryRun).toMatchObject({
|
|
status: "scheduled_retry",
|
|
scheduledRetryAttempt: 1,
|
|
});
|
|
});
|
|
|
|
it("escalates after repeated adapter_failed continuation retries with the cause in the comment", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
retryReason: "issue_continuation_needed",
|
|
runErrorCode: "adapter_failed",
|
|
runError: "ssh: connection reset",
|
|
});
|
|
// Backfill two more consecutive failed continuation retries so the cap (3) is reached.
|
|
const olderTimestamps = [
|
|
new Date("2026-03-18T23:50:00.000Z"),
|
|
new Date("2026-03-18T23:55:00.000Z"),
|
|
];
|
|
for (const finishedAt of olderTimestamps) {
|
|
await db.insert(heartbeatRuns).values({
|
|
id: randomUUID(),
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "failed",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_continuation_needed",
|
|
retryReason: "issue_continuation_needed",
|
|
source: "issue.continuation_recovery",
|
|
},
|
|
errorCode: "adapter_failed",
|
|
error: "ssh: connection reset",
|
|
startedAt: finishedAt,
|
|
finishedAt,
|
|
createdAt: finishedAt,
|
|
updatedAt: finishedAt,
|
|
});
|
|
}
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: "issue_continuation_needed",
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain("tried to continue this task again");
|
|
expect(comments[0]?.body).toContain("after 3 tries");
|
|
expect(commentMetadataRows(comments[0])).toContainEqual({
|
|
type: "key_value",
|
|
label: "Failure code",
|
|
value: "adapter_failed",
|
|
});
|
|
});
|
|
|
|
it("counts different failure causes against the same incident budget", async () => {
|
|
const { agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "adapter_failed",
|
|
runError: "ssh: connection reset",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ scheduledRetryAttempt: 2 })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(
|
|
await selectRecoveryRunsByAgent(agentId),
|
|
).toHaveLength(1);
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
evidence: expect.objectContaining({ attempt: 3 }),
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("escalates non-retryable continuation failures immediately without enqueuing another retry", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "budget_blocked",
|
|
runError: "Budget exceeded; refusing to dispatch.",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: null,
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain("retrying alone would not fix");
|
|
expect(comments[0]?.body).not.toContain("budget_blocked");
|
|
|
|
const followupRuns = await selectRecoveryRunsByAgent(agentId);
|
|
const continuationRetryRun = followupRuns.find((row) => {
|
|
const ctx = row.contextSnapshot as Record<string, unknown> | null;
|
|
return ctx?.retryReason === "issue_continuation_needed";
|
|
});
|
|
expect(continuationRetryRun).toBeUndefined();
|
|
for (const row of followupRuns) {
|
|
if (row.id !== runId) {
|
|
await waitForRunToSettle(heartbeat, row.id);
|
|
}
|
|
}
|
|
});
|
|
|
|
it("does not recover a finished native chat while its response publication is pending", async () => {
|
|
const { agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
resultJson: { finalizationReasonCode: "conversation_turn_finished" },
|
|
});
|
|
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true });
|
|
try {
|
|
await db.update(issues).set({
|
|
conversationAgentId: agentId,
|
|
conversationUserId: "responsible-user",
|
|
conversationState: "active",
|
|
}).where(eq(issues.id, issueId));
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs.map((run) => run.id)).toEqual([runId]);
|
|
const wakes = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakes).toHaveLength(1);
|
|
expect(wakes[0].reason).toBe("issue_assigned");
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
// No fabricated idle state: durable response publication still settles it.
|
|
expect(issue.status).toBe("in_progress");
|
|
expect(issue.conversationState).toBe("active");
|
|
} finally {
|
|
await instanceSettingsService(db).updateExperimental({ enableAgentChat: false });
|
|
}
|
|
});
|
|
|
|
it("does not turn a pre-adapter setup failure into a duplicate continuation run", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
runErrorCode: "setup_failed",
|
|
runError:
|
|
"Low-trust execution requires isolated workspaces to be enabled.",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
retryReason: null,
|
|
});
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(
|
|
runs.find((row) => {
|
|
const context = row.contextSnapshot as Record<string, unknown> | null;
|
|
return context?.retryReason === "issue_continuation_needed";
|
|
}),
|
|
).toBeUndefined();
|
|
});
|
|
|
|
it.each(["active", "waiting"] as const)(
|
|
"leaves a successful external-chat turn idle while its conversation is %s",
|
|
async (state) => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
runSource: "chat:slack",
|
|
livenessState: "advanced",
|
|
});
|
|
await bindChatConversation({
|
|
agentId,
|
|
companyId,
|
|
issueId,
|
|
state,
|
|
});
|
|
|
|
const result =
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.issueIds).toEqual([]);
|
|
await expect(
|
|
db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId)),
|
|
).resolves.toEqual([{ id: runId }]);
|
|
},
|
|
);
|
|
|
|
async function seedCommittedChatControlStop(
|
|
control: "close" | "new" = "close",
|
|
) {
|
|
const source = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
runSource: "chat:slack",
|
|
livenessState: "advanced",
|
|
});
|
|
const binding = await bindChatConversation({
|
|
...source,
|
|
state: "completed",
|
|
});
|
|
const [boundConversation] = await db
|
|
.select()
|
|
.from(chatConversations)
|
|
.where(eq(chatConversations.id, binding.conversationId));
|
|
const principalId = randomUUID();
|
|
const sourceDeliveryId = randomUUID();
|
|
const sourceCommentId = randomUUID();
|
|
const controlDeliveryId = randomUUID();
|
|
const publicationId = randomUUID();
|
|
const sourceAt = new Date("2026-03-19T00:00:00.000Z");
|
|
const closedAt = new Date("2026-03-19T00:06:00.000Z");
|
|
await db.insert(chatExternalPrincipals).values({
|
|
id: principalId,
|
|
companyId: source.companyId,
|
|
provider: "slack",
|
|
providerAccountId: "test-workspace",
|
|
externalId: randomUUID(),
|
|
});
|
|
await db.insert(issueComments).values({
|
|
id: sourceCommentId,
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
authorUserId: "responsible-user",
|
|
body: "Answer once; wait for another message.",
|
|
createdAt: sourceAt,
|
|
updatedAt: sourceAt,
|
|
});
|
|
await db.insert(chatDeliveries).values([
|
|
{
|
|
id: sourceDeliveryId,
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
principalId,
|
|
providerEventId: "source-event",
|
|
deduplicationKey: "source-event",
|
|
eventKind: "message",
|
|
normalizedEvent: {
|
|
provider: "slack",
|
|
runtimeContext: {
|
|
generation: 1,
|
|
credentialFingerprint: "fixture-fingerprint",
|
|
},
|
|
message: {
|
|
id: "source-event",
|
|
text: "Answer once; wait for another message.",
|
|
},
|
|
},
|
|
state: "processed",
|
|
receivedAt: sourceAt,
|
|
processedAt: sourceAt,
|
|
createdAt: sourceAt,
|
|
updatedAt: sourceAt,
|
|
},
|
|
{
|
|
id: controlDeliveryId,
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
principalId,
|
|
providerEventId: "control-event",
|
|
deduplicationKey: "control-event",
|
|
eventKind: "message",
|
|
normalizedEvent: {
|
|
provider: "slack",
|
|
runtimeContext: {
|
|
generation: 1,
|
|
credentialFingerprint: "fixture-fingerprint",
|
|
},
|
|
message: { id: "control-event", text: `/${control}` },
|
|
},
|
|
state: "processed",
|
|
receivedAt: closedAt,
|
|
processedAt: closedAt,
|
|
createdAt: closedAt,
|
|
updatedAt: closedAt,
|
|
},
|
|
]);
|
|
await db
|
|
.update(chatDeliveries)
|
|
.set({
|
|
normalizedEvent: {
|
|
providerEventId: "control-event",
|
|
kind: "message",
|
|
runtimeContext: {
|
|
generation: 1,
|
|
credentialFingerprint: "fixture-fingerprint",
|
|
},
|
|
conversation: {
|
|
externalConversationId: boundConversation!.externalConversationId,
|
|
externalThreadId: boundConversation!.externalThreadId,
|
|
},
|
|
message: { providerMessageId: "control-event", text: `/${control}` },
|
|
},
|
|
})
|
|
.where(eq(chatDeliveries.id, controlDeliveryId));
|
|
await db.insert(chatActions).values([
|
|
{
|
|
id: source.wakeupRequestId,
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
deliveryId: sourceDeliveryId,
|
|
principalId,
|
|
kind: "inbound_wakeup",
|
|
providerActionId: `inbound_wakeup:${sourceDeliveryId}`,
|
|
status: "processed",
|
|
payload: {
|
|
version: 1,
|
|
issueId: source.issueId,
|
|
agentId: source.agentId,
|
|
commentId: sourceCommentId,
|
|
sessionGeneration: 1,
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
},
|
|
createdAt: sourceAt,
|
|
updatedAt: sourceAt,
|
|
},
|
|
{
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
principalId,
|
|
kind: "task_control_authorization",
|
|
providerActionId: `task-control-authorization:${publicationId}`,
|
|
status: "processed",
|
|
payload: { publicationId },
|
|
result: { code: "task_control_authorized_and_sent" },
|
|
createdAt: closedAt,
|
|
updatedAt: closedAt,
|
|
},
|
|
]);
|
|
await db.insert(chatPublications).values({
|
|
id: publicationId,
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
issueId: source.issueId,
|
|
idempotencyKey: `control:${control}:${controlDeliveryId}`,
|
|
payload: { text: "Conversation closed." },
|
|
state: "published",
|
|
providerMessageId: "confirmed-close-receipt",
|
|
attempts: 1,
|
|
publishedAt: closedAt,
|
|
createdAt: closedAt,
|
|
updatedAt: closedAt,
|
|
});
|
|
await db.insert(chatMessageLinks).values([
|
|
{
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
deliveryId: sourceDeliveryId,
|
|
commentId: sourceCommentId,
|
|
providerMessageId: "source-event",
|
|
direction: "inbound",
|
|
createdAt: sourceAt,
|
|
},
|
|
{
|
|
companyId: source.companyId,
|
|
endpointId: binding.endpointId,
|
|
conversationId: binding.conversationId,
|
|
publicationId,
|
|
providerMessageId: "confirmed-close-receipt",
|
|
direction: "outbound",
|
|
createdAt: closedAt,
|
|
},
|
|
]);
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
issueId: source.issueId,
|
|
taskId: source.issueId,
|
|
source: "chat:slack",
|
|
commentId: sourceCommentId,
|
|
},
|
|
createdAt: sourceAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, source.runId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
status: "claimed",
|
|
payload: { issueId: source.issueId, commentId: sourceCommentId },
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
createdAt: sourceAt,
|
|
requestedAt: sourceAt,
|
|
})
|
|
.where(eq(agentWakeupRequests.id, source.wakeupRequestId));
|
|
return {
|
|
...source,
|
|
...binding,
|
|
principalId,
|
|
sourceDeliveryId,
|
|
sourceCommentId,
|
|
controlDeliveryId,
|
|
publicationId,
|
|
closedAt,
|
|
};
|
|
}
|
|
|
|
it.each(["close", "new"] as const)(
|
|
"does not automatically resume a source after its committed authorized /%s receipt",
|
|
async (control) => {
|
|
const source = await seedCommittedChatControlStop(control);
|
|
const heartbeat = heartbeatService(db);
|
|
for (let sweep = 0; sweep < 2; sweep++) {
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
}
|
|
expect(
|
|
await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, source.agentId)),
|
|
).toEqual([{ id: source.runId }]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(
|
|
(
|
|
await db
|
|
.select({ status: issues.status })
|
|
.from(issues)
|
|
.where(eq(issues.id, source.issueId))
|
|
)[0]?.status,
|
|
).toBe("in_progress");
|
|
},
|
|
);
|
|
|
|
async function seedChatAutomaticChild(
|
|
source: Awaited<ReturnType<typeof seedCommittedChatControlStop>>,
|
|
extra?: {
|
|
parentId?: string;
|
|
comments?: boolean;
|
|
status?: "queued" | "succeeded";
|
|
},
|
|
) {
|
|
const runId = randomUUID();
|
|
const wakeupRequestId = randomUUID();
|
|
const status = extra?.status ?? "queued";
|
|
const context = {
|
|
issueId: source.issueId,
|
|
taskId: source.issueId,
|
|
source: "native_status_decision",
|
|
...(extra?.comments ? { wakeCommentIds: [source.sourceCommentId] } : {}),
|
|
};
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeupRequestId,
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_continuation_needed",
|
|
requestedByActorType: "system",
|
|
requestedByActorId: null,
|
|
status: status === "queued" ? "queued" : "completed",
|
|
runId,
|
|
payload: {
|
|
issueId: source.issueId,
|
|
...(extra?.comments
|
|
? {
|
|
_paperclipWakeContext: {
|
|
wakeCommentIds: [source.sourceCommentId],
|
|
},
|
|
}
|
|
: {}),
|
|
},
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status,
|
|
wakeupRequestId,
|
|
retryOfRunId: extra?.parentId ?? source.runId,
|
|
contextSnapshot: context,
|
|
...(status === "succeeded"
|
|
? { finishedAt: new Date(), livenessState: "advanced" }
|
|
: {}),
|
|
});
|
|
return { runId, wakeupRequestId };
|
|
}
|
|
|
|
const chatStopScope = (
|
|
source: Awaited<ReturnType<typeof seedCommittedChatControlStop>>,
|
|
sourceRunId: string = source.runId,
|
|
) => ({
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
agentId: source.agentId,
|
|
sourceRunId,
|
|
});
|
|
|
|
it.each(["message", "direct_message", "mention"] as const)(
|
|
"recognizes the real generic control delivery event kind %s",
|
|
async (eventKind) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
await db
|
|
.update(chatDeliveries)
|
|
.set({
|
|
eventKind,
|
|
normalizedEvent: sql`jsonb_set(${chatDeliveries.normalizedEvent}, '{kind}', ${JSON.stringify(eventKind)}::jsonb)`,
|
|
})
|
|
.where(eq(chatDeliveries.id, source.controlDeliveryId));
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source))).kind,
|
|
).toBe("stopped");
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
"authorization",
|
|
"outbound",
|
|
"principal",
|
|
"command",
|
|
"generation",
|
|
] as const)(
|
|
"does not infer chat close authority from a mismatched %s receipt",
|
|
async (change) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
if (change === "authorization")
|
|
await db
|
|
.update(chatActions)
|
|
.set({ result: { code: "not_sent" } })
|
|
.where(
|
|
eq(
|
|
chatActions.providerActionId,
|
|
`task-control-authorization:${source.publicationId}`,
|
|
),
|
|
);
|
|
if (change === "outbound")
|
|
await db
|
|
.delete(chatMessageLinks)
|
|
.where(eq(chatMessageLinks.publicationId, source.publicationId));
|
|
if (change === "principal")
|
|
await db
|
|
.update(chatActions)
|
|
.set({ principalId: null })
|
|
.where(
|
|
eq(
|
|
chatActions.providerActionId,
|
|
`task-control-authorization:${source.publicationId}`,
|
|
),
|
|
);
|
|
if (change === "command")
|
|
await db
|
|
.update(chatDeliveries)
|
|
.set({
|
|
normalizedEvent: sql`jsonb_set(${chatDeliveries.normalizedEvent}, '{message,text}', '"not a close command"'::jsonb)`,
|
|
})
|
|
.where(eq(chatDeliveries.id, source.controlDeliveryId));
|
|
if (change === "generation")
|
|
await db
|
|
.update(chatActions)
|
|
.set({
|
|
payload: sql`jsonb_set(${chatActions.payload}, '{sessionGeneration}', '2'::jsonb)`,
|
|
})
|
|
.where(eq(chatActions.id, source.wakeupRequestId));
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source))).kind,
|
|
).toBe(change === "generation" ? "unresolved" : "clear");
|
|
},
|
|
);
|
|
|
|
it("orders chat close against original admitted sources, not a later failed retry action", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const retry = await seedChatAutomaticChild(source);
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
source: "on_demand",
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
})
|
|
.where(eq(agentWakeupRequests.id, retry.wakeupRequestId));
|
|
await db.insert(chatActions).values({
|
|
id: retry.wakeupRequestId,
|
|
companyId: source.companyId,
|
|
endpointId: source.endpointId,
|
|
conversationId: source.conversationId,
|
|
principalId: source.principalId,
|
|
kind: "failed_run_retry",
|
|
providerActionId: `failed-run-retry:${source.runId}`,
|
|
status: "processed",
|
|
payload: {
|
|
version: 1,
|
|
issueId: source.issueId,
|
|
agentId: source.agentId,
|
|
sessionGeneration: 1,
|
|
failedRunId: source.runId,
|
|
sourceWakeupRequestId: source.wakeupRequestId,
|
|
endpointId: source.endpointId,
|
|
conversationId: source.conversationId,
|
|
principalId: source.principalId,
|
|
sources: [
|
|
{
|
|
actionId: source.wakeupRequestId,
|
|
deliveryId: source.sourceDeliveryId,
|
|
principalId: source.principalId,
|
|
commentId: source.sourceCommentId,
|
|
receiptId: source.wakeupRequestId,
|
|
ownerId: source.wakeupRequestId,
|
|
},
|
|
],
|
|
},
|
|
});
|
|
expect(
|
|
(
|
|
await readChatControlRecoveryStop(
|
|
db,
|
|
chatStopScope(source, retry.runId),
|
|
)
|
|
).kind,
|
|
).toBe("stopped");
|
|
// Exact PostgreSQL microseconds: a new source after the close is fresh work.
|
|
await db.execute(
|
|
sql`update chat_actions set created_at = ${source.closedAt.toISOString()}::timestamptz + interval '1 microsecond' where id = ${source.wakeupRequestId}::uuid`,
|
|
);
|
|
expect(
|
|
(
|
|
await readChatControlRecoveryStop(
|
|
db,
|
|
chatStopScope(source, retry.runId),
|
|
)
|
|
).kind,
|
|
).toBe("clear");
|
|
});
|
|
|
|
it("preserves a genuinely later coalesced inbound source instead of selecting only the old canonical message", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const deliveryId = randomUUID();
|
|
const commentId = randomUUID();
|
|
const actionId = randomUUID();
|
|
const later = new Date(source.closedAt.getTime() + 1000);
|
|
const [original] = await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(eq(chatActions.id, source.wakeupRequestId));
|
|
await db.insert(issueComments).values({
|
|
id: commentId,
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
authorUserId: "responsible-user",
|
|
body: "New explicitly requested work after close",
|
|
createdAt: later,
|
|
updatedAt: later,
|
|
});
|
|
await db.insert(chatDeliveries).values({
|
|
id: deliveryId,
|
|
companyId: source.companyId,
|
|
endpointId: source.endpointId,
|
|
conversationId: source.conversationId,
|
|
principalId: source.principalId,
|
|
providerEventId: "later-source",
|
|
deduplicationKey: "later-source",
|
|
eventKind: "message",
|
|
normalizedEvent: {
|
|
providerEventId: "later-source",
|
|
kind: "message",
|
|
message: {
|
|
providerMessageId: "later-source",
|
|
text: "New explicitly requested work after close",
|
|
},
|
|
},
|
|
state: "processed",
|
|
receivedAt: later,
|
|
processedAt: later,
|
|
createdAt: later,
|
|
updatedAt: later,
|
|
});
|
|
await db.insert(chatActions).values({
|
|
id: actionId,
|
|
companyId: source.companyId,
|
|
endpointId: source.endpointId,
|
|
conversationId: source.conversationId,
|
|
principalId: source.principalId,
|
|
deliveryId,
|
|
providerActionId: `inbound_wakeup:${deliveryId}`,
|
|
kind: "inbound_wakeup",
|
|
status: "processed",
|
|
payload: { ...original!.payload, commentId },
|
|
createdAt: later,
|
|
updatedAt: later,
|
|
});
|
|
await db.insert(chatMessageLinks).values({
|
|
companyId: source.companyId,
|
|
endpointId: source.endpointId,
|
|
conversationId: source.conversationId,
|
|
deliveryId,
|
|
commentId,
|
|
providerMessageId: "later-source",
|
|
direction: "inbound",
|
|
createdAt: later,
|
|
});
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: actionId,
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_execution_same_name",
|
|
payload: {
|
|
issueId: source.issueId,
|
|
commentId,
|
|
coalescedIntoWakeupRequestId: source.wakeupRequestId,
|
|
},
|
|
status: "coalesced",
|
|
runId: source.runId,
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
createdAt: later,
|
|
requestedAt: later,
|
|
});
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source))).kind,
|
|
).toBe("clear");
|
|
});
|
|
|
|
it("follows exact automatic ancestry despite rewritten context and stops only that unused child", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const first = await seedChatAutomaticChild(source, { status: "succeeded" });
|
|
const child = await seedChatAutomaticChild(source, {
|
|
parentId: first.runId,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const [row] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
expect(row).toMatchObject({
|
|
status: "cancelled",
|
|
errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
startedAt: null,
|
|
});
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, first.runId))
|
|
)[0]?.status,
|
|
).toBe("succeeded");
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(
|
|
(await heartbeat.reconcileStrandedAssignedIssues()).continuationRequeued,
|
|
).toBe(0);
|
|
expect(
|
|
(await db.select().from(issues).where(eq(issues.id, source.issueId)))[0]
|
|
?.status,
|
|
).toBe("in_progress");
|
|
});
|
|
|
|
it.each(["claim", "dispatch", "queued_comments"] as const)(
|
|
"honors close committed at the %s boundary without a provider call",
|
|
async (boundary) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "pending" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
let checked = false;
|
|
const heartbeat = heartbeatService(db, {
|
|
beforeChatControlRecoveryCheck: async ({ stage, runId }) => {
|
|
if (
|
|
stage !== (boundary === "dispatch" ? "dispatch" : "claim") ||
|
|
checked
|
|
)
|
|
return;
|
|
checked = true;
|
|
const [child] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(child?.retryOfRunId).toBe(source.runId);
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "published" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
},
|
|
});
|
|
const run = await heartbeat.wakeup(source.agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_continuation_needed",
|
|
requestedByActorType: "system",
|
|
requestedByActorId: null,
|
|
payload: { issueId: source.issueId },
|
|
contextSnapshot: {
|
|
issueId: source.issueId,
|
|
taskId: source.issueId,
|
|
retryOfRunId: source.runId,
|
|
source: "issue.productive_terminal_continuation_recovery",
|
|
...(boundary === "queued_comments"
|
|
? { wakeCommentIds: [source.sourceCommentId] }
|
|
: {}),
|
|
},
|
|
});
|
|
expect(run).not.toBeNull();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(checked).toBe(true);
|
|
const [settled] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, run!.id));
|
|
expect(settled).toMatchObject({
|
|
status: "cancelled",
|
|
errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
});
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
expect(
|
|
(
|
|
await db.select().from(issues).where(eq(issues.id, source.issueId))
|
|
)[0],
|
|
).toMatchObject({ status: "in_progress", executionRunId: null });
|
|
},
|
|
);
|
|
|
|
it.each(["issue", "wake", "run", "native", "close", "cancel"] as const)(
|
|
"rechecks admission after transient database contention: %s",
|
|
async (mode) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
mockAdapterExecute.mockImplementation(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, source.issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "Recorded completion", provider: "test", model: "test-model" };
|
|
});
|
|
await db.update(chatPublications).set({ state: "pending" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
const child = await seedChatAutomaticChild(source);
|
|
// Board comments use the automation transport but are fresh user work.
|
|
if (!["close", "cancel"].includes(mode)) {
|
|
await db.update(agentWakeupRequests).set({
|
|
requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
reason: "issue_commented",
|
|
}).where(eq(agentWakeupRequests.id, child.wakeupRequestId));
|
|
await db.update(heartbeatRuns).set({ retryOfRunId: null })
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
}
|
|
if (mode === "native") {
|
|
await db.update(agents).set({
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
}).where(eq(agents.id, source.agentId));
|
|
}
|
|
const factory = vi.fn(() => { throw new NativeRunnerOwnershipUnverifiedError(); });
|
|
let release!: () => void;
|
|
let locked: Promise<unknown> | undefined;
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const heartbeat = heartbeatService(db, {
|
|
nativeSessionBackendFactory: factory,
|
|
beforeChatControlRecoveryCheck: async ({ stage }) => {
|
|
if (stage !== "dispatch") return;
|
|
let ready!: () => void;
|
|
const acquired = new Promise<void>((resolve) => { ready = resolve; });
|
|
const held = new Promise<void>((resolve) => { release = resolve; });
|
|
locked = db.transaction(async (tx) => {
|
|
if (mode === "wake") {
|
|
await tx.select().from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, child.wakeupRequestId)).for("update");
|
|
} else if (mode === "run" || mode === "cancel") {
|
|
await tx.select().from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId)).for("update");
|
|
} else if (mode === "close") {
|
|
await tx.select().from(chatConversations)
|
|
.where(eq(chatConversations.id, source.conversationId)).for("update");
|
|
} else {
|
|
await tx.select().from(issues)
|
|
.where(eq(issues.id, source.issueId)).for("update");
|
|
}
|
|
ready();
|
|
await held;
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(factory).not.toHaveBeenCalled();
|
|
if (mode === "close") {
|
|
await tx.update(chatPublications).set({ state: "published" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
} else if (mode === "cancel") {
|
|
await tx.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
}
|
|
});
|
|
await acquired;
|
|
timer = setTimeout(release, 250);
|
|
},
|
|
});
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
} finally {
|
|
if (timer) clearTimeout(timer);
|
|
release?.();
|
|
await locked;
|
|
await heartbeat.drainActiveRunExecutions();
|
|
}
|
|
expect(locked).toBeDefined();
|
|
const settled = await heartbeat.getRun(child.runId);
|
|
expect(settled?.errorCode).not.toBe(CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE);
|
|
if (mode === "native") {
|
|
expect(factory).toHaveBeenCalledTimes(1);
|
|
expect(readChatControlRecoveryAdmission(settled!)).toBe("admitted");
|
|
} else if (mode === "close" || mode === "cancel") {
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(settled?.status).toBe("cancelled");
|
|
if (mode === "close") expect(settled?.errorCode).toBe(CHAT_CONTROL_RECOVERY_STOP_CODE);
|
|
} else {
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
expect(settled?.status).toBe("succeeded");
|
|
expect(readChatControlRecoveryAdmission(settled!)).toBe("admitted");
|
|
}
|
|
},
|
|
);
|
|
|
|
it("checks an automatic continuation that names no retry source against the task's previous run", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source);
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ retryOfRunId: null, createdAt: new Date(Date.now() + 1_000) })
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source, child.runId))).kind,
|
|
).toBe("stopped");
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "pending" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source, child.runId))).kind,
|
|
).toBe("clear");
|
|
});
|
|
|
|
it("defers unresolved automatic ancestry at claim and records a distinct nonretrying failure after claim", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "pending" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
const child = await seedChatAutomaticChild(source);
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ retryOfRunId: child.runId })
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
)[0],
|
|
).toMatchObject({ status: "queued", startedAt: null });
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ retryOfRunId: source.runId })
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
const finalHeartbeat = heartbeatService(db, {
|
|
beforeChatControlRecoveryCheck: async ({ stage, runId }) => {
|
|
if (stage === "dispatch")
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ retryOfRunId: runId })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
},
|
|
});
|
|
await finalHeartbeat.resumeQueuedRuns();
|
|
await finalHeartbeat.drainActiveRunExecutions();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
)[0],
|
|
).toMatchObject({
|
|
status: "failed",
|
|
errorCode: CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE,
|
|
});
|
|
expect(
|
|
(await finalHeartbeat.reconcileStrandedAssignedIssues())
|
|
.continuationRequeued,
|
|
).toBe(0);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not confuse inherited warm-runner metadata with dispatch of the new child", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "pending" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
const child = await seedChatAutomaticChild(source);
|
|
const heartbeat = heartbeatService(db, {
|
|
beforeChatControlRecoveryCheck: async ({ stage, runId }) => {
|
|
if (stage !== "dispatch") return;
|
|
// Native warm preparation copies these fields before executeSession.
|
|
// They describe a retained runner, not a provider turn of this child.
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
processPid: 2_000_000_000,
|
|
processGroupId: 2_000_000_000,
|
|
processStartedAt: source.closedAt,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "published" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
},
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
)[0],
|
|
).toMatchObject({
|
|
status: "cancelled",
|
|
errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
});
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
expect(runningProcesses.size).toBe(0);
|
|
});
|
|
|
|
it.each(["intact", "lost", "copied"] as const)(
|
|
"keeps the claimed admission marker through legacy preparation: %s",
|
|
async (mode) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
mockAdapterExecute.mockImplementation(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, source.issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "Recorded completion", provider: "test", model: "test-model" };
|
|
});
|
|
await db
|
|
.update(chatPublications)
|
|
.set({ state: "pending" })
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
const child = await seedChatAutomaticChild(source);
|
|
let checked = false;
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
const [row] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
expect(readChatControlRecoveryAdmission(row!)).toBe("admitted");
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, source.issueId));
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Admitted",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
});
|
|
const heartbeat = heartbeatService(db, {
|
|
beforeChatControlRecoveryCheck: async ({ stage, runId }) => {
|
|
if (stage !== "dispatch") return;
|
|
const [row] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(readChatControlRecoveryAdmission(row!)).toBe("required");
|
|
checked = true;
|
|
if (mode !== "intact")
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runnerProfileJson:
|
|
mode === "lost"
|
|
? {}
|
|
: {
|
|
[CHAT_CONTROL_RECOVERY_ADMISSION_KEY]: {
|
|
...chatControlRecoveryAdmission(row!, "admitted"),
|
|
runId: source.runId,
|
|
},
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
},
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(checked).toBe(true);
|
|
const settled = await heartbeat.getRun(child.runId);
|
|
if (mode === "intact") {
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
expect(settled?.status).toBe("succeeded");
|
|
expect(readChatControlRecoveryAdmission(settled!)).toBe("admitted");
|
|
} else {
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(settled).toMatchObject({
|
|
status: "failed",
|
|
errorCode: CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE,
|
|
});
|
|
}
|
|
},
|
|
);
|
|
|
|
async function seedPreparedChatRecovery(
|
|
admission: "required" | "admitted" | "historical",
|
|
) {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source);
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
|
|
})
|
|
.where(eq(agents.id, source.agentId));
|
|
await db
|
|
.update(issues)
|
|
.set({ executionRunId: child.runId, checkoutRunId: child.runId })
|
|
.where(eq(issues.id, source.issueId));
|
|
let [run] = await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "running", startedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
.returning();
|
|
if (admission !== "historical")
|
|
[run] = await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runnerProfileJson: {
|
|
[CHAT_CONTROL_RECOVERY_ADMISSION_KEY]: chatControlRecoveryAdmission(
|
|
run!,
|
|
admission,
|
|
),
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
.returning();
|
|
const [issue] = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, source.issueId));
|
|
// Real preparation output, no process/checkpoint/provider evidence. The
|
|
// actual restart classifier must choose bootstrap_incomplete below; this
|
|
// fixture does not claim that a missing PID proves a retired provider.
|
|
await prepareNativeHeartbeatRun({
|
|
db,
|
|
run: run!,
|
|
issue: issue!,
|
|
environmentLeaseId: randomUUID(),
|
|
});
|
|
await db.insert(nativeRunFinalizations).values({
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
runId: child.runId,
|
|
phase: "observed",
|
|
});
|
|
return { source, child };
|
|
}
|
|
|
|
it.each(["required", "admitted", "historical"] as const)(
|
|
"rechecks only unadmitted native bootstrap recovery after a committed close: %s",
|
|
async (admission) => {
|
|
await withTempPaperclipHome(async () => {
|
|
await fs.mkdir(resolvePaperclipInstanceRoot(), { recursive: true });
|
|
const { source, child } = await seedPreparedChatRecovery(admission);
|
|
const [prepared] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
expect(readChatControlRecoveryAdmission(prepared!)).toBe(admission);
|
|
const factory = vi.fn(() => {
|
|
throw new NativeRunnerOwnershipUnverifiedError();
|
|
});
|
|
const heartbeat = heartbeatService(db, {
|
|
nativeSessionBackendFactory: factory,
|
|
});
|
|
const recovery = await heartbeat.recoverNativeRunsAfterRestart();
|
|
expect(recovery.claims).toEqual([
|
|
expect.objectContaining({
|
|
runId: child.runId,
|
|
kind: "bootstrap_incomplete",
|
|
}),
|
|
]);
|
|
await heartbeat.drainActiveRunExecutions();
|
|
if (admission === "required") {
|
|
expect(factory).not.toHaveBeenCalled();
|
|
expect(await heartbeat.getRun(child.runId)).toMatchObject({
|
|
status: "cancelled",
|
|
errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
});
|
|
} else expect(factory).toHaveBeenCalledTimes(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(
|
|
(
|
|
await db.select().from(issues).where(eq(issues.id, source.issueId))
|
|
)[0]?.status,
|
|
).toBe("in_progress");
|
|
});
|
|
},
|
|
);
|
|
|
|
it.each(["admitted", "historical"] as const)(
|
|
"does not acquire a new chat gate lock for protected native recovery: %s",
|
|
async (admission) => {
|
|
await withTempPaperclipHome(async () => {
|
|
await fs.mkdir(resolvePaperclipInstanceRoot(), { recursive: true });
|
|
const { source, child } = await seedPreparedChatRecovery(admission);
|
|
let release!: () => void;
|
|
let locked: Promise<unknown> | undefined;
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const factory = vi.fn(() => {
|
|
throw new NativeRunnerOwnershipUnverifiedError();
|
|
});
|
|
const heartbeat = heartbeatService(db, {
|
|
nativeSessionBackendFactory: factory,
|
|
beforeChatControlRecoveryCheck: async ({ stage }) => {
|
|
if (stage !== "dispatch") return;
|
|
let ready!: () => void;
|
|
const acquired = new Promise<void>((resolve) => {
|
|
ready = resolve;
|
|
});
|
|
locked = db.transaction(async (tx) => {
|
|
await tx
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, source.issueId))
|
|
.for("update");
|
|
ready();
|
|
await held;
|
|
});
|
|
await acquired;
|
|
},
|
|
});
|
|
try {
|
|
expect(
|
|
(await heartbeat.recoverNativeRunsAfterRestart()).claims,
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
runId: child.runId,
|
|
kind: "bootstrap_incomplete",
|
|
}),
|
|
]);
|
|
await vi.waitFor(() => expect(factory).toHaveBeenCalledTimes(1), {
|
|
timeout: 3_000,
|
|
});
|
|
} finally {
|
|
release();
|
|
await locked;
|
|
await heartbeat.drainActiveRunExecutions();
|
|
}
|
|
expect((await heartbeat.getRun(child.runId))?.errorCode).not.toBe(
|
|
CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE,
|
|
);
|
|
});
|
|
},
|
|
);
|
|
|
|
it.each(["required", "historical", "invalid"] as const)(
|
|
"native preparation preserves only the current run's reserved admission evidence: %s",
|
|
async (mode) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source);
|
|
const [initial] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
const current = chatControlRecoveryAdmission(initial!, "required");
|
|
const retained =
|
|
mode === "required"
|
|
? current
|
|
: mode === "invalid"
|
|
? { ...current, runId: source.runId }
|
|
: undefined;
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runnerProfileJson: retained
|
|
? { [CHAT_CONTROL_RECOVERY_ADMISSION_KEY]: retained }
|
|
: null,
|
|
})
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
const [issue] = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, source.issueId));
|
|
await prepareNativeHeartbeatRun({
|
|
db,
|
|
run: {
|
|
...initial!,
|
|
runnerProfileJson: {
|
|
[CHAT_CONTROL_RECOVERY_ADMISSION_KEY]: {
|
|
...current,
|
|
phase: "admitted",
|
|
runId: source.runId,
|
|
},
|
|
},
|
|
},
|
|
issue: issue!,
|
|
environmentLeaseId: randomUUID(),
|
|
});
|
|
const [prepared] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
expect(
|
|
prepared?.runnerProfileJson?.[CHAT_CONTROL_RECOVERY_ADMISSION_KEY],
|
|
).toEqual(retained);
|
|
expect(readChatControlRecoveryAdmission(prepared!)).toBe(mode);
|
|
},
|
|
);
|
|
|
|
it.each(["native", "legacy_pre_provider", "legacy_unknown"] as const)("retains closed chat ancestry and current retry authority: %s", async (mode) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source, { status: "succeeded" });
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "failed",
|
|
errorCode: "workspace_busy",
|
|
error: "Workspace occupied",
|
|
runtimeMode: mode === "native" ? "native" : "legacy",
|
|
nativeIssueId: mode === "native" ? source.issueId : null,
|
|
resultJson: mode === "legacy_pre_provider"
|
|
? { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }
|
|
: null,
|
|
})
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
const heartbeat = heartbeatService(db);
|
|
const scheduled = await heartbeat.scheduleBoundedRetry(child.runId, {
|
|
retryReason: "workspace_busy",
|
|
wakeReason: "workspace_busy_retry",
|
|
delayMs: 0,
|
|
maxAttempts: 1,
|
|
});
|
|
if (mode === "legacy_unknown") {
|
|
// Current master refuses a failed legacy attempt without proof that
|
|
// provider work never began. A chat close does not weaken that guard.
|
|
expect(scheduled).toMatchObject({
|
|
outcome: "not_scheduled",
|
|
errorCode: "legacy_execution_requires_reconciliation",
|
|
});
|
|
expect(await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.retryOfRunId, child.runId))).toEqual([]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
return;
|
|
}
|
|
expect(scheduled.outcome).toBe("scheduled");
|
|
if (scheduled.outcome !== "scheduled")
|
|
throw new Error("Expected actual scheduled retry");
|
|
expect(
|
|
(
|
|
await readChatControlRecoveryStop(
|
|
db,
|
|
chatStopScope(source, scheduled.run.id),
|
|
)
|
|
).kind,
|
|
).toBe("stopped");
|
|
await heartbeat.promoteDueScheduledRetries(new Date(Date.now() + 1000));
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, scheduled.run.id))
|
|
)[0],
|
|
).toMatchObject({
|
|
status: "cancelled",
|
|
errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
});
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("defers exhausted automatic ancestry without claiming a close or launching work", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
let parentId = source.runId;
|
|
for (let index = 0; index < 64; index++)
|
|
parentId = (
|
|
await seedChatAutomaticChild(source, {
|
|
parentId,
|
|
status: index === 63 ? "queued" : "succeeded",
|
|
})
|
|
).runId;
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source, parentId)))
|
|
.kind,
|
|
).toBe("unresolved");
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, parentId))
|
|
)[0],
|
|
).toMatchObject({ status: "queued", startedAt: null, errorCode: null });
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([false, true])(
|
|
"binds a native status continuation to its applied decision and exact delivered effect (mismatch=%s)",
|
|
async (mismatch) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source, {
|
|
status: "succeeded",
|
|
});
|
|
const contractId = randomUUID();
|
|
const resultId = randomUUID();
|
|
const assessmentId = randomUUID();
|
|
const decisionId = randomUUID();
|
|
const intentId = randomUUID();
|
|
await db.insert(completionContracts).values({
|
|
id: contractId,
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
revision: 1,
|
|
schemaVersion: "paperclip.completion-contract.v1",
|
|
policyVersion: "phase6-v3",
|
|
risk: "low",
|
|
completionAuthority: "agent_claim_policy",
|
|
incompleteCriteriaPolicy: "preserve_non_terminal",
|
|
contractJson: {},
|
|
canonicalSha256: `fixture-${contractId}`,
|
|
createdByActorType: "system",
|
|
createdByActorId: "test",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
nativeIssueId: source.issueId,
|
|
completionContractId: contractId,
|
|
})
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
await db.insert(nativeRunResults).values({
|
|
id: resultId,
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
runId: child.runId,
|
|
completionContractId: contractId,
|
|
serverFingerprint: `fixture-${resultId}`,
|
|
schemaStatus: "accepted",
|
|
resultJson: {},
|
|
canonicalSha256: `fixture-${resultId}`,
|
|
});
|
|
await db.insert(workAssessments).values({
|
|
id: assessmentId,
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
runId: child.runId,
|
|
contractId,
|
|
resultId,
|
|
triggerKind: "turn_finished",
|
|
triggerActorCompanyId: source.companyId,
|
|
priorIssueStatus: "in_progress",
|
|
priorStatusVersion: 0,
|
|
policyVersion: "phase6-v3",
|
|
assessmentJson: {},
|
|
inputDigest: `fixture-${assessmentId}`,
|
|
});
|
|
await db.insert(statusDecisions).values({
|
|
id: decisionId,
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
runId: child.runId,
|
|
assessmentId,
|
|
decisionVersion: 1,
|
|
policyVersion: "phase6-v3",
|
|
fromStatus: "in_progress",
|
|
toStatus: "in_progress",
|
|
reasonCode: "response_wake",
|
|
decisionJson: {},
|
|
decisionDigest: `fixture-${decisionId}`,
|
|
applicationState: "applied",
|
|
appliedAt: new Date(),
|
|
});
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: intentId,
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_status_changed",
|
|
payload: {
|
|
issueId: source.issueId,
|
|
taskId: source.issueId,
|
|
nativeDecisionId: decisionId,
|
|
continuationKind: "same_agent",
|
|
},
|
|
requestedByActorType: "system",
|
|
requestedByActorId: "native-status-committer",
|
|
idempotencyKey: `native-status:${decisionId}:continuation`,
|
|
});
|
|
await db.insert(statusDecisionEffects).values({
|
|
companyId: source.companyId,
|
|
issueId: source.issueId,
|
|
decisionId,
|
|
ordinal: 1,
|
|
effectKind: "enqueue_continuation",
|
|
targetType: "agent_wakeup_request",
|
|
targetId: mismatch ? randomUUID() : intentId,
|
|
idempotencyKey: `native-status:${decisionId}:1`,
|
|
payload: { continuationKind: "same_agent" },
|
|
deliveryState: "delivered",
|
|
deliveredAt: new Date(),
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.dispatchPendingNativeStatusWakeups({
|
|
companyId: source.companyId,
|
|
});
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(
|
|
await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, source.companyId)),
|
|
).toHaveLength(2);
|
|
const [dispatch] = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
eq(
|
|
agentWakeupRequests.requestedByActorId,
|
|
`native-status-wake-dispatch:${intentId}`,
|
|
),
|
|
);
|
|
expect(dispatch).toMatchObject({
|
|
status: "skipped",
|
|
reason: mismatch
|
|
? CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE
|
|
: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
});
|
|
},
|
|
);
|
|
|
|
it("allows fresh Board work and coalesced user causes after a committed chat close", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source);
|
|
await db.insert(agentWakeupRequests).values({
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
source: "on_demand",
|
|
triggerDetail: "manual",
|
|
reason: "issue_commented",
|
|
payload: { issueId: source.issueId },
|
|
status: "coalesced",
|
|
runId: child.runId,
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
});
|
|
expect(
|
|
(
|
|
await readChatControlRecoveryStop(
|
|
db,
|
|
chatStopScope(source, child.runId),
|
|
)
|
|
).kind,
|
|
).toBe("clear");
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(mockAdapterExecute).toHaveBeenCalled();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
)[0]?.errorCode,
|
|
).not.toBe(CHAT_CONTROL_RECOVERY_STOP_CODE);
|
|
});
|
|
|
|
it("defers a contended chat close proof without starving another queued Board task", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const child = await seedChatAutomaticChild(source);
|
|
const boardIssueId = randomUUID();
|
|
const boardRunId = randomUUID();
|
|
const boardWakeId = randomUUID();
|
|
await db.insert(issues).values({
|
|
companyId: source.companyId,
|
|
id: boardIssueId,
|
|
title: "Fresh Board request",
|
|
status: "in_progress",
|
|
priority: "low",
|
|
assigneeAgentId: source.agentId,
|
|
issueNumber: 100,
|
|
});
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: boardWakeId,
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
source: "on_demand",
|
|
triggerDetail: "manual",
|
|
reason: "issue_commented",
|
|
status: "queued",
|
|
runId: boardRunId,
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
payload: { issueId: boardIssueId },
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: boardRunId,
|
|
companyId: source.companyId,
|
|
agentId: source.agentId,
|
|
invocationSource: "on_demand",
|
|
triggerDetail: "manual",
|
|
status: "queued",
|
|
wakeupRequestId: boardWakeId,
|
|
contextSnapshot: { issueId: boardIssueId, source: "issue.comment" },
|
|
});
|
|
let release!: () => void;
|
|
let locked!: () => void;
|
|
const holding = new Promise<void>((resolve) => {
|
|
locked = resolve;
|
|
});
|
|
const unlock = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const lock = db.transaction(async (tx) => {
|
|
await tx
|
|
.select()
|
|
.from(chatConversations)
|
|
.where(eq(chatConversations.id, source.conversationId))
|
|
.for("update");
|
|
locked();
|
|
await unlock;
|
|
});
|
|
await holding;
|
|
const heartbeat = heartbeatService(db);
|
|
try {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
)[0],
|
|
).toMatchObject({ status: "queued", startedAt: null });
|
|
expect(mockAdapterExecute).toHaveBeenCalled();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, boardRunId))
|
|
)[0]?.status,
|
|
).toBe("succeeded");
|
|
} finally {
|
|
release();
|
|
await lock;
|
|
}
|
|
await heartbeat.resumeQueuedRuns();
|
|
expect(
|
|
(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, child.runId))
|
|
)[0],
|
|
).toMatchObject({
|
|
status: "cancelled",
|
|
errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE,
|
|
});
|
|
});
|
|
|
|
it.each([false, true])(
|
|
"requires the exact native close target generation (mismatch=%s)",
|
|
async (mismatch) => {
|
|
const source = await seedCommittedChatControlStop();
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ provider: "discord" })
|
|
.where(eq(chatEndpoints.id, source.endpointId));
|
|
const interactionId = "1546815225334865972";
|
|
await db
|
|
.update(chatPublications)
|
|
.set({
|
|
idempotencyKey: `control:close:discord:${source.endpointId}:${interactionId}`,
|
|
})
|
|
.where(eq(chatPublications.id, source.publicationId));
|
|
await db.insert(chatActions).values({
|
|
companyId: source.companyId,
|
|
endpointId: source.endpointId,
|
|
conversationId: source.conversationId,
|
|
principalId: source.principalId,
|
|
kind: "discord_native_command",
|
|
providerActionId: `discord-native-command:${interactionId}`,
|
|
status: "processed",
|
|
payload: {
|
|
version: 1,
|
|
invocation: { command: "close", interactionId },
|
|
target: {
|
|
conversationId: source.conversationId,
|
|
issueId: source.issueId,
|
|
sessionGeneration: mismatch ? 2 : 1,
|
|
},
|
|
},
|
|
result: {
|
|
kind: "discord_native_command_recorded",
|
|
publicationId: source.publicationId,
|
|
},
|
|
});
|
|
expect(
|
|
(await readChatControlRecoveryStop(db, chatStopScope(source))).kind,
|
|
).toBe(mismatch ? "clear" : "stopped");
|
|
},
|
|
);
|
|
|
|
it("does not let an old agent's closed-chat stop suppress reassigned ordinary work", async () => {
|
|
const source = await seedCommittedChatControlStop();
|
|
const newAgentId = randomUUID();
|
|
const [oldAgent] = await db
|
|
.select()
|
|
.from(agents)
|
|
.where(eq(agents.id, source.agentId));
|
|
await db.insert(agents).values({
|
|
companyId: source.companyId,
|
|
id: newAgentId,
|
|
name: "New assigned agent",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: oldAgent!.adapterType,
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: newAgentId })
|
|
.where(eq(issues.id, source.issueId));
|
|
const child = await seedChatAutomaticChild(source, { status: "succeeded" });
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "cancelled", errorCode: CHAT_CONTROL_RECOVERY_STOP_CODE })
|
|
.where(eq(heartbeatRuns.id, child.runId));
|
|
const heartbeat = heartbeatService(db);
|
|
const outcome = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(outcome.operatorCancelExempted).toBe(0);
|
|
expect(outcome.skipped).toBe(0);
|
|
await heartbeat.drainActiveRunExecutions();
|
|
});
|
|
|
|
it("recovers productive chat work after its conversation is completed", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
runSource: "chat:slack",
|
|
livenessState: "advanced",
|
|
});
|
|
await bindChatConversation({
|
|
agentId,
|
|
companyId,
|
|
issueId,
|
|
state: "completed",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
const retryRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId))
|
|
.then((rows) => rows.find((row) => row.id !== runId));
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
retryReason: "issue_disposition_repair",
|
|
source: "issue.deliberate_wait_disposition_repair",
|
|
});
|
|
if (retryRun) await waitForRunToSettle(heartbeat, retryRun.id);
|
|
});
|
|
|
|
it("recovers a non-chat productive run even when its issue has an active chat conversation", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
runSource: "issue.assignment",
|
|
livenessState: "advanced",
|
|
});
|
|
await bindChatConversation({
|
|
agentId,
|
|
companyId,
|
|
issueId,
|
|
state: "active",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
const retryRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.agentId, agentId))
|
|
.then((rows) => rows.find((row) => row.id !== runId));
|
|
expect(retryRun?.contextSnapshot).toMatchObject({
|
|
issueId,
|
|
retryReason: "issue_disposition_repair",
|
|
source: "issue.deliberate_wait_disposition_repair",
|
|
});
|
|
if (retryRun) await waitForRunToSettle(heartbeat, retryRun.id);
|
|
});
|
|
|
|
it("lets a child waiting for the shared workspace run before recovering its lead", async () => {
|
|
const { companyId, agentId, issueId, runId } = await seedStrandedIssueFixture({ status: "in_progress", runStatus: "succeeded", livenessState: "advanced" });
|
|
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, paperclipWorkspace: { mode: "shared_workspace" } } }).where(eq(heartbeatRuns.id, runId));
|
|
const projectId = randomUUID(), workspaceId = randomUUID(), childId = randomUUID(), workerId = randomUUID();
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Shared project" });
|
|
await db.insert(projectWorkspaces).values({ id: workspaceId, companyId, projectId, name: "Primary", sourceType: "local_path", cwd: "/tmp/recovery-shared", isPrimary: true });
|
|
await db.update(issues).set({ projectId, projectWorkspaceId: workspaceId }).where(eq(issues.id, issueId));
|
|
await db.insert(agents).values({ id: workerId, companyId, name: "Worker", role: "engineer", status: "idle", adapterType: "codex_local", adapterConfig: {} });
|
|
await db.insert(issues).values({ id: childId, companyId, parentId: issueId, title: "Build the project", status: "in_progress", assigneeAgentId: workerId, projectId, projectWorkspaceId: workspaceId });
|
|
await db.insert(heartbeatRuns).values({ companyId, agentId: workerId, status: "scheduled_retry", scheduledRetryAt: new Date(Date.now() + 60_000), scheduledRetryReason: "workspace_busy", contextSnapshot: { issueId: childId } });
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(1);
|
|
// Once the child finishes, normal recovery can continue the lead.
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, childId));
|
|
expect((await heartbeat.reconcileStrandedAssignedIssues()).continuationRequeued).toBe(1);
|
|
const next = (await selectRecoveryRunsByAgent(agentId)).find((r) => r.id !== runId);
|
|
if (next) await waitForRunToSettle(heartbeat, next.id);
|
|
});
|
|
|
|
it("resumes a shared-workspace lead when its child needs review", async () => {
|
|
const { companyId, agentId, issueId, runId } = await seedStrandedIssueFixture({ status: "in_progress", runStatus: "succeeded", livenessState: "advanced" });
|
|
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, paperclipWorkspace: { mode: "shared_workspace" } } }).where(eq(heartbeatRuns.id, runId));
|
|
const projectId = randomUUID(), workspaceId = randomUUID(), childId = randomUUID(), workerId = randomUUID();
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Shared project" });
|
|
await db.insert(projectWorkspaces).values({ id: workspaceId, companyId, projectId, name: "Primary", sourceType: "local_path", cwd: "/tmp/recovery-shared", isPrimary: true });
|
|
await db.update(issues).set({ projectId, projectWorkspaceId: workspaceId }).where(eq(issues.id, issueId));
|
|
await db.insert(agents).values({ id: workerId, companyId, name: "Worker", role: "engineer", status: "idle", adapterType: "codex_local", adapterConfig: {} });
|
|
await db.insert(issues).values({ id: childId, companyId, parentId: issueId, title: "Review the project", status: "in_review", assigneeAgentId: workerId, projectId, projectWorkspaceId: workspaceId });
|
|
await db.insert(issueThreadInteractions).values({ companyId, issueId: childId, kind: "request_confirmation", status: "pending", addresseeAgentId: agentId, payload: { version: 1, prompt: "Review this delivery" } });
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
const next = (await selectRecoveryRunsByAgent(agentId)).find((r) => r.id !== runId);
|
|
if (next) await waitForRunToSettle(heartbeat, next.id);
|
|
});
|
|
|
|
it("reuses the raced stranded recovery issue when duplicate active recovery creation conflicts", async () => {
|
|
const { companyId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
retryReason: "issue_continuation_needed",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const results = await Promise.allSettled(
|
|
Array.from({ length: 8 }, () =>
|
|
heartbeat.reconcileStrandedAssignedIssues(),
|
|
),
|
|
);
|
|
expect(results.every((result) => result.status === "fulfilled")).toBe(true);
|
|
|
|
const actions = await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(
|
|
and(
|
|
eq(issueRecoveryActions.companyId, companyId),
|
|
eq(issueRecoveryActions.sourceIssueId, issueId),
|
|
),
|
|
);
|
|
expect(actions).toHaveLength(1);
|
|
expect(actions[0]?.attemptCount).toBeGreaterThanOrEqual(1);
|
|
const recoveries = await selectStrandedRecoveryIssuesForSource(companyId, issueId);
|
|
expect(recoveries).toHaveLength(0);
|
|
await expect(sourceBlockerIssueIds(companyId, issueId)).resolves.toEqual(
|
|
[],
|
|
);
|
|
});
|
|
|
|
it("blocks stranded recovery issues in place instead of creating nested recovery issues", async () => {
|
|
const sourceIssueId = randomUUID();
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
title: "Recover stalled issue PAP-1",
|
|
originKind: "stranded_issue_recovery",
|
|
originId: sourceIssueId,
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
await db.insert(issues).values({
|
|
id: sourceIssueId,
|
|
companyId,
|
|
title: "Original stranded source",
|
|
status: "blocked",
|
|
priority: "medium",
|
|
issueNumber: 2,
|
|
identifier: `${issuePrefix}-2`,
|
|
});
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId,
|
|
relatedIssueId: sourceIssueId,
|
|
type: "blocks",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const recoveryIssue = await selectRecoveryIssueById(issueId);
|
|
expect(recoveryIssue?.status).toBe("blocked");
|
|
expect(recoveryIssue?.assigneeAgentId).toBe(agentId);
|
|
expect(recoveryIssue?.originKind).toBe("stranded_issue_recovery");
|
|
expect(recoveryIssue?.originId).toBe(sourceIssueId);
|
|
|
|
const nestedRecoveries = await selectStrandedRecoveryIssuesForSource(companyId, issueId);
|
|
expect(nestedRecoveries).toHaveLength(0);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]?.id).toBe(runId);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain(
|
|
"Paperclip stopped trying to recover this task automatically.",
|
|
);
|
|
expect(comments[0]?.body).toContain(
|
|
"The failure details are kept with the run",
|
|
);
|
|
expect(comments[0]?.body).toContain(
|
|
"This task was created to recover another task, so Paperclip does not create another recovery task for it.",
|
|
);
|
|
await expect(
|
|
sourceBlockerIssueIds(companyId, sourceIssueId),
|
|
).resolves.toEqual([issueId]);
|
|
});
|
|
|
|
it("keeps repeated recovery failures on the same canonical recovery issue", async () => {
|
|
const sourceIssueId = randomUUID();
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "failed",
|
|
});
|
|
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
|
await db.insert(issues).values({
|
|
id: sourceIssueId,
|
|
companyId,
|
|
title: "Original stranded source",
|
|
status: "blocked",
|
|
priority: "medium",
|
|
issueNumber: 2,
|
|
identifier: `${issuePrefix}-2`,
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
title: "Recover stalled issue PAP-1",
|
|
originKind: "stranded_issue_recovery",
|
|
originId: sourceIssueId,
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId,
|
|
relatedIssueId: sourceIssueId,
|
|
type: "blocks",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const firstResult = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(firstResult.escalated).toBe(1);
|
|
expect(firstResult.issueIds).toEqual([issueId]);
|
|
|
|
const secondRunId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({
|
|
id: secondRunId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
status: "failed",
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_assigned",
|
|
source: "stranded_issue_recovery",
|
|
},
|
|
startedAt: new Date("2030-03-19T00:10:00.000Z"),
|
|
finishedAt: new Date("2030-03-19T00:15:00.000Z"),
|
|
createdAt: new Date("2030-03-19T00:10:00.000Z"),
|
|
updatedAt: new Date("2030-03-19T00:15:00.000Z"),
|
|
errorCode: "adapter_failed",
|
|
error: "adapter failed while retrying recovery issue",
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
status: "in_progress",
|
|
checkoutRunId: secondRunId,
|
|
executionRunId: null,
|
|
})
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const secondResult = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(secondResult.dispatchRequeued).toBe(0);
|
|
expect(secondResult.continuationRequeued).toBe(0);
|
|
expect(secondResult.escalated).toBe(1);
|
|
expect(secondResult.issueIds).toEqual([issueId]);
|
|
|
|
const recoveryIssuesForSource = await selectStrandedRecoveryIssuesForSource(companyId, sourceIssueId);
|
|
expect(recoveryIssuesForSource.map((issue) => issue.id)).toEqual([issueId]);
|
|
|
|
const nestedRecoveries = await selectStrandedRecoveryIssuesForSource(companyId, issueId);
|
|
expect(nestedRecoveries).toHaveLength(0);
|
|
await expect(
|
|
sourceBlockerIssueIds(companyId, sourceIssueId),
|
|
).resolves.toEqual([issueId]);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(
|
|
await selectRecoveryActionsForIssue(issueId),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
cause: "legacy_execution_requires_reconciliation",
|
|
evidence: expect.objectContaining({ runId: secondRunId }),
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("does not escalate paused-tree recovery when the automatic continuation retry was cancelled by the hold", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "cancelled",
|
|
retryReason: "issue_continuation_needed",
|
|
activePauseHold: true,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBe(1);
|
|
expect(result.issueIds).toEqual([]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_progress");
|
|
expect(issue?.checkoutRunId).toBeTruthy();
|
|
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
|
|
const blockerRelations = await db
|
|
.select()
|
|
.from(issueRelations)
|
|
.where(
|
|
and(
|
|
eq(issueRelations.companyId, companyId),
|
|
eq(issueRelations.relatedIssueId, issueId),
|
|
eq(issueRelations.type, "blocks"),
|
|
),
|
|
);
|
|
expect(blockerRelations).toHaveLength(0);
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(0);
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakeups).toHaveLength(1);
|
|
});
|
|
|
|
it("does not accept unmanaged local-background wait evidence as a live continuation path", async () => {
|
|
const localWaitEvidence = {
|
|
summary: "Started a local polling watcher and will check the log later.",
|
|
externalWait: {
|
|
kind: "local_background",
|
|
pid: 12345,
|
|
logPath: "run/watch.log",
|
|
durable: false,
|
|
},
|
|
};
|
|
const { agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
resultJson: localWaitEvidence,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown> | undefined,
|
|
).toMatchObject({
|
|
issueId,
|
|
retryReason: "issue_disposition_repair",
|
|
retryOfRunId: runId,
|
|
source: "issue.deliberate_wait_disposition_repair",
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
});
|
|
|
|
it("escalates repeated unmanaged local-background waits instead of retrying forever", async () => {
|
|
const localWaitEvidence = {
|
|
summary: "Still waiting on the local background watcher.",
|
|
externalWait: {
|
|
kind: "local_background",
|
|
pid: 12345,
|
|
logPath: "run/watch.log",
|
|
durable: false,
|
|
},
|
|
};
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
retryReason: "issue_continuation_needed",
|
|
runSource: "issue.productive_terminal_continuation_recovery",
|
|
livenessState: "advanced",
|
|
resultJson: localWaitEvidence,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
kind: "deliberate_wait_without_target", cause: "deliberate_wait_without_target",
|
|
retryReason: "issue_continuation_needed",
|
|
});
|
|
|
|
const followupRuns = await selectRecoveryRunsByAgent(agentId);
|
|
expect(followupRuns).toHaveLength(1);
|
|
});
|
|
|
|
it("preserves a persisted issue monitor as the durable external-wait path", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
monitorNextCheckAt: new Date("2026-03-19T01:00:00.000Z"),
|
|
resultJson: {
|
|
summary: "Waiting for the deploy to settle; monitor is scheduled.",
|
|
externalWait: { kind: "issue_monitor", durable: true },
|
|
},
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBe(1);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_progress");
|
|
expect(issue?.monitorNextCheckAt?.toISOString()).toBe(
|
|
"2026-03-19T01:00:00.000Z",
|
|
);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
});
|
|
|
|
it("preserves a delegated blocker edge as the durable external-wait path", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
resultJson: {
|
|
summary: "Delegated the external account check to a child task.",
|
|
externalWait: { kind: "delegated_child", durable: true },
|
|
},
|
|
});
|
|
const blockerIssueId = randomUUID();
|
|
await db.insert(issues).values({
|
|
id: blockerIssueId,
|
|
companyId,
|
|
parentId: issueId,
|
|
title: "Check external account approval",
|
|
status: "todo",
|
|
priority: "medium",
|
|
assigneeUserId: "external-owner",
|
|
responsibleUserId: "responsible-user",
|
|
issueNumber: 2,
|
|
identifier: "PAP-2",
|
|
});
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId: blockerIssueId,
|
|
relatedIssueId: issueId,
|
|
type: "blocks",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.skipped).toBe(1);
|
|
|
|
const source = await selectRecoveryIssueById(issueId);
|
|
expect(source?.status).toBe("in_progress");
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
expect(runs).toHaveLength(1);
|
|
});
|
|
|
|
it("blocks stranded in-progress work after a productive continuation retry was already used", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
retryReason: "issue_continuation_needed",
|
|
runSource: "issue.productive_terminal_continuation_recovery",
|
|
livenessState: "advanced",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
|
|
const recoveryAction = await expectSourceScopedStrandedRecoveryAction({
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
previousStatus: "in_progress",
|
|
kind: "deliberate_wait_without_target", cause: "deliberate_wait_without_target",
|
|
retryReason: "issue_continuation_needed",
|
|
});
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
expect(comments).toHaveLength(1);
|
|
expect(comments[0]?.body).toContain("bounded original-owner disposition repair");
|
|
expect(comments[0]?.body).toContain("Attempts: 1/1");
|
|
expect(recoveryAction.evidence).toMatchObject({ sourceAttemptCount: 1, sourceMaxAttempts: 1 });
|
|
expect(recoveryAction.ownerType).toBe("board");
|
|
});
|
|
|
|
async function seedNativePassiveBoardResponse(
|
|
continuationKind:
|
|
"response_wake" | "same_agent" | "retry" = "response_wake",
|
|
options: { blockingWork?: boolean; repairUsed?: boolean; assignmentWake?: boolean; objectiveUnsatisfied?: boolean } = {},
|
|
) {
|
|
const fixture = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
});
|
|
const { companyId, agentId, issueId, runId, wakeupRequestId } = fixture;
|
|
const commentId = randomUUID();
|
|
const contractId = randomUUID();
|
|
const runnerInstanceId = randomUUID();
|
|
const request = options.blockingWork ? "Is this done?" :
|
|
"Read only this newly attached TXT. Report Object, Accent color and Count. Keep the task open; no other work.";
|
|
const summary = options.blockingWork ? "Not yet. Icons, screenshots, verification and the PR remain unfinished." :
|
|
"Object: lighthouse. Accent color: amber. Count: 63.";
|
|
// PostgreSQL's default clock retains microseconds; a later JS Date in the
|
|
// same millisecond could otherwise precede this supposedly admitted source.
|
|
const sourceAt = new Date(Date.now() - 1_000);
|
|
await db.insert(issueComments).values({
|
|
id: commentId,
|
|
companyId,
|
|
issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: request,
|
|
createdAt: sourceAt,
|
|
updatedAt: sourceAt,
|
|
});
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set(options.assignmentWake ? {
|
|
status: "completed",
|
|
requestedByActorType: "system",
|
|
requestedByActorId: "issue-assignment",
|
|
payload: { issueId },
|
|
} : {
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
status: "completed",
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
payload: { issueId, commentId, ...(options.repairUsed ? { continuationIdempotencyKey: "native-completion-incomplete" } : {}) },
|
|
})
|
|
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
|
await db.insert(completionContracts).values({
|
|
id: contractId,
|
|
companyId,
|
|
issueId,
|
|
revision: 1,
|
|
schemaVersion: "paperclip.completion-contract.v1",
|
|
policyVersion: "phase6-v4",
|
|
risk: "low",
|
|
completionAuthority: "agent_claim_policy",
|
|
incompleteCriteriaPolicy: "preserve_non_terminal",
|
|
contractJson: {
|
|
revision: "1",
|
|
objective: request,
|
|
criteria: [{ id: "objective", requirement: request }],
|
|
},
|
|
canonicalSha256: `passive-board-contract-${runId}`,
|
|
createdByActorType: "system",
|
|
createdByActorId: "test",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runtimeMode: "native",
|
|
nativeIssueId: issueId,
|
|
nativeSessionId: runId,
|
|
completionContractId: contractId,
|
|
completionContractSha256: `passive-board-contract-${runId}`,
|
|
runnerInstanceId,
|
|
startedAt: new Date(),
|
|
finishedAt: new Date(),
|
|
// The old status effect mutates this presentation context. It is not the
|
|
// authority for the original user request; the durable wake above is.
|
|
contextSnapshot: {
|
|
issueId,
|
|
taskId: issueId,
|
|
source: "native_status_decision",
|
|
wakeCommentIds: [commentId],
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const port = new PaperclipControlPlanePort(db, {
|
|
companyId,
|
|
issueId,
|
|
runId,
|
|
agentId,
|
|
sessionId: runId,
|
|
completionContractId: contractId,
|
|
completionContractSha256: `passive-board-contract-${runId}`,
|
|
sourceInstanceId: runnerInstanceId,
|
|
controlPlaneSourceInstanceId: `board-control-${runId}`,
|
|
});
|
|
await port.completeRun({
|
|
result: {
|
|
schema: "paperclip.run_result.v1",
|
|
reportedWorkDisposition: "yielded",
|
|
summary,
|
|
continuation: {
|
|
kind: continuationKind,
|
|
summary:
|
|
"Task remains open per the latest comment; wait for the next response.",
|
|
idempotencyKey: `board-wait-${runId}`,
|
|
},
|
|
completionClaim: {
|
|
contractRevision: "1",
|
|
objectiveSatisfied: !options.objectiveUnsatisfied,
|
|
criteria: [
|
|
{ criterionId: "objective", status: options.objectiveUnsatisfied ? "not_satisfied" : "satisfied",
|
|
evidenceRefs: options.objectiveUnsatisfied ? ["catalog:launch_export:quarantined"] : [] },
|
|
],
|
|
remainingWork: options.blockingWork ? [{ description: "Finish icons, screenshots, verification and PR", blocksCompletion: true }] : [],
|
|
},
|
|
evidence: options.objectiveUnsatisfied ? [{ ref: "catalog:launch_export:quarantined" }] : [],
|
|
verification: options.objectiveUnsatisfied ? [{ commandOrCheck: "GET /api/tool-connections/{connectionId}/catalog",
|
|
status: "passed", detail: "Catalog shows launch_export with status quarantined." }] : [],
|
|
attentionRequests: [],
|
|
artifacts: [],
|
|
},
|
|
terminal: {
|
|
schema: "paperclip.prp.terminal.v1",
|
|
runTerminalState: "succeeded",
|
|
turnTerminalState: "completed",
|
|
reportedWorkDisposition: "yielded",
|
|
},
|
|
});
|
|
return { ...fixture, commentId, contractId, summary };
|
|
}
|
|
|
|
it.each(["issue_commented", "issue_reopened_via_comment"])("commits a native passive Board response without manufacturing immediate work (%s)", async (reason) => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
await db.update(agentWakeupRequests).set({ reason }).where(eq(agentWakeupRequests.id, fixture.wakeupRequestId));
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
const decisions = await db
|
|
.select()
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId));
|
|
expect(decisions).toEqual([
|
|
expect.objectContaining({
|
|
reasonCode: "board_response_waiting",
|
|
toStatus: "in_progress",
|
|
applicationState: "applied",
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, fixture.companyId)),
|
|
).toHaveLength(1);
|
|
const heartbeat = heartbeatService(db);
|
|
expect(
|
|
(await heartbeat.reconcileStrandedAssignedIssues()).continuationRequeued,
|
|
).toBe(0);
|
|
expect(
|
|
(await heartbeat.reconcileStrandedAssignedIssues()).continuationRequeued,
|
|
).toBe(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, fixture.companyId)),
|
|
).toHaveLength(1);
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, fixture.issueId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
status: "in_progress",
|
|
assigneeAgentId: fixture.agentId,
|
|
}),
|
|
]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not queue a continuation from a latest run it read while that run was still finishing", async () => {
|
|
const { companyId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
});
|
|
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, runId));
|
|
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
|
const enqueueWakeup = vi.fn(async () => null);
|
|
const recovery = recoveryService(db, {
|
|
enqueueWakeup,
|
|
afterStrandedLatestRunRead: async (read) => {
|
|
if (read.runId !== runId) return;
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
|
await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId));
|
|
},
|
|
});
|
|
|
|
const result = await recovery.reconcileStrandedAssignedIssues({ companyId, issueId });
|
|
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(enqueueWakeup).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("leaves a chat turn that yielded to wait for a person without starting another run", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { blockingWork: true, objectiveUnsatisfied: true });
|
|
const previousSettings = await instanceSettingsService(db).getExperimental();
|
|
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true });
|
|
try {
|
|
await db.update(issues).set({ conversationAgentId: fixture.agentId, conversationUserId: "responsible-user",
|
|
conversationState: "active" }).where(eq(issues.id, fixture.issueId));
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
const [finalized] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
|
const { finalizationReasonCode: _reason, decisionId: _decision, assessmentId: _assessment, ...completionResult } =
|
|
finalized!.resultJson ?? {};
|
|
await db.update(heartbeatRuns).set({ livenessState: "blocked", livenessReason: "Run output declared a concrete blocker",
|
|
resultJson: completionResult }).where(eq(heartbeatRuns.id, fixture.runId));
|
|
const heartbeat = heartbeatService(db);
|
|
for (let sweep = 0; sweep < 2; sweep += 1) {
|
|
const recovery = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(recovery.continuationRequeued + recovery.escalated).toBe(0);
|
|
}
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, fixture.companyId))).toHaveLength(1);
|
|
expect(await db.select().from(issues).where(eq(issues.id, fixture.issueId))).toEqual([
|
|
expect.objectContaining({ status: "in_progress", assigneeAgentId: fixture.agentId }),
|
|
]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
|
|
expect(await hasCommittedNativeConversationTurnWait(db, fixture)).toBe(true);
|
|
expect(await hasCommittedNativeConversationTurnWait(db, { ...fixture, agentId: randomUUID() })).toBe(false);
|
|
} finally {
|
|
await instanceSettingsService(db).updateExperimental({ enableAgentChat: previousSettings.enableAgentChat });
|
|
}
|
|
});
|
|
|
|
it("parks a native response_wake that no response admitted instead of waking the same agent again", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { assignmentWake: true });
|
|
expect(await readNativeBoardResponseWaitSource(db, fixture)).toBeNull();
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
const heartbeat = heartbeatService(db);
|
|
for (let sweep = 0; sweep < 3; sweep += 1) {
|
|
await heartbeat.dispatchPendingNativeStatusWakeups({ companyId: fixture.companyId });
|
|
const recovery = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(recovery.continuationRequeued + recovery.escalated).toBe(0);
|
|
}
|
|
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId))).toEqual([
|
|
expect.objectContaining({ reasonCode: "response_wake_waiting_for_input", toStatus: "in_progress", applicationState: "applied" }),
|
|
]);
|
|
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(1);
|
|
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, fixture.companyId))).toHaveLength(1);
|
|
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId))).toHaveLength(0);
|
|
expect(await db.select().from(issues).where(eq(issues.id, fixture.issueId))).toEqual([
|
|
expect.objectContaining({ status: "in_progress", assigneeAgentId: fixture.agentId }),
|
|
]);
|
|
expect(await executionProjectionForRun(db, fixture.companyId, fixture.runId))
|
|
.toMatchObject({ phase: "waiting_for_answer", label: "Waiting for a reply" });
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, fixture.issueId));
|
|
expect(await executionProjectionForRun(db, fixture.companyId, fixture.runId))
|
|
.toMatchObject({ phase: "completed", label: "Completed" });
|
|
});
|
|
|
|
it.each([
|
|
{ saved: "before", read: "none", delivered: true },
|
|
{ saved: "after", read: "none", delivered: false },
|
|
{ saved: "after", read: "after the child finished", delivered: true },
|
|
{ saved: "after", read: "while the child was open", delivered: false },
|
|
] as const)("counts a child result as read by the finishing parent run (saved $saved the run started, read: $read)", async ({
|
|
saved: savedRelativeToStart, read, delivered,
|
|
}) => {
|
|
const expectedStatus = delivered ? "done" : "in_progress";
|
|
const expectedReason = delivered ? "completion_claim_policy_accepted" : "native_child_completion_pending";
|
|
const fixture = await seedStrandedIssueFixture({ status: "in_progress", runStatus: "succeeded", livenessState: "advanced" });
|
|
const { companyId, agentId, issueId, runId } = fixture;
|
|
const childId = randomUUID();
|
|
const contractId = randomUUID();
|
|
const runnerInstanceId = randomUUID();
|
|
const runStartedAt = new Date(Date.now() - 60_000);
|
|
const childResultSavedAt = new Date(runStartedAt.getTime() + (savedRelativeToStart === "before" ? -30_000 : 30_000));
|
|
await db.insert(issues).values({ id: childId, companyId, parentId: issueId, title: "Child ledger", status: "done",
|
|
priority: "medium", responsibleUserId: "responsible-user" });
|
|
const [childResult] = await db.insert(agentWakeupRequests).values({
|
|
companyId, agentId, source: "automation", triggerDetail: "system", reason: "issue_execution_deferred",
|
|
requestedByActorType: "system", requestedByActorId: `native-status-wake-dispatch:${randomUUID()}`,
|
|
status: "deferred_issue_execution", createdAt: childResultSavedAt, updatedAt: childResultSavedAt,
|
|
payload: { issueId, _paperclipWakeContext: {
|
|
issueId, wakeReason: "issue_children_completed", source: "native_status_decision",
|
|
nativeChildCompletionDecisionId: randomUUID(), completedChildIssueId: childId, childIssueIds: [childId],
|
|
childIssueSummaries: [{ id: childId, status: "done", summary: "Ledger saved." }],
|
|
} },
|
|
}).returning();
|
|
await db.insert(completionContracts).values({
|
|
id: contractId, companyId, issueId, revision: 1, schemaVersion: "paperclip.completion-contract.v1",
|
|
policyVersion: "phase6-v4", risk: "low", completionAuthority: "agent_claim_policy",
|
|
incompleteCriteriaPolicy: "preserve_non_terminal",
|
|
contractJson: { revision: "1", objective: "Merge the child ledgers.", criteria: [{ id: "objective", requirement: "Merge the child ledgers." }] },
|
|
canonicalSha256: `child-result-contract-${runId}`, createdByActorType: "system", createdByActorId: "test",
|
|
});
|
|
await db.update(heartbeatRuns).set({
|
|
runtimeMode: "native", nativeIssueId: issueId, nativeSessionId: runId, completionContractId: contractId,
|
|
completionContractSha256: `child-result-contract-${runId}`, runnerInstanceId,
|
|
startedAt: runStartedAt, finishedAt: new Date(),
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
await db.update(issues).set({ executionRunId: runId, executionLockedAt: runStartedAt }).where(eq(issues.id, issueId));
|
|
if (read !== "none") {
|
|
if (read === "while the child was open") await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, childId));
|
|
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, runId));
|
|
const reader = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
|
|
try {
|
|
const context = await reader.execute({ tool: "get_task_context", callId: `context-${runId}`, arguments: {} });
|
|
expect((context as { childTasks: Array<{ id: string }> }).childTasks.map(task => task.id)).toEqual([childId]);
|
|
} finally { reader.close(); }
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, childId));
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
|
}
|
|
await db.insert(issueComments).values({ companyId, issueId, authorType: "agent", authorAgentId: agentId,
|
|
createdByRunId: runId, body: "Both children are done; merged their ledgers. Task complete." });
|
|
await new PaperclipControlPlanePort(db, {
|
|
companyId, issueId, runId, agentId, sessionId: runId, completionContractId: contractId,
|
|
completionContractSha256: `child-result-contract-${runId}`, sourceInstanceId: runnerInstanceId,
|
|
controlPlaneSourceInstanceId: `child-result-control-${runId}`,
|
|
}).completeRun({
|
|
result: {
|
|
schema: "paperclip.run_result.v1", reportedWorkDisposition: "done",
|
|
summary: "Both children are done; merged their ledgers. Task complete.",
|
|
completionClaim: { contractRevision: "1", objectiveSatisfied: true,
|
|
criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }], remainingWork: [] },
|
|
evidence: [], verification: [], attentionRequests: [], artifacts: [],
|
|
},
|
|
terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded",
|
|
turnTerminalState: "completed", reportedWorkDisposition: "done" },
|
|
});
|
|
|
|
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
await createWakeQueue(db, {
|
|
resolveResponsibleUserId: async () => "responsible-user",
|
|
getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }),
|
|
resolveSessionBeforeForWakeup: async () => null,
|
|
wakeAdmissionHelpers: {} as Parameters<typeof createWakeQueue>[1]["wakeAdmissionHelpers"],
|
|
recovery: { escalateStrandedAssignedIssue: async () => {}, escalateStrandedRecoveryIssueInPlace: async () => {} },
|
|
}).releaseIssueExecution({ companyId, runId, now: new Date() });
|
|
|
|
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId))).toEqual([
|
|
expect.objectContaining({ reasonCode: expectedReason, toStatus: expectedStatus, applicationState: "applied" }),
|
|
]);
|
|
expect(await db.select().from(issues).where(eq(issues.id, issueId)))
|
|
.toEqual([expect.objectContaining({ status: expectedStatus })]);
|
|
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
|
|
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, childResult!.id));
|
|
if (delivered) {
|
|
expect(wake).toMatchObject({ status: "cancelled", runId: null });
|
|
expect(runs).toHaveLength(1);
|
|
} else {
|
|
const successor = runs.find((run) => run.id !== runId);
|
|
expect(runs).toHaveLength(2);
|
|
expect(wake).toMatchObject({ runId: successor!.id });
|
|
expect(successor!.contextSnapshot).toMatchObject({ wakeReason: "issue_children_completed",
|
|
childIssueSummaries: [{ id: childId, status: "done", summary: "Ledger saved." }] });
|
|
}
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("delays a no-progress native continuation until the rewake cooldown instead of dropping it", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse("same_agent", { assignmentWake: true });
|
|
const finishedAt = new Date(Date.now() - 30_000);
|
|
const priorRunId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: priorRunId, companyId: fixture.companyId, agentId: fixture.agentId,
|
|
invocationSource: "assignment", status: "succeeded", startedAt: new Date(finishedAt.getTime() - 5_000), finishedAt,
|
|
contextSnapshot: { issueId: fixture.issueId } });
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
const [intent] = await db.select().from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.companyId, fixture.companyId), eq(agentWakeupRequests.requestedByActorId, "native-status-committer")));
|
|
expect(intent?.payload).toMatchObject({ continuationKind: "same_agent" });
|
|
const heartbeat = heartbeatService(db);
|
|
const deadlines: number[] = [];
|
|
const dispatch = () => heartbeat.dispatchPendingNativeStatusWakeups({
|
|
companyId: fixture.companyId, requestId: intent!.id, onDeferredDeadline: (at) => deadlines.push(at),
|
|
});
|
|
const throttled = () => db.select().from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.companyId, fixture.companyId), eq(agentWakeupRequests.reason, "issue_rewake_throttled")));
|
|
const runCount = async () => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, fixture.companyId))).length;
|
|
|
|
await dispatch();
|
|
await dispatch();
|
|
const [receipt] = await throttled();
|
|
const nextAllowedAt = Date.parse(String((receipt?.payload as { heartbeatSkip?: { nextAllowedAt?: string } } | null)?.heartbeatSkip?.nextAllowedAt));
|
|
expect(deadlines).toEqual([nextAllowedAt, nextAllowedAt]);
|
|
expect(await throttled()).toHaveLength(1);
|
|
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, intent!.id)))
|
|
.toEqual([expect.objectContaining({ status: "queued", runId: null })]);
|
|
expect(await runCount()).toBe(2);
|
|
|
|
const past = new Date(Date.now() - 30 * 60_000);
|
|
await db.update(heartbeatRuns).set({ finishedAt: past }).where(eq(heartbeatRuns.companyId, fixture.companyId));
|
|
await db.update(agentWakeupRequests).set({
|
|
payload: sql`jsonb_set(${agentWakeupRequests.payload}, '{heartbeatSkip,nextAllowedAt}', to_jsonb(${past.toISOString()}::text))`,
|
|
}).where(eq(agentWakeupRequests.id, receipt!.id));
|
|
await dispatch();
|
|
expect(await runCount()).toBe(3);
|
|
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, intent!.id)))
|
|
.toEqual([expect.objectContaining({ status: "coalesced", runId: expect.any(String) })]);
|
|
});
|
|
|
|
it("rejects an unfinished native response wait while the finish report is still correctable", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { blockingWork: true });
|
|
const [stored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId));
|
|
const result = stored!.resultJson.result as PrpStructuredRunResult;
|
|
await expect(nativeCompletionFeedback(db, fixture.runId, result)).rejects.toThrow("blocking remaining work without a pending wait condition");
|
|
await expect(nativeCompletionFeedback(db, fixture.runId, {
|
|
...result, continuation: { ...result.continuation!, kind: "same_agent" },
|
|
})).resolves.toContain("accepted");
|
|
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId))).toHaveLength(0);
|
|
});
|
|
|
|
it.each([false, true])("bounds unfinished native response wait repair across repeated finalization (used=%s)", async (repairUsed) => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { blockingWork: true, repairUsed });
|
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
}
|
|
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId));
|
|
expect(decision?.reasonCode).toBe(repairUsed ? "prior_status_preserved_no_live_path" : "completion_evidence_incomplete");
|
|
expect(decision?.decisionJson).toMatchObject({
|
|
boardResponseWait: { sourceCommentId: fixture.commentId },
|
|
boardResponseWaitOrigin: { sourceCommentId: fixture.commentId },
|
|
});
|
|
expect(await db.select().from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId))).toHaveLength(0);
|
|
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId));
|
|
expect(wakes).toHaveLength(repairUsed ? 1 : 2);
|
|
if (!repairUsed) expect(wakes.find((wake) => wake.id !== fixture.wakeupRequestId)?.payload).toMatchObject({
|
|
continuationKind: "same_agent", continuationIdempotencyKey: "native-completion-incomplete",
|
|
});
|
|
const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId));
|
|
expect(actions).toHaveLength(repairUsed ? 1 : 0);
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(false);
|
|
});
|
|
|
|
it.each(["question", "approval", "dependency", "pause", "conversation"] as const)(
|
|
"preserves a real wait when an unfinished native response reports %s",
|
|
async (gate) => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { blockingWork: true });
|
|
if (gate === "question") await db.insert(issueThreadInteractions).values({
|
|
companyId: fixture.companyId, issueId: fixture.issueId, kind: "ask_user_questions", status: "pending",
|
|
sourceRunId: fixture.runId, createdByUserId: "responsible-user", payload: { version: 1, questions: [{ id: "account", prompt: "Which account should I use?", selectionMode: "single", required: true, options: [{ id: "primary", label: "Primary account" }] }] },
|
|
});
|
|
if (gate === "approval") {
|
|
const [approval] = await db.insert(approvals).values({ companyId: fixture.companyId, type: "hire_agent", status: "pending", payload: {} }).returning();
|
|
await db.insert(issueApprovals).values({ companyId: fixture.companyId, issueId: fixture.issueId, approvalId: approval!.id });
|
|
}
|
|
if (gate === "dependency") {
|
|
const [dependency] = await db.insert(issues).values({ companyId: fixture.companyId, title: "Required dependency", status: "todo" }).returning();
|
|
await db.insert(issueRelations).values({ companyId: fixture.companyId, issueId: dependency!.id, relatedIssueId: fixture.issueId, type: "blocks" });
|
|
}
|
|
if (gate === "pause") await db.insert(issueTreeHolds).values({ companyId: fixture.companyId, rootIssueId: fixture.issueId,
|
|
mode: "pause", status: "active", reason: "Operator pause", releasePolicy: { strategy: "manual" } });
|
|
if (gate === "conversation") await db.update(issues).set({ conversationAgentId: fixture.agentId,
|
|
conversationUserId: "responsible-user", conversationState: "active" }).where(eq(issues.id, fixture.issueId));
|
|
const [stored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId));
|
|
await expect(nativeCompletionFeedback(db, fixture.runId, stored!.resultJson.result as PrpStructuredRunResult)).resolves.toContain("accepted");
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(1);
|
|
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId));
|
|
expect(decision?.reasonCode).toBe({ question: "governed_response_waiting", approval: "governed_response_waiting",
|
|
dependency: "durable_dependency_blocker_bound", pause: "response_wait_pause_preserved", conversation: "conversation_turn_finished" }[gate]);
|
|
},
|
|
);
|
|
|
|
it.each([false, true])("reconsiders a legacy committed unfinished Board wait (superseded=%s)", async (superseded) => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { blockingWork: true });
|
|
const source = await readNativeBoardResponseWaitSource(db, fixture);
|
|
const origin = await readNativeBoardResponseWaitOrigin(db, fixture);
|
|
// Build the assessment, then emulate the old policy's accepted passive wait.
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", failpoint: "status_projection" });
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId));
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, fixture.issueId));
|
|
await commitNativeStatusDecision({ db, companyId: fixture.companyId, issueId: fixture.issueId, runId: fixture.runId,
|
|
assessmentId: coordinator!.assessmentId!, priorStatus: issue!.status, priorStatusVersion: issue!.statusVersion,
|
|
priorDecisionId: issue!.lastStatusDecisionId,
|
|
decision: { policyVersion: "phase6-v14", statusAction: "in_progress", toStatus: "in_progress",
|
|
reasonCode: "board_response_waiting", unblockDescriptor: null, effects: [] },
|
|
requireBoardResponseWaitSource: source!.source, requireBoardResponseWaitOrigin: origin!,
|
|
});
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(false);
|
|
if (superseded) {
|
|
await db.update(issueComments).set({ body: "Stop; I changed the request", updatedAt: new Date() }).where(eq(issueComments.id, fixture.commentId));
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
} else {
|
|
const recovery = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(recovery.escalated + recovery.continuationRequeued).toBe(1);
|
|
}
|
|
});
|
|
|
|
it("does not repair unfinished native work after its Board comment is superseded", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", { blockingWork: true });
|
|
await db.update(issueComments).set({ body: "Stop; scope changed", updatedAt: new Date() }).where(eq(issueComments.id, fixture.commentId));
|
|
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId));
|
|
expect(decision?.reasonCode).toBe("board_response_wait_superseded");
|
|
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(1);
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
});
|
|
|
|
describe("paused maintenance over committed native passive waits", () => {
|
|
async function seedPassive(kind: "board" | "chat") {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
let chat: Awaited<ReturnType<typeof bindChatConversation>> | undefined;
|
|
if (kind === "chat") {
|
|
chat = await bindChatConversation({ ...fixture, state: "active" });
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ providerAccountId: "test-workspace" })
|
|
.where(eq(chatEndpoints.id, chat.endpointId));
|
|
await db
|
|
.update(chatConversations)
|
|
.set({ isDirectMessage: true })
|
|
.where(eq(chatConversations.id, chat.conversationId));
|
|
const principalId = randomUUID();
|
|
const deliveryId = randomUUID();
|
|
await db
|
|
.insert(chatExternalPrincipals)
|
|
.values({
|
|
id: principalId,
|
|
companyId: fixture.companyId,
|
|
provider: "slack",
|
|
providerAccountId: "test-workspace",
|
|
externalId: randomUUID(),
|
|
});
|
|
await db
|
|
.insert(chatDeliveries)
|
|
.values({
|
|
id: deliveryId,
|
|
companyId: fixture.companyId,
|
|
endpointId: chat.endpointId,
|
|
conversationId: chat.conversationId,
|
|
principalId,
|
|
providerEventId: randomUUID(),
|
|
deduplicationKey: randomUUID(),
|
|
eventKind: "message",
|
|
normalizedEvent: {},
|
|
state: "processed",
|
|
processedAt: new Date(),
|
|
});
|
|
await db
|
|
.insert(chatMessageLinks)
|
|
.values({
|
|
companyId: fixture.companyId,
|
|
endpointId: chat.endpointId,
|
|
conversationId: chat.conversationId,
|
|
deliveryId,
|
|
commentId: fixture.commentId,
|
|
providerMessageId: "passive-message",
|
|
direction: "inbound",
|
|
});
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({
|
|
source: "assignment",
|
|
reason: "External chat message received",
|
|
payload: {
|
|
issueId: fixture.issueId,
|
|
wakeCommentId: fixture.commentId,
|
|
},
|
|
})
|
|
.where(eq(agentWakeupRequests.id, fixture.wakeupRequestId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "running",
|
|
contextSnapshot: {
|
|
issueId: fixture.issueId,
|
|
source: "chat:slack",
|
|
paperclipHarnessCheckedOut: true,
|
|
wakeCommentId: fixture.commentId,
|
|
wakeCommentIds: [fixture.commentId],
|
|
paperclipWake: {
|
|
externalChatProvider: "slack",
|
|
checkedOutByHarness: true,
|
|
issue: { id: fixture.issueId },
|
|
commentIds: [fixture.commentId],
|
|
},
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, fixture.runId));
|
|
await db
|
|
.update(issues)
|
|
.set({ executionRunId: fixture.runId })
|
|
.where(eq(issues.id, fixture.issueId));
|
|
}
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(
|
|
await db
|
|
.select({ reason: statusDecisions.reasonCode })
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId)),
|
|
).toEqual([
|
|
{
|
|
reason:
|
|
kind === "board"
|
|
? "board_response_waiting"
|
|
: "external_chat_response_waiting",
|
|
},
|
|
]);
|
|
await db
|
|
.update(agents)
|
|
.set({ status: "paused" })
|
|
.where(eq(agents.id, fixture.agentId));
|
|
return { ...fixture, chat };
|
|
}
|
|
|
|
it.each(["board", "chat"] as const)(
|
|
"preserves the exact %s passive receipt across repeated paused restart sweeps",
|
|
async (kind) => {
|
|
const f = await seedPassive(kind);
|
|
const before = await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.issueId, f.issueId));
|
|
const heartbeat = heartbeatService(db);
|
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.issueIds).not.toContain(f.issueId);
|
|
}
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, f.issueId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
status: "in_progress",
|
|
assigneeAgentId: f.agentId,
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, f.issueId)),
|
|
).toEqual([]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.issueId, f.issueId)),
|
|
).toEqual(before);
|
|
expect(
|
|
await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, f.companyId)),
|
|
).toEqual([{ id: f.runId }]);
|
|
expect(
|
|
await db
|
|
.select({ id: agentWakeupRequests.id })
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, f.companyId)),
|
|
).toEqual([{ id: f.wakeupRequestId }]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
"uncommitted",
|
|
"superseded_decision",
|
|
"newer_request",
|
|
"edited_source",
|
|
"failed_run",
|
|
"terminated_agent",
|
|
"reassigned",
|
|
"revoked_destination",
|
|
"malformed_source",
|
|
"pending_interaction",
|
|
"pending_approval",
|
|
] as const)(
|
|
"keeps ordinary escalation when a paused chat wait is not current (%s)",
|
|
async (mode) => {
|
|
const f = await seedPassive("chat");
|
|
if (mode === "uncommitted")
|
|
await db
|
|
.update(nativeRunFinalizations)
|
|
.set({ phase: "retryable_failure" })
|
|
.where(eq(nativeRunFinalizations.runId, f.runId));
|
|
if (mode === "superseded_decision")
|
|
await db
|
|
.update(issues)
|
|
.set({ lastStatusDecisionId: null })
|
|
.where(eq(issues.id, f.issueId));
|
|
if (mode === "newer_request")
|
|
await db
|
|
.insert(issueComments)
|
|
.values({
|
|
companyId: f.companyId,
|
|
issueId: f.issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "A new independent request needs attention",
|
|
});
|
|
if (mode === "edited_source")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ body: "Changed source", updatedAt: new Date() })
|
|
.where(eq(issueComments.id, f.commentId));
|
|
if (mode === "failed_run")
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "failed", errorCode: "adapter_failed" })
|
|
.where(eq(heartbeatRuns.id, f.runId));
|
|
if (mode === "terminated_agent")
|
|
await db
|
|
.update(agents)
|
|
.set({ status: "terminated" })
|
|
.where(eq(agents.id, f.agentId));
|
|
if (mode === "reassigned") {
|
|
const next = randomUUID();
|
|
await db
|
|
.insert(agents)
|
|
.values({
|
|
id: next,
|
|
companyId: f.companyId,
|
|
name: "Paused new assignee",
|
|
role: "engineer",
|
|
status: "paused",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: next })
|
|
.where(eq(issues.id, f.issueId));
|
|
}
|
|
if (mode === "revoked_destination")
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ allowDirectMessages: false })
|
|
.where(eq(chatEndpoints.id, f.chat!.endpointId));
|
|
if (mode === "malformed_source") {
|
|
const [run] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, f.runId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
...run!.contextSnapshot,
|
|
wakeCommentIds: ["-".repeat(36)],
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, f.runId));
|
|
}
|
|
if (mode === "pending_interaction")
|
|
await db
|
|
.insert(issueThreadInteractions)
|
|
.values({
|
|
companyId: f.companyId,
|
|
issueId: f.issueId,
|
|
kind: "request_confirmation",
|
|
status: "pending",
|
|
sourceRunId: f.runId,
|
|
createdByUserId: "responsible-user",
|
|
payload: { version: 1, prompt: "Review before continuing" },
|
|
});
|
|
if (mode === "pending_approval") {
|
|
const approvalId = randomUUID();
|
|
await db
|
|
.insert(approvals)
|
|
.values({
|
|
id: approvalId,
|
|
companyId: f.companyId,
|
|
type: "hire_agent",
|
|
status: "pending",
|
|
requestedByUserId: "responsible-user",
|
|
payload: {},
|
|
});
|
|
await db
|
|
.insert(issueApprovals)
|
|
.values({ companyId: f.companyId, issueId: f.issueId, approvalId });
|
|
}
|
|
const result =
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(
|
|
(await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]
|
|
?.status,
|
|
).toBe("blocked");
|
|
expect(
|
|
await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, f.companyId)),
|
|
).toEqual([{ id: f.runId }]);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it("preserves existing error-agent passive wait behavior without treating it as paused", async () => {
|
|
const f = await seedPassive("chat");
|
|
await db
|
|
.update(agents)
|
|
.set({ status: "error" })
|
|
.where(eq(agents.id, f.agentId));
|
|
const result =
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(
|
|
(await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]
|
|
?.status,
|
|
).toBe("in_progress");
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["edited_source", "newer_request"] as const)(
|
|
"does not use an obsolete Board wait to suppress paused recovery (%s)",
|
|
async (mode) => {
|
|
const f = await seedPassive("board");
|
|
if (mode === "edited_source")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ body: "Changed Board source", updatedAt: new Date() })
|
|
.where(eq(issueComments.id, f.commentId));
|
|
else
|
|
await db
|
|
.insert(issueComments)
|
|
.values({
|
|
companyId: f.companyId,
|
|
issueId: f.issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "New Board request",
|
|
});
|
|
const result =
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(
|
|
(await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]
|
|
?.status,
|
|
).toBe("blocked");
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
});
|
|
|
|
it("materializes the accepted native passive Board answer privately in the decision commit", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
await bindChatConversation({ ...fixture, state: "active" });
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
const comments = await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId));
|
|
expect(comments).toEqual([
|
|
expect.objectContaining({
|
|
body: fixture.summary,
|
|
authorAgentId: fixture.agentId,
|
|
}),
|
|
]);
|
|
expect(comments[0]?.metadata?.authorizationReason).toBe(
|
|
"internal_agent_write",
|
|
);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(chatPublications)
|
|
.where(eq(chatPublications.companyId, fixture.companyId)),
|
|
).toHaveLength(0);
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it("rolls the native passive Board answer back with its rejected decision, then recovers once", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
expect(
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
failpoint: "status_projection",
|
|
}),
|
|
).toMatchObject({ phase: "retryable_failure" });
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(false);
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it.each([
|
|
"source_edit",
|
|
"source_delete",
|
|
"different_user",
|
|
"wake_actor",
|
|
"wake_reason",
|
|
"wake_run",
|
|
"native_issue",
|
|
"new_comment",
|
|
"reassignment",
|
|
"pending_question",
|
|
] as const)(
|
|
"does not use stale native passive Board authority after %s",
|
|
async (change) => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
expect(
|
|
await readNativeBoardResponseWaitSource(db, fixture),
|
|
).not.toBeNull();
|
|
if (change === "wake_reason")
|
|
await db.update(agentWakeupRequests).set({ reason: "issue_continuation_needed" }).where(eq(agentWakeupRequests.id, fixture.wakeupRequestId));
|
|
if (change === "source_edit")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ body: "Changed request", updatedAt: new Date() })
|
|
.where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "source_delete")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ deletedAt: new Date() })
|
|
.where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "different_user")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ authorUserId: "other-user" })
|
|
.where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "wake_actor")
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ requestedByActorType: "system" })
|
|
.where(eq(agentWakeupRequests.id, fixture.wakeupRequestId));
|
|
if (change === "wake_run")
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ runId: randomUUID() })
|
|
.where(eq(agentWakeupRequests.id, fixture.wakeupRequestId));
|
|
if (change === "native_issue") {
|
|
// Accepted results FK-bind nativeIssueId, so test a foreign claimed
|
|
// issue instead of manufacturing a database state PostgreSQL rejects.
|
|
expect(
|
|
await readNativeBoardResponseWaitSource(db, {
|
|
...fixture,
|
|
issueId: randomUUID(),
|
|
}),
|
|
).toBeNull();
|
|
return;
|
|
}
|
|
if (change === "new_comment")
|
|
await db.insert(issueComments).values({
|
|
companyId: fixture.companyId,
|
|
issueId: fixture.issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "Now do the next explicit request.",
|
|
});
|
|
if (change === "reassignment")
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: null, assigneeUserId: "responsible-user" })
|
|
.where(eq(issues.id, fixture.issueId));
|
|
if (change === "pending_question")
|
|
await db.insert(issueThreadInteractions).values({
|
|
companyId: fixture.companyId,
|
|
issueId: fixture.issueId,
|
|
sourceRunId: fixture.runId,
|
|
kind: "ask_user_questions",
|
|
status: "pending",
|
|
continuationPolicy: "wake_assignee",
|
|
payload: { version: 1, questions: [] },
|
|
});
|
|
expect(await readNativeBoardResponseWaitSource(db, fixture)).toBeNull();
|
|
},
|
|
);
|
|
|
|
it.each(["same_agent", "retry"] as const)(
|
|
"preserves productive native Board %s continuations",
|
|
async (kind) => {
|
|
const fixture = await seedNativePassiveBoardResponse(kind);
|
|
expect(await readNativeBoardResponseWaitSource(db, fixture)).toBeNull();
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId)),
|
|
).toEqual([
|
|
expect.objectContaining({ reasonCode: "live_continuation_registered" }),
|
|
]);
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(
|
|
false,
|
|
);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(statusDecisionEffects)
|
|
.where(
|
|
and(
|
|
eq(statusDecisionEffects.companyId, fixture.companyId),
|
|
eq(statusDecisionEffects.effectKind, "enqueue_continuation"),
|
|
),
|
|
),
|
|
).toHaveLength(1);
|
|
},
|
|
);
|
|
|
|
it.each(
|
|
(["board_response_waiting", "completion_evidence_incomplete", "prior_status_preserved_no_live_path"] as const)
|
|
.flatMap((reasonCode) => (["edited", "deleted", "newer_comment", "wake_actor"] as const)
|
|
.map((change) => ({ reasonCode, change }))),
|
|
)("rechecks native Board source inside the status transaction ($reasonCode, $change)", async ({ reasonCode, change }) => {
|
|
const fixture = await seedNativePassiveBoardResponse("response_wake", {
|
|
blockingWork: reasonCode !== "board_response_waiting",
|
|
});
|
|
const expected = await readNativeBoardResponseWaitSource(db, fixture);
|
|
const origin = await readNativeBoardResponseWaitOrigin(db, fixture);
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
failpoint: "status_projection",
|
|
});
|
|
const [coordinator] = await db
|
|
.select()
|
|
.from(nativeRunFinalizations)
|
|
.where(eq(nativeRunFinalizations.runId, fixture.runId));
|
|
const [issue] = await db
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, fixture.issueId));
|
|
const recoveryActionsBefore = await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId));
|
|
if (change === "edited") await db
|
|
.update(issueComments)
|
|
.set({ body: "A later edit revoked this result", updatedAt: new Date() })
|
|
.where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "deleted") await db.update(issueComments)
|
|
.set({ deletedAt: new Date() }).where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "newer_comment") await db.insert(issueComments).values({
|
|
companyId: fixture.companyId, issueId: fixture.issueId, authorType: "user",
|
|
authorUserId: "responsible-user", body: "Stop; the request has changed.",
|
|
});
|
|
if (change === "wake_actor") await db.update(agentWakeupRequests)
|
|
.set({ requestedByActorType: "system" }).where(eq(agentWakeupRequests.id, fixture.wakeupRequestId));
|
|
await expect(
|
|
commitNativeStatusDecision({
|
|
db,
|
|
companyId: fixture.companyId,
|
|
issueId: fixture.issueId,
|
|
runId: fixture.runId,
|
|
assessmentId: coordinator!.assessmentId!,
|
|
priorStatus: issue!.status,
|
|
priorStatusVersion: issue!.statusVersion,
|
|
priorDecisionId: issue!.lastStatusDecisionId,
|
|
decision: {
|
|
policyVersion: "phase6-v14",
|
|
statusAction: reasonCode === "prior_status_preserved_no_live_path" ? "preserve" : "in_progress",
|
|
toStatus: "in_progress",
|
|
reasonCode,
|
|
unblockDescriptor: null,
|
|
effects: reasonCode === "board_response_waiting" ? [] : reasonCode === "completion_evidence_incomplete" ? [{
|
|
kind: "enqueue_continuation", continuationKind: "same_agent", agentId: fixture.agentId,
|
|
summary: "Finish remaining work", idempotencyKey: "native-completion-incomplete",
|
|
}] : [{
|
|
kind: "record_finalization_error", cause: "completion_evidence_incomplete",
|
|
nextAction: "Bind a durable continuation", agentId: fixture.agentId,
|
|
}],
|
|
},
|
|
requireBoardResponseWaitSource: expected!.source,
|
|
requireBoardResponseWaitOrigin: origin!,
|
|
}),
|
|
).rejects.toBeInstanceOf(NativeStatusRaceError);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
expect(await db.select().from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(1);
|
|
expect(await db.select().from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId))).toEqual(recoveryActionsBefore);
|
|
});
|
|
|
|
it("does not let a native passive Board wait suppress a fresh request or reassignment", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
await db.insert(issueComments).values({
|
|
companyId: fixture.companyId,
|
|
issueId: fixture.issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "Continue with this genuinely new request.",
|
|
});
|
|
// A fresh request is not permission to replay the previous passive run.
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
expect(
|
|
await hasCommittedNativeBoardResponseWait(db, {
|
|
...fixture,
|
|
agentId: randomUUID(),
|
|
}),
|
|
).toBe(false);
|
|
expect(
|
|
await hasCommittedNativeBoardResponseWait(db, {
|
|
...fixture,
|
|
runId: randomUUID(),
|
|
}),
|
|
).toBe(false);
|
|
});
|
|
|
|
it.each(["edited", "deleted", "newer_comment"] as const)(
|
|
"preserves the native passive Board origin after %s without presenting a stale answer",
|
|
async (change) => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
if (change === "edited")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ body: "A corrected request", updatedAt: new Date() })
|
|
.where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "deleted")
|
|
await db
|
|
.update(issueComments)
|
|
.set({ deletedAt: new Date() })
|
|
.where(eq(issueComments.id, fixture.commentId));
|
|
if (change === "newer_comment")
|
|
await db.insert(issueComments).values({
|
|
companyId: fixture.companyId,
|
|
issueId: fixture.issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "A new current request arrived while the old result was finalizing.",
|
|
});
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
reasonCode: "board_response_wait_superseded",
|
|
toStatus: "in_progress",
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
const heartbeat = heartbeatService(db);
|
|
expect(
|
|
(await heartbeat.reconcileStrandedAssignedIssues())
|
|
.continuationRequeued,
|
|
).toBe(0);
|
|
expect(
|
|
(await heartbeat.reconcileStrandedAssignedIssues())
|
|
.continuationRequeued,
|
|
).toBe(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, fixture.companyId)),
|
|
).toHaveLength(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it.each(["same_agent", "reassigned_agent"] as const)(
|
|
"admits a genuine new Board wake for %s after a native passive Board wait",
|
|
async (target) => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
const agentId = target === "same_agent" ? fixture.agentId : randomUUID();
|
|
if (target === "reassigned_agent") {
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId: fixture.companyId,
|
|
name: "New assigned agent",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: agentId })
|
|
.where(eq(issues.id, fixture.issueId));
|
|
}
|
|
mockAdapterExecute.mockImplementation(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, fixture.issueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, summary: "Recorded completion", provider: "test", model: "test-model" };
|
|
});
|
|
const commentId = randomUUID();
|
|
await db.insert(issueComments).values({
|
|
id: commentId,
|
|
companyId: fixture.companyId,
|
|
issueId: fixture.issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "Now explicitly continue with my new request.",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
const next = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_commented",
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "responsible-user",
|
|
payload: { issueId: fixture.issueId, commentId },
|
|
contextSnapshot: {
|
|
issueId: fixture.issueId,
|
|
taskId: fixture.issueId,
|
|
wakeCommentId: commentId,
|
|
wakeCommentIds: [commentId],
|
|
},
|
|
});
|
|
expect(next).not.toBeNull();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const [admitted] = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, next!.id));
|
|
expect(admitted).toMatchObject({
|
|
agentId,
|
|
retryOfRunId: null,
|
|
status: "succeeded",
|
|
});
|
|
expect(admitted!.contextSnapshot?.wakeCommentIds).toContain(commentId);
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
expect(
|
|
await hasCommittedNativeBoardResponseWait(db, {
|
|
...fixture,
|
|
agentId,
|
|
runId: next!.id,
|
|
}),
|
|
).toBe(false);
|
|
},
|
|
);
|
|
|
|
it("defers a native passive Board decision under a held source lock without partial presentation", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
let release!: () => void;
|
|
let acquired!: () => void;
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const ready = new Promise<void>((resolve) => {
|
|
acquired = resolve;
|
|
});
|
|
const lock = db.transaction(async (tx) => {
|
|
await tx
|
|
.select({ id: issueComments.id })
|
|
.from(issueComments)
|
|
.where(eq(issueComments.id, fixture.commentId))
|
|
.for("update");
|
|
acquired();
|
|
await held;
|
|
});
|
|
await ready;
|
|
try {
|
|
expect(
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
}),
|
|
).toMatchObject({
|
|
phase: "retryable_failure",
|
|
failureCode: "status_cas_exhausted",
|
|
});
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(statusDecisions)
|
|
.where(eq(statusDecisions.runId, fixture.runId)),
|
|
).toHaveLength(0);
|
|
} finally {
|
|
release();
|
|
await lock;
|
|
}
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.createdByRunId, fixture.runId)),
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it("recovers the native passive Board wait from its receipt, not mutable result or wake presentation", async () => {
|
|
const fixture = await seedNativePassiveBoardResponse();
|
|
await finalizeNativeRun({
|
|
db,
|
|
runId: fixture.runId,
|
|
workspaceFinalizeStatus: "succeeded",
|
|
projectRunStatus: true,
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
resultJson: {},
|
|
contextSnapshot: {
|
|
issueId: fixture.issueId,
|
|
source: "unrelated-presentation-value",
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, fixture.runId));
|
|
expect(await hasCommittedNativeBoardResponseWait(db, fixture)).toBe(true);
|
|
expect(
|
|
(await heartbeatService(db).reconcileStrandedAssignedIssues())
|
|
.continuationRequeued,
|
|
).toBe(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, fixture.companyId)),
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
async function seedNativeBlockedBoardRequest() {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
});
|
|
const commentId = randomUUID();
|
|
const contractId = randomUUID();
|
|
const runnerInstanceId = randomUUID();
|
|
const request =
|
|
"Inspect only this new attachment. Keep the answer internal and the task open.";
|
|
const unblockAction =
|
|
"Grant access to the attachment on the current Board comment, then explicitly retry.";
|
|
await db.insert(issueComments).values({
|
|
id: commentId,
|
|
companyId,
|
|
issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: request,
|
|
});
|
|
await db.insert(completionContracts).values({
|
|
id: contractId,
|
|
companyId,
|
|
issueId,
|
|
revision: 1,
|
|
schemaVersion: "paperclip.completion-contract.v1",
|
|
policyVersion: "phase6-v3",
|
|
risk: "low",
|
|
completionAuthority: "agent_claim_policy",
|
|
incompleteCriteriaPolicy: "preserve_non_terminal",
|
|
contractJson: {
|
|
revision: "1",
|
|
objective: "Respond to the latest comment",
|
|
criteria: [{ id: "objective", requirement: request }],
|
|
},
|
|
canonicalSha256: `board-contract-${runId}`,
|
|
createdByActorType: "system",
|
|
createdByActorId: "test",
|
|
});
|
|
const context = {
|
|
issueId,
|
|
taskId: issueId,
|
|
wakeReason: "issue_commented",
|
|
wakeCommentId: commentId,
|
|
wakeCommentIds: [commentId],
|
|
};
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
runtimeMode: "native",
|
|
nativeIssueId: issueId,
|
|
completionContractId: contractId,
|
|
completionContractSha256: `board-contract-${runId}`,
|
|
contextSnapshot: context,
|
|
nativeSessionId: runId,
|
|
runnerInstanceId,
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const port = new PaperclipControlPlanePort(db, {
|
|
companyId,
|
|
issueId,
|
|
runId,
|
|
agentId,
|
|
sessionId: runId,
|
|
completionContractId: contractId,
|
|
completionContractSha256: `board-contract-${runId}`,
|
|
sourceInstanceId: runnerInstanceId,
|
|
controlPlaneSourceInstanceId: `board-control-${runId}`,
|
|
});
|
|
await port.completeRun({
|
|
result: {
|
|
schema: "paperclip.run_result.v1",
|
|
reportedWorkDisposition: "blocked",
|
|
summary: "The current Board attachment could not be read.",
|
|
blocker: {
|
|
scope: "current_track",
|
|
owner: { kind: "system", name: "Attachment access" },
|
|
reasonCode: "permission_denied",
|
|
unblockAction,
|
|
},
|
|
completionClaim: {
|
|
contractRevision: "1",
|
|
objectiveSatisfied: false,
|
|
criteria: [
|
|
{
|
|
criterionId: "objective",
|
|
status: "not_satisfied",
|
|
evidenceRefs: [],
|
|
},
|
|
],
|
|
remainingWork: [{ description: request, blocksCompletion: true }],
|
|
},
|
|
evidence: [],
|
|
verification: [],
|
|
attentionRequests: [],
|
|
artifacts: [],
|
|
},
|
|
terminal: {
|
|
schema: "paperclip.prp.terminal.v1",
|
|
runTerminalState: "succeeded",
|
|
turnTerminalState: "completed",
|
|
reportedWorkDisposition: "blocked",
|
|
},
|
|
});
|
|
// Reproduce the old finalizer's persisted in_progress/advanced state after
|
|
// a real schema-validated, scope-bound accepted result. No provider runs.
|
|
await db
|
|
.update(nativeRunFinalizations)
|
|
.set({ phase: "committed" })
|
|
.where(eq(nativeRunFinalizations.runId, runId));
|
|
return {
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
commentId,
|
|
contractId,
|
|
context,
|
|
request,
|
|
unblockAction,
|
|
};
|
|
}
|
|
|
|
it("preserves a native blocked Board request instead of recovering the old task title", async () => {
|
|
const {
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
commentId,
|
|
contractId,
|
|
context,
|
|
request,
|
|
unblockAction,
|
|
} = await seedNativeBlockedBoardRequest();
|
|
const heartbeat = heartbeatService(db);
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(1);
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
status: "blocked",
|
|
assigneeAgentId: agentId,
|
|
unblockDescriptor: { owner: "board", action: unblockAction },
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, companyId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
id: runId,
|
|
contextSnapshot: context,
|
|
completionContractId: contractId,
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(completionContracts)
|
|
.where(eq(completionContracts.issueId, issueId)),
|
|
).toHaveLength(1);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.id, commentId)),
|
|
).toEqual([expect.objectContaining({ body: request })]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, companyId)),
|
|
).toHaveLength(1);
|
|
expect(
|
|
(await heartbeat.reconcileStrandedAssignedIssues()).continuationRequeued,
|
|
).toBe(0);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
"status",
|
|
"assignee",
|
|
"comment",
|
|
"wake",
|
|
"run",
|
|
"run_context",
|
|
"run_metadata",
|
|
"attention",
|
|
] as const)(
|
|
"does not clobber a newer %s while native blocker repair waits on the issue lock",
|
|
async (change) => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedNativeBlockedBoardRequest();
|
|
let release!: () => void;
|
|
let acquired!: (pid: number) => void;
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const lockReady = new Promise<number>((resolve) => {
|
|
acquired = resolve;
|
|
});
|
|
let snapshot: typeof issues.$inferSelect | undefined;
|
|
const lock = db.transaction(async (tx) => {
|
|
await tx
|
|
.select({ id: issues.id })
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId))
|
|
.for("update");
|
|
const pid = await tx.execute<{ pid: number }>(
|
|
sql`select pg_backend_pid() as pid`,
|
|
);
|
|
acquired(pid[0]!.pid);
|
|
await held;
|
|
if (change === "status")
|
|
await tx
|
|
.update(issues)
|
|
.set({ status: "done" })
|
|
.where(eq(issues.id, issueId));
|
|
if (change === "assignee")
|
|
await tx
|
|
.update(issues)
|
|
.set({ assigneeAgentId: null, assigneeUserId: "responsible-user" })
|
|
.where(eq(issues.id, issueId));
|
|
if (change === "comment")
|
|
await tx.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorType: "user",
|
|
authorUserId: "responsible-user",
|
|
body: "New instruction: wait for my next reply.",
|
|
});
|
|
if (change === "wake")
|
|
await tx.insert(agentWakeupRequests).values({
|
|
companyId,
|
|
agentId,
|
|
source: "automation",
|
|
reason: "issue_commented",
|
|
payload: { issueId },
|
|
status: "queued",
|
|
});
|
|
if (change === "run")
|
|
await tx.insert(heartbeatRuns).values({
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "automation",
|
|
status: "succeeded",
|
|
livenessState: "advanced",
|
|
contextSnapshot: { issueId },
|
|
startedAt: new Date(),
|
|
finishedAt: new Date(),
|
|
});
|
|
if (change === "attention")
|
|
await tx.insert(issueThreadInteractions).values({
|
|
companyId,
|
|
issueId,
|
|
sourceRunId: runId,
|
|
kind: "ask_user_questions",
|
|
status: "pending",
|
|
continuationPolicy: "wake_assignee",
|
|
payload: { version: 1, questions: [] },
|
|
});
|
|
if (change === "run_context")
|
|
await tx.update(heartbeatRuns).set({
|
|
contextSnapshot: sql`jsonb_set(${heartbeatRuns.contextSnapshot}, '{paperclipTaskMarkdown}', '"Changed execution instructions"'::jsonb)`,
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
if (change === "run_metadata")
|
|
await tx.update(heartbeatRuns).set({ stdoutExcerpt: "Late execution output" }).where(eq(heartbeatRuns.id, runId));
|
|
[snapshot] = await tx
|
|
.select()
|
|
.from(issues)
|
|
.where(eq(issues.id, issueId));
|
|
});
|
|
const pid = await lockReady;
|
|
const heartbeat = heartbeatService(db);
|
|
const repair = heartbeat.reconcileStrandedAssignedIssues();
|
|
try {
|
|
await vi.waitFor(async () => {
|
|
const waiters = await db.execute<{ count: number }>(
|
|
sql`select count(*)::int as count from pg_stat_activity where datname = current_database() and ${pid} = any(pg_blocking_pids(pid))`,
|
|
);
|
|
expect(waiters[0]!.count).toBeGreaterThan(0);
|
|
});
|
|
} finally {
|
|
release();
|
|
}
|
|
await lock;
|
|
const result = await repair;
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toEqual([snapshot]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.companyId, companyId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(
|
|
and(
|
|
eq(issueComments.issueId, issueId),
|
|
eq(issueComments.authorType, "system"),
|
|
),
|
|
),
|
|
).toHaveLength(0);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
if (change === "run_context" || change === "run_metadata") {
|
|
expect((await heartbeat.reconcileStrandedAssignedIssues()).escalated).toBe(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("preserves a later routed native attention decision after its wake was coalesced", async () => {
|
|
const { companyId, issueId, runId, contractId } =
|
|
await seedNativeBlockedBoardRequest();
|
|
const [result] = await db
|
|
.select()
|
|
.from(nativeRunResults)
|
|
.where(eq(nativeRunResults.runId, runId));
|
|
const candidate = {
|
|
route: "alternate_track" as const,
|
|
summary: "Continue the independently selected alternate track.",
|
|
targetCompanyId: companyId,
|
|
};
|
|
const assessment = await recordNativeAttentionAssessment({
|
|
db,
|
|
companyId,
|
|
issueId,
|
|
runId,
|
|
turnId: null,
|
|
contractId,
|
|
resultId: result!.id,
|
|
requestId: randomUUID(),
|
|
request: {
|
|
requestedCapability: "alternate_track",
|
|
summary: candidate.summary,
|
|
},
|
|
routingFacts: candidate,
|
|
priorIssueStatus: "in_progress",
|
|
priorStatusVersion: 0,
|
|
priorDecisionId: null,
|
|
supersedesAssessmentId: null,
|
|
});
|
|
const routed = await routeNativeAttention({
|
|
db,
|
|
runId,
|
|
assessmentId: assessment.id,
|
|
candidate,
|
|
});
|
|
expect(routed.decision.reasonCode).toBe("turn_waiting_other_track_live");
|
|
// Historical dispatcher coalescing is distinct from an absent attention
|
|
// decision. The original blocked result must not override that later owner.
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ status: "coalesced", runId })
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
eq(agentWakeupRequests.status, "queued"),
|
|
),
|
|
);
|
|
const before = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
const recovered =
|
|
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(recovered.continuationRequeued).toBe(0);
|
|
expect(recovered.escalated).toBe(0);
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toEqual(before);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(
|
|
and(
|
|
eq(issueComments.issueId, issueId),
|
|
eq(issueComments.authorType, "system"),
|
|
),
|
|
),
|
|
).toHaveLength(0);
|
|
});
|
|
|
|
it("does not grant a legacy summary authority to bind a native blocked wait", async () => {
|
|
const { companyId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
resultJson: {
|
|
nativeResult: {
|
|
schema: "paperclip.run_result.v1",
|
|
reportedWorkDisposition: "blocked",
|
|
blocker: {
|
|
scope: "current_track",
|
|
unblockAction: "Untrusted summary instruction",
|
|
},
|
|
},
|
|
},
|
|
});
|
|
const result = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
status: "in_progress",
|
|
unblockDescriptor: null,
|
|
}),
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(nativeRunResults)
|
|
.where(eq(nativeRunResults.companyId, companyId)),
|
|
).toHaveLength(0);
|
|
});
|
|
|
|
it("rolls back the native blocked wait when its durable notice cannot be persisted", async () => {
|
|
const { companyId, issueId } = await seedNativeBlockedBoardRequest();
|
|
const before = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
await db.execute(
|
|
sql.raw(
|
|
`create function test_native_blocked_wait_fault() returns trigger language plpgsql as $$ begin if new.issue_id = '${issueId}'::uuid and new.author_type = 'system' then raise exception 'native_blocked_wait_fixture_fault'; end if; return new; end $$`,
|
|
),
|
|
);
|
|
await db.execute(
|
|
sql`create trigger test_native_blocked_wait_fault before insert on issue_comments for each row execute function test_native_blocked_wait_fault()`,
|
|
);
|
|
try {
|
|
await expect(
|
|
heartbeatService(db).reconcileStrandedAssignedIssues(),
|
|
).rejects.toMatchObject({
|
|
cause: expect.objectContaining({
|
|
message: "native_blocked_wait_fixture_fault",
|
|
}),
|
|
});
|
|
} finally {
|
|
await db.execute(
|
|
sql`drop trigger test_native_blocked_wait_fault on issue_comments`,
|
|
);
|
|
await db.execute(sql`drop function test_native_blocked_wait_fault()`);
|
|
}
|
|
expect(
|
|
await db.select().from(issues).where(eq(issues.id, issueId)),
|
|
).toEqual(before);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueRecoveryActions)
|
|
.where(eq(issueRecoveryActions.companyId, companyId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(
|
|
and(
|
|
eq(issueComments.issueId, issueId),
|
|
eq(issueComments.authorType, "system"),
|
|
),
|
|
),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.companyId, companyId)),
|
|
).toHaveLength(0);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.companyId, companyId)),
|
|
).toHaveLength(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
|
expect(
|
|
(await heartbeatService(db).reconcileStrandedAssignedIssues()).escalated,
|
|
).toBe(1);
|
|
});
|
|
|
|
it("allows one productive-terminal recovery after regular continuation recovery made progress", async () => {
|
|
const { agentId, issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
retryReason: "issue_continuation_needed",
|
|
runSource: "issue.continuation_recovery",
|
|
livenessState: "advanced",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const runs = await selectRecoveryRunsByAgent(agentId);
|
|
const retryRun = runs.find((row) => row.id !== runId);
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown> | undefined,
|
|
).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
retryReason: "issue_disposition_repair",
|
|
retryOfRunId: runId,
|
|
source: "issue.deliberate_wait_disposition_repair",
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
});
|
|
|
|
it("does not treat a productive terminal run as healthy when in-progress work has no live path", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
livenessState: "advanced",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const sourceIssue = await selectRecoveryIssueById(issueId);
|
|
expect(sourceIssue).toMatchObject({
|
|
status: "in_progress",
|
|
assigneeAgentId: agentId,
|
|
assigneeUserId: null,
|
|
executionRunId: null,
|
|
});
|
|
|
|
const activeRuns = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
inArray(heartbeatRuns.status, ["queued", "running"]),
|
|
),
|
|
);
|
|
expect(activeRuns).toHaveLength(0);
|
|
|
|
const liveWakeups = await db
|
|
.select()
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.companyId, companyId),
|
|
inArray(agentWakeupRequests.status, [
|
|
"queued",
|
|
"deferred_issue_execution",
|
|
]),
|
|
),
|
|
);
|
|
expect(liveWakeups).toHaveLength(0);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.productiveContinuationObserved).toBe(0);
|
|
expect(result.successfulContinuationObserved).toBe(0);
|
|
expect(result.continuationRequeued).toBe(1);
|
|
expect(result.escalated).toBe(0);
|
|
expect(result.continuationRequeued + result.escalated).toBe(1);
|
|
expect(result.issueIds).toEqual([issueId]);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("in_progress");
|
|
|
|
const comments = await selectRecoveryCommentsForIssue(issueId);
|
|
const recoveryIssues = await selectStrandedRecoveryIssuesForCompany(companyId);
|
|
const followupRuns = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.agentId, agentId),
|
|
),
|
|
);
|
|
expect(comments).toHaveLength(0);
|
|
expect(recoveryIssues).toHaveLength(0);
|
|
expect(followupRuns).toHaveLength(2);
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(2);
|
|
const retryRun = followupRuns.find((row) => row.id !== runId);
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown> | undefined,
|
|
).toMatchObject({
|
|
issueId,
|
|
taskId: issueId,
|
|
retryReason: "issue_disposition_repair",
|
|
retryOfRunId: runId,
|
|
source: "issue.deliberate_wait_disposition_repair",
|
|
});
|
|
expect(
|
|
retryRun?.contextSnapshot as Record<string, unknown>,
|
|
).not.toHaveProperty("modelProfile");
|
|
|
|
const wakeups = await selectRecoveryWakesByAgent(agentId);
|
|
expect(wakeups).toHaveLength(2);
|
|
if (retryRun) {
|
|
await waitForRunToSettle(heartbeat, retryRun.id);
|
|
}
|
|
});
|
|
|
|
it("does not replenish exhausted legacy repair from a recent comment", async () => {
|
|
const { companyId, agentId, issueId, runId } =
|
|
await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
retryReason: "issue_continuation_needed",
|
|
runSource: "issue.productive_terminal_continuation_recovery",
|
|
livenessState: "advanced",
|
|
});
|
|
// Commentary does not authorize another repair or reset its budget.
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
body: "frame 02/08 generated, attaching shortly",
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.recentProgressExempted).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked", assigneeAgentId: agentId });
|
|
expect(await selectRecoveryRunsByAgent(agentId)).toHaveLength(1);
|
|
});
|
|
|
|
it("still escalates stranded-recovery work when the recent comment is older than the exemption window (GGU-809)", async () => {
|
|
const { companyId, agentId, issueId } = await seedStrandedIssueFixture({
|
|
status: "in_progress",
|
|
runStatus: "succeeded",
|
|
retryReason: "issue_continuation_needed",
|
|
runSource: "issue.productive_terminal_continuation_recovery",
|
|
livenessState: "advanced",
|
|
});
|
|
// Comment older than the exemption window must NOT suppress escalation.
|
|
const stale = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId,
|
|
authorAgentId: agentId,
|
|
body: "old progress note",
|
|
createdAt: stale,
|
|
updatedAt: stale,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.escalated).toBe(1);
|
|
expect(result.recentProgressExempted).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("blocked");
|
|
});
|
|
|
|
it("does not reconcile user-assigned work through the agent stranded-work recovery path", async () => {
|
|
const { issueId, runId } = await seedStrandedIssueFixture({
|
|
status: "todo",
|
|
runStatus: "failed",
|
|
assignToUser: true,
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
const result = await heartbeat.reconcileStrandedAssignedIssues();
|
|
expect(result.dispatchRequeued).toBe(0);
|
|
expect(result.continuationRequeued).toBe(0);
|
|
expect(result.escalated).toBe(0);
|
|
|
|
const issue = await selectRecoveryIssueById(issueId);
|
|
expect(issue?.status).toBe("todo");
|
|
|
|
const runs = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(runs).toHaveLength(1);
|
|
});
|
|
describe("accepted Cursor planning boundaries", () => {
|
|
const nativeImplementation = mockExecutePaperclipNativeSession.getMockImplementation();
|
|
beforeEach(() => {
|
|
mockExecutePaperclipNativeSession.mockImplementation(async () => { throw new Error("Accepted-plan tests must never execute a provider"); });
|
|
});
|
|
afterEach(() => { mockExecutePaperclipNativeSession.mockImplementation(nativeImplementation!); });
|
|
|
|
async function seedAcceptedCursorPlanWait(semanticFinish = false, sourceSequenceOffset = 0) {
|
|
const f = await seedStrandedIssueFixture({ status: "in_progress", runStatus: "succeeded", livenessState: "advanced" });
|
|
const instance = randomUUID(), interactionId = randomUUID();
|
|
const contractInput = { db, companyId: f.companyId,
|
|
issue: { id: f.issueId, title: "Review the plan before further work", description: "Explicit completion required" }, actorId: "test" };
|
|
const { row: persistedContract, contract } = await ensureNativeCompletionContract(contractInput);
|
|
const reused = await ensureNativeCompletionContract(contractInput);
|
|
expect(reused.row.id).toBe(persistedContract.id);
|
|
expect(reused.contract).toEqual(contract);
|
|
const contractId = persistedContract.id, contractSha = persistedContract.canonicalSha256;
|
|
// Production binds policy/schema as well as the body; a body-only hash is not a valid contract receipt.
|
|
expect(contractSha).not.toBe(nativeSha256(contract));
|
|
const model = "gpt-5.6-luna[context=272k,reasoning=medium,fast=false]";
|
|
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "cursor", model, acpxSessionMode: "plan", acpxPermissionMode: "approve-all" } }).where(eq(agents.id, f.agentId));
|
|
await db.update(agentWakeupRequests).set({ status: "completed" }).where(eq(agentWakeupRequests.id, f.wakeupRequestId));
|
|
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: f.issueId, nativeSessionId: f.runId,
|
|
completionContractId: contractId, completionContractSha256: contractSha, runnerInstanceId: instance,
|
|
runnerProfileJson: { nativeExecutionInput: { binding: { companyId: f.companyId, issueId: f.issueId, runId: f.runId, agentId: f.agentId }, provider: { kind: "acpx", agent: "cursor", model, mode: "plan", permissionMode: "approve-all",
|
|
profile: paperclipRunner.resolveQualifiedAcpxProfile("cursor", model) }, session: { normalizedSessionId: f.runId },
|
|
completionContract: { id: contractId, sha256: contractSha, contract } } } }).where(eq(heartbeatRuns.id, f.runId));
|
|
const planId = `plan-${"a".repeat(64)}`;
|
|
const questionSet = { schema: "paperclip.question_set.v1", title: "Native plan", description: "Exact accepted revision", questions: [{ id: planId, prompt: "Proceed?", required: true,
|
|
answerMode: "single_select", options: [{ id: "accept", label: "Accept" }, { id: "reject", label: "Reject" }, { id: "cancel", label: "Cancel" }] }] };
|
|
const [interaction] = await db.insert(issueThreadInteractions).values({ id: interactionId, companyId: f.companyId, issueId: f.issueId, sourceRunId: f.runId,
|
|
createdByAgentId: f.agentId, kind: "ask_user_questions", status: "answered", continuationPolicy: "none",
|
|
idempotencyKey: `paperclip-runner-question:${f.runId}:request`, resolvedByUserId: "responsible-user", resolvedAt: new Date(Date.now() - 1000),
|
|
payload: { version: 1, questions: [{ id: planId, prompt: "Proceed?", selectionMode: "single", required: true, allowOther: false, options: [{ id: "accept", label: "Accept" }, { id: "reject", label: "Reject" }, { id: "cancel", label: "Cancel" }] }], runtimeRequestId: "request", questionSet: questionSet as never }, result: { version: 1, answers: [{ questionId: planId, optionIds: ["accept"] }] } }).returning();
|
|
const answer = buildQuestionResponseDeliveryEnvelope(interaction as never);
|
|
const [delivery] = await db.insert(issueQuestionResponseDeliveries).values({ companyId: f.companyId, issueId: f.issueId, interactionId,
|
|
sourceRunId: f.runId, targetRunId: f.runId, correlationId: randomUUID(), status: "delivered", deliveryMode: "steered", acknowledgedAt: new Date(), payloadSha256: nativeSha256(answer) }).returning();
|
|
const port = new PaperclipControlPlanePort(db, { companyId: f.companyId, issueId: f.issueId, runId: f.runId, agentId: f.agentId,
|
|
sessionId: f.runId, completionContractId: contractId, completionContractSha256: contractSha, sourceInstanceId: instance, controlPlaneSourceInstanceId: `control-${f.runId}` });
|
|
const events = [
|
|
{ eventType: "runtime_request.created", payload: { request: { schema: "paperclip.runtime_request.v2", requestKind: "runtime", requestId: "request", type: "input", status: "pending", turnId: "turn", itemId: "native-plan-tool", prompt: "Review plan",
|
|
origin: { adapter: "acpx-runtime-sidecar", provider: "cursor", method: "cursor/create_plan" }, input: questionSet } } },
|
|
{ eventType: "tool.execution.started", payload: { schema: "paperclip.tool.execution.v1", executionId: "native-plan-tool", transport: "builtin", operation: "execute", status: "running", readOnly: false, namespace: null, name: "Create Plan", target: null, inputUpdated: true, output: null, outputBytes: 0, outputTruncated: false, outputDigest: null, progress: null, exitCode: null, durationMs: null } },
|
|
{ eventType: "runtime_request.resolved", payload: { requestId: "request", turnId: "turn", action: "submit", response: answer.response } },
|
|
{ eventType: "tool.execution.completed", payload: { schema: "paperclip.tool.execution.v1", executionId: "native-plan-tool", transport: "builtin", operation: "execute", status: "completed", readOnly: false, namespace: null, name: "Create Plan", target: null, inputUpdated: false, output: null, outputBytes: 0, outputTruncated: false, outputDigest: null, progress: null, exitCode: null, durationMs: null } },
|
|
{ eventType: "turn.completed", payload: { status: "completed", error: null } },
|
|
];
|
|
for (const [index, event] of events.entries()) await port.appendEvent({ schema: "paperclip.prp.event.v1", sourceEventId: `${instance}:${sourceSequenceOffset + index + 1}`, sourceSeq: sourceSequenceOffset + index + 1,
|
|
sourceInstanceId: instance, sourceKind: "runner", runId: f.runId, normalizedSessionId: f.runId, turnId: "turn", schemaVersion: 1, priority: 0,
|
|
emittedAt: new Date().toISOString(), ...event } as paperclipRunner.PrpEvent);
|
|
const proof = await readNativePlanWait(db, f);
|
|
expect(proof).not.toBeNull();
|
|
const result = semanticFinish ? { ...proof!.result, reportedWorkDisposition: "done" as const, summary: "Explicit semantic finish wins", continuation: undefined,
|
|
completionClaim: { contractRevision: "1", objectiveSatisfied: true, criteria: [{ criterionId: "objective", status: "satisfied" as const, evidenceRefs: [] }], remainingWork: [] } } : proof!.result;
|
|
await port.completeRun({ result, turnId: "turn", terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: result.reportedWorkDisposition } });
|
|
return { ...f, interactionId, deliveryId: delivery!.id, proof: proof! };
|
|
}
|
|
|
|
it("keeps an accepted Cursor plan passive across restart, future configuration changes, and paused recovery", async () => {
|
|
const f = await seedAcceptedCursorPlanWait();
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId))).toEqual([expect.objectContaining({ reasonCode: "native_plan_accepted_waiting_for_continuation", toStatus: "in_progress" })]);
|
|
expect(await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.issueId, f.issueId))).toEqual([expect.objectContaining({ effectKind: "issue_status_projection", targetType: "issue", deliveryState: "delivered" })]);
|
|
expect(await db.select().from(issueComments).where(eq(issueComments.createdByRunId, f.runId))).toEqual([expect.objectContaining({ body: expect.stringContaining("next message") })]);
|
|
const current = paperclipRunner.resolveQualifiedAcpxProfile("cursor", "gpt-5.6-luna[context=272k,reasoning=medium,fast=false]");
|
|
const resolver = vi.spyOn(paperclipRunner, "resolveQualifiedAcpxProfile").mockReturnValue({ ...current,
|
|
agentProfileVersion: current.agentProfileVersion + 1, commandDigest: `sha256:${"b".repeat(64)}` });
|
|
try {
|
|
expect(await readNativePlanWait(db, f)).toBeNull(); // Old profile cannot create a new wait.
|
|
for (const status of ["idle", "paused"] as const) {
|
|
await db.update(agents).set({ status, adapterConfig: { provider: "acpx", acpxAgent: "cursor",
|
|
model: "future-model", acpxSessionMode: "agent", acpxPermissionMode: "approve-reads" } }).where(eq(agents.id, f.agentId));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
const recovered = await heartbeatService(db).reconcileStrandedAssignedIssues();
|
|
expect(recovered.continuationRequeued).toBe(0); expect(recovered.escalated).toBe(0);
|
|
}
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
const changed = structuredClone(run!.runnerProfileJson!);
|
|
(changed.nativeExecutionInput as { provider: { profile: { commandDigest: string } } }).provider.profile.commandDigest = "tampered-original-profile";
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: changed }).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: run!.runnerProfileJson }).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
const [tool] = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, f.runId), eq(heartbeatRunEvents.eventType, "tool.execution.completed")));
|
|
const changedTool = structuredClone(tool!.payload!) as { prpEvent: { payload: { name: string } } };
|
|
changedTool.prpEvent.payload.name = "mutated committed tool evidence";
|
|
await db.update(heartbeatRunEvents).set({ payload: changedTool, sourcePayloadSha256: nativeSha256(changedTool.prpEvent) }).where(eq(heartbeatRunEvents.id, tool!.id));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
await db.update(heartbeatRunEvents).set({ payload: tool!.payload, sourcePayloadSha256: tool!.sourcePayloadSha256 }).where(eq(heartbeatRunEvents.id, tool!.id));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
} finally { resolver.mockRestore(); }
|
|
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(1);
|
|
expect(mockAdapterExecute).not.toHaveBeenCalled(); expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("retains an exact historical Cursor6 committed wait across more than 1000 ignored progress rows without allowing new unbound admission", async () => {
|
|
const progressCount = 1002;
|
|
const f = await seedAcceptedCursorPlanWait(false, progressCount);
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
const profile = structuredClone(run!.runnerProfileJson!) as any;
|
|
Object.assign(profile.nativeExecutionInput.provider.profile, { agentProfileVersion: 6, commandDigest: "sha256:377dcea64a727ce799cc112458d4b40ba4bc6574cd6c6f7233b6efd5917a6c4b" });
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: profile }).where(eq(heartbeatRuns.id, f.runId));
|
|
await db.delete(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, f.runId), inArray(heartbeatRunEvents.eventType, ["tool.execution.started", "tool.execution.completed"])));
|
|
// Reconstruct the persisted Cursor6 receipt format using its unchanged
|
|
// source facts. This historical format had no tool lifecycle binding.
|
|
const rows = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, f.runId));
|
|
const event = (kind: string) => (rows.find(r => r.eventType === kind)!.payload as any).prpEvent;
|
|
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.id, run!.completionContractId!));
|
|
const [interaction] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, f.interactionId));
|
|
const [delivery] = await db.select().from(issueQuestionResponseDeliveries).where(eq(issueQuestionResponseDeliveries.id, f.deliveryId));
|
|
profile.nativeExecutionInput.provider.cursorMode = profile.nativeExecutionInput.provider.mode;
|
|
delete profile.nativeExecutionInput.provider.mode;
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: profile }).where(eq(heartbeatRuns.id, f.runId));
|
|
const legacy = { ...f.proof.source, schema: "paperclip.native_cursor_plan_wait.v1" }; delete legacy.toolExecutionId; delete legacy.toolLifecycleSha256;
|
|
legacy.authoritySha256 = nativeSha256({ admission: profile.nativeExecutionInput, contract, created: event("runtime_request.created"), resolved: event("runtime_request.resolved"), terminal: event("turn.completed"), interaction, delivery, resolvedAt: interaction!.resolvedAt!.toISOString(), acknowledgedAt: delivery!.acknowledgedAt!.toISOString() });
|
|
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId));
|
|
const [savedResult] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId));
|
|
const resultJson = structuredClone(savedResult!.resultJson!) as any;
|
|
resultJson.result.continuation.idempotencyKey = resultJson.result.continuation.idempotencyKey.replace("native-plan-wait:", "cursor-plan-wait:");
|
|
const canonicalSha256 = nativeSha256(resultJson);
|
|
await db.update(nativeRunResults).set({ resultJson, canonicalSha256 }).where(eq(nativeRunResults.id, savedResult!.id));
|
|
const decisionJson = { ...decision!.decisionJson } as any;
|
|
delete decisionJson.planWait; delete decisionJson.planWaitResult;
|
|
decisionJson.cursorPlanWait = legacy;
|
|
decisionJson.cursorPlanWaitResult = { resultId: savedResult!.id, resultSha256: canonicalSha256 };
|
|
await db.update(statusDecisions).set({ decisionJson }).where(eq(statusDecisions.id, decision!.id));
|
|
expect(await readNativePlanWait(db, f)).toBeNull();
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
// Fill the reserved source prefix with genuine durable progress rows. Shift
|
|
// only DB ordering keys; the original PRP facts and committed receipt stay
|
|
// byte-identical. Cursor6 never queried these rows, even above its budget.
|
|
await db.update(heartbeatRunEvents).set({ seq: sql`${heartbeatRunEvents.seq} + ${progressCount}` }).where(eq(heartbeatRunEvents.runId, f.runId));
|
|
const progress = Array.from({ length: progressCount }, (_, index) => {
|
|
const seq = index + 1;
|
|
const prpEvent = { ...event("runtime_request.created"), sourceEventId: `${run!.runnerInstanceId}:${seq}`, sourceSeq: seq, eventType: "tool.execution.progressed",
|
|
payload: { schema: "paperclip.tool.execution.v1", executionId: "earlier-tool", transport: "builtin", operation: "read", status: "running" } };
|
|
return { companyId: f.companyId, runId: f.runId, agentId: f.agentId, seq, eventType: prpEvent.eventType, payload: { prpEvent }, sourceInstanceId: run!.runnerInstanceId,
|
|
sourceEventId: prpEvent.sourceEventId, sourceSeq: seq, sourcePayloadSha256: nativeSha256(prpEvent), protocolSchemaVersion: 1 };
|
|
});
|
|
await db.insert(heartbeatRunEvents).values(progress);
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
const [unchangedDecision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, decision!.id));
|
|
expect(unchangedDecision!.decisionJson!.cursorPlanWait).toEqual(legacy);
|
|
// Completed rows belonged to the old query. A later completion must still
|
|
// invalidate the normal-terminal boundary rather than being filtered away.
|
|
const completion = { ...event("turn.completed"), sourceEventId: `${run!.runnerInstanceId}:99999`, sourceSeq: 99999, eventType: "tool.execution.completed", payload: { ...progress[0]!.payload.prpEvent.payload, status: "completed" } };
|
|
const [extra] = await db.insert(heartbeatRunEvents).values({ ...progress[0]!, seq: 99999, eventType: completion.eventType, payload: { prpEvent: completion }, sourceEventId: completion.sourceEventId, sourceSeq: 99999, sourcePayloadSha256: nativeSha256(completion) }).returning();
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.id, extra!.id));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
profile.nativeExecutionInput.provider.profile.commandDigest = "tampered-history";
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: profile }).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
});
|
|
|
|
it("admits a later ordinary user message after an accepted Cursor plan without changing Plan mode or replaying its run", async () => {
|
|
const f = await seedAcceptedCursorPlanWait();
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
// Occupy the single dispatch slot: this checks actual user-wake admission
|
|
// without executing any provider or fabricating a second semantic result.
|
|
const occupied = randomUUID();
|
|
await db.update(agents).set({ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } }).where(eq(agents.id, f.agentId));
|
|
await db.insert(heartbeatRuns).values({ id: occupied, companyId: f.companyId, agentId: f.agentId, status: "running", startedAt: new Date(), contextSnapshot: {} });
|
|
const [comment] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "responsible-user", body: "Continue reviewing the accepted plan in Plan mode." }).returning();
|
|
try {
|
|
const heartbeat = heartbeatService(db);
|
|
const next = await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented", requestedByActorType: "user", requestedByActorId: "responsible-user",
|
|
payload: { issueId: f.issueId, commentId: comment!.id }, contextSnapshot: { issueId: f.issueId, taskId: f.issueId, wakeCommentId: comment!.id, wakeCommentIds: [comment!.id] } });
|
|
expect(next).not.toBeNull(); expect(next!.id).not.toBe(f.runId);
|
|
const [admitted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, next!.id));
|
|
expect(admitted).toMatchObject({ status: "queued", retryOfRunId: null });
|
|
expect(admitted!.contextSnapshot?.wakeCommentIds).toContain(comment!.id);
|
|
const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId));
|
|
expect(agent!.adapterConfig.acpxSessionMode).toBe("plan");
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled();
|
|
} finally {
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and(eq(heartbeatRuns.companyId, f.companyId), inArray(heartbeatRuns.status, ["running", "queued"])));
|
|
await db.update(agentWakeupRequests).set({ status: "cancelled", finishedAt: new Date() }).where(and(eq(agentWakeupRequests.companyId, f.companyId), inArray(agentWakeupRequests.status, ["queued", "claimed"])));
|
|
}
|
|
});
|
|
|
|
it.each(["delivery", "assignment", "admission", "user_request", "result_or_decision"] as const)("revokes an accepted Cursor plan passive wait after %s changes", async change => {
|
|
const f = await seedAcceptedCursorPlanWait();
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
if (change === "delivery") await db.update(issueQuestionResponseDeliveries).set({ acknowledgedAt: null }).where(eq(issueQuestionResponseDeliveries.id, f.deliveryId));
|
|
if (change === "assignment") await db.update(issues).set({ assigneeAgentId: null }).where(eq(issues.id, f.issueId));
|
|
if (change === "admission") {
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
const profile = structuredClone(run!.runnerProfileJson!);
|
|
(profile.nativeExecutionInput as { provider: { cursorMode: string } }).provider.cursorMode = "agent";
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: profile }).where(eq(heartbeatRuns.id, f.runId));
|
|
}
|
|
if (change === "user_request") await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "responsible-user", body: "Continue reviewing this plan in Plan mode." });
|
|
if (change === "result_or_decision") {
|
|
const [accepted] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.runId));
|
|
await db.update(nativeRunResults).set({ canonicalSha256: "changed" }).where(eq(nativeRunResults.id, accepted!.id));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
await db.update(nativeRunResults).set({ canonicalSha256: accepted!.canonicalSha256 }).where(eq(nativeRunResults.id, accepted!.id));
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(true);
|
|
await db.update(issues).set({ lastStatusDecisionId: null }).where(eq(issues.id, f.issueId));
|
|
}
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
});
|
|
|
|
it("rechecks accepted Cursor plan delivery under the status transaction before presentation or effects", async () => {
|
|
const f = await seedAcceptedCursorPlanWait();
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", failpoint: "status_projection" });
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId));
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId));
|
|
await db.update(issueQuestionResponseDeliveries).set({ payloadSha256: "changed" }).where(eq(issueQuestionResponseDeliveries.id, f.deliveryId));
|
|
await expect(commitNativeStatusDecision({ db, companyId: f.companyId, issueId: f.issueId, runId: f.runId, assessmentId: coordinator!.assessmentId!,
|
|
priorStatus: issue!.status, priorStatusVersion: issue!.statusVersion, priorDecisionId: issue!.lastStatusDecisionId,
|
|
decision: { policyVersion: "phase6-v14", statusAction: "in_progress", toStatus: "in_progress", reasonCode: "native_plan_accepted_waiting_for_continuation", unblockDescriptor: null, effects: [] },
|
|
requirePlanWaitSource: f.proof.source })).rejects.toBeInstanceOf(NativeStatusRaceError);
|
|
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId))).toHaveLength(0);
|
|
expect(await db.select().from(issueComments).where(eq(issueComments.createdByRunId, f.runId))).toHaveLength(0);
|
|
});
|
|
|
|
it("preserves explicit semantic finish priority over accepted Cursor plan evidence", async () => {
|
|
const f = await seedAcceptedCursorPlanWait(true);
|
|
await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
|
expect(await hasCommittedNativePlanWait(db, f)).toBe(false);
|
|
const decisions = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId));
|
|
expect(decisions).toHaveLength(1); expect(decisions[0]!.reasonCode).not.toBe("native_plan_accepted_waiting_for_continuation");
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
enableRunFailureReporting();
|