Skip to content

refactor(sessions): persist run outcomes only; liveness comes from the run registry - #165733

Merged
steipete merged 25 commits into
mainfrom
steipete/session-status-outcome-only
Oct 6, 2026
Merged

steipete merged 25 commits into
mainfrom
steipete/session-status-outcome-only

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A cut-short restart could leave a persisted session marked running long after its run disappeared. The sidebar Working badge and Workboard then disagreed with the live run registry.

This PR supersedes #165188, the narrow restart-settlement fix. Keep that PR open until this cutover lands. The plugin facts work overlapped #165189, which landed first; this branch preserves its registry/queue derivation and shared pull-request owner improvements.

Solution

Persist only run outcomes: done, failed, killed, timeout, and interrupted. Starts clear the previous outcome and retain run identity/timing. Gateway rows derive running and queued activity from the run registry and queue owner. Restart-aborted runs persist interruption, reason, and end time; eligible work retains the recovery owner's existing claims.

Coordinator-decided contracts:

  • Gateway-backed sessions tail: select running sessions through sessions.list when reachable, matching session identities. Offline selection uses activity order and prints Gateway unreachable: showing the most recently active session; explicit --store uses activity order and prints explicit store: ordered by activity. Authorization and policy errors do not silently fall back.
  • Admission-time recovery claims: eligible turns, including turns without a channel route, record execution claims in the existing admission write. Channel delivery authority remains separate. Excluded spawned children gain no new claim; existing claims remain intact.
  • Exclusive local cleanup authority: destructive local sessions cleanup --enforce refuses while a Gateway owns the store, names the owner, and directs the operator to Gateway-delegated cleanup or to stop the Gateway. Delegation and dry-run previews retain their existing behavior.
  • Doctor-only legacy yield exception: the one-time running|queued → interrupted transform leaves the outcome unset for verified yielded-parent ownership, guarded against an active writer, a recovery fence, or terminal evidence. Other legacy liveness values settle to interrupted. Liveness always remains registry-derived.

Startup invokes the existing Doctor transform before admitting each store. The transform is idempotent, logs its count, preserves timestamps/history and claims, and arms existing recovery fields for eligible legacy running entries that lacked claims. Recovery discovers work through mainRestartRecovery, restartRecoveryRuns, before-reply, and delivery fields. Storage workers receive explicit live-session-key snapshots and revalidate before destructive writes. No new schema version or sidecar store is introduced.

Terminal cleanup retires only the execution or delivery claim it owns. Accepted terminal writes drain first; unrelated claims, successor generations, and source reservations survive. The CI follow-up also removes remaining persisted-liveness fixtures, updates the canonical Gateway test inventory, and prunes the obsolete assertion-safety allowance.

User Impact

Sessions no longer display indefinite Working badges because of stale saved liveness. Eligible interrupted work can resume, including turns without a channel delivery route. Verified yielded parents retain continuation ownership without a spurious recovery turn. Local cleanup cannot prune a store owned by a live Gateway.

Why This Change Was Made

Run liveness already has an authoritative registry and queue. Persisting another liveness flag let restart settlement, recovery discovery, readers, and maintenance disagree. Durable session metadata now records outcomes, while runtime owners supply activity.

The coordinator accepted the −418 production-line reduction; −476 was a target, not a publication gate. The coordinator also authorized publishing the rebased head while hosted CI runs the full changed plan. No merge or auto-merge is requested.

Evidence

Team evidence supplied read-only for 2026-10-04:

20:27:38 [gateway] received SIGTERM; restarting
20:27:39 [gateway] draining active work before external-restart with timeout 44597ms: queueSize=14 pendingReplies=4 embeddedRuns=6 agentRuns=7 sessionAdmissions=14 …
20:28:23 [gateway] restart drain budget 44597ms exhausted; cutting short queueSize=12 pendingReplies=4 embeddedRuns=6 backgroundExecSessions=1 agentRuns=6 …
20:28:23 [openai-transport] [responses] error … name=AbortError code=OPENCLAW_RESTART_ABORT (×2)

Ninety minutes later sessions.list still reported, for several agent:roboclaw:dashboard:… sessions: status: "running", hasActiveRun: false, updatedAt: 2026-10-04T20:28:24Z (five rows share that second), last activity hours earlier. Nothing is running for them (no live run in the registry), yet every surface that reads the persisted status (sidebar "Working" badge, Workboard) shows them as running. The run registry is right; the persisted session status is stale.

Baseline reproduction on 382c987dbe1c7ee08634ef72e752085ed7639d2e failed through the real restart-shutdown and startup entry points (34.69 s wall):

FAIL src/gateway/server-run-shutdown.recovery.test.ts
  persists interruption after a cut-short restart while recovering eligible work from its claim
AssertionError: expected 'running' to be 'interrupted' // Object.is equality
FAIL src/gateway/session-startup-run-outcomes.test.ts
  settles legacy liveness once before startup returns, preserving recovery claims and history

Rebase and publication

Published head: bc60cd6c9122555b81db318f54794c84bb331018, rebased onto c20c6e5822d741c03831cac8ad805aace1735de3. 98684e45ec2d was pushed as authorized; subsequent pushes resolved verified conflicts as main advanced. GitHub reported MERGEABLE immediately after this publication. Merge-tree against the fetched main is clean. These were conflict-resolution pushes, not attempts to rerun CI for green.

Conflicted file Resolution
src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts Preserve main's removal of the duplicated privilege-mismatch case: its stronger real-queue scenario remains in agent-runner.runreplyagent.steering-receipts.cases.ts. Retain the cutover's session-key alignment, the retained follow-up/ownership assertions, and main's structured steering diagnostics.
src/infra/gateway-lock.test.ts Preserve main's consolidated lifecycle/maintenance tests and removal of obsolete port-probe fixtures. Carry the cleanup command's recognition check into the retained verified-maintenance-owner test, covering both Doctor and sessions cleanup --enforce.
src/auto-reply/reply/agent-runner-result-accounting.fallback.test.ts Preserve the cutover registry fixture imports and main's move of disposeOpenClawAgentDatabaseByPath into openclaw-agent-db-disposal.ts; retain async database-close cleanup.
src/gateway/server-plugins.session-facts.test.ts Preserve the union of imports needed by main's selected-facts cache/redaction suites and the cutover's registry/queue fixtures. Consolidate the duplicate liveness case into the existing projection test to meet the combined file's line limit, retaining queued/live override of an old failure and its restoration after retirement.

The generated worker inventory was refreshed after integration. Main's per-agent inbound-admission wait and exact terminal-dispatch cleanup remain intact. The temporary-error allowance from 98684e45ec2d was dropped because main's admission wait supersedes it; the hard-kill test again rejects every failure reply.

Proven checks and limits

Scope Result Wall seconds
Earlier rebase: src/infra/gateway-lock.test.ts and src/channels/turn/run-channel-turn.startup-admission.test.ts, through node scripts/run-vitest.mjs ... --maxWorkers=1 2 files / 31 tests passed 40.81
Final rebase: src/gateway/server-plugins.session-facts.test.ts, through the native Vitest wrapper 1 file / 26 tests passed after consolidation; initial merged suite also passed in 33.95 s 19.88
Final rebase: touched-file oxfmt, scoped oxlint, generated worker inventory, and merge-tree Pass; inventory has 630 files / 2,548 call expressions Not separately timed
Earlier rebase: touched-file oxfmt Pass 1.16
Earlier rebase: targeted oxlint using the emitted canonical core config Pass 11.90
Earlier rebase: generated worker inventory Pass; 628 files / 2,539 call expressions 7.29
Auth-worker rebase: src/auto-reply/reply/agent-runner-result-accounting.fallback.test.ts, through the native Vitest wrapper 1 file / 3 tests passed 35.42
Auth-worker rebase: touched-file oxfmt, oxlint, and generated worker inventory Pass; 629 files / 2,541 call expressions Not separately timed
Before latest rebase: local command failure/terminal-drain owner packet 4 files / 41 tests passed 70.44
Earlier focused/recovery Testbox packet 45 files / 1,149 tests passed; historical proof, not full-plan success 1,548.27

The local command-error regression failed before the owner fix (2 expected failures, 43.05 s), then passed its focused cases (61.61 s). It exercises actual agentCommand admission and preserves sibling recovery claims. The real drain/startup regressions require their existing Gateway lifecycle composition; the hard-kill case requires a real process restart. Their process/build overhead is included in wall times and is not replaced with helper-only proof.

The complete changed-plan packet at 128bf7545380412578e71a5fd67623fa936ba00c selected 152 units, including 42 changed-check commands and 80 canonical Node rows, plus required supplemental owners. 14 units executed: 12 passed, 2 failed; 138 remained unrun. No full green result is claimed.

Testbox unit at 128bf7545380 Result Wall seconds
Extension test types Pass 88.47
Root test types Pass 207.20
Production core/UI/extension types Pass 140.71
Core test-type stripe 5 Pass 132.77
checks-node-changed-compact-large-16-1 Pass 550.95
Runtime wave's nine Node rows 7 passed; the two failures below 1,854.67 total row time

Type/storage Testbox run: native command 1,321.931 s, successful settled wrapper receipt. Runtime Testbox run: native command 2,743.315 s, including a 691.79 s runtime prerequisite; failed receipt preserved. Lease cleanup status is separate from command success. All task leases were released.

The two failed units

  1. checks-node-changed-1 — 293.68 s. Its sole failure was extensions/qa-lab/src/gateway-kill-restart-send.e2e.test.ts, “reconciles an orphaned run and replies to a new inbound send after SIGKILL.” The original unacknowledged inbound was replayed while agent database preparation was pending, producing an error reply before recovery could be observed. The empty-transcript checkpoint race had already been corrected with allowEmpty: true, while still requiring an unfinished tool call. Main subsequently added the actual abortable per-agent wait in 8e3c6beb8f65, in src/channels/turn/execution.ts before metadata writes/dispatch; this rebase includes it. Its four focused startup-admission tests pass locally. The full hard-kill E2E awaits hosted CI; no post-fix E2E pass is claimed.
  2. checks-node-changed-4 — 485.00 s. Its sole failure was test/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts, “records suppressed Slack announcements without claiming delivery.” The child was terminal but delivery remained pending because embedded cleanup stalled at openclaw-trajectory-flush, timeoutMs=10000, pendingRows=7, queuedBytes=30062, activeOperation=sqlite-append. The stall is in the trajectory append/flush path (src/trajectory/runtime-store-writer.ts, src/agents/embedded-agent-runner/run/attempt-trajectory-flush.ts), before command-level claim cleanup. Fifteen other tests in that file passed; the originally reported usage/memory test also passed. A prior Testbox packet passed this same Slack case (76.874 s), and the trajectory/attempt cleanup owners were unchanged by this PR. These facts suggest timing or admission contention rather than a stale-status assertion, but attribution is unproven. Pending delivery is the correct unresolved state; it was not relabeled to manufacture success.

Hosted CI owns the remaining full plan

Per coordinator decision, the remaining compact Node rows, test-type stripes, ratchets, lint/guard, build, SDK, and recovery coverage are delegated to hosted CI on the published head. Historical local/Testbox passes above are labeled with their scope; they do not establish full-plan success on this head. The coordinator is watching CI; this task does not rerun workflows or re-push merely for green.

Baseline attribution attempts never executed a test: Testbox admission remained queued for 15 minutes, then AWS sync stalled for 10 minutes twice, including a fresh full resync. Both AWS receipts recorded zero command time. A local hard-kill diagnostic reached its 600.15 s host budget during runtime prerequisites, before test execution. An earlier rebase's E2E selection again requested that full build and was stopped before tests (131.27 s); the separate core packet above passed. No build-skip flag, longer test timeout, or passing-baseline claim was used.

Final branch autoreview

Direct-route Codex full-branch review completed on bc60cd6c9122555b81db318f54794c84bb331018, against origin/main (captured base c20c6e5822d741c03831cac8ad805aace1735de3), at P1 with a 3,600-second engine timeout. All four passes completed with zero findings; final source verification passed. The complete selected branch diff and supplied committed owner context were reviewed. Runtime proof limits remain as recorded above.

{
  "schema_version": 1,
  "status": "scoped-clean",
  "exit_code": 0,
  "engine": "codex",
  "report_produced": true,
  "reason": null,
  "reviewer_exit_code": null,
  "timed_out": false,
  "usage": {
    "attempts": 4,
    "reported_attempts": 4,
    "unknown_attempts": 0,
    "partial_attempts": 0,
    "complete": true,
    "tokens": {
      "input_tokens": 408769,
      "cached_input_tokens": 0,
      "output_tokens": 12531,
      "reasoning_output_tokens": 11928
    }
  }
}

Production LOC

Physical lines in the same touched production files, compared with base c20c6e5822d741c03831cac8ad805aace1735de3. Tests, test support, docs, and tooling are excluded. The coordinator accepted −418.

Production files Before After Net
86 33,208 32,790 −418
Production LOC by file
File Before After Net
src/agents/agent-command-restart-recovery.ts 494 484 -10
src/agents/agent-command.ts 729 724 -5
src/agents/agent-harness-completion-delivery.ts 158 157 -1
src/agents/command/cleanup.ts 107 138 +31
src/agents/command/post-run.ts 681 677 -4
src/agents/command/session-preparation.ts 290 303 +13
src/agents/embedded-agent-runner/runs.ts 1796 1804 +8
src/agents/main-session-recovery/main-session-recovery-admitted-interruption.ts 51 51 +0
src/agents/main-session-recovery/main-session-recovery-lifecycle.ts 245 244 -1
src/agents/main-session-recovery/main-session-recovery-state.ts 732 725 -7
src/agents/main-session-recovery/main-session-recovery-store.ts 350 354 +4
src/agents/main-session-recovery/main-session-recovery-types.ts 146 145 -1
src/agents/main-session-recovery/main-session-restart-dispatch.ts 642 640 -2
src/agents/main-session-recovery/main-session-restart-recovery-checkpoint.ts 378 381 +3
src/agents/main-session-recovery/main-session-restart-recovery-delivery.ts 113 112 -1
src/agents/main-session-recovery/main-session-restart-recovery-failure.ts 190 189 -1
src/agents/main-session-recovery/main-session-restart-recovery-marking.ts 467 469 +2
src/agents/main-session-recovery/main-session-restart-recovery-runtime.ts 435 432 -3
src/agents/main-session-recovery/main-session-restart-recovery-shared.ts 138 122 -16
src/agents/main-session-recovery/main-session-restart-recovery-store.ts 659 663 +4
src/agents/main-session-recovery/main-session-restart-recovery-target.ts 104 104 +0
src/agents/subagents/registry/subagent-delivery-state.ts 387 357 -30
src/agents/subagents/registry/subagent-registry-helpers.ts 379 385 +6
src/agents/subagents/registry/subagent-registry-restart-recovery-helpers.ts 61 62 +1
src/agents/subagents/registry/subagent-registry.store.sqlite.ts 519 494 -25
src/agents/subagents/registry/subagent-session-reconciliation.ts 254 225 -29
src/auto-reply/reply/agent-runner-execute.ts 475 475 +0
src/auto-reply/reply/agent-runner-run.ts 701 706 +5
src/auto-reply/reply/reply-turn-admission.ts 758 759 +1
src/auto-reply/reply/restart-recovery-claim.ts 622 605 -17
src/cli/program/register.status-health-sessions.ts 535 543 +8
src/commands/doctor-session-delivery-state.ts 293 293 +0
src/commands/doctor-session-title-repair.ts 196 189 -7
src/commands/doctor/shared/session-entry-rewrite.ts 264 337 +73
src/commands/doctor/shared/session-entry-shape.ts 164 265 +101
src/commands/sessions-cleanup.runtime.ts 163 220 +57
src/commands/sessions-tail.ts 312 339 +27
src/config/sessions/disk-budget-files.ts 167 169 +2
src/config/sessions/disk-budget.types.ts 36 37 +1
src/config/sessions/lifecycle.ts 241 231 -10
src/config/sessions/restart-recovery-receipt.ts 272 271 -1
src/config/sessions/restart-recovery-state.ts 565 610 +45
src/config/sessions/session-accessor.entry.ts 610 609 -1
src/config/sessions/session-accessor.sqlite-contract.ts 234 227 -7
src/config/sessions/session-accessor.sqlite-maintenance-candidates.ts 217 221 +4
src/config/sessions/session-accessor.sqlite-replacement-projection.ts 470 461 -9
src/config/sessions/session-accessor.sqlite-replacement-read.ts 104 81 -23
src/config/sessions/session-accessor.sqlite-status.ts 148 86 -62
src/config/sessions/session-accessor.sqlite-transcript-reports.kernel.ts 463 365 -98
src/config/sessions/session-accessor.sqlite-transcript-reports.ts 710 677 -33
src/config/sessions/session-accessor.sqlite-transcript-reports.types.ts 142 92 -50
src/config/sessions/session-accessor.sqlite-transcript-reports.worker.ts 290 255 -35
src/config/sessions/session-accessor.ts 310 309 -1
src/config/sessions/session-cold-storage-eligibility.ts 114 115 +1
src/config/sessions/session-cold-storage-selection.ts 152 157 +5
src/config/sessions/session-cold-storage-worker.ts 709 714 +5
src/config/sessions/session-cold-storage.ts 599 606 +7
src/config/sessions/session-entry-read.types.ts 129 126 -3
src/config/sessions/session-entry-read.worker.ts 693 669 -24
src/config/sessions/session-entry-state-format.ts 46 47 +1
src/config/sessions/session-entry-status-read.ts 100 0 -100
src/config/sessions/session-history-eviction-candidates.ts 184 186 +2
src/config/sessions/session-history-eviction.ts 674 697 +23
src/config/sessions/session-history.ts 8 7 -1
src/config/sessions/startup-migration.ts 387 397 +10
src/config/sessions/store-maintenance-preserve.ts 168 178 +10
src/config/sessions/store-maintenance.ts 621 622 +1
src/config/sessions/terminal-status.ts 44 32 -12
src/config/sessions/types.ts 875 873 -2
src/gateway/agent-turn/agent-session-persist.ts 562 561 -1
src/gateway/server-chat-event-admission.ts 133 141 +8
src/gateway/server-methods/agent-session-patch.ts 313 315 +2
src/gateway/server-methods/chat-restart-recovery.ts 494 468 -26
src/gateway/server-methods/chat-send-admission.ts 736 721 -15
src/gateway/server-methods/chat-send-handler.ts 716 718 +2
src/gateway/server-startup-session-migration.ts 282 102 -180
src/gateway/session-lifecycle-state.ts 590 590 +0
src/gateway/session-row-projection-record.ts 681 681 +0
src/gateway/session-utils-core.ts 261 260 -1
src/gateway/session-utils-display.ts 215 213 -2
src/gateway/session-utils-row.ts 717 717 +0
src/gateway/sessions-patch-lifecycle-flags.ts 95 93 -2
src/infra/gateway-lock.ts 744 742 -2
src/infra/outbound/delivery-completion.ts 448 445 -3
src/sessions/session-run-error.ts 127 92 -35
src/status/status-text.ts 624 632 +8
Total (86 production files) 33208 32790 -418

@clawsweeper

clawsweeper Bot commented Oct 5, 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 docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 6, 2026, 1:42 PM ET / 17:42 UTC (Revision 16).

ClawSweeper review

What this changes

The branch stores completed run outcomes, derives session activity from runtime registries, and updates recovery, maintenance, CLI selection, and regression coverage.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 9 items remain

Keep open: the two prior compatibility blockers remain, and the legacy-yield migration introduces an additional continuation-admission failure. Current main and the merged Workboard fix do not replace the remaining cutover.

Priority: P2
Reviewed head: 85a4f42f2071385946c602c6ceecfbdb0c0799d7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Substantial validation supports the useful refactor, but three compatibility and continuation blockers prevent a correctness pass.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies this as member-authored, so ordinary contributor setup proof is exempt; supplied validation includes production restart and SIGKILL paths. Existing-state compatibility remains independently insufficient: no verified released-plugin transition or predecessor-to-candidate-to-rollback result establishes safety.
Patch quality 🦐 gold shrimp (3/6) 3 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies this as member-authored, so ordinary contributor setup proof is exempt; supplied validation includes production restart and SIGKILL paths. Existing-state compatibility remains independently insufficient: no verified released-plugin transition or predecessor-to-candidate-to-rollback result establishes safety.
Evidence reviewed 12 items Pinned introduction and continuity: Reviewed introduction is 9e56928..85a4f42. The SDK type, legacy detector, migration, recovery-store admission, and recovery-marking files are unchanged since the previous reviewed head. The supplied test merge is stale and was not used to claim removal of main-only behavior.
Released SDK contract: v2026.9.8 defines PersistedSessionRunStatus as SessionRunStatus and exports SessionEntry through session-store-runtime, accepting it in patch, update, and upsert operations. This establishes a shipped public contract beyond internal session storage.
Released tag identity: GitHub resolves the annotated v2026.9.8 tag to fc23bc8. Its agent database contract declares schema version 24, matching the candidate.
Findings 3 actionable findings [P1] Preserve or version the shipped SessionEntry status contract
[P1] Protect same-schema rollback before rewriting recovery statuses
[P1] Avoid arming an empty recovery cycle for a verified yielded parent
Security None None.

How this fits together

Session metadata preserves outcomes and recovery custody across Gateway restarts. Runtime run and queue owners supply current activity to session lists, while recovery owners decide whether interrupted work may resume.

flowchart TD
  A[Incoming agent turn] --> B[Admission and recovery owner]
  B --> C[Live run registry and queue]
  B --> D[Durable session metadata]
  C --> E[Gateway session presentation]
  D --> E
  D --> F[Restart recovery]
  F --> B
Loading

Decision needed

Question Recommendation
Should this cutover preserve the v2026.9.8 plugin and rollback contracts, or proceed through an explicitly versioned compatibility transition? Preserve released compatibility: Retain compatible plugin reads and writes and safe predecessor recovery semantics while moving internal liveness to runtime owners.

Why: The coordinator decisions cover internal behavior but do not establish permission to break released SDK writes or reinterpret recovery state for older schema-24 readers.

Before merge

  • Preserve or version the shipped SessionEntry status contract (P1) - This prior blocker remains. v2026.9.8 exports SessionEntry through openclaw/plugin-sdk/session-store-runtime and accepts it in patch, update, and upsert operations. Excluding running and queued breaks valid assignments and comparisons; compiled plugins writing those values now reach the expanded legacy detector and throw SessionStoreMigrationRequiredError. Doctor cannot repair a plugin that continues making supported writes. Preserve the released boundary or implement an approved versioned transition.
  • Protect same-schema rollback before rewriting recovery statuses (P1) - This prior blocker remains. Startup converts unfinished running rows to interrupted while retaining their recovery claims and schema version 24. v2026.9.8 also accepts schema 24, but its pending-recovery predicate and startup discovery require running, so reopening the migrated store can strand unfinished work without an admission refusal. The new docs acknowledge the mismatch but do not protect custody. Preserve predecessor-readable recovery semantics or provide an approved compatibility fence and rollback proof.
  • Avoid arming an empty recovery cycle for a verified yielded parent (P1) - The yielded case clears status and keeps abortedLastRun: false, but this block still creates an empty mainRestartRecovery aggregate. Startup leaves it intact while the durable child continuation exists. When the child finishes, claim_foreground returns no_change because the parent is not aborted, while healthyExpectedSession rejects the aggregate, causing SESSION_WORK_START_CHANGED instead of delivering the result. The migration test currently asserts this broken shape. Exclude verified yields from new recovery custody or safely retire the empty aggregate before admission. This is a late discovery on code verified unchanged since the preceding review.
  • Resolve merge risk (P1) - The permanent transition for released plugin status reads and writes has no explicit compatibility acceptance or supporting plugin upgrade proof.
  • Resolve merge risk (P1) - Existing-store migration and rollback need evidence that unfinished recovery custody remains resumable or is safely fenced before the older runtime opens the store.
  • Complete next step (P2) - Record the accepted SDK transition and rollback contract, supported by existing-plugin and predecessor-to-candidate-to-rollback evidence.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P1] Preserve or version the shipped SessionEntry status contract — src/config/sessions/types.ts:54
  • [P1] Protect same-schema rollback before rewriting recovery statuses — src/commands/doctor/shared/session-entry-shape.ts:78-82
  • [P1] Avoid arming an empty recovery cycle for a verified yielded parent — src/commands/doctor/shared/session-entry-shape.ts:109-121
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Compatibility boundaries 2: released plugin SDK and schema-24 recovery state Both require compatibility evidence beyond ordinary typechecks and runtime regression tests.

Stored data model

Persistent data-model change detected: database schema: scripts/database-worker-inventory.mjs, migration/backfill/repair: scripts/database-worker-inventory.mjs, unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Complete a compatible cutover (recommended)
    Preserve released plugin operations, protect predecessor recovery custody, and remove the empty aggregate produced for yielded parents.
  2. Pause for a versioned transition
    Hold the branch until the SDK and storage owners approve and validate the intended compatibility boundary.

Technical review

Best possible solution:

Keep registry-derived liveness behind a compatible SDK transition, preserve rollback custody, and avoid creating recovery ownership for completed yields.

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

Yes, the three blockers have explicit source paths: a previously valid plugin status write, a migrated unfinished row reopened by v2026.9.8, and a migrated yielded parent entering foreground admission. These paths were inspected, not executed.

Is this the best way to solve the issue?

No, the owner consolidation is sound in direction, but the current implementation breaks released compatibility and creates recovery residue for a completed yield.

Full review comments:

  • [P1] Preserve or version the shipped SessionEntry status contract — src/config/sessions/types.ts:54
    This prior blocker remains. v2026.9.8 exports SessionEntry through openclaw/plugin-sdk/session-store-runtime and accepts it in patch, update, and upsert operations. Excluding running and queued breaks valid assignments and comparisons; compiled plugins writing those values now reach the expanded legacy detector and throw SessionStoreMigrationRequiredError. Doctor cannot repair a plugin that continues making supported writes. Preserve the released boundary or implement an approved versioned transition.
    Confidence: 0.99
  • [P1] Protect same-schema rollback before rewriting recovery statuses — src/commands/doctor/shared/session-entry-shape.ts:78-82
    This prior blocker remains. Startup converts unfinished running rows to interrupted while retaining their recovery claims and schema version 24. v2026.9.8 also accepts schema 24, but its pending-recovery predicate and startup discovery require running, so reopening the migrated store can strand unfinished work without an admission refusal. The new docs acknowledge the mismatch but do not protect custody. Preserve predecessor-readable recovery semantics or provide an approved compatibility fence and rollback proof.
    Confidence: 0.98
  • [P1] Avoid arming an empty recovery cycle for a verified yielded parent — src/commands/doctor/shared/session-entry-shape.ts:109-121
    The yielded case clears status and keeps abortedLastRun: false, but this block still creates an empty mainRestartRecovery aggregate. Startup leaves it intact while the durable child continuation exists. When the child finishes, claim_foreground returns no_change because the parent is not aborted, while healthyExpectedSession rejects the aggregate, causing SESSION_WORK_START_CHANGED instead of delivering the result. The migration test currently asserts this broken shape. Exclude verified yields from new recovery custody or safely retire the empty aggregate before admission. This is a late discovery on code verified unchanged since the preceding review.
    Confidence: 0.97
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against cca16bed6373.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a useful session-state correction and refactor with bounded user impact, rather than an established current emergency.
  • merge-risk: 🚨 compatibility: The branch narrows a released SDK type and rejects previously accepted plugin status writes.
  • merge-risk: 🚨 session-state: Migration changes unfinished recovery semantics and can leave yielded-parent continuation blocked by an empty aggregate.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Repository State identifies this as member-authored, so ordinary contributor setup proof is exempt; supplied validation includes production restart and SIGKILL paths. Existing-state compatibility remains independently insufficient: no verified released-plugin transition or predecessor-to-candidate-to-rollback result establishes safety.

Evidence

What I checked:

  • Pinned introduction and continuity: Reviewed introduction is 9e56928..85a4f42. The SDK type, legacy detector, migration, recovery-store admission, and recovery-marking files are unchanged since the previous reviewed head. The supplied test merge is stale and was not used to claim removal of main-only behavior. (85a4f42f2071)
  • Released SDK contract: v2026.9.8 defines PersistedSessionRunStatus as SessionRunStatus and exports SessionEntry through session-store-runtime, accepting it in patch, update, and upsert operations. This establishes a shipped public contract beyond internal session storage. (src/plugin-sdk/session-store-runtime.ts:639, fc23bc864e45)
  • Released tag identity: GitHub resolves the annotated v2026.9.8 tag to fc23bc8. Its agent database contract declares schema version 24, matching the candidate. (src/state/openclaw-agent-db-contract.ts:29, fc23bc864e45)
  • Previously valid writes now fail: The introduced detector treats running and queued as legacy. Plugin patch projection retains status, and the SQLite writer calls projectCanonicalSessionEntryShape, which throws SessionStoreMigrationRequiredError for these values. (src/config/sessions/session-entry-state-format.ts:42, 85a4f42f2071)
  • Rollback recovery mismatch: Candidate startup rewrites legacy running rows to interrupted while retaining recovery custody. The released recovery owner requires status running for pending recovery and scans running rows for startup orphan handling; interrupted rows with retained aggregates therefore fall outside that recovery path. (src/agents/main-session-recovery/main-session-recovery-state.ts:160, fc23bc864e45)
  • Introduced yielded-parent residue: The migration creates an empty recovery aggregate even when yielded is true. The migration test explicitly expects that aggregate with abortedLastRun false. Startup retains it while the child continuation exists; claim_foreground then returns no_change, and healthyExpectedSession rejects the aggregate, producing state_changed. (src/commands/doctor/shared/session-entry-shape.ts:121, 85a4f42f2071)

Likely related people:

  • steipete: 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.

  • Resolve the shipped SDK transition and cover previously valid plugin status reads and writes.
  • Prove predecessor-to-candidate migration followed by rollback preserves or safely fences unfinished recovery custody.
  • Exercise a migrated yielded parent through actual requester-settle admission and successful result delivery.

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 (15 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-06T02:49:15.714Z sha bc60cd6 :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T06:22:29.542Z sha 47a7637 :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T10:47:52.912Z sha 5fe118a :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T11:55:14.151Z sha 6b1cd9f :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T12:05:14.439Z sha f0e950c :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T13:13:43.380Z sha 9e97e89 :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T15:40:05.672Z sha 9e97e89 :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses
  • reviewed 2026-10-06T16:58:11.755Z sha 61264c8 :: blocked before merge. :: [P1] Preserve or version the shipped SessionEntry status contract | [P1] Protect same-schema rollback before rewriting recovery statuses

@openclaw-barnacle openclaw-barnacle Bot closed this Oct 5, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. labels Oct 5, 2026
@steipete
steipete force-pushed the steipete/session-status-outcome-only branch 2 times, most recently from ca37244 to 98684e4 Compare October 6, 2026 01:06
@steipete
steipete force-pushed the steipete/session-status-outcome-only branch 5 times, most recently from 47a7637 to 5fe118a Compare October 6, 2026 10:40
steipete added a commit that referenced this pull request Oct 6, 2026
Use live reply ownership when admitting turns with durable execution fences,
and release an unclaimed recovery route only with its delivered pending intent.
Preserve explicit message-tool-only policy when early run IDs make fallback
execution and finalization share options.

Migrate current-main fixtures away from persisted liveness and retired event
fields without relaxing their behavior assertions. Refresh worker inventory.

Validation: production and core test types, formatting, lint, import cycles,
worker inventory, focused owner suites, and direct-route review passed.
Progress presentation passed all 16 cases with a canonical macOS fixture root.
Broader proof identified inherited database-admission and rotation-spy failures
on main 6d94780; those remain unchanged. Final integration proof continues
on the rebased head before publication.

Refs #165733
steipete added a commit that referenced this pull request Oct 6, 2026
Move unchanged fence normalization and recording into the existing persisted
recovery utility owner. Update every caller and remove the old exports so the
consolidated transition module stays below its lint budget without splitting
its authority decisions.

Validation: core and extension types, all 27 core test-type shards, formatting,
type-aware lint, both import-cycle checks, worker inventory, and independent
review passed. The 13-file integration packet passed 244 tests in 277.03s;
the preceding 22-file packet passed 708 tests in 757.78s. The E2E packet passed
243 tests, including 16 progress-presentation cases and real SIGKILL recovery,
in 1549.79s including the runtime build. Linux-only restart handoff stayed
platform-skipped on macOS. Temporary canonical temp-root fixture overrides
were removed after proof.

Refs #165733
steipete added a commit that referenced this pull request Oct 6, 2026
A database close refusal left queued input intact and the drain's finally
block immediately rescheduled it. With debounce disabled this starved the
event loop and flooded shutdown logs. This owner defect is inherited from
main b2fab20, where the new deterministic regression also fails with
"expected 2 to be 1" before its safety stop.

Classify the refusal with the existing shared admission-closed error and
park the queue without completing or discarding its input. Release detached
work; a fresh drain signal or durable restart recovery owns continuation.
Move the singleton error to a leaf module and migrate all consumers so this
admission boundary introduces no runtime or type-inclusive import cycle.
Retain explicit requests received while a refused attempt unwinds on that
exact drain owner. One successor consumes the request and parks again if
admission still refuses it; no automatic retry loop is restored.
Persisted session outcomes and durable recovery contracts are unchanged.

The fake-clock regression proves one attempt while closing, retained input,
released root work, and successful draining after admission reopens. The
final standalone drain suite passes 23 tests in 12.04 seconds wall; the
new cases use only fake-clock advancement. The queue/recovery sweep passes 1,063 tests across 60 files. This is a separate
production fix for the shutdown hot loop exposed by #165733's RPC fixture.
@steipete
steipete force-pushed the steipete/session-status-outcome-only branch from 6b1cd9f to f0e950c Compare October 6, 2026 11:59
steipete added a commit that referenced this pull request Oct 6, 2026
Use live reply ownership when admitting turns with durable execution fences,
and release an unclaimed recovery route only with its delivered pending intent.
Preserve explicit message-tool-only policy when early run IDs make fallback
execution and finalization share options.

Migrate current-main fixtures away from persisted liveness and retired event
fields without relaxing their behavior assertions. Refresh worker inventory.

Validation: production and core test types, formatting, lint, import cycles,
worker inventory, focused owner suites, and direct-route review passed.
Progress presentation passed all 16 cases with a canonical macOS fixture root.
Broader proof identified inherited database-admission and rotation-spy failures
on main 6d94780; those remain unchanged. Final integration proof continues
on the rebased head before publication.

Refs #165733
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 6, 2026
Frozen upstream: 10334ec (previous base 14fe10d).
Nine conflicts, resolved hunk by hunk:
- config-baseline.counts.json, worker-access-inventory.md: upstream's copy; regenerated in follow-up commits.
- agent-runner-run.ts: keep the feature's bindVisiblePartialReplyObserver; re-apply upstream's always-present runId (openclaw#165733).
- agent-runner-result-payloads.ts: drop upstream-removed stale "drain" comment; keep queued-delegate counts.
- session-accessor.sqlite-lifecycle.ts: add upstream's captureIncognitoSessionOperation import; history maintenance stays in the feature's sibling module; drop upstream-removed jsdoc.
- openclaw-agent-db-lifecycle.ts: upstream's validation-cache imports (get/invalidate) replace hasRevoked.
- doctor-health.migration-refusal.test.ts: both sides added the same maintenance facts; keep the typed one.
- get-reply-run.media-only.test.ts: helpers stay in the continuation test-support; upstream's expectDefined form re-homed there.
- subagent-announce.format.e2e.test.ts: upstream's call.params form + feature continuationTrigger assertion and omitted-trigger case; matrix stays in the feature's nested-matrix test-support; drop redundant embedded-run mock resets (upstream consolidation openclaw#166052).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
vincentkoc added a commit that referenced this pull request Oct 6, 2026
* commit 'c39d9b0692dbaafa5b1bfe02514c9f6411ab5546': (30 commits)
  fix(ci): clear MCP audit and service-worker test blockers (#166217)
  test(gateway): wait for steering admission in FIFO fixtures
  fix(llama-cpp): managed setup crashes and loops on macOS below 13.3 (#163358)
  perf(worktrees): avoid full session parsing during GC (#166072)
  fix(update): recover stopped legacy managed services (#166232)
  perf(gateway): stream bounded link preview metadata (#166195)
  perf(diagnostics): release completed Git operation state (#166214)
  chore(deps): update fs-safe to 0.24.1 and clone plugin source captures (#166189)
  feat(clients): adopt worker-local inference placement (#163647)
  test: serialize PowerShell completion process suites (#166229)
  test: stabilize release timing boundaries (#166218)
  refactor(sessions): persist run outcomes only; liveness comes from the run registry (#165733)
  test(gateway): prove mention refresh after config retargeting
  fix(team-reports): keep the missed closed day when catch-up runs after midnight (#165780)
  test(gateway): join WebChat queue admission and drain completion
  fix(logging): reject blank diagnostic stability query fields (#145532)
  fix(agents): report unparseable serialized edit arguments (#163577)
  improve(anthropic): log Claude Code version probe failures (#157697)
  fix(agents): clarify prompt-size provider failures (#159712)
  fix(memory): re-throw non-ENOENT/ENOTDIR errors in root memory file lookup (#107921)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
…e run registry (openclaw#165733)

Persisted session status now records only run outcomes (done, failed, killed, timeout, interrupted). Running and queued are derived from the live run registry and queue, so a cut-short restart drain can no longer leave a session showing "Working" forever.

- Restart-aborted runs record `interrupted` with a reason and end time while keeping recovery claims; the startup orphan reconciler is removed.
- Startup runs the Doctor transform once to normalize legacy persisted running/queued values to interrupted (verified legacy yields keep ownership).
- Turn admission, chat restart recovery, sessions tail, and session cleanup read liveness from the live owners.
- Follow-up queue drains park instead of retrying in a hot loop when agent database admission is closing.
- agent.wait wakes when queued chat admission publishes after the wait began.
- Explicit message-tool-only delivery policy survives model fallback.

Net production LOC is reduced. CI: all test shards green on 85a4f42; security-fast fails on the same two MCP SDK advisories that fail on main (run 37501461189), not caused by this change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations docs Improvements or additions to documentation extensions: qa-lab gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant