Skip to content

fix(security): stop delegated restart recovery - #150702

Merged
steipete merged 14 commits into
mainfrom
sec/fail-closed-delegated-tool-cap-v2
Sep 25, 2026
Merged

steipete merged 14 commits into
mainfrom
sec/fail-closed-delegated-tool-cap-v2

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

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

  • Seven added regression cases failed before their corresponding repairs through the registered recoverRestartAbortedMainSessions entry. The transcript cases preserve readable navigation while corrupting a later payload, verify the actual reader error, and then prove recovery succeeds after repair.
  • The complete final owning file passed 222/222 with one worker: 423.27 seconds command wall time (405.71 seconds in Vitest). The seven added cases accounted for 16.591 seconds of reported per-case time in that serial run. The prior owning/sibling run passed 267 tests; after both review corrections, all 25 affected cases passed again.
  • Production TypeScript and the owning agents-other test graph passed, along with scoped lint, formatting, line-cap/max-lines/assertion ratchets, docs MDX, and diff checks.
  • Fresh independent review has no remaining actionable findings. Both review findings received causal regression tests before correction.

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.

@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 24, 2026, 10:58 PM ET / September 25, 2026, 02:58 UTC (Revision 8).

ClawSweeper review

What this changes

The 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
Reviewed head: 71bebdd1a4090c88b2f5eb525a880d522529c0a5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The recovery repair has focused regressions, exact-head final-effect proof, and no remaining actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): At the exact PR head, a controlled Gateway receiver exercised production recovery, admitted completion authority, and durable final delivery against reopened SQLite state and a real filesystem final-write adapter: allowed recovery wrote once, cancellation and reassignment wrote zero times, and an unowned delegated final did not dispatch. No stored-data format changes are introduced.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): At the exact PR head, a controlled Gateway receiver exercised production recovery, admitted completion authority, and durable final delivery against reopened SQLite state and a real filesystem final-write adapter: allowed recovery wrote once, cancellation and reassignment wrote zero times, and an unowned delegated final did not dispatch. No stored-data format changes are introduced.
Evidence reviewed 8 items Current main remains vulnerable: Current main resumes a replayable pending final after a transcript read error and checks completion custody only after an earlier pending-final dispatch path. The PR's central repair is therefore still needed.
Introduced recovery ordering: The pinned base-to-head patch moves harness completion checks ahead of dispatch, reads source and checkpoint together, and refuses delegated replay without surviving authority.
Source classification: The snapshot-bound visitor classifies the latest non-recovery user input while retaining the replay-safe checkpoint decision; the recovery store consumes both facts before starting another run.
Findings None None.
Security None None.

How this fits together

After 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +36, Tests +230, Docs +7. Total +273 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 135 99 +36
Tests 1 231 1 +230
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 373 100 +273

Review metrics

Metric Value Why it matters
Code versus regression coverage production +36 net lines; tests +230 net lines The added production logic is concentrated in recovery eligibility and snapshot inspection, with larger boundary regression coverage.
Owning test cost 7 added cases: 16.591 s reported; full file: 423.27 s wall The full file is costly in CI, and the PR records both the added-case time and the one-worker file measurement.

Technical review

Best 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.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. At the exact PR head, a controlled Gateway receiver exercised production recovery, admitted completion authority, and durable final delivery against reopened SQLite state and a real filesystem final-write adapter: allowed recovery wrote once, cancellation and reassignment wrote zero times, and an unowned delegated final did not dispatch. No stored-data format changes are introduced.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): At the exact PR head, a controlled Gateway receiver exercised production recovery, admitted completion authority, and durable final delivery against reopened SQLite state and a real filesystem final-write adapter: allowed recovery wrote once, cancellation and reassignment wrote zero times, and an unowned delegated final did not dispatch. No stored-data format changes are introduced.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A Gateway restart can otherwise resume delegated work after its sender authority is gone.
  • merge-risk: 🚨 compatibility: Previously recoverable delegated turns now stop with replacement-session guidance; that intentional continuity change was explicitly accepted in the linked maintainer disposition.
  • merge-risk: 🚨 message-delivery: Recovery eligibility affects pending final replies, while the proof and existing queue checks show queue-owned delivery remains with its owner.
  • merge-risk: 🚨 security-boundary: The change decides whether a restarted turn may regain execution authority; allowed and revoked final effects were exercised in the exact-head proof.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): At the exact PR head, a controlled Gateway receiver exercised production recovery, admitted completion authority, and durable final delivery against reopened SQLite state and a real filesystem final-write adapter: allowed recovery wrote once, cancellation and reassignment wrote zero times, and an unowned delegated final did not dispatch. No stored-data format changes are introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. At the exact PR head, a controlled Gateway receiver exercised production recovery, admitted completion authority, and durable final delivery against reopened SQLite state and a real filesystem final-write adapter: allowed recovery wrote once, cancellation and reassignment wrote zero times, and an unowned delegated final did not dispatch. No stored-data format changes are introduced.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 45ae22e adds src/agents/main-session-recovery/main-session-restart-recovery-replay-safety.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 45ae22e03daa; files: src/agents/main-session-recovery/main-session-restart-recovery-replay-safety.ts)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Galin Iliev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-17T07:15:04.065Z sha 330a2ba :: needs real behavior proof before merge. :: [P1] Preserve owed completion custody before tombstoning
  • reviewed 2026-09-17T07:36:14.081Z sha e8ca7f4 :: needs real behavior proof before merge. :: [P1] Retain owed completions when the later transcript read fails
  • reviewed 2026-09-17T07:42:00.831Z sha e8ca7f4 :: needs real behavior proof before merge. :: [P1] Retain owed completions when the later transcript read fails
  • reviewed 2026-09-17T08:10:15.587Z sha 6e60f5f :: needs real behavior proof before merge. :: [P1] Retain owed completions when the later transcript read fails
  • reviewed 2026-09-17T08:25:17.986Z sha 59ce1c6 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-17T09:01:40.047Z sha b4a5b8c :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-25T02:18:05.247Z sha 71bebdd :: needs real behavior proof before merge. :: none

@vincentkoc
vincentkoc force-pushed the sec/fail-closed-delegated-tool-cap-v2 branch from 330a2ba to 971b785 Compare September 17, 2026 07:24
@vincentkoc
vincentkoc marked this pull request as ready for review September 17, 2026 07:24
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 17, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

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

@vincentkoc

Copy link
Copy Markdown
Member Author

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

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Sep 25, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels Sep 25, 2026
@steipete

Copy link
Copy Markdown
Contributor

Exact-head evidence for 71bebdd1a4090c88b2f5eb525a880d522529c0a5, addressing the fresh review's final-effect, existing-state, and test-cost questions.

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.

Case Recovery dispatches Physical final writes Pending queue entries Observed outcome
Allowed completion 1 1 0 Task delivery became delivered
Cancelled after dispatch 1 0 0 Non-retryable handoff rejection; task remained cancelled
Requester reassigned after dispatch 1 0 0 Non-retryable handoff rejection; completion remained pending for its owner
Saved delegated session with an unowned pending final 0 0 0 Tombstone and actionable /new or /reset notice; repeated recovery stayed inert

Both revoked cases reported OPENCLAW_PLATFORM_MESSAGE_NOT_DISPATCHED, caused by SESSION_WORK_START_CHANGED, with retryable=false, sentBeforeError=false, and released queue custody. The allowed case traversed the same sender and produced exactly one file write. All processes and fixture workers joined, and their temporary state was removed.

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 source

Saved under .local/150702-final-effect-proof.mts in the reviewed checkout and run through the repository's scripts/tsx.mjs loader, once per named case in a fresh process. The output argument is a task-owned result file. No production source changes were required.

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));

@steipete

Copy link
Copy Markdown
Contributor

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 71bebdd1a4090c88b2f5eb525a880d522529c0a5.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 25, 2026
@steipete
steipete merged commit 6b5fb4b into main Sep 25, 2026
228 checks passed
@steipete
steipete deleted the sec/fail-closed-delegated-tool-cap-v2 branch September 25, 2026 03:04
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 25, 2026
* 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]>
roboclaw-bot added a commit that referenced this pull request Sep 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants