Skip to content

fix(agents): honor the configured system agent for ambient owner resolution - #126504

Merged
steipete merged 1 commit into
mainfrom
steipete/ambient-owner-consolidation
Aug 20, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/ambient-owner-consolidation

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves a problem where operators running more than one agent could not get OpenClaw to honor
agents.defaults.systemAgent.agentId, the setting documented as the owner for unscoped operator
reads. Two separate things went wrong on multi-agent rosters:

  • Commands and checks that resolve an agent-owned model or auth state without an explicit --agent
    could fail outright. With agents.ownership: "explicit" and two agents, openclaw doctor reported
    doctor:hooks-model run failed: Multiple agents are configured, but this operation has no explicit owner even when systemAgent.agentId was set, because the ambient owner never consulted it.
  • Worse, the context-window token cache silently never populated. Both catalog-owner call sites in
    src/agents/context.ts resolved their own owner and swallowed the resulting throw, so every model
    quietly fell back to configured-only context limits with no error anywhere.

Underneath both: there were two competing definitions of "who owns ambient work", and they disagreed.

Why This Change Was Made

agent-scope-config.ts carried four overlapping helpers — a system-agent pair that tried
systemAgent.agentId first, and an ambient pair that tried the legacy default=true marker first.
The same decision was additionally open-coded in state-migrations.doctor.ts, spelled out as a
two-clause condition in validation-core.ts, and duplicated at three consumers.

The two families genuinely disagree on a roster zod accepts (exactly one legacy marker, so
ownership: "explicit" is not required, plus a systemAgent.agentId naming a different entry):
legacy-first resolves alpha while system-agent-first resolves beta. Legacy-first is the wrong
precedence — agents.defaults.systemAgent.agentId is documented as the owner for unscoped reads
with "explicit request agentId always wins", so a stripped legacy marker must not outrank config the
operator explicitly wrote.

This collapses all of it into one canonical pair with precedence
requested -> systemAgent.agentId -> legacy compatibility -> sole agent, deletes the two
system-agent functions outright rather than aliasing them, migrates every caller, and removes the
duplicated policy at consumers. Ambiguous rosters still fail closed, now naming the config knob.

Non-goals: resolveDefaultAgentId and its remaining callers are untouched, and onboarding,
session-ownership, and auth-inheritance compatibility boundaries are deliberately preserved because
they own different shipped contracts and should not inherit ambient system-agent precedence.

User Impact

Operators running multi-agent rosters can now set agents.defaults.systemAgent.agentId once and
have unscoped reads actually use it. Model context limits are correct on those rosters instead of
silently degrading to configured-only values. When ownership really is ambiguous the error now names
the setting to fix rather than emitting generic selection guidance.

Behavior change worth calling out for review: on a roster carrying both a legacy default=true
marker and a different configured systemAgent.agentId, the ambient owner is now the configured
system agent rather than the legacy marker. The previous ordering is not in any release tag.

Production LOC is net -91.

Evidence

Regression tests fail on pre-change code for the right reason, verified by reverting only the
production file and re-running:

  • precedence, 5 failures: Expected: "beta" / Received: "alpha" for a configured system agent
    versus a raw legacy marker, the same for a retained migrated marker,
    Expected: "gamma" / Received: "alpha" for an explicit requested owner, plus the fail-closed
    context assertion and default-agent-directory resolution.
  • context-window cache, 4 failures in context.lookup.test.ts including Number of calls: 0.

Validation:

  • Focused suites across agents, config, gateway, commands, cli, system-agent, infra, plugins,
    skills, flows, auto-reply, cron, and talk: 52 files, 1,532 tests passing across 12 shards.
  • node scripts/check-changed.mjs clean, including all three Knip unused-export scans and
    0 runtime import cycles.
  • pnpm build clean.
  • Structured second-model review clean, no accepted or actionable findings.

Live proof, isolated OPENCLAW_STATE_DIR per case, hooks.gmail.model configured,
node dist/index.js doctor --non-interactive:

  • legacy alpha.default: true plus systemAgent.agentId: beta resolves agentDir under
    agents/beta/agent (the behavior change, proved end to end), doctor exit 0.
  • ownership: "explicit" two-agent roster plus systemAgent.agentId: beta resolves under
    agents/beta/agent, no doctor:hooks-model failure, doctor exit 0.
  • sole-agent roster unchanged, doctor exit 0.

@clawsweeper

clawsweeper Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation r: skill Auto-close: skills should be published on ClawHub, not added to core. gateway Gateway runtime cli CLI command changes labels Aug 20, 2026
@steipete
steipete marked this pull request as ready for review August 20, 2026 01:25
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations agents Agent runtime and tooling labels Aug 20, 2026
@steipete
steipete requested a review from a team as a code owner August 20, 2026 01:25
@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Aug 20, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Aug 20, 2026
@clawsweeper

clawsweeper Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 19, 2026, 9:32 PM ET / August 20, 2026, 01:32 UTC.

ClawSweeper review

What this changes

The PR makes unscoped agent-owned operations consistently prefer an explicit request, then systemAgent.agentId, before legacy default ownership or a sole agent.

Regression provenance

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

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This PR is still necessary: current main resolves a retained legacy owner before the configured system agent, contrary to the documented unscoped-owner contract. The patch centralizes the intended precedence, has no discrete correctness finding, and should remain open for maintainer review and exact-head CI.

Priority: P2
Reviewed head: b01ff9a76bf310a0cb560e55c2096969ce20d976

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, net-negative canonicalization with credible real terminal proof and targeted regression coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body provides after-fix isolated terminal runs of doctor --non-interactive for conflicting legacy/system-agent, explicit-ownership, and sole-agent rosters, all reporting the intended owner and successful exit; redact any local paths or credentials if evidence is reposted.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body provides after-fix isolated terminal runs of doctor --non-interactive for conflicting legacy/system-agent, explicit-ownership, and sole-agent rosters, all reporting the intended owner and successful exit; redact any local paths or credentials if evidence is reposted.
Evidence reviewed 7 items Current-main defect: Current main's ambient resolver returns the legacy compatibility owner before the system-agent target, so a roster containing both conflicting values selects the legacy owner.
Documented contract: The PR documentation now states the complete owner precedence, with an explicit request and configured system agent ahead of retained legacy ownership.
Canonical owner boundary: The branch replaces competing resolver families with one ambient resolver that implements requested → configured system agent → legacy compatibility.
Findings None None.
Security None None.

Live Verification

Command: pnpm openclaw doctor --help

Result: PASS (completed)

pnpm openclaw doctor --help
runner@runnervm76f27:/tmp/clawsweeper-live-proof-126504-CdPoC5/target$ pnpm openclaw doctor --help
$ node scripts/run-node.mjs doctor --help
pnpm openclaw doctor --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 111.63 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

[tsdown-build] invocation 2/2 finished in 13.1s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 10 phases completed in 3893ms (slowest: built plugin control-plane loads 3269ms)


Assertions:

  • PASS expect_output: doctor

How this fits together

Agent-scope configuration selects the agent whose model, credentials, workspace, and catalog serve unscoped operations such as Doctor and model status. Callers supply an optional owner; the resolver selects one agent before downstream model/auth and plugin work.

flowchart LR
  A[Unscoped command or service] --> B[Optional requested agent]
  B --> C[Ambient owner resolution]
  C --> D[Configured system agent]
  C --> E[Legacy owner or sole agent]
  D --> F[Model auth workspace state]
  E --> F
  F --> G[Doctor gateway and CLI output]
Loading

Before merge

  • Resolve merge risk (P1) - Upgrades whose roster carries both a legacy default: true marker and a different systemAgent.agentId will deliberately switch ambient model/auth ownership; exact-head CI should confirm the documented precedence before landing.
  • Complete next step (P2) - This maintainer-labeled PR has no narrow repair finding; retain it for maintainer landing review once the exact head is green.
Agent review details

Security

None.

PR surface

Source -91, Tests +51, Docs 0. Total -40 across 48 files.

View PR surface stats
Area Files Added Removed Net
Source 37 102 193 -91
Tests 8 155 104 +51
Docs 3 3 3 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 48 260 300 -40

Review metrics

Metric Value Why it matters
Production vs test LOC production +102/-193 (net -91); tests +155/-104 (net +51); docs +3/-3 The bug fix removes duplicate production owner-selection paths while adding focused regression coverage.
Existing config precedence 1 changed precedence rule Conflicting legacy and system-agent ownership settings will now select the documented system-agent owner on upgrade.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor/shared/context-engine-host-compat.ts, serialized state: src/config/sessions/main-session.ts, serialized state: src/infra/state-migrations.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Land the documented owner precedence (recommended)
    After exact-head checks pass, accept the intentional upgrade behavior that makes an explicitly configured system agent outrank a retained legacy marker.

Technical review

Best possible solution:

Keep one canonical ambient-owner resolver with documented precedence and preserve explicit-agent selection only on surfaces that intentionally require it.

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

Yes. Current main visibly selects the legacy compatibility owner first, while the documented system-agent contract and focused multi-agent regression cases establish the conflicting-roster path.

Is this the best way to solve the issue?

Yes. Centralizing precedence in the ambient resolver is the narrowest maintainable repair and removes caller-specific policy copies rather than adding fallbacks.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This corrects unscoped multi-agent model/auth ownership with a bounded but meaningful operator impact.
  • add merge-risk: 🚨 compatibility: The changed owner precedence can redirect existing conflicting multi-agent configurations to a different persisted model/auth/workspace owner.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix isolated terminal runs of doctor --non-interactive for conflicting legacy/system-agent, explicit-ownership, and sole-agent rosters, all reporting the intended owner and successful exit; redact any local paths or credentials if evidence is reposted.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body provides after-fix isolated terminal runs of doctor --non-interactive for conflicting legacy/system-agent, explicit-ownership, and sole-agent rosters, all reporting the intended owner and successful exit; redact any local paths or credentials if evidence is reposted.

Label justifications:

  • P2: This corrects unscoped multi-agent model/auth ownership with a bounded but meaningful operator impact.
  • merge-risk: 🚨 compatibility: The changed owner precedence can redirect existing conflicting multi-agent configurations to a different persisted model/auth/workspace owner.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body provides after-fix isolated terminal runs of doctor --non-interactive for conflicting legacy/system-agent, explicit-ownership, and sole-agent rosters, all reporting the intended owner and successful exit; redact any local paths or credentials if evidence is reposted.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix isolated terminal runs of doctor --non-interactive for conflicting legacy/system-agent, explicit-ownership, and sole-agent rosters, all reporting the intended owner and successful exit; redact any local paths or credentials if evidence is reposted.

Evidence

What I checked:

Likely related people:

  • steipete: Current and historical ownership-resolution work, including the preceding system-agent preservation change, is authored by Peter Steinberger; the PR author maps to this handle. (role: feature owner and recent area contributor; confidence: high; commits: b01ff9a76bf3, 867c029d5a85, 1ca60fbc3a3f; files: src/agents/agent-scope-config.ts, src/agents/prepared-model-catalog.ts, docs/gateway/config-agents.md)

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.

@steipete

Copy link
Copy Markdown
Contributor Author

Addressing the two before-merge items ahead of landing.

Resolve merge risk (P1) — done. Exact-head CI is green at b01ff9a76bf310a0cb560e55c2096969ce20d976: 185 success, 38 skipped, 1 neutral, 0 failures. The precedence switch is intentional and is the point of the change: agents.defaults.systemAgent.agentId is documented as the owner for unscoped operator reads with "explicit request agentId always wins", so a stripped legacy default=true marker must not outrank it. The prior legacy-first ordering is not reachable from any stable release tag, so no deprecation window applies.

Complete next step (P2) — done. Landing as maintainer with exact head green.

On the flagged stored-data-model change: verified as a false positive. Both flagged files are pure call-site migrations with no schema, serialization-format, or migration-logic change. The one semantically meaningful line is resolveSystemMainSessionTarget in src/config/sessions/main-session.ts, which now resolves through the unified ambient owner. Enumerating the cases, since main-session keys are persisted:

  • single-agent roster: identical.
  • multi-agent with systemAgent.agentId set: identical, the configured system agent still wins.
  • multi-agent with a legacy marker and a different systemAgent.agentId: identical, the configured system agent wins.
  • multi-agent with a legacy marker and no systemAgent.agentId: previously threw AgentSelectionRequiredError and produced no session key at all; now resolves to the legacy owner.

Only the last case changes, and it changes from a dead end to a working resolution, so no existing persisted session can be re-pointed and no migration is required.

@steipete
steipete merged commit 1931666 into main Aug 20, 2026
287 of 290 checks passed
@steipete
steipete deleted the steipete/ambient-owner-consolidation branch August 20, 2026 01:54
@steipete

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

agents Agent runtime and tooling cli CLI command changes commands Command implementations docs Improvements or additions to documentation 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. r: skill Auto-close: skills should be published on ClawHub, not added to core. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant