fix(runner): preserve durable native session authority across recovery (#13092)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runner carries tool results and task output to the
control plane.
> - A lost connection must not change which run owns a result.
> - A session must not become reusable while provider output is still
pending.
> - This pull request adds strict recovery evidence and bounded drain
barriers.
> - It preserves current PRP version negotiation and session-goal
support.
> - The benefit is safer reuse of native sessions after a transport
failure.

## Linked Issues or Issue Description

Refs #13038. This is the first of two stacked pull requests. It contains
the native runtime prerequisites. The second pull request contains the
experimental chat-channel integration. It preserves the provider
identity and typed terminal-failure contracts in #13074 and the durable
recovery work in #13075.

**What happened?**

Native session failures could leave retained provider events, incomplete
tool results, or warm handoff state that was not safe to reuse. A later
run could observe output from an earlier authority.

**Expected behavior**

Recovery must preserve exact run, tool, process, artifact, and lease
evidence. Uncertain or corrupt state must fail closed. A successful
close must prove that retained provider output is settled.

**Steps to reproduce**

Run the transport and control-plane regressions. They hold and drop
authenticated frames, fail durable writes, and restart fresh controllers
and runner processes with retained state. Provider executables are local
test fixtures.

## What Changed

- Preserve pending provider cleanup and semantic-result evidence across
session close and restart.
- Add an authenticated warm handoff with exact old and new identities,
durable receipts, and completion acknowledgement.
- Drain retained provider events under the cumulative acknowledgement
fence.
- Reject corrupt tool-result contracts without unsafe provider replay or
reusable checkpoints.
- Keep ordinary PRP v1 sessions and current session-goal behavior.
Require negotiated PRP v2 and acknowledged native session evidence
before warm authority rotation.
- Preserve late semantic inputs and exact durable result receipts until
close can prove settlement.
- Add transport, crash-window, artifact, checkpoint, and final-output
regressions.
- Deduplicate resolved execution delivery under the current issue lock.
Reuse the exact existing successor after concurrent scans or a lost
acknowledgement. Preserve newer operator evidence.
- Persist idle provider integrity/capacity failures before process
retirement, retain permanent model-rejection classification, and keep
external question identifiers out of task instructions.
- Expose only the context source on native status events. Keep thin
dispatch projections compatible without exposing the complete context.

## Verification

- Review-fix revision: 128 runtime-context/native-session tests, five
idle-failure/adjacent Rust cases, 24 warm crash-window cases, three
startup-notification/close cases, and five attach/backlog cases passed.
The security and idle-failure cases were first reproduced failing.
- Prior merged revision: runner production build, TypeScript typecheck,
complete Rust workspace tests and formatting passed; 272 focused runner
tests and two real PostgreSQL regressions passed.
- Earlier full runner runs and CI Build failed on missing
semantic-result fixture receipts, stale local provider fixture bytes,
startup-notification ordering, and a confirmation-loss fixture that
could accidentally send its final ACK. Each cause was reproduced and
corrected without relaxing production authority or close assertions.
These earlier runs are retained as failures, not represented as passing
verification.
- The first local repository-wide run failed before later phases because
the isolated install omitted PostgreSQL's native-library aliases; it
also encountered an unrelated occupied-port fixture. Those results are
retained, not represented as a passing run.
- Exact `335b2ee52709afb3885d4d6ebb2a3ece4b5864d6`: the complete runner
suite passed 1,888 tests, with 10 existing skips. The full Rust release
workspace passed with serial test scheduling. The unchanged parallel
Rust run hit the five-second 300-descendant fixture deadline; that
failure is retained. No deadline or assertion was relaxed.
- The resolved-execution regression suite passed 57 tests, including
concurrent delivery, lost acknowledgement, superseded authority, and
newer operator evidence. Plain server typecheck passed. The
duplicate-delivery cases were first reproduced failing.
- Prior exact `335b2ee52709afb3885d4d6ebb2a3ece4b5864d6` CI passed all
required jobs and Greptile reported 5/5. Its local general-server run
passed 7,208 tests but failed one responsibility fixture; later phases
did not run. The fixture started the next wake while its bounded handoff
was active. It also used nonexistent comment IDs, which hid the current
stored-message-author identity rule. The updated tests use real message
authors, preserve task ownership, and await exact automatic handoffs. No
production identity policy changed.
- Current head `aa39275a1f300f7d1a0b16cd0885eea567cff6b0` includes
current master and the native context-source projection. The focused
identity/status cohort passed 27 tests and plain server typecheck
passed. Fresh full repository tests, types, build, required CI, and
Greptile review are pending. Final results will be updated before merge.
- This is deterministic local-provider evidence. It is not a claim of
complete live-provider qualification.

## Risks

- This changes authenticated recovery and close ordering. The TypeScript
transport and runner binary must be built from the same revision.
- Failed or incomplete evidence intentionally prevents reuse and can
require a fresh run.
- PRP v1 ordinary/cold sessions remain supported. A v1 connection lease
cannot upgrade in place. A current v2-capable runner held on a v1 lease
was qualified through owned-process retirement/join, fresh bootstrap on
the same old authority, v2 observation/ACK, then warm rotation. Legacy
binary replacement and adopted-owner migration are not qualified by that
test; rollout must not present them as automatic same-lease upgrades.
- This pull request has no database migration or chat-channel
activation. The second pull request keeps the channel feature
experimental.

## Model Used

OpenAI Codex assisted with implementation, tool execution, tests, and
reconciliation. The existing implementation records OpenAI `gpt-6-astra`
assistance. The current environment does not report a context-window
size. No private reasoning traces are included.

## 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
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-09 11:02:59 -05:00
1 parent bf753b997a
commit fac07b42ad
50 files changed
+18439 -1780

No files matched your search

@@ -149,7 +149,7 @@ describeEmbeddedPostgres("heartbeat responsible-user invariant", () => {
return { companyId, ownerUserId, agentId };
}
it("uses the issue responsible user for comment, mention, and dependency wakes", async () => {
it("uses the issue responsible user for automated dependency wakes without a message context", async () => {
const { companyId, agentId } = await seedCompany();
const issueResponsibleUserId = `issue-owner-${randomUUID()}`;
const commenterUserId = `commenter-${randomUUID()}`;
@@ -163,22 +163,90 @@ describeEmbeddedPostgres("heartbeat responsible-user invariant", () => {
responsibleUserId: issueResponsibleUserId,
});
for (const wakeReason of ["issue_commented", "issue_comment_mentioned", "issue_blockers_resolved"]) {
const sourceRunIds: string[] = [];
for (let attempt = 0; attempt < 3; attempt += 1) {
const wakeReason = "issue_blockers_resolved";
const run = await heartbeat.wakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: wakeReason,
payload: { issueId, commentId: randomUUID() },
payload: { issueId },
requestedByActorType: "user",
requestedByActorId: commenterUserId,
contextSnapshot: { issueId, taskId: issueId, wakeReason },
});
expect(run).not.toBeNull();
sourceRunIds.push(run!.id);
const completed = await waitForRun(db, run!.id);
expect(completed?.responsibleUserId).toBe(issueResponsibleUserId);
expect(completed?.status).toBe("succeeded");
// A terminal row can precede the execution's final queue/lease cleanup.
// This test starts independent wakes, not a burst that may be deferred.
await drainHeartbeatRunsToQuiescence(db, heartbeat);
}
// The deliberately disposition-free adapter response schedules one bounded
// handoff per source run. Those automatic continuations retain its identity.
const runs = await db.select().from(heartbeatRuns);
const handoffs = runs.filter((run) => !sourceRunIds.includes(run.id));
expect(handoffs).toHaveLength(3);
expect(
handoffs.map((run) => run.contextSnapshot?.parentRunId).sort(),
).toEqual(sourceRunIds.sort());
for (const handoff of handoffs) {
expect(handoff.contextSnapshot?.wakeReason).toBe(
"finish_successful_run_handoff",
);
expect(handoff.responsibleUserId).toBe(issueResponsibleUserId);
expect(handoff.status).toBe("succeeded");
}
expect(mockAdapterExecute).toHaveBeenCalledTimes(runs.length);
});
it.each(["issue_commented", "issue_comment_mentioned"])(
"uses the persisted message author for %s without changing issue ownership",
async (wakeReason) => {
const { companyId, agentId } = await seedCompany();
const issueResponsibleUserId = `issue-owner-${randomUUID()}`;
const commenterUserId = `commenter-${randomUUID()}`;
const issueId = randomUUID();
const commentId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Message-authored work",
status: "todo",
assigneeAgentId: agentId,
responsibleUserId: issueResponsibleUserId,
});
await db.insert(issueComments).values({
id: commentId,
companyId,
issueId,
authorUserId: commenterUserId,
body: `Current request for ${wakeReason}`,
});
const run = await heartbeat.wakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: wakeReason,
payload: { issueId, commentId },
// Request metadata is not authority to replace the stored author.
requestedByActorType: "user",
requestedByActorId: `different-requester-${randomUUID()}`,
contextSnapshot: { issueId, taskId: issueId, wakeReason },
});
expect(run).not.toBeNull();
const completed = await waitForRun(db, run!.id);
expect(completed?.status).toBe("succeeded");
expect(completed?.responsibleUserId).toBe(commenterUserId);
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
expect(issue?.responsibleUserId).toBe(issueResponsibleUserId);
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
},
);
it("uses the triggering user for manual UI/API runs", async () => {
const { agentId } = await seedCompany();
const triggeringUserId = `manual-${randomUUID()}`;
@@ -226,11 +294,11 @@ describeEmbeddedPostgres("heartbeat responsible-user invariant", () => {
const run = await heartbeat.wakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: { issueId, commentId: randomUUID() },
reason: "issue_blockers_resolved",
payload: { issueId },
requestedByActorType: "user",
requestedByActorId: `commenter-${randomUUID()}`,
contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_commented" },
contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_blockers_resolved" },
});
expect(run).not.toBeNull();
const completed = await waitForRun(db, run!.id);
@@ -10,21 +10,27 @@ function run(status: string, resultJson: Record<string, unknown> | null) {
triggerDetail: "system",
error: null,
errorCode: null,
contextSnapshot: { source: "native_status_decision" },
startedAt: new Date("2026-07-23T12:00:00.000Z"),
finishedAt: status === "running" ? null : new Date("2026-07-23T12:01:00.000Z"),
finishedAt:
status === "running" ? null : new Date("2026-07-23T12:01:00.000Z"),
resultJson,
} as never;
};
}
describe("buildHeartbeatRunStatusLiveEventPayload", () => {
it("attaches the canonical final assistant text to terminal status events", () => {
expect(
buildHeartbeatRunStatusLiveEventPayload(
run("succeeded", { summary: "Hello! How can I help?", stdout: "raw logs" }),
run("succeeded", {
summary: "Hello! How can I help?",
stdout: "raw logs",
}),
),
).toMatchObject({
runId: "run-1",
status: "succeeded",
contextSource: "native_status_decision",
finalText: "Hello! How can I help?",
});
});
@@ -39,4 +45,36 @@ describe("buildHeartbeatRunStatusLiveEventPayload", () => {
finalText: null,
});
});
it.each([undefined, null, "", " ", 7, {}])(
"does not invent a source for missing or invalid persisted context: %j",
(source) => {
expect(
buildHeartbeatRunStatusLiveEventPayload({
...run("succeeded", { summary: "Accepted response" }),
contextSnapshot: { source },
}).contextSource,
).toBeNull();
},
);
it("preserves a trimmed source without exposing the rest of the context", () => {
const payload = buildHeartbeatRunStatusLiveEventPayload({
...run("running", null),
contextSnapshot: { source: " chat:slack ", privateContext: "not-public" },
});
expect(payload.contextSource).toBe("chat:slack");
expect(payload).not.toHaveProperty("contextSnapshot");
expect(JSON.stringify(payload)).not.toContain("not-public");
});
it("keeps thin dispatch projections compatible without inventing a source", () => {
const { contextSnapshot: _contextSnapshot, ...projection } = run(
"failed",
null,
);
expect(
buildHeartbeatRunStatusLiveEventPayload(projection).contextSource,
).toBeNull();
});
});
@@ -5,6 +5,8 @@ import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
agentRuntimeState,
authUsers,
agentWakeupRequests,
activityLog,
companies,
@@ -24,7 +26,8 @@ import {
} from "./helpers/embedded-postgres.js";
import { errorHandler } from "../middleware/index.js";
import { issueRoutes } from "../routes/issues.js";
import { buildPaperclipWakePayload } from "../services/heartbeat.js";
import { buildPaperclipWakePayload, heartbeatService } from "../services/heartbeat.js";
import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.js";
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
import { recoveryService } from "../services/recovery/service.js";
import { noticeMetadataReferencesRecoveryAction } from "../services/recovery/successful-run-handoff.js";
@@ -144,8 +147,10 @@ describeEmbeddedPostgres("issue recovery actions", () => {
await db.delete(environments);
await db.delete(issueInboxArchives);
await db.delete(issues);
await db.delete(agentRuntimeState);
await db.delete(agents);
await db.delete(companies);
await db.delete(authUsers);
});
afterAll(async () => {
@@ -1655,6 +1660,283 @@ describeEmbeddedPostgres("issue recovery actions", () => {
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action!.id)))[0]).toEqual(recorded);
});
async function seedReconciledDelivery() {
const fixture = await seedCompany();
const { companyId, coderId, sourceIssueId } = fixture;
const responsibleUserId = randomUUID();
await db.insert(authUsers).values({
id: responsibleUserId,
name: "Recovery operator",
email: `${responsibleUserId}@example.test`,
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
});
await db
.update(companies)
.set({ defaultResponsibleUserId: responsibleUserId })
.where(eq(companies.id, companyId));
await db
.update(agents)
.set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } })
.where(eq(agents.id, coderId));
const previousRunId = randomUUID();
await seedHeartbeatRun({
companyId,
agentId: coderId,
runId: previousRunId,
issueId: sourceIssueId,
status: "failed",
});
// Occupy the agent's only dispatch slot, independently of this issue. These
// tests exercise real wake admission, but cannot launch a provider process.
await seedHeartbeatRun({
companyId,
agentId: coderId,
runId: randomUUID(),
status: "running",
});
const [action] = await db
.insert(issueRecoveryActions)
.values({
companyId,
sourceIssueId,
kind: "active_run_watchdog",
status: "resolved",
outcome: "restored",
ownerType: "board",
returnOwnerAgentId: coderId,
cause: "uncertain_external_action",
fingerprint: previousRunId,
nextAction: "Continue from the verified reconciliation.",
evidence: {
runId: previousRunId,
continuationDelivery: "pending",
executionReconciliation: {
runId: previousRunId,
providerStopped: true,
actionOutcome: "not_performed",
outcomeEvidence: "Verified absent provider effect.",
},
},
})
.returning();
return {
...fixture,
previousRunId,
action: action!,
heartbeat: heartbeatService(db, { runtimeEnv: {} }),
};
}
it("delivers a reconciled execution once across concurrent sweeps without a deferred duplicate", async () => {
const { action, heartbeat } = await seedReconciledDelivery();
let entered = 0;
let release!: () => void;
const bothEntered = new Promise<void>((resolve) => {
release = resolve;
});
const wake: typeof heartbeat.wakeup = async (...args) => {
entered += 1;
if (entered === 2) release();
await bothEntered;
return heartbeat.wakeup(...args);
};
await Promise.all([
deliverReconciledExecutions(db, wake),
deliverReconciledExecutions(db, wake),
]);
const wakes = await db
.select()
.from(agentWakeupRequests)
.where(
eq(
agentWakeupRequests.idempotencyKey,
`execution-reconciliation:${action.id}`,
),
);
expect(wakes).toHaveLength(1);
expect(wakes[0]).toMatchObject({ status: "queued" });
const [receipt] = await db
.select()
.from(issueRecoveryActions)
.where(eq(issueRecoveryActions.id, action.id));
expect(receipt!.evidence).toMatchObject({
continuationDelivery: "delivered",
continuationRunId: wakes[0]!.runId,
});
});
it("reconciles a lost wake acknowledgement after the exact successor has already finished", async () => {
const { action, heartbeat, companyId, previousRunId } =
await seedReconciledDelivery();
let successorId: string | undefined;
await deliverReconciledExecutions(db, async (...args) => {
const run = await heartbeat.wakeup(...args);
expect(run).not.toBeNull();
successorId = run!.id;
expect(run!.retryOfRunId).toBe(previousRunId);
throw new Error("fixture lost post-commit wake acknowledgement");
});
expect(successorId).toBeDefined();
await db
.update(heartbeatRuns)
.set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, successorId!));
await deliverReconciledExecutions(db, heartbeat.wakeup);
const wakes = await db
.select()
.from(agentWakeupRequests)
.where(
eq(
agentWakeupRequests.idempotencyKey,
`execution-reconciliation:${action.id}`,
),
);
expect(wakes).toHaveLength(1);
const [successor] = await db
.select()
.from(heartbeatRuns)
.where(
and(
eq(heartbeatRuns.companyId, companyId),
eq(heartbeatRuns.id, successorId!),
),
);
expect(successor).toMatchObject({
status: "succeeded",
retryOfRunId: previousRunId,
});
const [receipt] = await db
.select()
.from(issueRecoveryActions)
.where(eq(issueRecoveryActions.id, action.id));
expect(receipt!.evidence).toMatchObject({
continuationDelivery: "delivered",
continuationRunId: successorId,
});
});
it.each(["owner", "status", "decision"] as const)(
"rechecks the current reconciliation %s after the sweep read",
async (changed) => {
const { action, heartbeat, sourceIssueId, managerId } =
await seedReconciledDelivery();
await deliverReconciledExecutions(db, async (...args) => {
if (changed === "owner")
await db
.update(issues)
.set({ assigneeAgentId: managerId })
.where(eq(issues.id, sourceIssueId));
if (changed === "status")
await db
.update(issues)
.set({ status: "done" })
.where(eq(issues.id, sourceIssueId));
if (changed === "decision")
await db
.update(issueRecoveryActions)
.set({
evidence: {
...action.evidence,
executionReconciliation: {
...(action.evidence.executionReconciliation as object),
runId: randomUUID(),
},
},
})
.where(eq(issueRecoveryActions.id, action.id));
return heartbeat.wakeup(...args);
});
expect(
await db
.select()
.from(agentWakeupRequests)
.where(
eq(
agentWakeupRequests.idempotencyKey,
`execution-reconciliation:${action.id}`,
),
),
).toHaveLength(0);
const [receipt] = await db
.select()
.from(issueRecoveryActions)
.where(eq(issueRecoveryActions.id, action.id));
expect(receipt!.evidence.continuationDelivery).toBe("pending");
},
);
it("keeps reconciliation pending behind unrelated issue work without creating a second deferred outbox", async () => {
const { action, heartbeat, sourceIssueId, companyId, coderId } =
await seedReconciledDelivery();
const occupiedRunId = randomUUID();
await seedHeartbeatRun({
companyId,
agentId: coderId,
runId: occupiedRunId,
issueId: sourceIssueId,
status: "queued",
});
await deliverReconciledExecutions(db, heartbeat.wakeup);
await deliverReconciledExecutions(db, heartbeat.wakeup);
expect(
await db
.select()
.from(agentWakeupRequests)
.where(
eq(
agentWakeupRequests.idempotencyKey,
`execution-reconciliation:${action.id}`,
),
),
).toHaveLength(0);
const [occupied] = await db
.select()
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, occupiedRunId));
expect(occupied!.contextSnapshot).toEqual({ issueId: sourceIssueId });
await db
.update(heartbeatRuns)
.set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, occupiedRunId));
await deliverReconciledExecutions(db, heartbeat.wakeup);
const wakes = await db
.select()
.from(agentWakeupRequests)
.where(
eq(
agentWakeupRequests.idempotencyKey,
`execution-reconciliation:${action.id}`,
),
);
expect(wakes).toHaveLength(1);
expect(wakes[0]!.runId).not.toBe(occupiedRunId);
});
it("does not overwrite a newer reconciliation decision after a prior wake commits", async () => {
const { action, heartbeat } = await seedReconciledDelivery();
const newerEvidence = {
...action.evidence,
continuationDelivery: "invalidated",
operatorNote: "Do not continue after new evidence.",
};
await deliverReconciledExecutions(db, async (...args) => {
const run = await heartbeat.wakeup(...args);
expect(run).not.toBeNull();
await db
.update(issueRecoveryActions)
.set({ evidence: newerEvidence })
.where(eq(issueRecoveryActions.id, action.id));
return run;
});
const [receipt] = await db
.select()
.from(issueRecoveryActions)
.where(eq(issueRecoveryActions.id, action.id));
expect(receipt!.evidence).toEqual(newerEvidence);
});
it("resolves an active recovery action and removes it from active projections", async () => {
const { companyId, managerId, sourceIssueId } = await seedCompany();
const recoveryActionSvc = issueRecoveryActionService(db);
@@ -186,6 +186,13 @@ export async function deliverReconciledExecutions(
const decision = action.evidence.executionReconciliation as
ExecutionReconciliation | undefined;
if (!decision || !action.returnOwnerAgentId) continue;
const pendingDecision = and(
eq(issueRecoveryActions.companyId, action.companyId),
eq(issueRecoveryActions.id, action.id),
eq(issueRecoveryActions.status, "resolved"),
sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'pending'`,
sql`${issueRecoveryActions.evidence}->'executionReconciliation' = ${JSON.stringify(decision)}::jsonb`,
);
const [task] = await db
.select()
.from(issues)
@@ -203,12 +210,9 @@ export async function deliverReconciledExecutions(
await db
.update(issueRecoveryActions)
.set({
evidence: {
...action.evidence,
continuationDelivery: "invalidated",
},
evidence: sql`${issueRecoveryActions.evidence} || '{"continuationDelivery":"invalidated"}'::jsonb`,
})
.where(eq(issueRecoveryActions.id, action.id));
.where(pendingDecision);
continue;
}
const run = await wake(action.returnOwnerAgentId, {
@@ -239,18 +243,22 @@ export async function deliverReconciledExecutions(
and(
eq(heartbeatRuns.companyId, action.companyId),
eq(heartbeatRuns.id, run.id),
eq(heartbeatRuns.agentId, action.returnOwnerAgentId!),
sql`${heartbeatRuns.contextSnapshot}->>'recoveryActionId' = ${action.id}`,
sql`${heartbeatRuns.contextSnapshot}->>'previousRunId' = ${decision.runId}`,
),
);
await tx
.update(issueRecoveryActions)
.set({
evidence: {
...action.evidence,
continuationDelivery: "delivered",
continuationRunId: run.id,
},
evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify(
{
continuationDelivery: "delivered",
continuationRunId: run.id,
},
)}::jsonb`,
})
.where(eq(issueRecoveryActions.id, action.id));
.where(pendingDecision);
});
} catch {
logger.warn(
@@ -14,7 +14,8 @@ export function buildHeartbeatRunStatusLiveEventPayload(
| "startedAt"
| "finishedAt"
| "resultJson"
>,
> &
Partial<Pick<typeof heartbeatRuns.$inferSelect, "contextSnapshot">>,
) {
return {
runId: run.id,
@@ -24,6 +25,11 @@ export function buildHeartbeatRunStatusLiveEventPayload(
triggerDetail: run.triggerDetail,
error: run.error ?? null,
errorCode: run.errorCode ?? null,
contextSource:
typeof run.contextSnapshot?.source === "string" &&
run.contextSnapshot.source.trim()
? run.contextSnapshot.source.trim()
: null,
startedAt: run.startedAt ? new Date(run.startedAt).toISOString() : null,
finishedAt: run.finishedAt ? new Date(run.finishedAt).toISOString() : null,
finalText: [
+123
View File
@@ -23597,6 +23597,9 @@ export function heartbeatService(
};
const reason = opts.reason ?? null;
const payload = opts.payload ?? null;
const executionReconciliationWake =
contextSnapshot.source === "execution.reconciled" ||
opts.idempotencyKey?.startsWith("execution-reconciliation:") === true;
const {
contextSnapshot: enrichedContextSnapshot,
issueIdFromPayload,
@@ -23611,6 +23614,7 @@ export function heartbeatService(
});
let issueId =
readNonEmptyString(enrichedContextSnapshot.issueId) ?? issueIdFromPayload;
if (executionReconciliationWake && !issueId) return null;
let agent = await getAgent(agentId);
if (!agent) throw notFound("Agent not found");
@@ -24026,6 +24030,113 @@ export function heartbeatService(
return { kind: "skipped" as const };
}
let reconciledSourceRunId: string | null = null;
if (executionReconciliationWake) {
const actionId = readNonEmptyString(
enrichedContextSnapshot.recoveryActionId,
);
if (
!actionId ||
!isUuidLike(actionId) ||
source !== "automation" ||
triggerDetail !== "system" ||
reason !== "issue_recovery_action_restored" ||
opts.requestedByActorType !== "system" ||
opts.requestedByActorId !== "execution-recovery" ||
opts.idempotencyKey !== `execution-reconciliation:${actionId}` ||
enrichedContextSnapshot.source !== "execution.reconciled" ||
enrichedContextSnapshot.forceFreshSession !== true ||
payload?.issueId !== issue.id ||
payload?.recoveryActionId !== actionId ||
issue.assigneeAgentId !== agentId ||
["done", "cancelled"].includes(issue.status)
)
return { kind: "skipped" as const };
// The issue lock serializes all admissions for this source. Validate
// the durable operator decision, then reconcile a prior queue commit
// before considering a new wake (including a now-terminal successor).
const [action] = await tx
.select()
.from(issueRecoveryActions)
.where(
and(
eq(issueRecoveryActions.companyId, issue.companyId),
eq(issueRecoveryActions.sourceIssueId, issue.id),
eq(issueRecoveryActions.id, actionId),
),
)
.for("update");
const decision = parseObject(
action?.evidence.executionReconciliation,
);
const sourceRunId = readNonEmptyString(decision.runId);
if (
!action ||
action.status !== "resolved" ||
action.kind !== "active_run_watchdog" ||
action.returnOwnerAgentId !== agentId ||
!sourceRunId ||
!isUuidLike(sourceRunId) ||
decision.providerStopped !== true ||
!["completed", "not_performed", "mixed"].includes(
String(decision.actionOutcome),
) ||
!readNonEmptyString(decision.outcomeEvidence) ||
enrichedContextSnapshot.previousRunId !== sourceRunId ||
enrichedContextSnapshot.retryOfRunId !== sourceRunId ||
!["pending", "delivered"].includes(
String(action.evidence.continuationDelivery),
)
)
return { kind: "skipped" as const };
const [existingWake] = await tx
.select()
.from(agentWakeupRequests)
.where(
and(
eq(agentWakeupRequests.companyId, issue.companyId),
eq(agentWakeupRequests.agentId, agentId),
eq(agentWakeupRequests.idempotencyKey, opts.idempotencyKey),
ne(agentWakeupRequests.status, "skipped"),
),
)
.orderBy(asc(agentWakeupRequests.requestedAt))
.limit(1);
if (existingWake) {
if (
existingWake.payload?.issueId !== issue.id ||
existingWake.payload?.recoveryActionId !== action.id ||
existingWake.requestedByActorType !== "system" ||
existingWake.requestedByActorId !== "execution-recovery" ||
!existingWake.runId
)
return { kind: "deferred" as const };
const [existingRun] = await tx
.select()
.from(heartbeatRuns)
.where(
and(
eq(heartbeatRuns.companyId, issue.companyId),
eq(heartbeatRuns.agentId, agentId),
eq(heartbeatRuns.id, existingWake.runId),
),
);
if (
!existingRun ||
existingRun.contextSnapshot?.issueId !== issue.id ||
existingRun.contextSnapshot?.recoveryActionId !== action.id ||
existingRun.contextSnapshot?.previousRunId !== sourceRunId
)
return { kind: "deferred" as const };
return { kind: "replayed" as const, run: existingRun };
}
if (action.evidence.continuationDelivery !== "pending")
return { kind: "skipped" as const };
reconciledSourceRunId = sourceRunId;
}
const issueStateGuard = opts.issueStateGuard;
if (
issueStateGuard &&
@@ -24528,6 +24639,10 @@ export function heartbeatService(
}
if (activeExecutionRun) {
// The resolved action is already a durable retry outbox. Do not merge
// its fresh-session contract into unrelated work or create a second
// deferred wake that could later replay the same reconciliation.
if (reconciledSourceRunId) return { kind: "deferred" as const };
const executionAgent = await tx
.select({ name: agents.name })
.from(agents)
@@ -24867,6 +24982,9 @@ export function heartbeatService(
contextSnapshot: enrichedContextSnapshot,
sessionIdBefore: sessionBefore,
continuationAttempt,
...(reconciledSourceRunId
? { retryOfRunId: reconciledSourceRunId }
: {}),
})
.returning()
.then((rows) => rows[0]);
@@ -24901,6 +25019,11 @@ export function heartbeatService(
await startNextQueuedRunForAgent(agent.id);
return outcome.run;
}
if (outcome.kind === "replayed") {
if (outcome.run.status === "queued")
await startNextQueuedRunForAgent(agent.id);
return outcome.run;
}
const newRun = outcome.run;
publishLiveEvent({