Repository navigation
fix(security): stop delegated restart recovery - #150702
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 24, 2026, 10:58 PM ET / September 25, 2026, 02:58 UTC (Revision 8). ClawSweeper reviewWhat this changesThe branch checks saved completion custody and transcript source before restart recovery dispatch, retains pending work after transcript-read failures, and adds recovery tests and documentation. Merge readiness✅ Ready for maintainer review Current main still permits recovery dispatch before checking the interrupted source and completion custody. This branch addresses that gap, and the documented delegated-continuity tradeoff has been explicitly accepted. Priority: P1 Review scores
Verification
How this fits togetherAfter a Gateway restart, main-session recovery reads saved session and transcript state to decide whether to resume an interrupted agent turn. That decision can start a new turn and ultimately deliver a final reply. flowchart LR
A[Gateway restart] --> B[Saved session and pending delivery]
B --> C{Queue owner still active?}
C -->|Yes| D[Queue settles delivery]
C -->|No| E[Read transcript and completion custody]
E --> F{Source authorized?}
F -->|Yes| G[Resume agent and deliver reply]
F -->|No| H[Retain or close recovery with notice]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +36, Tests +230, Docs +7. Total +273 across 4 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep recovery eligibility with the main-session recovery owner, preserving independent queue delivery and giving denied delegated turns clear replacement-session guidance. Do we have a high-confidence way to reproduce the issue? Yes, from source: current main can dispatch a replayable pending final before reading the full transcript and checking completion custody. This read-only review did not execute the reported pre-fix failure. Is this the best way to solve the issue? Yes. Checking source and custody in the recovery owner before dispatch is a narrow repair, and the exact-head proof covers allowed delivery and post-dispatch revocation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against ac52478247ca. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
330a2ba to
971b785
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Maintainer update: moved unresolved harness-completion custody ahead of the delegated recovery denial and made the source probe non-vacuous for an empty transcript. The exact completion claim now stays pending without dispatch; the latter empty-source case is covered by the existing completion harness. @clawsweeper re-review |
|
Exact-head focused recovery suite passed (217 tests). The prior rank move is reflected in the body and completion custody now has an absent-source-key case. @clawsweeper re-review |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Exact-head evidence for The bounded probe ran the production recovery entry, command recovery binding, admitted source assertion, pending-final marker, and durable automatic sender. A controlled in-process Gateway receiver supplied synthetic model output. The final channel adapter performed a real task-local file append only after the production platform-dispatch/handoff guards. This is isolated component-boundary proof, not an external channel or model run. Each case first persisted and closed its SQLite state, then reopened it for recovery. For revocation cases, the probe waited for actual recovery adoption and held the production adapter-preparation boundary before cancelling the task or changing its requester. It did not manually clear the aborted marker or bypass a source guard.
Both revoked cases reported Maintainer disposition: ending automatic replay after the process-bound delegated sender authority is lost is intentional, including an unowned pending final. The transcript and replacement-session guidance remain available. A durable queue owner still retains its independent delivery responsibility; direct inputs and valid completion claims remain retryable after read faults. This accepts the documented continuity tradeoff without reconstructing authority from provenance or an old run ID. Persisted formats and updater/migration code are unchanged; the existing-state result above is a cold-reopened SQLite recovery check, not a published-installer test. Measured cost: the complete final owning file passed 222/222 with one worker, in 423.27 seconds command wall time (405.71 seconds within Vitest) on the shared macOS host with Node 24.21.0. The seven added cases' reported durations sum to 16.591 seconds within that serial run; this is not a counterfactual baseline delta. Ordinary CI run 36085089085 passed at this exact head on attempt 1; its start-to-completion span was 32m 36s including queue time. No deadlines or assertions were relaxed. The initial standalone probe setup failures are retained separately and are not counted as passing evidence: a Vitest-only registry reset was replaced with the production reload owner, and the receiver was corrected to honor execution-start/adoption ordering before final-marker persistence. The four successful cases below use the unchanged published source. Sanitized observed trace{
"head": "71bebdd1a4090c88b2f5eb525a880d522529c0a5",
"boundary": "Production recovery, generic admitted source/custody and durable delivery owners with a controlled in-process Gateway receiver, synthetic model output, and a task-local filesystem transport. No external service or model inference.",
"node": "v24.21.0",
"cases": [
{
"scenario": "allowed",
"recovery": {
"started": 1,
"settled": 0,
"failed": 0,
"skipped": 0
},
"dispatches": 1,
"physicalFinalWrites": 1,
"actionableNotice": false,
"deliveryStatus": {
"requested": true,
"attempted": true,
"status": "sent",
"succeeded": true,
"resultCount": 1,
"payloadOutcomes": [
{
"index": 0,
"status": "sent",
"resultCount": 1
}
]
},
"taskStatus": "succeeded",
"taskDelivery": "delivered",
"pendingQueueEntries": 0,
"trace": [
"saved-state-reopened",
"recovery-dispatched",
"recovery-adoption-committed",
"delivery-preparation-entered",
"platform-handoff-entered",
"physical-final-written"
],
"elapsedMs": 28921
},
{
"scenario": "cancelled",
"recovery": {
"started": 1,
"settled": 0,
"failed": 0,
"skipped": 0
},
"dispatches": 1,
"physicalFinalWrites": 0,
"actionableNotice": false,
"deliveryStatus": {
"error": "OutboundDeliveryError"
},
"taskStatus": "cancelled",
"taskDelivery": "pending",
"pendingQueueEntries": 0,
"trace": [
"saved-state-reopened",
"recovery-dispatched",
"recovery-adoption-committed",
"delivery-preparation-entered",
"task-cancelled-after-dispatch",
"delivery-rejected"
],
"elapsedMs": 61904,
"observedRefusal": {
"code": "OPENCLAW_PLATFORM_MESSAGE_NOT_DISPATCHED",
"cause": "SESSION_WORK_START_CHANGED",
"retryable": false,
"sentBeforeError": false,
"queueCustody": "released"
}
},
{
"scenario": "reassigned",
"recovery": {
"started": 1,
"settled": 0,
"failed": 0,
"skipped": 0
},
"dispatches": 1,
"physicalFinalWrites": 0,
"actionableNotice": false,
"deliveryStatus": {
"error": "OutboundDeliveryError"
},
"taskStatus": "succeeded",
"taskDelivery": "pending",
"pendingQueueEntries": 0,
"trace": [
"saved-state-reopened",
"recovery-dispatched",
"recovery-adoption-committed",
"delivery-preparation-entered",
"task-reassigned-after-dispatch",
"delivery-rejected"
],
"elapsedMs": 61912,
"observedRefusal": {
"code": "OPENCLAW_PLATFORM_MESSAGE_NOT_DISPATCHED",
"cause": "SESSION_WORK_START_CHANGED",
"retryable": false,
"sentBeforeError": false,
"queueCustody": "released"
}
},
{
"scenario": "saved-delegated",
"recovery": {
"started": 0,
"settled": 0,
"failed": 0,
"skipped": 1
},
"dispatches": 0,
"physicalFinalWrites": 0,
"actionableNotice": true,
"taskStatus": "succeeded",
"taskDelivery": "pending",
"pendingQueueEntries": 0,
"trace": [
"saved-state-reopened"
],
"elapsedMs": 55493
}
],
"cleanup": "All four processes joined successfully; fixture-owned state and workers were removed."
}Exact standalone probe sourceSaved under import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import fs from "node:fs/promises";
import path from "node:path";
import {
prepareAgentRunAdmission,
createOperationalRunInstanceRef,
resolveAdmittedRunActiveAssertion,
} from "../src/agents/admitted-run-context.js";
import {
buildCurrentRunRestartRecoveryClaim,
bindCommandHarnessCompletionAssertion,
} from "../src/agents/agent-command-restart-recovery.js";
import { deliverAgentCommandResult } from "../src/agents/command/delivery.js";
import { prepareCommandSessionRecoveryEntry } from "../src/agents/command/session-preparation.js";
import { recoverRestartAbortedMainSessions } from "../src/agents/main-session-recovery/main-session-restart-recovery.js";
import { persistPendingFinalDeliveryMarker } from "../src/agents/pending-final-delivery-marker.js";
import { createMessageReceiptFromOutboundResults } from "../src/channels/message/receipt.js";
import type { ChannelPlugin } from "../src/channels/plugins/types.public.js";
import {
appendTranscriptMessage,
loadExactSessionEntry,
replaceSessionEntry,
} from "../src/config/sessions/session-accessor.js";
import type { GatewayRecoveryRuntime } from "../src/gateway/server-instance-runtime.types.js";
import type { AgentRunRequest } from "../src/gateway/server-methods/agent-request-types.js";
import { loadDeliveryQueueEntries } from "../src/infra/delivery-queue-sqlite.js";
import { OUTBOUND_DELIVERY_QUEUE_NAME } from "../src/infra/outbound/delivery-queue-media-staging.js";
import { createAgentHarnessTaskRuntime } from "../src/plugin-sdk/agent-harness-task-runtime.js";
import { resetGlobalHookRunner } from "../src/plugins/hook-runner-global.js";
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../src/plugins/runtime.js";
import { captureOpenClawStateWorkerContext } from "../src/state/openclaw-state-worker-context.js";
import { captureHarnessCompletionRecovery } from "../src/tasks/agent-harness-completion-recovery.js";
import { createAgentHarnessTaskRuntimeScope } from "../src/tasks/agent-harness-task-runtime-scope.js";
import { updateTask } from "../src/tasks/task-registry-mutation.js";
import { reloadTaskRegistryFromStoreAsync } from "../src/tasks/task-registry-state.js";
import { getTaskById, markTaskTerminalById } from "../src/tasks/task-registry.js";
import { stopTaskRegistryMaintenance } from "../src/tasks/task-registry.maintenance.js";
import { createOutboundTestPlugin, createTestRegistry } from "../src/test-utils/channel-plugins.js";
import { withOpenClawTestState } from "../src/test-utils/openclaw-test-state.js";
import { cleanupSessionStateForTest } from "../src/test-utils/session-state-cleanup.js";
import { createDeferred } from "../test/helpers/promise.js";
const head = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
assert.equal(head, "71bebdd1a4090c88b2f5eb525a880d522529c0a5");
const results: unknown[] = [];
const started = performance.now();
for (const scenario of ["allowed", "cancelled", "reassigned", "saved-delegated"] as const) {
if (scenario !== process.argv[3]) continue;
const caseStarted = performance.now();
await withOpenClawTestState(
{ scenario: "minimal", label: `recovery-final-${scenario}` },
async (state) => {
const key = "agent:main:matrix:direct:proof";
const child = "proof:child";
const source = "announce:proof:child:succeeded";
const target = {
agentId: "main",
sessionKey: key,
storePath: path.join(state.sessionsDir(), "sessions.json"),
};
const route = { channel: "matrix", to: "!proof:example", accountId: "default" };
const entry = {
sessionId: "proof-parent",
lifecycleRevision: "proof-revision",
status: "running" as const,
abortedLastRun: true,
updatedAt: Date.now(),
permissionMode: "guarded" as const,
};
const tasks = createAgentHarnessTaskRuntime({
runtime: "subagent",
taskKind: "generic-proof",
scope: createAgentHarnessTaskRuntimeScope({ requesterSessionKey: key }),
runIdPrefix: "proof:",
});
const task = tasks.createRunningTaskRun({
runId: child,
sourceId: child,
task: "Synthetic completion",
requesterAgentId: "main",
notifyPolicy: "silent",
});
tasks.finalizeTaskRunByRunId({
runId: child,
status: "succeeded",
endedAt: Date.now(),
terminalSummary: "Synthetic result",
});
tasks.setDetachedTaskDeliveryStatusByRunId({ runId: child, deliveryStatus: "pending" });
const provenance = {
kind: "inter_session",
sourceTool: scenario === "saved-delegated" ? "sessions_send" : "agent_harness_task",
sourceChannel: "internal",
sourceSessionKey: child,
};
const claim =
scenario === "saved-delegated"
? undefined
: captureHarnessCompletionRecovery({
agentId: "main",
sessionKey: key,
entry,
runId: source,
inputProvenance: provenance,
});
if (scenario !== "saved-delegated") assert.ok(claim);
const persisted = {
...entry,
...buildCurrentRunRestartRecoveryClaim({
entry,
runId: source,
sourceRunId: source,
sourceIngress: "internal",
sourceReplyDeliveryMode: "automatic",
deliveryContext: route,
harnessCompletion: claim,
}),
...(scenario === "saved-delegated"
? {
pendingFinalDelivery: {
kind: "replayable" as const,
text: "Unsent delegated final",
createdAt: Date.now(),
intentId: "old-unowned-final",
deliveries: [{ id: "old-unowned-delivery", state: "prepared" as const }],
},
}
: {}),
};
await replaceSessionEntry(target, persisted);
await appendTranscriptMessage(
{ ...target, sessionId: entry.sessionId },
{
message: {
role: "user",
content: "Saved interrupted input",
idempotencyKey: `${source}:user`,
provenance,
__openclaw: { runId: source },
},
},
);
// Reopen saved SQLite state, rather than lending the producer's live handles to recovery.
await cleanupSessionStateForTest({ stateDir: state.stateDir });
await reloadTaskRegistryFromStoreAsync(captureOpenClawStateWorkerContext());
const effectPath = state.path("final-effect.txt");
const noticePath = state.path("notice.txt");
const trace: string[] = ["saved-state-reopened"];
const entered = createDeferred();
const release = createDeferred();
const adopted = createDeferred();
let dispatches = 0;
let terminalStatus: "ok" | "error" | undefined;
let deliveryStatus: unknown;
let receiver: Promise<{ runId: string; status: "ok" | "error" }> | undefined;
const plugin: ChannelPlugin = {
...createOutboundTestPlugin({
id: "matrix",
outbound: {
deliveryMode: "direct",
sendText: async () => {
throw new Error("message adapter owns final I/O");
},
},
}),
message: {
id: "matrix",
durableFinal: { capabilities: { text: true } },
send: {
lifecycle: {
beforeSendAttempt: async () => {
trace.push("delivery-preparation-entered");
entered.resolve();
await release.promise;
},
},
text: async ({ text, onPlatformSendDispatch, assertDirectAdapterHandoff }) => {
trace.push("platform-handoff-entered");
await onPlatformSendDispatch?.();
assertDirectAdapterHandoff?.();
await fs.appendFile(effectPath, `${text}\n`, "utf8");
trace.push("physical-final-written");
return {
messageId: "proof-final",
receipt: createMessageReceiptFromOutboundResults({
results: [{ channel: "matrix", messageId: "proof-final" }],
kind: "text",
}),
};
},
},
},
};
setActivePluginRegistry(createTestRegistry([{ pluginId: "matrix", source: "test", plugin }]));
const runReceiver = async (
request: AgentRunRequest,
options?: Parameters<GatewayRecoveryRuntime["dispatchAgent"]>[2],
) => {
dispatches++;
trace.push("recovery-dispatched");
const runId = String(request.idempotencyKey);
const current = loadExactSessionEntry(target)?.entry;
assert.ok(current);
const opts = {
message: String(request.message),
deliver: true,
replyChannel: "matrix",
replyTo: route.to,
accountId: route.accountId,
sessionKey: key,
runId,
inputProvenance: request.inputProvenance,
};
const prepared = prepareCommandSessionRecoveryEntry({
entry: current,
sessionId: entry.sessionId,
sessionKey: key,
runId,
agentId: "main",
opts,
deliveryContext: route,
now: Date.now(),
isSessionRollover: false,
});
const bound = bindCommandHarnessCompletionAssertion({
claim: prepared.guardedHarnessCompletion,
persisted: current,
sessionKey: key,
storePath: target.storePath,
opts,
});
await appendTranscriptMessage(
{ ...target, sessionId: entry.sessionId },
{
message: {
role: "user",
content: opts.message,
idempotencyKey: `${runId}:user`,
provenance: request.inputProvenance,
__openclaw: { runId },
},
},
);
const admission = prepareAgentRunAdmission({
cfg: {},
facts: {
agentId: "main",
runId,
ingress: { kind: "system", boundary: "isolated-recovery-receiver", state: "present" },
},
operationalRunInstance: createOperationalRunInstanceRef(runId),
assertSourceCurrent: bound.assertSourceCurrent,
});
try {
const context = await admission.admit("embedded");
const expiresAtMs = Date.now() + 60_000;
options?.onStartOwner?.({
observe: () => ({ executionStarted: true, expiresAtMs }),
abort: () => false,
});
options?.onAccepted?.({ runId, status: "accepted" });
options?.onExecutionStarted?.();
await adopted.promise;
const running = loadExactSessionEntry(target)?.entry;
assert.ok(running);
assert.equal(running.abortedLastRun, false);
trace.push("recovery-adoption-committed");
const assertCurrent = resolveAdmittedRunActiveAssertion(context);
assert.ok(assertCurrent);
const payloads = [{ text: "Synthetic completed result" }];
const marker = await persistPendingFinalDeliveryMarker({
agentId: "main",
deliver: true,
sessionStore: { [key]: running },
sessionKey: key,
sessionEntry: running,
storePath: target.storePath,
suppressVisibleSessionEffects: false,
sessionReboundDuringRun: false,
payloads,
deliveryContext: route,
runOwnedSessionId: entry.sessionId,
});
assert.equal(marker.pendingFinalDeliveryMarkerPersisted, true);
const delivered = await deliverAgentCommandResult({
cfg: {},
deps: {},
runtime: { log: () => {}, error: () => {}, exit: () => {} },
opts: bound,
outboundSession: { agentId: "main", key },
sessionEntry: marker.sessionEntry,
result: { meta: { durationMs: 1 } },
payloads,
assertDeliveryCurrent: assertCurrent,
});
deliveryStatus = delivered.deliveryStatus;
terminalStatus = "ok";
} catch (error) {
trace.push("delivery-rejected");
console.error("Receiver failure:", error);
deliveryStatus = { error: error instanceof Error ? error.name : "unknown" };
terminalStatus = "error";
} finally {
admission.close();
}
return { runId, status: terminalStatus };
};
const gateway: GatewayRecoveryRuntime = {
dispatchAgent: <T,>(
request: AgentRunRequest,
_timeout?: number,
options?: Parameters<GatewayRecoveryRuntime["dispatchAgent"]>[2],
) => {
receiver = runReceiver(request, options);
return receiver as Promise<T>;
},
dispatchSessionMethod: async () => {
throw new Error("unexpected session RPC");
},
waitForAgent: async <T,>() =>
(terminalStatus
? { status: terminalStatus, endedAt: Date.now() }
: { status: "timeout" }) as T,
sendRecoveryNotice: async (notice) => {
if (notice.isCurrent && !notice.isCurrent({})) return { suppressed: true };
await fs.appendFile(noticePath, `${notice.text}\n`, "utf8");
return { suppressed: false };
},
};
const recovering = recoverRestartAbortedMainSessions({
cfg: {},
stateDir: state.stateDir,
gatewayRuntime: gateway,
});
try {
const recovery = await recovering;
if (scenario !== "saved-delegated") {
assert.equal(recovery.started, 1);
adopted.resolve();
await Promise.race([
entered.promise,
receiver!.then(() => {
throw new Error(
`receiver ended before final-send preparation: ${JSON.stringify({ trace, deliveryStatus })}`,
);
}),
]);
await assert.rejects(fs.stat(effectPath), { code: "ENOENT" });
if (scenario === "cancelled") {
markTaskTerminalById({
taskId: task.taskId,
status: "cancelled",
endedAt: Date.now() + 1,
});
assert.equal(getTaskById(task.taskId)?.status, "cancelled");
trace.push("task-cancelled-after-dispatch");
} else if (scenario === "reassigned") {
updateTask(task.taskId, { requesterSessionKey: "agent:main:replacement" });
assert.equal(getTaskById(task.taskId)?.requesterSessionKey, "agent:main:replacement");
trace.push("task-reassigned-after-dispatch");
}
release.resolve();
}
await receiver;
const effects = await fs.readFile(effectPath, "utf8").catch((error) => {
if (error.code === "ENOENT") return "";
throw error;
});
const notices = await fs.readFile(noticePath, "utf8").catch((error) => {
if (error.code === "ENOENT") return "";
throw error;
});
assert.equal(effects, scenario === "allowed" ? "Synthetic completed result\n" : "");
assert.equal(dispatches, scenario === "saved-delegated" ? 0 : 1);
assert.deepEqual(
loadDeliveryQueueEntries(OUTBOUND_DELIVERY_QUEUE_NAME, state.stateDir),
[],
);
if (scenario === "saved-delegated") {
assert.ok(loadExactSessionEntry(target)?.entry.mainRestartRecovery?.tombstone);
assert.match(notices, /\/new or \/reset/);
await recoverRestartAbortedMainSessions({
cfg: {},
stateDir: state.stateDir,
gatewayRuntime: gateway,
});
assert.equal(dispatches, 0);
assert.equal(await fs.readFile(noticePath, "utf8"), notices);
}
results.push({
scenario,
recovery,
dispatches,
physicalFinalWrites: effects ? 1 : 0,
actionableNotice: /\/new or \/reset/.test(notices),
deliveryStatus,
taskStatus: getTaskById(task.taskId)?.status,
taskDelivery: getTaskById(task.taskId)?.deliveryStatus,
pendingQueueEntries: 0,
trace,
elapsedMs: Math.round(performance.now() - caseStarted),
});
} finally {
adopted.resolve();
release.resolve();
await receiver?.catch(() => {});
resetGlobalHookRunner();
resetPluginRuntimeStateForTest();
await stopTaskRegistryMaintenance();
}
},
);
}
assert.equal(execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(), head);
const report = {
head,
scope:
"Production recovery, generic admitted source/custody and automatic delivery owners; synthetic model output and a task-local filesystem transport, no external service.",
node: process.version,
cases: results,
elapsedMs: Math.round(performance.now() - started),
cleanup: "fixture-owned state and workers joined and removed",
};
await fs.writeFile(process.argv[2], `${JSON.stringify(report, null, 2)}\n`);
console.log(JSON.stringify(report, null, 2)); |
|
The updated body now links the exact-head allowed/cancelled/reassigned final-effect trace, cold-reopened saved-session outcome, explicit maintainer disposition, measured one-worker cost, and first-attempt green CI. The production source remains unchanged at @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
* fix(security): stop delegated restart recovery * fix(security): retain unresolved completion custody * fix(security): require completion source evidence * test(security): exercise empty completion source * test(security): use a genuinely absent source key * fix(security): retain owned recovery on read failure * test(security): fold delegated recovery coverage into route case * test(security): keep delegated recovery case under line cap * test(security): keep delegated coverage ratchet-neutral * refactor(recovery): remove obsolete tail helper * test(security): keep transcript fallback coverage * test(security): keep delegated notice transcript-only * test(security): correct delegated notice claim fixture Co-authored-by: Vincent Koc <[email protected]>
Backport #157571: 0484d7a Adapted backport #150702: 6b5fb4b Backport #157958: 3802abe Backport #158259: 847863a Backport #156858: a5f1d09 Keep completion carriers within current-turn traversal and stop terminal transcript assertion retries. Preserve delegated restart provenance and owed completion custody; unknown provenance cannot inherit human evidence. Never let a queued, unstarted timeout end a different active turn. Reuse warm device identity and reacquire complete admission after observed rotation. Move the unchanged synchronous abort event into its existing lifecycle owner to satisfy the frozen line budget without weakening tests or guards. Source proof, recovery correction and owner-extraction checks are retained at their exact trees. Independent findings are resolved and composition preserves all 32 postimages; frozen ratchets and Madge pass. The two embedded-fallback attempt-count E2E cases remain unexecuted because canonical runtime preparation refused ownership; no guard was bypassed. Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: Jason (Json) <[email protected]> Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: jalehman <[email protected]>
Summary
Restart recovery could dispatch a pending final reply before checking the interrupted source and saved completion custody. A later transcript read failure could also trigger replay instead of retaining the interrupted work for another attempt.
Validate completion custody and the source before every new recovery dispatch. The existing snapshot-bound transcript visitor now reads the source and replay-safety checkpoint together with constant memory. Read failures preserve direct and admitted completion work, including pending replies. Delegated requests and unverified internal inputs cannot resume without surviving authority, and an internal harness completion cannot substitute provenance for its missing saved claim.
Keep the existing parent-continuation behavior from #153243 and outbound delivery ownership from #154591. Pending or settling queue owners still retain delivery custody; already completed deliveries settle without starting another model turn. No configuration, protocol, schema, or authority state is added.
Validation
recoverRestartAbortedMainSessionsentry. The transcript cases preserve readable navigation while corrupting a later payload, verify the actual reader error, and then prove recovery succeeds after repair.agents-othertest graph passed, along with scoped lint, formatting, line-cap/max-lines/assertion ratchets, docs MDX, and diff checks.Exact-head final-effect and saved-state proof exercised production recovery, command custody binding, admitted authority, and durable final delivery with a controlled in-process Gateway receiver and a task-local filesystem transport. Allowed completion produced one physical final write and settled delivery. Cancellation and requester reassignment after dispatch each produced zero final writes, non-retryable handoff rejection, and no queued retry. A cold-reopened delegated session with an unowned pending final received an actionable replacement-session notice and remained inert on repeat. All fixture workers and processes joined and their temporary state was removed. Synthetic model output was used; no external channel or model service is claimed.
Ordinary CI run 36085089085 passed at this exact head on attempt 1, with a 32m 36s workflow span including queue time. No test deadlines or assertions were relaxed.
Maintainer disposition: refusing automatic replay after delegated sender authority is lost is intentional, including an unowned pending final. Existing queue-owned delivery continues through its owner; direct and valid completion work remains retryable after read faults. The transcript and visible replacement-session guidance are preserved. The linked proof records the existing saved-state outcome in the unchanged SQLite format; updater and migration behavior is not changed by this PR.
Credit
This is the recovery slice of #144269, based on the original diagnosis and implementation by @pgondhi987 and the PR work by @vincentkoc. Vincent's commit credit and the original branch ancestry are preserved. Tool-cap transport and live continuations remain outside this repair.