Skip to content

fix: preserve owed final replies when restart retires the sender - #157127

Merged
joshavant merged 8 commits into
mainfrom
codex/qa-remediation-restart-custody
Sep 25, 2026
Merged

joshavant merged 8 commits into
mainfrom
codex/qa-remediation-restart-custody

Conversation

@joshavant

@joshavant joshavant commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #156102. Consumes merged prerequisite #157709 (83d24ab022eecbed2459f5257c76f2d671c6a01d).

What Problem This Solves

Fixes lost final replies when Gateway restart invalidates source admission after durable delivery admission, while preventing a retained final from sending after its original channel owner is revoked.

User Impact

A still-authorized channel owner, including a configured commands.ownerAllowFrom owner, recovers the original queued payload once. Revoked, replaced, missing, or corrupt owner references produce no adapter writes and cannot replay. Existing session/task and incarnation fences remain in force.

Owner-bound session markers are transport-only: the original queued payload owns recovery. If the process fails before queue admission, recovery records the existing uncertainty notice instead of replaying bare text without authorization. Owner assertions without a recoverable native reference fail closed during recovery. Previously queued entries without owner metadata retain their existing contract; this change cannot reconstruct their missing original authority.

No new SQLite schema version, authority store, raw identity, execution-identity authorization, bearer credential, retry loop, timeout, dependency change, or fallback path. The prerequisite's schema-19 admission fence and backup-only downgrade contract still apply.

Why This Change Was Made

The live handoff assertion runs before post-run examines the restart signal. Typed source invalidation therefore became permanent rejection even when restart only retired the process. Conversely, retaining a read failure lost the process-local channel-owner assertion during recovery.

The command owner carries its recovery reference into pending-final completion metadata. Admission and recovery share prepareCommandOwnerAuthority: linked owners use prepareChannelOperatorAdmin, configured owners use the existing policy row. Both revalidate immediately at adapter handoff. Unavailable reads and stale process captures retain custody; fresh durable refusal permanently settles it. A later empty command also preserves markers with durable delivery IDs.

Returned best-effort failures now share the existing thrown-error settlement path. This removes duplicate recovery bookkeeping and ensures definitive authorization refusal is terminal. Both live handoff callbacks retain one guard, using the narrow signal contract.

Persistence and downgrade

outbound-command-owner-v1 uses the existing queue table and operations. Its c1- media names use the existing spool owner. Older executors ignore both, following the landed session-generation queue precedent; they cannot drop an unknown JSON authorization field and send anyway. New readers turn a missing reference in this namespace into a closed authorization result. No old record is rewritten or migrated. An older schema-19 runtime can settle its unrecognized session marker as an uncertainty notice; replay after downgrade/upgrade is therefore not guaranteed, while unauthorized sends remain fenced. Full backup/media and snapshot sanitization retain the existing queue contract.

The campaign previously approved enforceable original-owner revocation. The native schema-19 authority contract was accepted in the prerequisite's maintainer decision. This PR consumes that owner and adds no new revocation policy producer.

Scope and LOC

After GitHub reported an actual merge conflict, the candidate was mechanically rebased once onto 79399a653aab550016c73734c0b4e3ef46adb903. The single textual conflict retained both independent upgrade-survivor scenario blocks unchanged; one duplicate test registration introduced by the replay was removed. No additional worker, Testbox, verifier, or coordination artifact was created.

Final LOC: production +348 / -148 (net +200); tests/routing +591 / -189 (net +402); docs +40.

The net-neutral absorption attempt removed duplicate best-effort failure settlement (net -18 there), replaced repeated queue inventories with one executable namespace list, and absorbed the follow-up recovery dispatcher into existing command-owner preparation. That consolidation reduced the follow-up candidate by 14 production lines. The unused session-generation namespace export was removed; compatibility tests name the persisted namespace directly. Remaining positive blocks are: command guard/marker ownership (+15), command-owner preparation and private reference propagation (+41), queue namespace/media/admission isolation (+20), recovery preparation and settlement after absorption (+18), and the existing state owner's configured-policy publication/read/fence extension (+106). These total +200. The state block retains revoke/restore history without raw identities or a parallel store; the prior profile-link path cannot represent an owner with no link. Five final lines place the schema-19 issuance fence in the reader so deferred publication does not require another config reload. No test-only production seam remains.

Evidence

Candidate: 25015481b69393b2ab3730f3ad287cbb25abd00c, base 79399a653aab550016c73734c0b4e3ef46adb903.

Pre-fix proof

The original campaign's 14-cell fixture on 23f5c6763362576a395ea56bece35a52855c9f76 failed six cases (36.19 s wrapper wall). After restacking, current-main production still fails the restart/source-invalidation overlap:

node scripts/run-vitest.mjs src/agents/command/delivery.restart-final.integration.test.ts \
  --maxWorkers=1 -t 'restart-(invalidated|changed)'

Historical run: 4 failed / 20 skipped, 28.42 s wrapper wall, using current-main delivery-authority.ts, then restoring the candidate. The two exact restart-invalidated cells establish lost owed custody at both callbacks. The two restart-changed expectations were subsequently corrected: Changed means source/transcript continuity was lost and must remain terminal, even with an owner reference; those two cells are not evidence of an owed-final defect.

The restacked pre-integration candidate also reproduces the latest ClawSweeper finding:

node scripts/run-vitest.mjs src/agents/command/delivery.restart-final.integration.test.ts \
  --maxWorkers=1 -t 'source-unavailable-owner'

4 failed / 20 skipped, 36.91 s wrapper wall: role removal, including removal then restoration, sent both original payloads after retention, at both real handoff callbacks.

A producer cleanup regression independently failed before its correction: the existing empty-command fixture persisted pendingFinalDelivery: undefined for a marker with a queued delivery ID (one failing owned case; unowned control passed; 13.67 s wrapper wall).

Fixed proof

Before the configured-owner follow-up, the existing restart integration had 52 passing cases at onPlatformSendDispatch and assertDirectAdapterHandoff. Real host admission, policy activation, isolated SQLite custody, and a recording adapter prove allowed recovery exactly once and revoked recovery with zero writes/no replay. Cases include role and link ABA, profile replacement, role/default/identity-scope policy ABA, original/replaced plugin grants, revocation at recovered I/O, process retirement/reopen, missing/corrupt JSON reference, and existing cancellation/replacement fences.

223 tests / 9 files passed, 278.95 s wrapper wall through Node 24 and repository wrappers. The 52-case integration's single-worker shard took 81.23 s wall; it owns the real worker, queue, and admission composition and uses no sleeps or per-case Gateway boots. The media test extends the existing published-reader compatibility table.

node scripts/run-vitest.mjs \
  src/agents/command/delivery.restart-final.integration.test.ts \
  src/agents/command/delivery.custody.integration.test.ts \
  src/infra/outbound/delivery-queue.recovery.test.ts \
  src/infra/outbound/delivery-queue.producer-recovery.test.ts \
  src/infra/outbound/delivery-completion.integration.test.ts \
  src/infra/outbound/deliver.session-generation.integration.test.ts \
  src/infra/outbound/delivery-queue-media-spool.test.ts \
  src/agents/pending-final-delivery-marker.test.ts \
  src/channels/message-access/operator-authority.test.ts --maxWorkers=1

Producer/cleanup siblings passed 28 selected tests across 4 files, 51.91 s wrapper wall, including the red empty-run cleanup case. The final standalone 52-case integration rerun passed in 123.10 s wrapper wall (120.35 s Vitest shard, including a cold module cache while the changed gate ran). After the unused-export cleanup, 72 tests across the three affected suites passed again (including all 52 restart cases): 132.56 s wrapper wall; restart shard 93.23 s. No timers, polling, or Gateway boots were added.

The earlier native-only candidate passed the complete proportional changed gate after removing an unused namespace export. The configured-owner candidate's gate disposition and final affected-surface checks are recorded below; the earlier pass is not claimed for changed inputs.

The E2E prerequisite runtime build was attempted through the repository wrapper in an isolated profile/state/port. It stopped in bundled declaration emit because unchanged extensions/openai/token-sharing-oauth.runtime.ts:3 cannot resolve jose; the package and lockfile already declare 6.2.12, but this checkout lacks its dependency link. No dependency state was altered. Full bundled build and the selected agent-runner.runreplyagent.e2e.test.ts cases therefore remain unproven locally; source-level producer, native recovery and queue proof are green. The failed build’s retained artifact lock was cleared only after verifying its recorded owner, compiler descendants and open handles had stopped, using the wrapper’s documented recovery procedure.

The test-audit invariant is retained final custody with enforceable original-owner revocation. Earlier coverage checked restart abort and live revocation but did not revoke the owner after a failed source read and then execute real recovery. The existing fixture was extended, preserving queue admission before adapter callbacks. Existing sibling tests retain task cancellation/failure, writer/session replacement, partial sends, ambiguous sends, retry budgets, settlement, and native policy ownership.

Personally rechecked sibling Codex at 39598ed17885970828acd42a6370131ed0190a98: codex-rs/protocol/src/protocol.rs:586–605, codex-rs/core/src/tasks/mod.rs:805–845, and codex-rs/exec/src/lib.rs:328–332. Interrupt/aborted events do not provide OpenClaw delivery receipts or authorize replay. No live platform send or full Gateway process restart is claimed.

Review and CI

The ordinary autoreview P2, Restart can retain invalidated unbound finals, is accepted and fixed. The earlier disposition incorrectly treated durable session/task checks as equivalent to the entire native source assertion. They are not: createHarnessCompletionSourceAssertion also validates transcript continuity (src/tasks/agent-harness-completion-recovery.ts:197–225), which queue recovery deliberately does not reconstruct from a retired execution claim.

The existing custody fixture now admits the unbound native harness final, appends an intervening user input while keeping the session/task tuple intact, and aborts for restart at each real handoff. Before correction, recovery sent The completed child result instead of zero writes: 2 failed, 2 allowed controls passed, 18 skipped; 15.85 s wrapper wall on 6314903eb460d0b006d378eea70339136453d9a7 production:

node scripts/run-vitest.mjs src/agents/command/delivery.custody.integration.test.ts \
  --maxWorkers=1 -t 'across restart'

The refreshed ordinary-review P2 is also accepted and fixed: bindCommandHarnessCompletionAssertion explicitly composes a prior owner assertion with the native harness assertion and preserves its recovery reference. This is a supported owner contract; current registered-caller reachability was not a valid reason to reject it.

The same two-handoff fixture now uses that actual composer and native host admission. Against the first follow-up guard, both owner-bound transcript-interleaved cases incorrectly wrote The completed child result; both unchanged controls recovered once. 2 failed, 2 passed, 22 skipped; 30.85 s wrapper, 11.69 s shard:

node scripts/run-vitest.mjs src/agents/command/delivery.custody.integration.test.ts \
  src/agents/command/delivery.restart-final.integration.test.ts \
  --maxWorkers=1 -t 'owner-bound|restart-changed'

The wrapper stopped at the first failing custody shard; the restart-final shard did not run in that red command. The guard now uses the canonical stable code to distinguish the classes: Changed is terminal regardless of reference; exact Invalidated can retain restart custody only with a native owner reference. Unbound typed invalidation remains terminal. A pure restart can still recover an allowed unbound final. Both handoffs reconstruct recovery from SQLite without the old assertion and check zero writes/no replay versus exactly one allowed write. The process-retired owner row uses its real assertion, without also injecting a Changed error.

Earlier composite-source proof: 78 tests passed across both existing suites, 144.47 s wrapper wall. The custody suite has 26 cases (37.06 s shard); the restart-final suite has 52 (86.42 s shard). This follow-up adds 2 net production lines over the published integration and 76 net test lines in existing fixtures. No production seam, schema, storage, fallback, timer, retry, or new authority owner was added.

ClawSweeper Revision 9's source-continuity P1 is accepted and fixed. An unclassified source assertion failure could previously transfer custody even though recovery cannot rerun the live transcript check. The canonical delivery guard now permits custody transfer only for recognized restart retirement; unreadable or changed source assertions fail closed.

The existing custody fixture now fails the real transcript read, retains the queued entry, appends intervening user input, and drains recovery twice at both adapter handoffs, with and without a bound owner. Before the fix all four cases replayed the stale final; after the fix they produce zero adapter writes. Pure-restart and configured-owner recovery remain covered.

Final follow-up proof: 94 focused cases and 268 delivery/queue siblings passed; all 25 selected test-type graphs plus proportional changed guards passed. Ordinary autoreview is scoped-clean through P2. TruffleHog 3.97.8 found zero verified or unverified secrets in the final diff. Follow-up LOC is production +8 / -8 (net 0) and tests +83 / -59 (net +24). The intentional fail-closed tradeoff is that an unreadable source prevents automatic final recovery.

Complete unbound-producer disposition

There are three canonical fresh pending-final producers, with the command producer's native-harness specialization listed separately below. Follow-up and restart turns reuse them. Settlement, marker normalization, payload copies, and cleanup do not create another authority producer.

Production path without commandOwnerReference Durable custody recovery actually checks Boundary and disposition
Ordinary agent-command final: post-run.ts:360 → pending-final-delivery-marker.ts:41–135; includes CLI/Gateway and resumed commands without a captured channel-owner reference The stored session ID, intent ID, delivery ID and nonterminal delivery state. Optional payload writer facts are retained when present. These facts do not reconstruct arbitrary source assertions. Changed is always terminal, and exact Invalidated is terminal when unbound; a restart abort alone can still recover.
Native harness completion through that same command producer: agent-command.ts:325–380, agent-command-restart-recovery.ts:489–520, marker lines 108–123 In addition to the session intent: requester agent/key, expected session and lifecycle/writer revisions where supplied, exact task ID/run/outcome and owed delivery state (getOwedHarnessCompletionTask). The full live assertion additionally checks source transcript continuity. Both unbound and owner-bound composite two-handoff regressions prove that Changed must remain terminal; task tuple equality or a native owner reference cannot reconstruct transcript continuity.
Ordinary auto-reply/model final, including queued follow-ups: agent-runner-result-complete.ts:216–281 when no private command-owner capability is present Same session/intent/delivery state; if the embedded settled-turn finalizer attached writer authority, recovery also checks its session/lifecycle/writer tuple (settled-turn-finalization.ts:340–399). No blanket writer or task authority is inferred for ordinary payloads. This producer does not call the agent-command restart guard; its existing session-custody contract is retained.
before_agent_reply handled-hook final: agent-runner-execute.ts:214–263 → restart-recovery-claim.ts:350–389 Checkpoint admission compares session, recovery run, source run and hook state; subsequent queued recovery checks persisted session/intent/delivery state, plus any supplied writer metadata. This hook-owned terminal checkpoint has no command-owner reference and does not use the changed command guard. Its admission-time checks are not claimed to reconstruct arbitrary source authority during queue recovery.

For every queued pending final, resolveCompletedOwnerBeforeRecovery (delivery-queue-recovery.ts:482–548) calls markDurableDeliveryQueued/settlePendingFinalDelivery (delivery-completion.ts:158–229) before dispatch; stale or terminal custody prevents replay. At recovered I/O, delivery-queue-recovery-params.ts:51–62,108–117 invokes assertSessionWriterDeliveryAuthorized, whose session/task predicates are in session-writer-delivery-authority.ts:22–57. No authority is invented when that optional metadata is absent. Startup marker recovery defers to a present queue owner (main-session-restart-recovery-store.ts:59–85,385–395), and a suppressed final completes instead of replaying bare text. Legacy marker/import normalization retains only recorded custody and cannot retroactively supply an original owner.

Final ordinary autoreview: scoped-clean through P2, using codex --yolo on the complete final candidate; no actionable findings. Final proportional changed-gate disposition: all attributable phases green. The full attempt's only failures were four unchanged max-lines violations, explicitly classified below; it was not rerun for them. Preserved green phases include all 25 test graphs, boundaries and unused exports. After the final behavioral edits, core types plus affected commands/plugin-sdk/messaging/state test graphs, changed-source lint, format/growth/assertion guards, unused exports, and import cycles were revalidated as applicable. The previously unreached script lint, native schema, database-first storage, media/sidecar, and webhook/auth guards all passed. TruffleHog 3.97.8 scanned the complete final diff (9ef6fea75aab9e9cf7151c2e950126aaa8e4895b21ab59359d0185fcede669dd): zero verified or unverified secrets.

ClawSweeper Revision 7 and the refreshed ordinary review identified configured commands.ownerAllowFrom finals with null references as a supported recovery gap. Accepted and repaired, following the user's explicit authorization to extend the existing policy seam without a schema bump or raw identity persistence.

node scripts/run-vitest.mjs src/agents/command/delivery.restart-final.integration.test.ts \
  --maxWorkers=1 -t 'restart-configured'

Pre-fix: 2 failed / 6 passed / 52 skipped, 21.32 s wrapper (19.43 s shard). A still-configured owner with its profile channel link removed lost both queued payloads at each handoff; removal, replacement, and restore controls produced no writes. This is final-effect proof through real host admission, durable queue admission and SQLite recovery. An earlier fixture attempt replaced the registered channel set and changed prefixed-owner normalization before admission; it is recorded as a fixture failure, not defect evidence. The final test uses the existing supported unqualified configured-owner entry.

Configured-owner recovery retains one policy-level UUID in the existing operator.channelPolicy JSON row, with only an allowlist fingerprint; its queue reference is version 2. The fingerprint uses the existing sorted/unique/trimmed normalization, preserving set-like membership when order or duplicates change. Empty/undefined lists retain no configured continuity state. Membership changes retire it, including remove-and-restore; unrelated role/profile/link changes do not. The existing pre-publication transaction and rollback owner commit retirement before changed config becomes effective. The existing worker read, mutation fence and database lifecycle qualify recovery at adapter I/O. No new authority table, lifecycle registry, raw identity, bearer credential, or schema/public-config change was added. Live admission remains owned by the configured-owner predicate; absent durable policy cannot permit recovery.

The version distinguishes authority classes without replacement admission. Profile references remain version 1. Older schema-19 policy writers overwrite the JSON row without the new field; re-upgrade creates a fresh UUID and cannot revive old references. Older queue readers reject version 2. The policy is recorded at activation, but the reader issues references only after published schema 19, preserving the prerequisite's retained-v18-writer fence. The existing two-handoff fixture proves older-writer/re-upgrade refusal and revocation during recovered adapter I/O, with a second drain proving no replay.

The same existing key is the least compatible-change-sensitive safe seam available: older writers necessarily replace it. A separate config-machine key would survive unobserved old-writer revoke/restore and could resurrect custody; updated_at_ms is not a generation and audit snapshots are not authority. The predecessor native reader compares the entire policy JSON and therefore fails closed while the extension exists; its own startup publication removes the extension and also retires linked-owner references. This conservative downgrade loss is explicit. Empty/native-only deployments keep the exact prior JSON shape. No schema change is needed for safety.

The configured-owner extension adds 116 net production lines beyond the corrected native-source candidate. Required blocks are the policy-row fingerprint/reference parser and publication, reuse of the existing reader and mutation fence, common command-owner preparation, the pre-publication caller input, and typed propagation. The source-class correction adds 2 lines over the published integration. Both authority classes use one command-owner preparation path; distinct state readers consume their actual native facts rather than inventing a person link for configured owners.

Additional owner-boundary red proof against the first configured candidate:

node scripts/run-vitest.mjs src/agents/command/delivery.restart-final.integration.test.ts \
  --maxWorkers=1 -t restart-configured-allowed
node scripts/run-vitest.mjs src/channels/message-access/operator-authority.test.ts \
  --maxWorkers=1 -t 'without configured owners'

Equivalent list order/duplicates/whitespace edits lost the original final: 2 failed / 62 skipped, 14.33 s wrapper. Undefined and empty lists both failed predecessor policy-reader equality because unnecessary continuity metadata was persisted: 1 failed case, both soft assertions failed / 35 skipped, 26.16 s wrapper. The latter uses the pre-fix fingerprint expression with the final fixture. No test seam was added. After correction and consolidation, all 64 restart cases passed, 102.40 s shard; 163 owner/custody/queue/Discord sibling tests passed across six files, 239.33 s wrapper (217.29 s shard).

The publication audit then extended the existing normal/deferred schema-upgrade table: config activation writes policy once, the old updater completes, and the schema owner publishes v19 without a config reload. Before the final reader-fence correction, the deferred case still returned no configured reference after v19 while the normal control passed: 1 failed / 1 passed / 6 skipped, 24.40 s wrapper (4.36 s shard) with node scripts/run-vitest.mjs src/state/user-profiles.schema.test.ts --maxWorkers=1 -t 'upgrades channel links'. The five-line correction records policy at activation and withholds issuance in the reader until published v19. This preserves the older-writer fence and exact reference after another reopen, without a new lifecycle hook. The existing fixture uses the native host-broker test group now that it exercises the real async reader. Final proof: 86 tests / 3 files passed, 136.85 s wrapper, comprising all 8 schema cases, 14 shared-reader siblings, and all 64 restart cases (108.86 s shard).

Current proof: the expanded 64-case restart integration passed (98.49 s shard), as did native owner/source custody (61 tests in two files, 68.01 s shard), schema upgrade/deferred-publication (8 tests, 4.40 s), and activation/rollback (12 tests, 7.59 s). The Discord slash-command sibling then exposed two deterministic host-broker refusals in its thread-based test route; its unchanged test now belongs to the existing database-worker fork group, alongside the native owner siblings. That one-line routing repair changes neither assertions nor production authority. Final repaired sibling/queue rerun: 179 tests / 6 files passed, 295.69 s wrapper wall (115 tests in the native/queue/reader shard: 161.05 s; all 64 restart cases: 114.49 s). All four Discord cases pass in the correct host-broker group.

The changed-gate startup stop was a retained artifact lock from the explicitly interrupted prior gate. Its recorded owner/child, detached compilers and open artifact handles were verified stopped before the wrapper's documented manual recovery. The unchanged core typecheck passed. The subsequent complete changed-gate attempt passed core typecheck (47.92 s), all 25 test graphs (1045.90 s), formatting, boundary and all unused-export scans, then failed only max-lines in four untouched files: src/agents/workspace.test.ts:1215, src/agents/auth-profiles/oauth-refresh-fence.test.ts:1089, src/commands/auth-choice.apply.plugin-provider.test.ts:1106, and packages/ai/src/transports/openai-responses-prompt-observer.test.ts:1091. All four are byte-identical to the pinned base. The campaign explicitly classifies these as non-attributable; no duplicate full rerun, suppression, or edits were made for them. The final canonical refactor revalidated affected types/lint and completed the remaining gate phases instead of discarding the valid green evidence.

Exact-head ClawSweeper and CI are pending on 25015481b69393b2ab3730f3ad287cbb25abd00c. The rebased candidate passed 94 focused custody cases, 241 sibling cases, core and messaging typechecks, shell syntax, formatting, and diff checks before push. Exact-head CI exposed the shell-invoked upgrade scenario as missing from Knip executable roots; the one-line registration reproduced red/green through the canonical unused-file check and passed pnpm deadcode:full. It also exposed an attributable test synchronization gap after configured-owner preparation gained a state-worker read: the existing watcher fixture now awaits its owned notification promise, with the exact 19-file group passing 217 tests and five watcher/notice sibling files passing 68 tests.

The earlier Gateway/catalog timeout remains classified non-attributable: run 35979086701 reached draft catalogs at 57.753 s of a 60 s budget; subsequent history-worker cleanup also failed. Its exact 14-file local replay previously passed (391 tests, 82.51 s), which was not claimed as a fix. No timeout, fixture, baseline, or branch change was made for it, and no CI rerun is requested.

This PR remains open for maintainer review. Never merge, queue, or enable automerge as part of this task.

@clawsweeper

clawsweeper Bot commented Sep 24, 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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 24, 2026
@joshavant
joshavant marked this pull request as ready for review September 24, 2026 07:42
@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: 25015481b69393b2ab3730f3ad287cbb25abd00c
  • Maintainer: @joshavant
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/command/delivery-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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: 🦐 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 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 25, 2026, 6:11 AM ET / 10:11 UTC (Revision 12).

ClawSweeper review

What this changes

The branch preserves queued final replies across Gateway restarts, rechecks the original channel owner before delivery, and adds policy-state, queue-format, regression, and upgrade-scenario coverage.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open. Current main still rejects an owed final when restart invalidates source admission after queue custody, and the merged related PRs do not cover this recovery path. The remaining merge blocker is published-updater compatibility proof for the changed persisted policy.

Priority: P1
Reviewed head: 25015481b69393b2ab3730f3ad287cbb25abd00c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong boundary coverage supports the repair, while the persisted-policy upgrade check remains a merge gate.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body records red/green production-path runs through host admission, SQLite queue recovery, and a recording channel adapter: authorized finals write once and revoked owners write zero times at both handoffs. The new persisted policy still lacks a recorded published-updater run, so existing-state compatibility is insufficient.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body records red/green production-path runs through host admission, SQLite queue recovery, and a recording channel adapter: authorized finals write once and revoked owners write zero times at both handoffs. The new persisted policy still lacks a recorded published-updater run, so existing-state compatibility is insufficient.
Evidence reviewed 12 items Current-main defect: Fetched main treats a source-invalidation error as permanently non-retryable even when restart has retired the sender after queue admission.
Introduced custody guard: The pinned PR delta makes restart retirement retryable only for recognized source errors with a recoverable owner reference; unreadable or changed source assertions remain terminal.
Final-effect authority check: Queue recovery parses the stored owner reference, prepares current authority, and checks it at both adapter handoffs before outbound I/O.
Findings None None.
Security None None.

How this fits together

An agent turn produces a final reply for a channel command and hands it to the durable outbound queue. After a Gateway restart, recovery checks session custody and the original channel owner's current authority before the channel adapter sends the saved payload.

flowchart LR
A[Channel command] --> B[Agent final reply]
B --> C[Durable delivery queue]
C --> D[Restart recovery]
D --> E[Original owner check]
E --> F{Authorized now}
F -- Yes --> G[Channel adapter send]
F -- No --> H[Settle without send]
Loading

Before merge

  • Resolve merge risk (P1) - The published 2026.9.4 updater has not been observed carrying an existing operator policy row into this candidate and through two Gateway starts; a publication-order or compatibility failure could strand configured-owner finals on upgrade.
  • Complete next step (P2) - Run and record the added published [email protected] updater × candidate scenario, including existing-row preservation and configured-owner reference stability across two Gateway starts, before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +207, Tests +414, Docs +50, Other +124. Total +795 across 48 files.

View PR surface stats
Area Files Added Removed Net
Source 29 358 151 +207
Tests 11 696 282 +414
Docs 2 50 0 +50
Config 0 0 0 0
Generated 0 0 0 0
Other 6 124 0 +124
Total 48 1228 433 +795

Review metrics

Metric Value Why it matters
Persisted contracts 1 policy-row extension, 1 queue namespace These stored formats make existing-state upgrade behavior material to merge readiness.
Production versus test delta production +348/-148 (net +200); tests/routing +591/-189 (net +402) The PR attributes production growth to policy publication and recovery authority; the published upgrade check remains the validation gap.

Stored data model

Persistent data-model change detected: database schema: scripts/e2e/lib/upgrade-survivor/channel-owner-policy.mjs, migration/backfill/repair: config/knip.config.ts, migration/backfill/repair: scripts/e2e/lib/upgrade-survivor/channel-owner-policy.mjs, migration/backfill/repair: scripts/e2e/lib/upgrade-survivor/run.sh, serialized state: scripts/e2e/lib/upgrade-survivor/channel-owner-policy.mjs, unknown-data-model-change: scripts/e2e/lib/upgrade-survivor/channel-owner-policy.mjs, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #157127
Summary: This PR is the remaining recovery integration; one merged PR fixed a narrower restart case and the other supplied its durable owner-authority prerequisite.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Prove the shipped updater path (recommended)
    Run the added 2026.9.4 published-driver scenario and record preservation of the existing row and the configured-owner reference across both candidate starts.

Technical review

Best possible solution:

Keep durable queue custody and current original-owner checks at adapter handoff, with the existing policy row proven stable through a published-updater upgrade.

Do we have a high-confidence way to reproduce the issue?

Yes, by source inspection: current main makes restart-time source invalidation terminal after queue admission, and the PR body records failing cases at both adapter callbacks. This read-only review did not execute them.

Is this the best way to solve the issue?

Yes in design: the existing queue and policy owners can retain the payload while rechecking authority at final I/O. Published-updater compatibility still needs its recorded run.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against cbcd4df569eb.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A Gateway restart can lose final replies in an active channel workflow.
  • merge-risk: 🚨 compatibility: The branch extends a persisted policy row and adds a queue format whose upgrade behavior needs shipped-updater proof.
  • merge-risk: 🚨 message-delivery: Recovery decisions at adapter handoff determine whether a queued final sends once or is suppressed.
  • merge-risk: 🚨 security-boundary: A persisted original-owner reference now controls whether a recovered reply may reach channel I/O; the accepted fail-closed contract and final-effect tests are relevant review evidence.
  • 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): The PR body records red/green production-path runs through host admission, SQLite queue recovery, and a recording channel adapter: authorized finals write once and revoked owners write zero times at both handoffs. The new persisted policy still lacks a recorded published-updater run, so existing-state compatibility is insufficient.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body records red/green production-path runs through host admission, SQLite queue recovery, and a recording channel adapter: authorized finals write once and revoked owners write zero times at both handoffs. The new persisted policy still lacks a recorded published-updater run, so existing-state compatibility is insufficient.

Evidence

What I checked:

Likely related people:

  • joshavant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the added published 2026.9.4 updater scenario's existing-row and two-start result.

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 (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-24T09:17:12.183Z sha e175a8b :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-24T09:41:20.782Z sha e175a8b :: needs real behavior proof before merge. :: [P1] Fence recovered finals against revoked channel owners
  • reviewed 2026-09-24T09:57:33.990Z sha e175a8b :: needs real behavior proof before merge. :: [P1] Fence owner authority before replaying source-read failures
  • reviewed 2026-09-25T03:58:02.044Z sha 6314903 :: blocked before merge. :: [P1] Keep configured owners' queued finals recoverable
  • reviewed 2026-09-25T05:19:52.443Z sha 6ebbc38 :: blocked before merge. :: [P1] Keep mixed best-effort failures retryable until the batch is terminal
  • reviewed 2026-09-25T08:13:48.687Z sha bf78f6381b785c9962361c3240df0ac7b2ed8dce :: needs real behavior proof before merge. :: [P1] Recheck source continuity after a retryable read failure
  • reviewed 2026-09-25T09:00:09.795Z sha 91f3709168fa6020df67261bf4e17c8052f8361e :: blocked before merge. :: none
  • reviewed 2026-09-25T09:23:40.108Z sha 886dbdb :: blocked before merge. :: none

@joshavant
joshavant marked this pull request as draft September 24, 2026 07:57
@joshavant
joshavant marked this pull request as ready for review September 24, 2026 08:05
@clawsweeper clawsweeper Bot added 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 24, 2026
@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Please review current head 2c6bbd4bccc2a0e7573d5e8bc92afee824ecdda1. The automatic dispatch ended with a superseded lease and left the previous-head verdict in place. This revision consolidates the delivery owner's two rejection paths and uses the built-in AbortSignal contract: production is net -5 LOC. All 236 existing regression and sibling tests passed. The PR body records the independent completion-owner session/intent fence relevant to recovery without optional writer metadata. Leave the PR open; no merge or automerge is requested.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 24, 2026
@joshavant
joshavant marked this pull request as draft September 24, 2026 09:45
@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts docker Docker and sandbox tooling labels Sep 25, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 25, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 25, 2026
Keep custody retryable only for recognized restart retirement. Unknown source assertion failures cannot transfer continuity checks to recovery after the live closure disappears.

Prove source-read failure followed by intervening input cannot replay at either adapter handoff, with bound and unbound owners. Preserve genuine restart retention and revocation coverage; retain suppression reason literals in the batch recovery table.
@joshavant
joshavant force-pushed the codex/qa-remediation-restart-custody branch from 91f3709 to 886dbdb Compare September 25, 2026 09:15
@joshavant
joshavant marked this pull request as ready for review September 25, 2026 09:15
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 25, 2026
The upgrade-survivor shell invokes this CLI by path. Model it in the shared executable-root list alongside sibling scenarios so the full-tree unused-file audit recognizes the real consumer.

The canonical unused-file check reproduced one unused file before registration and passes with zero entries afterward. pnpm deadcode:full and formatting also pass.
@joshavant
joshavant merged commit 39183ae into main Sep 25, 2026
231 checks passed
@joshavant
joshavant deleted the codex/qa-remediation-restart-custody branch September 25, 2026 18:14
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…nclaw#157127)

* fix: preserve owed final replies when restart retires the sender

* fix: retain live owner checks during restart delivery

* refactor: consolidate final delivery rejection handling

* fix: distinguish source read failures from owner revocation

* fix: recover queued finals with original owner authority

* fix(agents): reject finals after source read failures

Keep custody retryable only for recognized restart retirement. Unknown source assertion failures cannot transfer continuity checks to recovery after the live closure disappears.

Prove source-read failure followed by intervening input cannot replay at either adapter handoff, with bound and unbound owners. Preserve genuine restart retention and revocation coverage; retain suppression reason literals in the batch recovery table.

* fix(ci): register channel owner policy scenario with Knip

The upgrade-survivor shell invokes this CLI by path. Model it in the shared executable-root list alongside sibling scenarios so the full-tree unused-file audit recognizes the real consumer.

The canonical unused-file check reproduced one unused file before registration and passes with zero entries afterward. pnpm deadcode:full and formatting also pass.

* test(gateway): await watcher-owned notice completion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime 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. scripts Repository scripts security-sensitive-changed size: XL 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.

1 participant