Skip to content

fix(cli): detect CLI/gateway state-dir split-brain before credential writes - #134403

Merged
obviyus merged 1 commit into
mainfrom
fix/state-dir-split-brain
Sep 1, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/state-dir-split-brain

Conversation

@obviyus

@obviyus obviyus commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Local credential and configuration commands could report success while writing to a state directory that the running Gateway never reads. This happens when the CLI and Gateway use different OPENCLAW_STATE_DIR or OPENCLAW_CONFIG_PATH values.

Why This Change Was Made

The CLI command catalog now marks models auth, channels add, channels login, and configure as local state writers. One global Commander pre-action checks those commands before bootstrap or action code can persist state.

The check uses this evidence order:

  1. An authenticated admin hello provides the live Gateway paths.
  2. If no hello arrives, an installed Gateway service provides its configured paths, whether running or stopped.
  3. If credentials block the hello and no service exists, a read-only protocol probe can warn that a Gateway is present but cannot expose its paths.

Proven path mismatches refuse the write. Remote or unverifiable Gateway paths warn. An offline host with no installed service stays silent. The check adds no waiver flag, config key, protocol field, or storage migration.

Doctor reuses the same path comparison in warning mode after its existing authenticated status hello.

User Impact

Operators no longer get a false success from the guarded local setup and credential commands when a live or installed Gateway uses another state tree. The refusal shows the exact quoted state/config environment needed to target the Gateway.

Intentional writes to another local tree require stopping the running Gateway, or uninstalling or reconfiguring the divergent installed service first.

Evidence

  • Baseline e44c4b8a3e0e9e8bae58ebf1a50e239176d8e4cd: a real channels add command returned success and wrote the Telegram token into the CLI config while an authenticated admin hello reported a different Gateway state directory. The refusal contract failed.
  • Head 41d56a74efa55ad36634fa4f87ff7138db1ced09: the same command raised No credentials or configuration were written; the CLI config contained no token; the same authenticated hello still reported the different Gateway directory.
  • Anti-cheat: the proof read the Gateway path from the post-command authenticated admin hello. It did not infer the path from the CLI environment or an open TCP port.
  • Real Gateway coverage: matching token-auth paths allow, mismatched token-auth paths refuse, and a tokenless CLI against a token Gateway warns from protocol evidence only.
  • Focused local proof: 55 CLI tests and 21 Doctor tests passed; targeted Oxlint, Oxfmt, and git diff --check passed. Local TypeScript build/typecheck commands were not run under the host safety rule; exact-head CI owns them.
  • Pre-commit Autoreview: clean, no accepted P0 finding.
  • Size: production +198/-2, tests and test support +548/-8, docs +6.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus
obviyus marked this pull request as ready for review August 31, 2026 19:01
@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes commands Command implementations size: L maintainer Maintainer-authored PR labels Aug 31, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. 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 Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed September 1, 2026, 9:40 AM ET / 13:40 UTC.

ClawSweeper review

What this changes

The PR adds a CLI pre-action check that compares local state paths with a local Gateway or installed service before selected setup and credential commands run.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

The PR remains necessary, but its parent-level model-auth policy blocks read-only commands and bare help whenever the local Gateway/service uses another state tree.

Priority: P1
Reviewed head: 41d56a74efa55ad36634fa4f87ff7138db1ced09
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The central guard has useful source and supplied behavior evidence, but an introduced P1 command-scope regression blocks merge.
Proof confidence 🌊 off-meta tidepool Not applicable: This is a maintainer-authored PR, so external-contributor proof gating does not apply; its body reports a real before/after credential-write run, but that evidence does not cover the introduced read-only command regression.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is a maintainer-authored PR, so external-contributor proof gating does not apply; its body reports a real before/after credential-write run, but that evidence does not cover the introduced read-only command regression.
Evidence reviewed 6 items Introduced overbroad policy: The introduced non-exact models-auth policy applies the guard to every descendant; policy resolution assigns matching entries to the full Commander action path.
Read-only affected command: The models auth list command loads and displays saved profiles; its target is explicitly resolved with kind read and it contains no credential/config persistence operation.
Bare help is also affected: The models auth parent action only invokes help, but the inherited guard runs before that action and can throw a refusal first.
Findings 1 actionable finding [P1] Do not guard read-only model-auth commands
Security None None.

How this fits together

CLI setup and authentication commands write local state, while the Gateway and its installed service choose the state tree the running bot consumes. The new guard queries those paths before a command action and permits, warns, or refuses execution.

flowchart LR
  A[CLI command] --> B[Command-path policy]
  B --> C[Pre-action state check]
  C --> D[Gateway hello]
  C --> E[Installed service state]
  D --> F{Paths match?}
  E --> F
  F -->|Yes or unknown| G[Run command]
  F -->|Proven mismatch| H[Refuse execution]
Loading

Decision needed

Question Recommendation
After the narrow read-only-command repair, should this maintainer-labeled CLI compatibility change merge? Repair write-path classification: Guard only auth subcommands that can persist credentials or configuration, preserving list and help behavior.

Why: The PR is marked maintainer and changes credential/config startup behavior, so a maintainer must make the final merge decision.

Before merge

  • Do not guard read-only model-auth commands (P1) - The non-exact models auth policy is inherited by models auth list and bare models auth. Those paths only display profiles or help, yet a divergent installed service makes pre-action throw before either action. Restrict the guard to write-capable leaves and cover list/help under a mismatch.
  • Resolve merge risk (P1) - The PR adds 196 net production lines across CLI and Doctor for a bug fix; that scope is justified only if the corrected command classification remains the single canonical guard boundary.
  • Complete next step (P2) - The introduced overbroad policy has a narrow mechanical repair and focused validation path; final merge remains maintainer-owned.

Findings

  • [P1] Do not guard read-only model-auth commands — src/cli/command-catalog.ts:353
Agent review details

Security

None.

PR surface

Source +196, Tests +540, Docs +6. Total +742 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 5 198 2 +196
Tests 9 548 8 +540
Docs 3 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 752 10 +742

Review metrics

Metric Value Why it matters
Production versus test delta production +198/-2; tests and test support +548/-8; docs +6 The substantial new guard surface needs exact write-path classification to justify its compatibility cost.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-gateway-health.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Narrow the auth policy (recommended)
    Replace the inherited models-auth rule with explicit write-capable leaves and cover read-only list/help behavior.
  2. Pause the guard
    Hold the PR if maintainers prefer a broader state-write inventory before changing CLI authentication command behavior.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Apply the P1 command-policy fix and add focused regression coverage for models auth list and bare models auth help under a state mismatch.

Technical review

Best possible solution:

Mark only write-capable models auth leaves as guarded, keep models auth list and bare help runnable, and add focused regression coverage for both read-only paths under a divergent local service.

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

Yes—source-reproducible: run models auth list or bare models auth while the installed local service reports different state paths; the new pre-action guard refuses before the read-only action or help handler. The reviewer did not execute target code in this read-only checkout.

Is this the best way to solve the issue?

No. A parent policy overmatches read-only inspection and help; explicit write-capable auth leaves preserve the stated protection boundary without blocking recovery commands.

Full review comments:

  • [P1] Do not guard read-only model-auth commands — src/cli/command-catalog.ts:353
    The non-exact models auth policy is inherited by models auth list and bare models auth. Those paths only display profiles or help, yet a divergent installed service makes pre-action throw before either action. Restrict the guard to write-capable leaves and cover list/help under a mismatch.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This is a maintainer-authored PR, so external-contributor proof gating does not apply; its body reports a real before/after credential-write run, but that evidence does not cover the introduced read-only command regression.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: A divergent local service can make normal model-auth inspection and help unavailable before their actions run.
  • merge-risk: 🚨 compatibility: The introduced pre-action policy changes whether existing CLI commands can run against divergent local state.
  • merge-risk: 🚨 auth-provider: The affected command group manages provider authentication profiles and login flows.
  • 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: This is a maintainer-authored PR, so external-contributor proof gating does not apply; its body reports a real before/after credential-write run, but that evidence does not cover the introduced read-only command regression.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/cli/command-path-policy.test.ts src/cli/program/preaction-state-store.test.ts src/cli/models-cli.test.ts.
  • [P1] node scripts/run-vitest.mjs src/cli/state-dir-gateway-check.test.ts.
  • [P1] git diff --check.

What I checked:

Likely related people:

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

  • Restrict the model-auth guard to write-capable leaves and add list/help mismatch regressions.

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 (22 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-01T09:04:36.385Z sha d6acf2e :: found issues before merge. :: [P2] Quote Gateway paths in the recovery command
  • reviewed 2026-09-01T09:26:31.818Z sha 8874a41 :: found issues before merge. :: [P1] Do not inherit CLI paths as service paths
  • reviewed 2026-09-01T09:35:23.171Z sha 8874a41 :: needs changes before merge. :: [P1] Read the installed service target without inheriting CLI paths
  • reviewed 2026-09-01T09:48:00.688Z sha afde37c :: needs changes before merge. :: [P1] Keep the CLI state-dir guard out of the shared login runtime
  • reviewed 2026-09-01T09:54:59.259Z sha afde37c :: found issues before merge. :: [P1] Keep the CLI state-dir guard out of the shared login runtime
  • reviewed 2026-09-01T10:30:25.849Z sha ade37fc :: found issues before merge. :: [P1] Support parent waiver before dynamic channel setup flags | [P1] Use canonical loopback detection before skipping the guard | [P1] Use the Gateway hello snapshot after a status request fails | [P1] Probe the configured service endpoint before calling it offline
  • reviewed 2026-09-01T11:18:50.789Z sha 26c1699 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T11:38:28.192Z sha 13596581cd11584bf791a05c62c93cca5091ce4d :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 1, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Sep 1, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 1, 2026
@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Both P1 findings are fixed at head 5d2b9bc4a65 (read-only probe; realpath-normalized config-path comparison), and the two maintainer questions are decided in the PR body along with the production LOC justification. Exact-head CI is green (208 success, 44 skipped, 1 neutral, 0 failures).

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review — all four state-dir waiver alias gaps are closed at 008d8f9184d, with real-parser coverage enumerating every applicable leaf.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@obviyus
obviyus force-pushed the fix/state-dir-split-brain branch from 008d8f9 to 633e62d Compare September 1, 2026 05:07
@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

P1 resolved: missing config leaves now canonicalize through their nearest existing parent

Head 9fb0509a54597f0b04cb5a31a0e18558097a6ad1 applies the recommended repair and the single rank-up move.

Root cause. realpathSync rejects a path that does not exist yet. Before the first credential write openclaw.json is absent, so the old normalizeStateDir fell back to path.resolve. A CLI state dir reached through a symlink then compared unequal to the Gateway's real dir, and the guard refused a write that targeted the same future file.

Fix. canonicalizeStatePath walks up to the nearest existing ancestor, canonicalizes that, and re-appends the missing tail. Same shape the worktree resolver already uses for the same reason (scripts/pr-lib/worktree.sh:231-234). All five call sites moved to it; the old name is gone.

src/cli/state-dir-gateway-check.ts:12-26

Regression test. src/cli/state-dir-gateway-check.test.ts — "matches a missing config path through a symlinked state directory": real temp dir, symlink to it, CLI env pointed at the symlink, openclaw.json absent, Gateway reporting real paths, command set. Asserts kind: "match".

Pre-fix (production file reverted to 633e62d816f, test kept):

 × state-dir-gateway-check > matches a missing config path through a symlinked state directory
 Tests  1 failed | 10 passed (11)

Post-fix:

 Test Files  1 passed (1)
      Tests  11 passed (11)

Production LOC. +18/-10 for this commit; the rename is mechanical, the added lines are the ancestor walk and its invariant comment.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 1, 2026
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts and removed scripts Repository scripts labels Sep 1, 2026
@obviyus
obviyus force-pushed the fix/state-dir-split-brain branch 2 times, most recently from b0d4f00 to 091a157 Compare September 1, 2026 13:19
@openclaw-barnacle openclaw-barnacle Bot removed docs Improvements or additions to documentation commands Command implementations labels Sep 1, 2026
@obviyus
obviyus force-pushed the fix/state-dir-split-brain branch from 091a157 to b0d4f00 Compare September 1, 2026 13:20
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations labels Sep 1, 2026
@obviyus
obviyus force-pushed the fix/state-dir-split-brain branch from b0d4f00 to 41d56a7 Compare September 1, 2026 13:31
@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. 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. labels Sep 1, 2026
@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Land-ready proof for 41d56a74efa55ad36634fa4f87ff7138db1ced09.

  • Root cause: guarded CLI commands resolved and wrote the caller's state/config tree without checking the tree used by the live or installed Gateway.
  • Owner: the CLI command catalog and global Commander pre-action now own one state-store guard.
  • Canonical fix: authenticated hello paths first, installed-service paths second, and a read-only protocol warning only when missing credentials prevent path evidence.
  • Removed paths: per-command guard plumbing, the permanent waiver flag, unauthenticated probe fallback outside the credential-only/no-service case, and the 476-line mock-shape suite.
  • ClawSweeper rank-up: the waiver decision is resolved by deleting the waiver; exact-head Autoreview is clean.
Proof Before After
Real channels add with separate CLI/Gateway state trees Command returned success and wrote the token; authenticated admin hello reported the other Gateway tree Command refused before persistence; no token was written; the same hello still reported the other tree

Commands:

node scripts/run-vitest.mjs src/cli/state-dir-gateway-check.process.test.ts
node scripts/run-vitest.mjs src/cli/state-dir-gateway-check.server.test.ts
node scripts/run-vitest.mjs src/cli/state-dir-gateway-check.test.ts src/cli/command-path-policy.test.ts src/cli/program/preaction-state-store.test.ts
node scripts/run-vitest.mjs src/commands/doctor-gateway-health.test.ts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json <changed TypeScript files>
node_modules/.bin/oxfmt --check <changed files>
git diff --check
OPENCLAW_TESTBOX=1 scripts/pr prepare-run 134403

Production +198/-2 | tests/test support +548/-8 | docs +6.

Known gap: local build and TypeScript checks were not run under the host safety rule. Exact-head CI/Testbox passed those gates.

@obviyus
obviyus merged commit ef44eab into main Sep 1, 2026
356 of 523 checks passed
@obviyus
obviyus deleted the fix/state-dir-split-brain branch September 1, 2026 14:55
@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merged via squash.

@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @obviyus!

Proof: A real channels add command and separate Gateway process reproduced the split on current main. The fixed head refused before persistence, while the same authenticated admin hello still reported the different Gateway tree.

  • Bug: CLI credential/config commands could report success after writing a state tree the Gateway did not read.
  • Fix: One catalog-owned pre-action compares authenticated Gateway paths or installed-service paths before guarded writes. Remote or unverifiable targets warn; proven mismatches refuse.
Before After
Command returned success, wrote the token, and the Gateway reported another state tree. Command failed before persistence, no token was written, and the Gateway still reported the other tree.

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

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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