Repository navigation
fix(auth): create a fresh install with canonical shared-auth ownership - #126783
Conversation
A brand-new install was born in the retired shape. `parseSharedAuthStoreOwnership(undefined)` returns
`legacy-main`, which is the correct compat answer for an existing install whose profiles really do
live in the main agent database -- but a new install has no ownership row and no legacy data either,
so onboarding wrote its first credential into `agents/main/agent/openclaw-agent.sqlite` and the
operator's very first `openclaw doctor` told them to run a migration for state OpenClaw had created
seconds earlier. The main agent also stayed undeletable until they did.
Record `auth.sharedStore = {"location":"state-db"}` when the shared store is first written and the
legacy source provably holds nothing: no `auth_profile_store` row, no `auth_profile_state` row, and
no unfinished cleanup ledger entry. Any legacy row, or any inspection error, leaves ownership alone
so doctor keeps owning the relocation. The check is memoized per ownership generation with a WeakSet
keyed on the process-stable ownership object, so a legacy root is inspected once per process and
doctor's committed flip naturally invalidates it.
The legacy row inspection moves out of `state-migrations.shared-auth-store.ts` into the auth-profiles
owner so doctor and runtime share one contract instead of runtime importing migration code. Explicit
main-agent credential writes now follow the shared target, which is a no-op on legacy roots where
both routes already resolve to the same file.
No SQLite schema change; the ownership row is data. Existing installs take exactly the path they take
today.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Draft again — hosted CI found a real defect that my local proof missed, and it is the exact failure mode this PR is supposed to prevent.
Root cause: On an install upgrading from the JSON era, credentials sit in Fixing the freshness check to consult the existing legacy-source predicate rather than re-deriving it, keeping it fail-closed on any probe error, and adding a regression test for the JSON-era case specifically. Also auditing the rest of the diff for the same "no SQLite rows means nothing to preserve" assumption. Worth noting why it slipped: |
|
Codex review: needs maintainer review before merge. Reviewed August 20, 2026, 5:10 PM ET / 21:10 UTC. ClawSweeper reviewWhat this changesThis PR writes first-run shared credentials to the shared state database only when no legacy SQLite, JSON, or unfinished migration source exists, while preserving Doctor migration for legacy installs. Regression provenancePossible regression — probable (reviewed change; reproduction). No predecessor PR is attributed. Merge readinessKeep open for maintainer review: the prior explicit-main write concern is now covered by effective runtime reads and sibling-isolation assertions, and no new blocking correctness defect was found. The remaining decision is whether fresh installs should canonically store credentials for the configured shared main agent in shared state. Priority: P1 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
How this fits togetherAuth-profile persistence stores provider credentials for agents and shared runtime use. Onboarding and provider setup write credentials, runtime reads resolve effective shared credentials, and Doctor relocates only legacy state. flowchart LR
A[Provider setup or onboarding] --> B[Shared ownership check]
B --> C{Legacy source exists?}
C -->|Yes| D[Main agent database]
C -->|No| E[Shared state database]
D --> F[Doctor relocation]
E --> G[Runtime credential resolution]
F --> G
Decision needed
Why: The PR preserves effective credential resolution but deliberately changes the durable location for this supported relocation path; source evidence cannot choose the intended persistence contract. Before merge
Agent review detailsSecurityNone. PR surfaceSource +141, Tests +321, Other 0. Total +462 across 15 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Adopt one explicit contract: fresh shared credentials belong only in shared state, while every detectable legacy source remains legacy until Doctor completes its verified relocation. Do we have a high-confidence way to reproduce the issue? Yes, from source: current main treats an absent ownership record as legacy-main and selects the main-agent database; the PR’s built-CLI transcript also records the resulting first-Doctor migration prompt. Is this the best way to solve the issue? Unclear pending the persistence-contract decision: producer-side initialization is the right layer, but maintainers must confirm that configured-main explicit writes are semantically shared credentials. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 4c52d3fe9df3. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
|
Draft again. The re-fired CI run surfaced a second cross-lane failure, and this one is a design question rather than a bug I can quietly patch.
Cause: I ran the decisive experiment before concluding anything. With
So the redirect is load-bearing for three of this PR's own fresh-install and memo tests, and is simultaneously what breaks the four The question being settled next, with evidence rather than by editing assertions: after an explicit Worth flagging either way: |
A fresh root records state-db shared ownership, so the model-catalog credential migration persists into the shared store rather than the agent file. The assertion read the agent file directly and saw an empty store while all three credentials were present and correct in state/openclaw.sqlite. Read through the owner for that state root instead of pinning storage layout; the credential contents are still asserted exactly.
|
Merged via squash.
|
openclaw#126783) * fix(auth): create a fresh install with canonical shared-auth ownership A brand-new install was born in the retired shape. `parseSharedAuthStoreOwnership(undefined)` returns `legacy-main`, which is the correct compat answer for an existing install whose profiles really do live in the main agent database -- but a new install has no ownership row and no legacy data either, so onboarding wrote its first credential into `agents/main/agent/openclaw-agent.sqlite` and the operator's very first `openclaw doctor` told them to run a migration for state OpenClaw had created seconds earlier. The main agent also stayed undeletable until they did. Record `auth.sharedStore = {"location":"state-db"}` when the shared store is first written and the legacy source provably holds nothing: no `auth_profile_store` row, no `auth_profile_state` row, and no unfinished cleanup ledger entry. Any legacy row, or any inspection error, leaves ownership alone so doctor keeps owning the relocation. The check is memoized per ownership generation with a WeakSet keyed on the process-stable ownership object, so a legacy root is inspected once per process and doctor's committed flip naturally invalidates it. The legacy row inspection moves out of `state-migrations.shared-auth-store.ts` into the auth-profiles owner so doctor and runtime share one contract instead of runtime importing migration code. Explicit main-agent credential writes now follow the shared target, which is a no-op on legacy roots where both routes already resolve to the same file. No SQLite schema change; the ownership row is data. Existing installs take exactly the path they take today. * fix(auth): preserve JSON-era shared credentials * docs(auth): explain why doctor names the main agent dir during a shared JSON import * test(auth): assert shared-owner runtime reads * test(doctor): read migrated catalog credentials through the shared owner A fresh root records state-db shared ownership, so the model-catalog credential migration persists into the shared store rather than the agent file. The assertion read the agent file directly and saw an empty store while all three credentials were present and correct in state/openclaw.sqlite. Read through the owner for that state root instead of pinning storage layout; the credential contents are still asserted exactly.
What Problem This Solves
A brand-new OpenClaw install is created in the retired shared-auth-store shape, so the operator's very
first
openclaw doctorasks them to migrate state that OpenClaw itself created seconds earlier.Onboard a fresh isolated state dir with the documented non-interactive flow, then run doctor:
Nothing is legacy about this install. Verified on that same state dir:
agents/main/agent/openclaw-agent.sqlite->auth_profile_storeholds theprimaryrow;state/openclaw.sqlite->auth_profile_storeshas 0 rows;config_machine_statehas noauth.sharedStorerow.doctor --fixthen relocates cleanly and prints "The main agent no longer owns shared credentials andcan now be deleted." — a migration with nothing to preserve, on an install minutes old. Until the
operator runs it, the main agent is also not deletable.
Why This Change Was Made
parseSharedAuthStoreOwnership(undefined)insrc/agents/auth-profiles/path-resolve.tsreturns{ location: "legacy-main" }. That is the correct compat answer for an existing install: noownership row means the profiles really do live in the main agent database, and reading them from
anywhere else would lose them. But a new install also has no row, and no legacy data either, so it is
classified legacy and writes its first credential into the retired location.
6405a59c45aalready silenced the empty case innoteSharedAuthStoreStatus. It did not stop newinstalls from being created in the legacy shape, so as soon as a real credential exists the nag is
truthful again. This is a producer defect: state is created in the retired shape and repaired
downstream, which Repair Doctrine says to fix at the lifecycle owner.
The fix records
auth.sharedStore = {"location":"state-db"}when the shared store is first writtenand the legacy source provably holds nothing: no
auth_profile_storerow, noauth_profile_staterow, and no unfinished cleanup ledger entry. Any legacy row present, or any inspection error, leaves
ownership untouched so doctor keeps owning the relocation. Nothing infers past unreadable or partially
migrated state.
Three deliberate design points:
The check is memoized, not repeated. A naive version re-opens the legacy SQLite on every credential
write for any install that stays legacy — repeated request-time discovery that the root
AGENTS.mdforbids on runtime paths. A
WeakSetkeyed on the process-stable ownership object inspects a legacyroot once per process, and doctor's
noteCommittedSharedAuthStoreOwnershipreplaces that object, sothe flip invalidates the memo without any manual bookkeeping.
Legacy inspection moved to the auth-profiles owner. The bootstrap needs the same row and cleanup
checks the doctor migration uses. Importing them from
state-migrations.shared-auth-store.tswouldmake runtime depend on migration code, which the architecture rules prohibit, and duplicating them
would create two definitions of "is there anything legacy here". They now live in
shared-store-bootstrap.tsand both consumers share one contract.Explicit main-agent writes follow the shared target. A main-agent credential is a shared
credential. On legacy roots this is a no-op because both routes already resolve to the same file; on a
fresh root it is what makes the ownership record meaningful.
saveAuthProfileStoreInTransactiondropsthe agent scope for shared-state rows so shared credentials are never published or cached as
agent-local state. Both invariants are commented at their call sites.
No SQLite schema change — the ownership row is data in an existing table.
User Impact
A new operator's first
openclaw doctorno longer opens with a migration request for state that wasjust created, and the main agent is deletable from the start. Existing installs are untouched: they
still resolve
legacy-main, still see the nag, anddoctor --fixstill relocates them exactly asbefore.
Evidence
Three scenarios, live on a built CLI, verified independently of the change author and re-verified
after the rebase.
Fresh install:
An install created by a pre-fix binary, then read by this build — untouched:
doctor --fixon that legacy install still relocates, and the credential survives:Tests.
src/agents/auth-profiles— 28 files, 399 tests, passing. Shared-auth migration — 9 tests,passing.
auth-profiles.sqlite-store— 22 tests, passing. The new memo regression spies onfs.lstatSync, proves two consecutive credential writes cause exactly one legacy inspection, thenruns doctor's migration and proves the ownership flip is observed afterwards. Unreadable and
partially-migrated legacy sources are covered and must not flip.
node scripts/check-changed.mjsclean, including the schema-version and database-first guards.pnpm buildpasses. Autoreview clean. Theconfig/assertion-safety-baseline.txtedit is shrink-only(2 -> 1) because an assertion moved out of that file; no baseline is grown.
Production
+267/-153(net +114), tests+217/-18. The production growth buys a fail-closedinitialization owner, one shared legacy-inspection contract replacing a duplicated one, the memo, and
the write-routing hook; the relocation itself is roughly a wash (
+185in the new module against-104removed from the migration module).Two defects hosted CI caught after the first draft
Both were real, both were fixed here, and both are worth reading before reviewing the diff — they say
where this change's risk actually lives.
1. JSON-era credentials were stranded. The first draft decided a root was "fresh" from the legacy
SQLite rows and the cleanup ledger alone. It ignored the retired file sources that predate the
SQLite store —
auth-profiles.json,auth-state.json,auth.json,oauth.json— whichlistLegacyAuthProfileSourcesalready enumerates. On an install upgrading from the JSON era thebootstrap saw no rows, declared the root fresh, recorded
state-db, and doctor's later JSON importfailed with
unable to open database file/auth profile migration target verification failed.That is the exact outcome this change exists to prevent. Fixed by consulting the canonical
legacy-source enumeration, memoized like the SQLite probe, fail-closed on any probe error. Verified on
a hand-built JSON-era fixture: read-only doctor leaves ownership absent and the JSON in place, and
doctor --fiximports the credential into the shared store intact. A regression test locks it down byperforming two shared writes on a JSON-era root, asserting the JSON file is probed exactly once, then
proving both the JSON-era credential and the ones written in between survive the import.
2. The explicit-main redirect changed where a relocated agent's credentials persist. Four
onboard-authtests failed withExpected SQLite auth profile store for <state>/agents/kid/agent.resolveSharedMainAuthAgentDirhonorsOPENCLAW_AGENT_DIR, so a process pointed at an agent makesthat agent the shared main dir, and its explicit credential writes route to the shared store.
That one was resolved by evidence rather than by adjusting assertions. Setting
allowExplicitMain: falsemakesonboard-authpass 13/13 but breaks three of this PR's ownfresh-install and memo tests, so the requirements genuinely conflict and the contract had to be
decided rather than patched. A probe answered it: after an explicit write, the credential resolves
normally for that agent through
ensureAuthProfileStore/resolveApiKeyForProvider(
source: "profile:openai:default"), a sibling agent inherits it through the main store as it alwayshas, and the sibling's own persisted map stays
{}. Only the persistence location moved. The fourtests were coupled to storage layout, so they now read through the ownership-aware path — and the
direct-persistence assertion proving sibling isolation is kept verbatim, plus a new explicit assertion
that the sibling really does resolve the inherited credential. Production delta for that round was
+0/-0.Updated accounting
Production
+371/-230(net +141), tests+355/-34, baseline+1/-1shrink-only.The relocation is the large part and deserves the reviewer's attention:
+185forshared-store-bootstrap.tsand+80forlegacy-source-files.tsagainst-104removed fromstate-migrations.shared-auth-store.tsand-87fromlegacy-source-diagnostic.ts. Both moves areforced rather than cosmetic — runtime must not import migration code, and the filename enumeration had
to become dependency-free to break an import cycle — but roughly 70 lines of that is expansion beyond
what was removed, and it is fair to push back on it.
Validation after both fixes
onboard-auth13/13,auth-profiles.sqlite-store23/23,doctor-auth-flat-profiles53/53,src/agents/auth-profiles399/399, eightdoctor-auth*suites 115/115. Suites were selected by symbolsearch rather than by change-based lane selection, which is what missed both of these: 20 related
suites, 991 tests, all passing. All four live scenarios re-verified against a rebuilt
dist— freshinstall, legacy SQLite before and after doctor, and the JSON-era path.
check-changedclean,pnpm buildpassing, autoreview clean.