Skip to content

fix(models): clear stale auth cooldowns after early limit resets - #107671

Closed
Glucksberg wants to merge 6 commits into
openclaw:mainfrom
Glucksberg:fix/auth-clear-cooldown-command
Closed

Glucksberg wants to merge 6 commits into
openclaw:mainfrom
Glucksberg:fix/auth-clear-cooldown-command

Conversation

@Glucksberg

@Glucksberg Glucksberg commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Related: #70903

What Problem This Solves

Operators who resolve a provider billing or usage condition before its recorded reset time stay locked out of the saved auth profile until the stored window expires. There is no supported way to clear it, and the models auth list / doctor billing hint is a dead end.

Why This Change Was Made

  • New openclaw models auth clear-cooldown <profileId>: one owner-routed, locked write that resets the persisted cooldown, block, disable, and failure counters. It does not touch credentials or auth order. After the write it runs the same shared Gateway auth refresh (models.authRefresh) as the sibling models auth write commands, so no manual Gateway restart is needed.
  • The models auth list / models status / doctor billing hint now names this command, including --agent <id> for the store it came from, because the mutation path rejects an ambiguous agent roster.
  • Inline models.providers.<id>.apiKey failures have a health record (inline-api-key:<provider>) but no profile row. The command accepts that id when the record exists, so the hint shown for inline keys also works.
  • The reset follows the health row that was displayed, not only the credential owner. A row in the agent's own database (a child's local override of an inherited credential, or an inline-key failure) wins over the owner's row after reload, so it is reset too; an agent without such a row gets no database created.
  • usage.ts is a grandfathered oversized file, so the line-cap ratchet rejects any growth there. updateOwnedAuthProfileUsage moved unchanged into usage-owner-write.ts, next to the new reset. The dropped-bookkeeping log comes from main's state-observation.ts. usage.ts shrinks by 29 lines (751 → 722). The move adds no test seam: the dropped-write test mocks the store-runtime.js module boundary, as main does since refactor(testing): deslop test-only production seams #164320.

It does not add polling, shorten provider backoffs, change fallback policy, or remove credentials.

User Impact

Operators can re-evaluate a recovered provider with one command, without editing SQLite or repeating OAuth. If the failure still applies, the next request restores the cooldown normally.

Evidence

Head 509ead90b58, rebased onto main at 2f620b970a0. The last commit addresses the two open P2 findings on ba7b9103fb4:

  • Local health row (P2): the reset wrote only the credential owner's store, so a child's own usage row for an inherited credential stayed, won again after reload, and the command still reported success. It now also resets the agent's own row when one exists. A real-store test seeds that row, clears it, and rereads through a fresh runtime; it fails on the previous implementation. A second test shows an agent with no row keeps no database (it fails if the second write is not gated).
  • Shared state-db hint (P2): with a roster such as coder/reviewer no agent owns the shared store, so doctor printed the command without --agent. The Shared target now falls back to a configured agent; owner routing reaches the shared profile from any of them. A doctor test covers it and fails without the fallback.

Results on this head:

  • node scripts/run-vitest.mjs passed on usage-owner-write, usage.inherited-owner, auth-profiles.markauthprofilefailure, usage, auth-clear-cooldown, auth-unavailability, doctor-auth.profile-health, doctor-auth.shared-health, models-cli, and root-command-descriptions.
  • pnpm tsgo:core and the tsgo test configs core.test.agents-root, agents-other, agents-tools, commands, and commands-doctor passed.
  • check:line-cap-ratchet --base upstream/main and check:test-mock-exports --base upstream/main reported OK; oxlint, oxfmt --check, and git diff --check were clean.
  • check:max-lines-ratchet currently fails on main itself (ui/src/pages/agents/agents-page-state.ts is listed as stale); this PR does not touch it.

Remaining merge evidence

  • No inspectable real-flow proof yet. A shipped-CLI run against an isolated state directory is refused by the CLI's state-store guard while an installed Gateway service uses another state directory, and the command would refresh that Gateway. Needs an environment without that service for: blocked profile -> models auth clear-cooldown <profileId> -> Gateway auth refresh -> recovered provider request.
  • Maintainer approval of the user-facing CLI contract is still required before merge.

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes commands Command implementations size: M labels Jul 14, 2026
@Glucksberg
Glucksberg marked this pull request as ready for review July 14, 2026 17:59
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jul 15, 2026
@clawsweeper

clawsweeper Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Adds an agent-scoped command to clear saved authentication failure windows and advertises it in model and Doctor diagnostics.

Example: An operator restores Anthropic credit while anthropic:work remains billing-disabled.

  • Before: Requests continue skipping the profile until its stored deadline expires.
  • After: The proposed clear-cooldown command clears its health state and requests a Gateway auth refresh.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful recovery proposal, but unresolved ownership defects, missing real-flow evidence, and unproven existing-state compatibility prevent merge readiness.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Operators who restore provider credit or capacity can remain blocked by saved authentication health state.
Reason: Manual recovery has concrete value, but it supplies only part of the linked recovery request and introduces a CLI contract without recorded owner approval.

Merge readiness

⛔ Blocked before merge - 8 items remain

Keep this PR open: manual recovery still has value, but the three previously reported implementation findings remain unresolved.

Priority: P2
Reviewed head: 764d9885c45ec87a7b508bb202e97d559431d85a
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should OpenClaw expose clear-cooldown as a supported operator command for manually resetting authentication health?
  • Recommendation: Approve the focused recovery command: Accept explicit manual recovery while retaining provider backoff and fallback policy.
  • Why: The recovery problem is established, but no inspected maintainer discussion approves this new CLI contract.

Before merge

  • Add real behavior proof - The supplied evidence exercises SQLite reset helpers and mocked command dispatch, while the PR explicitly supplies no shipped-CLI reset, Gateway acknowledgment, and recovered provider request; provide terminal screenshots, redacted logs, or a recording with credentials, IPs, phone numbers, and private endpoints removed. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Select the state owner before loading the cooldown mutation (P1) - With a live Gateway using the same state directory, this registration loads and runs the local SQLite mutation directly, bypassing runAuthModelCommand and runWithLocalStateOwner. The state-directory guard only checks that paths agree; it does not acquire exclusive ownership or dispatch the mutation to the Gateway. Calling models.authRefresh after the write cannot supply the missing custody or publication boundary. Route the command through the existing auth owner wrapper, or implement the reset in the Gateway owner.
  • Preserve the shared health-row owner in recovery hints (P2) - Under state-db shared ownership, Doctor can print a shared billing reset with --agent coder while coder has a distinct local credential using the same profile ID. The persisted-owner resolver then selects coder's local store, and the second reset inspects only that same local database. Both operations can succeed while the shared billing row Doctor displayed remains disabled, potentially clearing unrelated local health instead. Carry the displayed store identity into recovery, or omit a command that cannot reach it.
  • Replace the broad auth-runtime partial mocks (P2) - This focused command test calls importOriginal on the auth-profiles barrel, evaluating store-runtime and its native plugin-loader graph even though both consumed operations are replaced. The added partial mock in models-cli.test.ts likewise imports the real mutation handler before replacing it. These introduced imports violate the applicable requirement to keep focused tests off broad runtime barrels. Use explicit factories containing only the bindings each test consumes.
  • Await maintainer action - A maintainer must approve the current security-sensitive revision before merging.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Auth command state ownership - 510255d: Protect provider credentials from concurrent CLI writes by selecting the state owner before loading mutation-capable handlers.

Findings

  • [P1] Select the state owner before loading the cooldown mutation — src/cli/models-cli.ts:477-482
  • [P2] Preserve the shared health-row owner in recovery hints — src/agents/auth-profiles/usage-owner-write.ts:66-69
  • [P2] Replace the broad auth-runtime partial mocks — src/commands/models/auth-clear-cooldown.test.ts:18-21

Provenance

  • Auth command state ownership changes intended behavior without addressing why it exists (510255d: Protect provider credentials from concurrent CLI writes by selecting the state owner before loading mutation-capable handlers.)

Tests

  • Low-value test src/commands/models/auth-clear-cooldown.test.ts: Remove or replace the happy-path test that mocks target resolution, persistence, and refresh and primarily asserts calls; it misses both unresolved ownership defects.
  • Missing end-to-end proof: Missing shipped-CLI reset followed by Gateway acknowledgment and a recovered provider request; baseline-failing execution of the remaining ownership regressions is also unshown.
Agent review details

How this fits together

Model authentication stores credentials and usage health in shared or agent-local SQLite stores; CLI diagnostics read those records, while credential selection uses them to admit requests or choose fallbacks.

flowchart TD
  A[Model and Doctor diagnostics] --> B[Operator recovery command]
  B --> C[State ownership selection]
  C --> D[Auth health store]
  D --> E[Gateway auth refresh]
  E --> F[Provider request]
Loading

Technical review

Best possible solution:

Provide one state-owner-routed reset that targets the displayed health record and preserves credentials, selection settings, and unrelated usage.

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

Current source preserves active billing disables after external recovery, and supported shared/local credential ownership demonstrates the wrong-store reset path; no target code was executed.

Is this the best way to solve the issue?

Explicit recovery complements existing automatic subscription recovery, but it must use the existing state owner and address health-record ownership rather than infer it solely from credential ownership.

Full review comments:

  • [P1] Select the state owner before loading the cooldown mutation — src/cli/models-cli.ts:477-482
    With a live Gateway using the same state directory, this registration loads and runs the local SQLite mutation directly, bypassing runAuthModelCommand and runWithLocalStateOwner. The state-directory guard only checks that paths agree; it does not acquire exclusive ownership or dispatch the mutation to the Gateway. Calling models.authRefresh after the write cannot supply the missing custody or publication boundary. Route the command through the existing auth owner wrapper, or implement the reset in the Gateway owner.
    Confidence: 0.98
  • [P2] Preserve the shared health-row owner in recovery hints — src/agents/auth-profiles/usage-owner-write.ts:66-69
    Under state-db shared ownership, Doctor can print a shared billing reset with --agent coder while coder has a distinct local credential using the same profile ID. The persisted-owner resolver then selects coder's local store, and the second reset inspects only that same local database. Both operations can succeed while the shared billing row Doctor displayed remains disabled, potentially clearing unrelated local health instead. Carry the displayed store identity into recovery, or omit a command that cannot reach it.
    Confidence: 0.99
  • [P2] Replace the broad auth-runtime partial mocks — src/commands/models/auth-clear-cooldown.test.ts:18-21
    This focused command test calls importOriginal on the auth-profiles barrel, evaluating store-runtime and its native plugin-loader graph even though both consumed operations are replaced. The added partial mock in models-cli.test.ts likewise imports the real mutation handler before replacing it. These introduced imports violate the applicable requirement to keep focused tests off broad runtime barrels. Use explicit factories containing only the bindings each test consumes.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Inherited usage mutation owner keeps the original intent (1e7b255: Persist inherited health in the credential owner's store while preserving child-local state; subsequent worker and async-preparation changes retain that boundary.)
  • Doctor shared and local health targets keeps the original intent (177eabf: Inspect shared authentication independently from configured agents and preserve local cooldown ownership in diagnostics.)
  • Unavailable-profile diagnostics keeps the original intent (6725e57: Share unavailable-profile facts while retaining command-specific projections and existing recovery behavior.)
  • Billing recovery hint changes intended behavior with a stated reason (f461701: Expose recorded authentication failures and concrete recovery guidance; this proposal explains adding early billing recovery.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +185, Tests +392, Docs +3. Total +580 across 19 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 10 243 58 +185
Tests 8 394 2 +392
Docs 1 4 1 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 641 61 +580

Root-cause cluster

Relationship: partial_overlap
Canonical: #70903
Summary: The canonical issue owns stale billing recovery; this PR proposes explicit clearing, while existing subscription recovery covers a narrower automatic path.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a useful operator recovery improvement with limited scope and unresolved implementation defects.
  • merge-risk: 🚨 auth-provider: The reset can clear a different credential's health while leaving the reported shared billing disable active.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (67 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-27T01:13:22.737Z sha 00e49bc7711afd554309b40de1c4edb45e555876 :: needs real behavior proof before merge. :: [P2] Carry the selected agent into cooldown guidance | [P2] Suppress saved-profile reset guidance for inline API keys
  • reviewed 2026-09-27T01:55:08.561Z sha f09dd2a :: needs real behavior proof before merge. :: [P2] Carry the selected agent into the recovery command | [P2] Avoid recommending saved-profile reset for inline API keys
  • reviewed 2026-10-05T12:49:10.101Z sha 9fe388225e27cd5198cc3643b63b489eb4f052ae :: needs real behavior proof before merge. :: [P2] Carry the selected agent into the recovery command | [P2] Suppress saved-profile reset guidance for inline API keys
  • reviewed 2026-10-09T14:30:52.340Z sha 804b5aa5bf7eecdafd10fe05761ecc7de3949950 :: needs real behavior proof before merge. :: [P2] Carry the selected agent into the recovery hint | [P2] Suppress saved-profile reset guidance for inline API keys
  • reviewed 2026-10-09T15:49:52.071Z sha 0f6409cb35ad2e1b19e57b5a90aa901a578ac0b5 :: needs real behavior proof before merge. :: [P2] Bind override-store recovery hints to the inspected store | [P2] Give shared state-database recovery hints a valid agent
  • reviewed 2026-10-10T23:38:05.167Z sha ba7b9103fb49dc5a835aa92300656fc82f5bc1a4 :: needs real behavior proof before merge. :: [P2] Clear the health record that supplied the displayed cooldown | [P2] Avoid reset hints without a reachable agent target
  • reviewed 2026-10-12T14:07:29.648Z sha 509ead90b58c937ce5172d9896fffb1d62b84d08 :: needs real behavior proof before merge. :: [P1] Select the state owner before loading the cooldown mutation | [P2] Preserve the shared health-row owner in recovery hints
  • reviewed 2026-10-12T20:25:11.734Z sha 764d988 :: needs real behavior proof before merge. :: [P1] Select the state owner before loading the cooldown mutation | [P2] Preserve the shared health-row owner in recovery hints | [P2] Replace the broad auth-runtime partial mocks

Reviewed October 27, 2026, 9:13 PM ET / October 28, 2026, 01:13 UTC (Revision 68).

@Glucksberg
Glucksberg force-pushed the fix/auth-clear-cooldown-command branch 2 times, most recently from 822cbf3 to 5b6430f Compare July 15, 2026 06:57
@Glucksberg
Glucksberg force-pushed the fix/auth-clear-cooldown-command branch from 5b6430f to 1f4f070 Compare July 16, 2026 06:32
@Glucksberg
Glucksberg force-pushed the fix/auth-clear-cooldown-command branch from 1f4f070 to 7b9bb6a Compare July 16, 2026 08:49
@Glucksberg
Glucksberg requested a review from a team as a code owner July 16, 2026 08:49
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Jul 16, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. label Jul 16, 2026
@Glucksberg
Glucksberg force-pushed the fix/auth-clear-cooldown-command branch from 7b9bb6a to 3ec6ff8 Compare July 17, 2026 06:54
@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. and removed P2 Normal backlog priority with limited blast radius. labels Jul 17, 2026
@Glucksberg
Glucksberg force-pushed the fix/auth-clear-cooldown-command branch 2 times, most recently from 224f128 to 1039d9c Compare July 17, 2026 07:07
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 17, 2026
@Glucksberg
Glucksberg force-pushed the fix/auth-clear-cooldown-command branch from 1039d9c to 27dd961 Compare July 18, 2026 06:35
@clawsweeper clawsweeper Bot removed the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label Jul 18, 2026
@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Maintainer security review required

This external contributor PR changes sensitive security components. A maintainer must review these changes before merging.

Current SHA: 764d9885c45ec87a7b508bb202e97d559431d85a

These sensitive security changes were made:

  • src/agents/auth-profiles.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-refresh-failure.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/usage-owner-write.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/usage.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

After reviewing the changes, post a new PR comment containing only approval commands, each on its own line:

/allow-security-sensitive-change

A later push requires a fresh approval comment.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T19:43:45.155054Z 764d988 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 804b5aa5bf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const cfg = await loadModelsConfig({ commandName: "models auth clear-cooldown", runtime });
const { agentId, agentDir } = resolveModelsTargetAgent(cfg, opts.agent, { kind: "mutation" });
const store = ensureAuthProfileStore(agentDir);
if (!Object.hasOwn(store.profiles, profileId)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Accept cooldown records for inline API keys

When a literal or secret-backed models.providers.<id>.apiKey receives a billing failure, markInlineProviderApiKeyFailure persists it only as usageStats["inline-api-key:<provider>"]; listUnavailableAuthProfiles enumerates that key and the new billing hint instructs the operator to pass it to this command. There is intentionally no matching store.profiles row, so this check always throws not found and the advertised early-recovery path cannot work for configured inline keys. Either reset these usage-only records here or avoid emitting this command for them.

AGENTS.md reference: AGENTS.md:L69-L69

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a5c7d4e3ffa. clear-cooldown now accepts an inline-api-key:<provider> id when the store has a health record for it, and the owner-routed reset persists it. A real-store test in auth-profiles.markauthprofilefailure.test.ts records an inline billing failure, clears it, and rereads the persisted store.

return "Top up credits (provider billing) or switch provider.";
}
const command = formatCliCommand(
`openclaw models auth clear-cooldown ${quoteShellArg(profileId)}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the selected agent in cooldown recovery commands

When more than one agent is configured, a billing hint produced by models auth list --agent child (or scoped status/Doctor output) omits the target agent. Running the printed command enters the mutation branch of resolveModelsTargetAgent, which calls resolveSoleAgentId and rejects the ambiguous roster, so the recovery action fails before clearing anything. Pass the target agent into the hint and append a quoted --agent option.

AGENTS.md reference: AGENTS.md:L69-L69

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a5c7d4e3ffa. buildAuthProfileUnusableHint takes the store's agentId and appends a quoted --agent option to the billing command. models auth list, models status (through auth-unavailability.ts), and doctor pass it. Covered in doctor-auth.profile-health.test.ts and auth-unavailability.test.ts.

Comment on lines +5 to +6
vi.mock("./store-runtime.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./store-runtime.js")>()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Replace the broad store-runtime partial mock

This focused test only needs updateAuthProfileStoreWithLock, but importOriginal() executes the entire store-runtime.js graph first, including the native plugin-loader composition, which adds unrelated initialization cost and coupling to a one-function unit test. Replace it with an explicit mock factory that exposes only the binding under test, as required for import-bound agent tests.

AGENTS.md reference: src/agents/AGENTS.md:L33-L35

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a5c7d4e3ffa. The test now uses an explicit factory that exposes only updateAuthProfileStoreWithLock, with a mock-isolation reason, instead of an importOriginal partial mock of store-runtime.js.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0f6409cb35

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

),
)
.toSorted((a, b) => a.remainingMs - b.remainingMs);
const unusableProfiles = listUnusableAuthProfilesWithHints(store, workspaceAgentId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep override-store recovery on the inspected store

When models status runs without --agent under OPENCLAW_AGENT_DIR or PI_CODING_AGENT_DIR and the override has a local billing cooldown, status reads auth state from agentDirOverride (list.status-command.ts:253-255) but this call embeds workspaceAgentId in the recovery command. Running that command enters mutation mode, which maps the ID back to its configured directory (shared.ts:252-254), so it does not clear the inspected store; if the same profile ID exists there, it can instead clear unrelated state and report success. Keep the recovery target bound to the inspected directory, or do not emit an executable command for override-only stores.

AGENTS.md reference: AGENTS.md:L44-L44

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba7b9103fb4. Mutation target resolution ignores the env dir override (resolveEffectiveAgentDir reads only config), so no --agent value reaches an override store. When models status reads the store from OPENCLAW_AGENT_DIR / PI_CODING_AGENT_DIR, it now passes agentId: null and the billing hint omits the command: "Top up credits (provider billing) or switch provider." Covered in auth-unavailability.test.ts.

Comment thread src/commands/doctor-auth.ts Outdated
Comment on lines +215 to +218
const existing = targets.get(databasePath);
if (existing) {
// The agent that owns the shared store addresses it in recovery commands.
existing.agentId ??= agentId;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Assign an agent to shared state-db recovery hints

When shared auth ownership is state-db and multiple agents are configured, resolveSharedAuthStorePath() is the state database while every path computed here is <agentDir>/openclaw-agent.sqlite, so existing is never found and the Shared target keeps agentId undefined. Doctor then prints a billing clear-cooldown command without --agent, and mutation target resolution rejects the ambiguous roster before clearing anything. Fresh evidence beyond the earlier review comment is the state-db path split in path-resolve.ts:157-161 versus sqlite.ts:122-125; assign a valid configured agent to the Shared target even when no database path matches.

AGENTS.md reference: AGENTS.md:L69-L69

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba7b9103fb4. In the state-db layout no agent database is the shared store, so the Shared target now also takes the agent whose dir is resolveSharedMainAuthAgentDir(). Owner routing sends that agent's write for a shared profile to the shared store. A new doctor test mocks a state-db shared path with two agents and expects --agent 'main'; it fails without the fix.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ba7b9103fb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

agentDir?: string;
}): Promise<boolean> {
const { store, profileId, agentDir } = params;
const updated = await updateOwnedAuthProfileUsage(store, profileId, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the store that supplied the cooldown

When an agent has an agent-local billing usage row for an inherited shared credential, the effective store reports that local disable, but this call routes by credential ownership and writes the shared store because the credential itself is inherited. The local row still wins after reload, so models auth clear-cooldown ... --agent <child> reports success while the profile remains disabled and may reset a different shared row. Unlike the earlier override-directory case, fresh evidence here is the supported local-row shape exercised in src/commands/doctor-auth.shared-health.test.ts:63-87; recovery needs the owner of the displayed usage row rather than the credential owner.

AGENTS.md reference: AGENTS.md:L44-L44

Useful? React with 👍 / 👎.

for (const agentId of listAgentIds(cfg)) {
const agentDir = resolveAgentDir(cfg, agentId);
const databasePath = resolveAuthProfileDatabasePath(agentDir);
// The agent that owns the shared store addresses it in recovery commands. In the
// state-db layout no agent database is the shared store, so match the shared-main dir.
const ownsShared = targets.get(databasePath) === shared || agentDir === sharedMainAgentDir;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Select a reachable agent when no shared-main owner exists

Under state-db ownership with an explicit multi-agent roster whose IDs do not resolve to the legacy shared-main directory (for example {coder, reviewer} or main with a custom agentDir), both checks here are false and shared.agentId remains undefined. Doctor consequently prints clear-cooldown without --agent, and the mutation branch of resolveModelsTargetAgent rejects the ambiguous roster before writing. Fresh evidence beyond the earlier review comment is that explicit rosters need not contain any agent mapped to .../agents/main/agent; provide a reachable target for this shared store or omit the executable command.

AGENTS.md reference: AGENTS.md:L69-L69

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 509ead90b5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/cli/models-cli.ts
.argument("<profileId>", "Auth profile id from models auth list")
.option("--agent <id>", "Agent id (default: configured default agent)")
.action(async (profileId: string, _opts, command) => {
await withModelsRuntime(async ({ defaultRuntime, resolveModelAgentOption }) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Route cooldown clears through the state owner

When a Gateway or another OpenClaw process owns the state database, registering this mutation with withModelsRuntime bypasses the runAuthModelCommand/runWithLocalStateOwner path used by the neighboring models auth commands. The handler then writes the auth SQLite store directly before calling models.authRefresh; that refresh cannot retroactively provide exclusive custody, so the write races the live owner and bypasses its cache/publication contract. Route this action through the auth mutation owner wrapper or a Gateway-owned RPC before loading the handler.

AGENTS.md reference: AGENTS.md:L68-L68

Useful? React with 👍 / 👎.

Comment on lines +66 to +69
const ownerWrite = await updateOwnedAuthProfileUsage(store, profileId, {
agentDir,
updater: reset,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset the store that supplied the shared cooldown

When Doctor reports a shared-store billing row under state-db, its recovery target can be an agent with a distinct same-ID local credential; in that supported shape updateOwnedAuthProfileUsage resolves the local credential owner here, and the later hasLocalRow check also inspects only that agent database. The shared row Doctor displayed is therefore untouched, but both writes are non-null and clear-cooldown reports success. Fresh evidence beyond the earlier health-row comment is that the final dual-reset implementation still never addresses the shared source in this local-override case (the ownership split is exercised by doctor-auth.shared-health.test.ts:140,163-168); carry the displayed usage-row owner into the reset.

AGENTS.md reference: AGENTS.md:L51-L51

Useful? React with 👍 / 👎.

Glucksberg and others added 6 commits October 12, 2026 18:10
Operators who resolve a provider billing or usage condition before its
recorded reset time stay locked out of the saved profile until the stored
window expires, with no supported way to clear it.

Add `openclaw models auth clear-cooldown <profileId>`: one owner-routed
locked write that resets the persisted cooldown, block, disable, and failure
counters without touching credentials or auth order, then reuses the shared
gateway auth refresh like the sibling `models auth` write commands. The
`models auth list` / doctor billing hint now names that command, so the
recovery path is discoverable where the dead end is reported.

Move the owner-routed usage write (updateOwnedAuthProfileUsage) from the
grandfathered oversized usage.ts into usage-owner-write.ts unchanged and put
the reset there; usage.ts shrinks by 29 lines instead of growing past its
line-cap ratchet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The root command JSON-output audit requires every built-in command to
either support --json or be listed with a reason. clear-cooldown is a
pure side-effect write like its models auth activate/logout siblings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…agent hints

Billing hints name `models auth clear-cooldown`, but two cases could not
run the printed command:

- Inline `models.providers.<id>.apiKey` failures persist only as
  `usageStats["inline-api-key:<provider>"]` with no profile row, so the
  command rejected the id as not found. It now accepts an inline-key id
  that has a health record; the owner-routed reset already persists it.
- With several agents, the mutation path requires `--agent`, but hints
  from `models auth list`, `models status`, and doctor omitted it. The
  hint now carries the store's agent. The status row mapping moved into
  `auth-unavailability.ts` so the grandfathered status command does not
  grow.

The owner-write unit test now mocks only the locked writer instead of a
broad `importOriginal` partial mock of the store runtime.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The status billing case pushed list.status.test.ts past its line-cap
ratchet. Cover the agent-scoped hint in auth-unavailability.test.ts,
next to the helper that now builds it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `models status` under OPENCLAW_AGENT_DIR / PI_CODING_AGENT_DIR reads the
  override store, but `clear-cooldown` mutates the configured agent dir.
  Printing `--agent <id>` there would clear a different store, so the
  hint omits the command for override-only stores.
- In the state-db layout the shared store matches no agent database, so
  doctor printed the shared hint without `--agent`. The shared target now
  takes the agent that owns the shared-main dir.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… doctor hints reachable

clear-cooldown only wrote the credential owner's store, so a health row kept in
the agent's own database (a child's local override of an inherited credential,
or an inline-key failure) survived, won again after reload, and the command
still reported success. After the owner-routed reset, also reset the agent's
own row when one exists; an agent without a row gets no database created.

Doctor printed the command without --agent when no configured agent owned the
shared state-db store, which the mutation path rejects for several agents.
Fall back to a configured agent: all of them reach the shared profile through
owner routing.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 764d9885c4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +18 to +19
vi.mock("../../agents/auth-profiles.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../../agents/auth-profiles.js")>()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Replace the broad auth-profile partial mock

This focused command test only needs ensureAuthProfileStore and clearAuthProfileCooldown, but importOriginal() evaluates the entire auth-profiles.js barrel (including store-runtime.js and its native plugin-loader composition) during module setup. That defeats the lazy-loading boundary and violates the root rule that new tests avoid broad barrel imports; use an explicit factory exposing only those two bindings.

AGENTS.md reference: AGENTS.md:L88-L88

Useful? React with 👍 / 👎.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @Glucksberg for surfacing the early-recovery lockout. A focused, credited replacement landed in #189427 (ef60dd0): authenticated quota checks now honor an earlier provider reset while preserving other profiles' health and credential checks. Markus is credited as co-author. Closing this in favor of the merged replacement; thank you for the recovery report and investigation.

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

Labels

agents Agent runtime and tooling clawtributors PR from a clawtributor cli CLI command changes commands Command implementations docs Improvements or additions to documentation merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. security-review-required security-sensitive-changed size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: blank-template Candidate: PR template appears mostly untouched.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants