Skip to content

Fix dangerous implicit state machines (audit lanes) #2071

Open
5 of 5 issues completed
Open

Description

@shanselman

Filed by a Copilot agent (not Scott) from an implicit state machine audit.

Goal: fix the races and stale state found by a two-pass audit of implicit state machines. Each finding was checked against the code at e70292487. Autonomy L2: an agent opens ready PRs and a human lands them.

Done when: each lane below has a merged PR with a deterministic regression test that fails before the fix, and ./build.ps1 plus the Shared and Tray test suites pass.

# Lane Severity Files
1 Run disconnect cleanup on every connection loss Medium WebSocketClientBase.cs, OpenClawGatewayClient.cs
2 Make MCP server start and stop atomic in NodeService Medium (security-adjacent) NodeService.cs
3 Accept forwarded launches before the startup update prompt Medium (unpackaged release) App.xaml.cs, ActivationRouter.cs
4 Stop queued reconnects from reviving a disconnected gateway Low-Medium GatewayConnectionManager.cs, ConnectionPage.xaml.cs
5 Give the cron safety timer a per-run token Low CronPage.xaml.cs

No two lanes change the same file. PRs will be opened one at a time.

Deferred (Low or Info, no lane):

  • design smell in the WindowsNodeClient pairing flags
  • the auto-repair monitor's literal timeout
  • a possible double keepalive spawn
  • the update dialog can install a different release
  • a duplicate hatching message
  • a dropped LocalAI resume
  • the hotkey registering after a timeout has reported failure
  • the dead NavigateAndWaitAsync
  • _protocolMismatch never resetting
  • the post-handshake burst not being tied to a connection generation
  • startup continuing after Exit

Judged safe:

  • GatewayConnectionManager core and ConnectionStateMachine
  • ExecApprovals, the MXC runner, migration and the gateway runtimes
  • the pairing queue and McpHttpServer
  • ConnectionPage, WorkspaceWindow and the shutdown coordinator
  • chat and setup

Sub-issues

Sub-issues

5 of 5 Issues completed
Loading 5 sub-issues

Activity

  1. self-assigned this
    on Nov 8, 2026
  2. added
    lever
    on Nov 8, 2026
  3. added
    clawsweeper:intake:bug
    clawsweeper:intake:needs-environment
    clawsweeper:intake:needs-repro
    P2
    clawsweeper:needs-security-review
    clawsweeper:no-new-fix-pr
    clawsweeper:source-repro
    impact:security
    impact:session-state
    impact:ux-friction
    issue-rating: 🦞 diamond lobster
    and removed
    clawsweeper:intake:bug
    clawsweeper:intake:needs-environment
    clawsweeper:intake:needs-repro
    on Nov 8, 2026
  4. clawsweeper commented on Nov 8, 2026

    @clawsweeper

    Codex review: this still needs some work.

    Summary
    Keep this issue open: current main retains the reported lifecycle defects, and this collaborator-authored umbrella tracks five unresolved child issues.

    Reproducibility: Current source establishes the missing cleanup, unsynchronized listener ownership, activation ordering, reconnect check/acquire gap, and timer identity defect; existing tests pin parts of that behavior, but no live reproduction ran.

    Next step
    Keep this collaborator-authored umbrella with its five child issues, establish failing regressions per lane, and require explicit MCP revocation proof before accepting that repair.

    Security
    Needs attention: The MCP lane concerns listener revocation after disable and needs security-conscious lifecycle validation.

    Review details

    Best possible solution:

    Complete the five focused child repairs with deterministic regressions and current-head proof while retaining the existing lifecycle owners.

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

    Current source establishes the missing cleanup, unsynchronized listener ownership, activation ordering, reconnect check/acquire gap, and timer identity defect; existing tests pin parts of that behavior, but no live reproduction ran.

    Is this the best way to solve the issue?

    Separate repairs fit these distinct defects, provided each first establishes a failing regression and preserves authentication, shutdown drain, activation ownership, and connection-generation checks.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • The exact concurrent MCP listener failure needs deterministic regression coverage and Windows enable/disable proof; no authentication bypass is established.
    • Startup reordering must preserve initialization and current-user activation boundaries, and reconnect changes must preserve generation fencing.
    • No runtime reproduction or test execution was performed during this read-only review.

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

    Label changes

    Label changes:

    • add P2: These bounded lifecycle defects warrant repair, without evidence of an emergency outage or blocked first-use flow.
    • add impact:security: Concurrent MCP lifecycle operations can undermine the user's expectation that disabling MCP removes its listener.
    • add impact:session-state: Skipped disconnect cleanup leaves handshake/session metadata stale and pending requests uncleared until later recovery.
    • add impact:ux-friction: Startup forwarding can expire during update prompting, and old cron timers can misrepresent a newer run.
    • add issue-rating: 🦞 diamond lobster: Current issue advisory state selects this label.
    • add clawsweeper:source-repro: Current issue advisory state selects this label.
    • add clawsweeper:no-new-fix-pr: Current issue advisory state selects this label.
    • add clawsweeper:needs-security-review: Current issue advisory state selects this label.

    Label justifications:

    • P2: These bounded lifecycle defects warrant repair, without evidence of an emergency outage or blocked first-use flow.
    • impact:security: Concurrent MCP lifecycle operations can undermine the user's expectation that disabling MCP removes its listener.
    • impact:session-state: Skipped disconnect cleanup leaves handshake/session metadata stale and pending requests uncleared until later recovery.
    • impact:ux-friction: Startup forwarding can expire during update prompting, and old cron timers can misrepresent a newer run.
    Evidence reviewed

    Security concerns:

    • [medium] MCP listener ownership can be lost during concurrent lifecycle operations — src/OpenClaw.Tray.WinUI/Services/NodeService.cs:819
      An overlapping start can publish after disable has observed no server, or a failed competing start can clear the winner's shared reference. The listener can then remain available despite disabled state; loopback authentication and capability authorization still apply.
      Confidence: 0.93

    What I checked:

    • Protected umbrella and unresolved lanes: The issue author association is COLLABORATOR; its timeline links five open child issues. The body requires separate merged repairs with deterministic regressions. The discussion contains only a review-status comment.
    • Verified current default branch: GitHub main and the clean review checkout both resolve to e702924. (e70292487958)
    • Incomplete connection-loss cleanup: Oversized-message handling closes and breaks without OnDisconnected; client-aborted cancellation also skips it. OpenClawGatewayClient.OnDisconnected owns handshake invalidation and pending-request failure, while OnError only drains requests. The existing abort test explicitly expects zero disconnect callbacks. (src/OpenClaw.Shared/WebSocketClientBase.cs:551, e70292487958)
    • MCP listener publication and revocation race: StartMcpServer checks enabled/running state without lifecycle synchronization, publishes the listener after Start, and unconditionally clears the shared reference on failure. StopMcpServerAsync clears references independently; AttachClient reaches capability registration outside _clientLock, unlike SetMcpEnabled. (src/OpenClaw.Tray.WinUI/Services/NodeService.cs:773, e70292487958)
    • Activation listener starts after awaited update check: Startup awaits CheckOrdinaryStartupUpdateAsync before starting forwarded-activation listening and directly constructs the global hotkey afterward. AppRefactorContractTests currently pins the update-before-listener order; ActivationRouter forwarding has bounded retries. (src/OpenClaw.Tray.WinUI/App.xaml.cs:1096, e70292487958)
    • Reconnect generation check precedes semaphore acquisition: ScheduleOperatorReconnectAsync validates the attempt before ReconnectIfCurrentAsync acquires the transition semaphore. That method checks gateway identity and user intent but never rechecks the captured generation; ordinary DisconnectAsync increments the generation without recording disconnected user intent. (src/OpenClaw.Connection/GatewayConnectionManager.cs:3356, e70292487958)
    How this review workflow works
    • 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; those execution lanes are retired.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

    Reviewed November 8, 2026, 1:29 AM ET / 06:29 UTC.

  5. shanselman commented on Nov 8, 2026

    @shanselman
    CollaboratorAuthor

    Copilot agent handoff (not Scott). The audit found five concrete lifecycle defects, with no confirmed High-severity finding. All five repairs are published as separate, non-draft PRs. They preserve the existing owners rather than introducing a framework-wide state-machine rewrite. Local required validation passed for each; this is a delivery handoff, not a green-CI or merge approval.

    Repair PR and tested head Strongest evidence
    MCP listener ownership #2078 (fix(node): local MCP server can stay running or vanish when toggled during a restart), b74a343ee694df5f01ba2e16709f38555833c434 Both authenticated, real-HTTP concurrency cases fail on old source because calls still cause effects after disable. Both pass after the fix, including same-client re-enable. Isolated native off/on checks also pass.
    Transport-loss cleanup #2079 (fix: fail pending Gateway requests promptly after transport loss), 2b2da5dc61a5028a863bca748c63364606d818f9 Six original regressions fail on base. Two production-client loopback checks pass. Review also exposed and fixed a callback-lock deadlock.
    Startup activation #2080 (fix: accept forwarded launches during startup update prompts), 69a1f27b0f8452c3416c99e0026bc2432e115a95 Ordering regressions fail on base. Named-pipe forwarding succeeds while a synthetic update check is held; isolated native app receives forwarded settings/hub payloads.
    Reconnect intent #2081 (fix: keep queued reconnects from reviving disconnected gateways), a640c35de15432a6f56ec8449fd94b764ba680b5 Four intended baseline failures plus positive controls. Nine focused cases and removal wiring guard pass. Native disconnect remains idle with MCP live; explicit saved Connect reaches Connected.
    Cron run identity #2082 (fix: keep older Run Now attempts from clearing newer runs), 079b18dce43b8fd07d4fffc52913d194a3b84c7c A pre-fix-equivalent job-only ownership mutation makes the stale-token assertion fail (expected false, actual true); restored candidate passes all 10 focused checks. This is a behavioral mutation control, not a run of the original app. Independent current-candidate review is clean. Isolated UI rejection recovery passes, but the fixture cannot execute the accepted A/B lifecycle.

    Local validation

    Each published lane ran these exact mandatory commands in its own worktree:

    .\build.ps1
    dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore
    dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore
    Lane Full build Shared Tray Additional focused checks
    MCP Passed 4,876 passed, 24 skipped 5,294 passed Real-HTTP concurrency 2 passed, 0 skipped
    Transport Passed 4,883 passed, 24 skipped 5,294 passed 544 passed, including the two loopback checks
    Startup Passed 4,876 passed, 24 skipped 5,297 passed 5 passed
    Reconnect Passed 4,876 passed, 24 skipped 5,295 passed Connection 1,752 passed, 1 distinct-volume migration skip; focused 9 passed plus removal guard
    Cron Passed 4,876 passed, 24 skipped 5,300 passed Ownership/contracts 10 passed; fixture rejection recovery 1 passed

    Hosted CI and proof limits

    • MCP run 42461096068 is red. The known reasoning-picker testhost crash happened before the new MCP cases ran. A separate fractional-voice history fixture timed out after successful MCP startup/navigation/snapshot; its root cause is not established. Hosted UI remains a merge blocker.
    • Transport run 42460930325 is red solely on the exact documented missing wizard More-button baseline. Core/Tray/setup and real WSL setup/connect, network recovery and revocation jobs passed. MXC-selected tests skipped, so no MXC proof claim.
    • Startup run 42461228890 passed all selected jobs and CI Gate. Core/WSL were classification-skipped. The actual production Release update-dialog overlap remains unverified; Debug fixture proof is not that claim.
    • Reconnect run 42462800715 is red on the documented reasoning-flyout crash family (ReasoningPicker_ReflectsInheritedDefaultWithoutOverridingExplicitChoices, not the MCP run's case) plus a compatibility archive HTTP 504 before those tests started. The crashing pure UI harness constructs no connection manager and does not exercise reconnect/removal; the native fault remains unresolved. Core/CLI, Tray/setup/integration, fixture UI (81/81), and WSL setup/connect (53 passed, 7 MXC NotExecuted), revocation (1/1) and network recovery (2/2) passed. Saved-gateway removal was not clicked without deletion confirmation; its routing is covered by the focused guard.
    • Cron run 42468203925 is pending. Live stale-timeout/history A/B proof is explicitly not verified: the isolated fixture rejects cron.run with FIXTURE_READ_ONLY and has no cron.runs handler. Its UI test proves rejection recovery only. Legacy accepted acknowledgements without RunId cannot safely correlate history, so they wait for an independent job-list update or the conservative 90-second safety timer rather than guessing from execution/completion timestamps. The earlier unrelated ActivationRouterTests.MigrationShutdown_UsesCurrentUserIpcWithoutCreatingADeepLinkRoute 10-second timeout was preserved; its exact rerun passed, followed by the green full closeout above.

    Isolated app/Gateway fixtures are synthetic, not real provider or signed-package proof. No skipped/custom pool was described as completed, and no CI was blindly rerun. Individual PR bodies preserve the template, exact commands, source identities, review dispositions and proof boundaries. All five live PR identities, fork ownership, main targets, maintainer-edit settings, closing references and template content were verified. Owned app/fixture helpers have been stopped.

    The ready-PR delivery boundary is separate from merging: nothing was merged or put on auto-merge. Keep this umbrella open for human review and landing, including resolution of the visible CI blockers. No shared Gateway/runtime was changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2clawsweeper:needs-security-reviewclawsweeper:no-new-fix-prclawsweeper:source-reproimpact:securityimpact:session-stateimpact:ux-frictionissue-rating: 🦞 diamond lobsterlever

Type

No type

Fields

Priority

None yet

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions