Skip to content

fix(cli): keep gateway-backed agent turns cold - #117705

Merged
steipete merged 2 commits into
mainfrom
codex/fix-agent-cli-cold-start
Aug 2, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/fix-agent-cli-cold-start

Conversation

@steipete

@steipete steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every gateway-backed openclaw agent turn paid a large fixed startup tax before the request ever reached the Gateway. On a production host (Hetzner, 48 cores, Node 26.5, ~150 installed plugins, idle) an ordinary turn took 13.0 s wall while the Gateway-measured turn itself (meta.durationMs) was only 3.3–4.9 s. Roughly 9 s was pure client-side startup for a command whose work happens in another process.

Genuinely cold CLI commands on the same host show what the baseline should be:

Command Wall
openclaw --version 36 ms
openclaw automations list --json 1392 ms
openclaw gateway status --json 1589 ms
openclaw gateway call health 1811 ms
openclaw agent … --json 13045 ms
openclaw channels status --json (no probe) 9968 ms

A CPU profile of one agent run (13.6 s sampled) showed ~5 s of module transform/compile plus filesystem walking: jiti 2540 ms, package_json_reader.get 913 ms, compileSourceTextModule 531 ms, node:vm Script 496 ms, lstat 683 ms, GC 693 ms, alongside a legitimate 3451 ms idle wait for the Gateway's answer.

This is not the jiti transform cache underperforming. That cache (#117355) is populated and effective: ~/.cache/openclaw/jiti/<version> holds 9221 files and a repeat plugins list adds zero new files, yet three consecutive runs still take 9.6 / 9.9 / 9.8 s with no warming. The remaining cost is reading, compiling, and executing plugin modules in every short-lived CLI process. Caching transforms cannot remove that; not importing them can.

This is a default-path cost: every scripted turn, cron-invoked turn, and operator openclaw agent call pays it.

Why This Change Was Made

The eager work came from the global pre-action hook, not from anything the turn needs:

src/cli/program/preaction.ts → command-execution-startup.ts → command-bootstrap.ts → config-guard.ts → doctor-config-preflight.ts → doctor-state-migrations.ts → state-migrations.doctor.ts

config-guard.ts classified every agent invocation as migration-sensitive. The doctor migration module then eagerly imported bundled channel registries and plugin doctor contracts; the contract registry scanned installed manifests and loaded their modules through the jiti-backed loader.

Two edges compounded it: text-mode agent calls selected full plugin activation, and agent-via-gateway.ts unconditionally loaded the session resolver, whose re-export chain reached SQLite session maintenance and the bundled channel runtime.

For a remote turn the Gateway — not the CLI — owns config migration, plugin resolution, and session-key derivation. The already-cold commands prove the intended shape: gateway call explicitly skips state migration, and automations bypasses local Gateway config bootstrap.

The fix follows the existing catalog-policy convention rather than adding a new mechanism. bypassConfigGuard becomes invocation-aware (the same predicate form loadPlugins and networkProxy already use), so remote turns skip config migration and plugin activation while --local retains both. The session resolver moves behind a real *.runtime.ts lazy boundary; ordinary --agent turns omit sessionKey because the Gateway already derives it from agentId. Explicit session IDs, recipients, and non-agent session keys still load it. The same owner fix covers successful JSON channels status, which returns the Gateway payload before loading local rendering; text formatting and the unreachable-Gateway fallback stay behind the runtime boundary.

plugins list is intentionally unchanged: it is a local plugin-inventory command, not an RPC-only client.

User Impact

Gateway-backed openclaw agent turns and successful openclaw channels status --json requests no longer pay local config-migration and plugin-runtime startup. Local cold repro (isolated state dir, unreachable loopback Gateway): 5.38 s → 0.52 s. That machine does not have the production fleet's ~150 plugins, so the production win should be larger.

No behavior change to --local runs, --deliver, reply channel/account routing, best-effort delivery, the JSON envelope, or text rendering. Delivery fields are untouched.

Evidence

  • Focused CLI suites: 6 files, 88/88 passed.
  • Agent Gateway suites: 77 passed, 1 pre-existing skip.
  • Channel command tests: 37/37. Gateway channel tests: 81/81.
  • New cold-import guards assert zero config/plugin/session runtime module evaluations on an ordinary Gateway-backed turn, and on both probe and non-probe JSON channels status success paths. These are the scale-independent proof; they fail if the eager import returns.
  • pnpm build passed including check-cli-bootstrap-imports, with zero [INEFFECTIVE_DYNAMIC_IMPORT] warnings.
  • git diff --check and targeted oxfmt clean.
  • Autoreview (Codex gpt-5.6-sol, high): clean, no accepted/actionable findings, "patch is correct" (0.87).

Known proof gap: the broad node scripts/run-vitest.mjs src/cli directory composition did not finish cleanly on the authoring host — an unconstrained run produced unrelated cross-file failures and hung. The first reported failures pass independently at 195/195 and 181/181, indicating order-dependent shared suite-state contamination rather than a changed-path failure. Remote confirmation was unavailable (Blacksmith Testbox binary missing; AWS Crabbox broker login unavailable), so CI is the arbiter for the full composition.

Production delta +293/-265, net +28 lines; most churn is a 249-line channels formatter moving behind its runtime boundary. Tests +146/-17.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes commands Command implementations size: L maintainer Maintainer-authored PR labels Aug 2, 2026
@steipete steipete self-assigned this Aug 2, 2026
@steipete
steipete marked this pull request as ready for review August 2, 2026 00:06
@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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 1, 2026, 8:24 PM ET / August 2, 2026, 00:24 UTC.

ClawSweeper review

What this changes

The branch makes gateway-backed openclaw agent turns and successful JSON channels status calls avoid local config, plugin, session, and rendering startup work.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 5 items remain

This PR remains necessary: the supplied current main commit does not contain its cold-start boundary changes. The source review found a coherent gateway-first design and no discrete patch defect, but this compatibility-sensitive startup change still needs inspectable after-fix CLI proof before merge; the existing maintainer label also requires human handling.

Priority: P2
Reviewed head: 3736f3e9977c67e8120b96dbb9568d0fa19aa3b2

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The patch has targeted owner-boundary tests and no discrete source defect found, but required real-behavior proof is not inspectable.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: The PR body reports timing and tests, but the supplied context has no inspectable after-fix terminal capture, live output, redacted runtime log, recording, or linked artifact. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR body reports timing and tests, but the supplied context has no inspectable after-fix terminal capture, live output, redacted runtime log, recording, or linked artifact. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current main lacks the change: The PR head is not an ancestor of supplied current main ab8090e0; its central command-policy, agent session, and channel-status lazy-runtime files differ from main, so this work is neither implemented nor superseded.
Gateway owns omitted session-key routing: The Gateway request-routing owner accepts an omitted session key, resolves explicit recipient/session inputs, and derives the effective target from the request. That supports deferring only the CLI-side session resolver when no explicit local routing fact is needed.
Branch keeps the explicit local path guarded: The proposed catalog makes config-guard and plugin loading conditional on --local, while the remote agent path continues to read reduced dispatch configuration and call the Gateway.
Findings None None.
Security None None.

How this fits together

The CLI normally runs startup policy that validates local configuration and loads plugin metadata. Gateway-backed agent and channel-status commands instead send an RPC to the running Gateway, which resolves the request and returns a result for CLI output.

flowchart LR
  A[CLI invocation] --> B[Startup policy]
  B --> C{Local or Gateway-backed}
  C -->|Gateway-backed| D[Gateway RPC]
  C -->|Local| E[Config and plugin runtime]
  D --> F[Agent or channel result]
  E --> F
  F --> G[CLI JSON or text output]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR body reports timing and tests, but the supplied context has no inspectable after-fix terminal capture, live output, redacted runtime log, recording, or linked artifact. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - Remote agent and channels status invocations would stop performing local config migration and plugin activation before dispatch, so merge proof must cover both the gateway-backed path and the retained --local guarded path.
  • Resolve merge risk (P1) - The PR body reports benchmarks and focused tests, but the supplied context contains no inspectable after-fix terminal capture, recording, live output, redacted runtime log, or linked artifact.
  • Resolve merge risk (P1) - The supplied GitHub timestamps are dated August 2, 2026, after the August 1, 2026 review date, so status and proof metadata are not independently live-verifiable.
  • Complete next step (P2) - Contributor-supplied real behavior and upgrade evidence are required before a maintainer can safely merge this compatibility-sensitive startup change.
Agent review details

Security

None.

PR surface

Source +28, Tests +129. Total +157 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 9 293 265 +28
Tests 11 147 18 +129
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 440 283 +157

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: src/commands/agent/session.runtime.ts, serialized state: src/commands/agent/session.test.ts, serialized state: src/commands/agent/session.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove both startup modes before merge (recommended)
    Add redacted real CLI evidence for gateway-backed agent/channel status and confirm that --local still uses the prior config and plugin bootstrap path.
  2. Accept the upgrade boundary
    Merge with the deliberate behavior that remote calls rely on the running Gateway for migration and plugin ownership, while acknowledging that local migration preflight no longer runs.
  3. Pause the optimization
    Hold the branch if maintainers intend remote CLI commands to retain local migration preflight as an upgrade contract.

Technical review

Best possible solution:

Keep the Gateway RPC fast path cold, retain the guarded --local path, and add redacted real CLI proof for both gateway-backed commands before merge.

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

No high-confidence executed reproduction was established in this read-only review. Source and the branch’s focused import-guard tests make the eager local-startup path source-reproducible, but inspectable real runtime proof is still missing.

Is this the best way to solve the issue?

Yes, provisionally: the branch moves work behind the Gateway-versus-local owner boundary instead of adding a cache or fallback path, and it preserves explicit --local handling. Upgrade and real-runtime evidence are still needed before merge.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs a broad default CLI latency cost but does not evidence a crash, data-loss, or message-delivery regression.
  • merge-risk: 🚨 compatibility: The branch changes whether remote agent and channel-status invocations run local config migration and plugin activation before dispatch.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body reports timing and tests, but the supplied context has no inspectable after-fix terminal capture, live output, redacted runtime log, recording, or linked artifact. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current main lacks the change: The PR head is not an ancestor of supplied current main ab8090e0; its central command-policy, agent session, and channel-status lazy-runtime files differ from main, so this work is neither implemented nor superseded. (src/cli/command-catalog.ts:87, ab8090e0d32f)
  • Gateway owns omitted session-key routing: The Gateway request-routing owner accepts an omitted session key, resolves explicit recipient/session inputs, and derives the effective target from the request. That supports deferring only the CLI-side session resolver when no explicit local routing fact is needed. (src/gateway/server-methods/agent-request-routing.ts:84, ab8090e0d32f)
  • Branch keeps the explicit local path guarded: The proposed catalog makes config-guard and plugin loading conditional on --local, while the remote agent path continues to read reduced dispatch configuration and call the Gateway. (src/cli/command-catalog.ts:87, 3736f3e9977c)
  • Cold-path regression tests exist on the branch: The branch adds import guards for successful JSON channel-status calls and tests that agent-scoped gateway turns omit session-runtime loading while retaining explicit routing cases. (src/commands/channels.status-cold-imports.test.ts:31, 3736f3e9977c)
  • Current-main startup policy provenance: Current-main blame attributes the existing agent startup policy to a recent CLI policy commit; recent history also includes agent-startup timing work in the same area. (src/cli/command-catalog.ts:85, 77796591370d)
  • Timeline timestamp inconsistency: The supplied GitHub context marks this PR created and updated on August 2, 2026, while the review date is August 1, 2026; live workflow/proof state therefore cannot be treated as independently current from this context alone. (3736f3e9977c)

Likely related people:

  • Vincent Koc: Current-main blame attributes the existing agent startup policy to this contributor, and recent history includes agent startup-stage work. (role: recent area contributor; confidence: high; commits: 77796591370d, 4153451a9a1d; files: src/cli/command-catalog.ts, src/commands/agent-via-gateway.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Post a redacted after-fix terminal capture for gateway-backed openclaw agent and openclaw channels status --json.
  • Include an upgrade-style invocation or explicit --local transcript showing that the guarded local path remains intact.

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 (1 earlier review cycle)
  • reviewed 2026-08-02T00:11:59.033Z sha 49315ca :: needs real behavior proof before merge. :: none

@steipete

steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Maintainer landing note: I am skipping the optional terminal-capture Rank-up moves because this is an explicitly authorized, already-reviewed mechanics-only landing, and the task excludes new proof collection or PR-body polish. The exact head has green CI and focused regression coverage for the startup boundary.

I accept the reviewed ownership tradeoff for this PR: gateway-backed agent and channels status calls rely on the running Gateway, while explicit --local execution retains the local config and plugin bootstrap path.

@steipete
steipete merged commit 681e8c5 into main Aug 2, 2026
120 checks passed
@steipete
steipete deleted the codex/fix-agent-cli-cold-start branch August 2, 2026 00:34
@steipete

steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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 gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant