Skip to content

fix: honor selected agent context caps in embedded runs - #119277

Closed
wenrizc wants to merge 13 commits into
openclaw:mainfrom
wenrizc:fix/agent-context-cap-71136
Closed

wenrizc wants to merge 13 commits into
openclaw:mainfrom
wenrizc:fix/agent-context-cap-71136

Conversation

@wenrizc

@wenrizc wenrizc commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #71136

What Problem This Solves

Embedded runs can ignore the selected agent's existing contextTokens cap, so an agent-specific context budget is honored by the CLI path but not by the normal embedded runtime. Safeguard compaction and low-context recovery guidance must use the same selected-agent budget.

Why This Change Was Made

The embedded context-budget owner now resolves the selected agent's merged configuration and passes its resolved contextTokenBudget through both the normal embedded session and the separate compaction session. Direct compaction treats a caller-resolved budget as the selected-agent cap, while Gateway-started compaction derives the selected agent's cap from the session agent when no caller budget is supplied. Both paths still clamp to the actual compaction model limit.

User Impact

Per-agent contextTokens settings now consistently cap context budgets for embedded runs, safeguard compaction, and Gateway-started manual compaction, including agent-specific entries that differ from the global default.

Evidence

  • Current head: acd01cb587f30eb8a449ccb40b81530284843517, a sync-only merge of the remote PR head and upstream/main=e5d4fe02a46a; none of this PR's 13 files changed during synchronization.
  • node scripts/run-vitest.mjs run --config test/vitest/vitest.unit-fast.config.ts src/agents/context-window-guard.test.ts src/agents/embedded-agent-runner/compaction-runtime-context.test.ts src/agents/embedded-agent-runner/extensions.test.ts src/agents/embedded-agent-runner/run/setup.test.ts: passed; 25 tests in the unit-fast owner group.
  • node scripts/run-vitest.mjs run --config test/vitest/vitest.agents-embedded-agent.config.ts embedded-agent-runner/compaction-runtime-context.test.ts embedded-agent-runner/extensions.test.ts: passed; 2 files, 46 tests.
  • node scripts/run-vitest.mjs run --config test/vitest/vitest.agents-embedded-agent-run.config.ts setup.test.ts: passed; 1 file, 22 tests.
  • pnpm check: passed on the current head in manual verification.
  • git diff --check upstream/main...HEAD: passed.
  • PI_CODING_AGENT_DIR=/root/.pi/agent AUTOREVIEW_PROVIDER_ENV_ALLOW=ASXS_API_KEY .agents/skills/autoreview/scripts/autoreview --mode branch --base upstream/main --engine pi --model 'asxs/gpt-5.5' --thinking high --pi-bin /usr/local/bin/pi: passed; TruffleHog clean; autoreview clean: no accepted/actionable findings reported.
  • CI: will run for current head after this push.

This PR was AI-assisted. I reviewed the embedded model-policy owner, its normal-session and compaction-session callers, safeguard runtime, the CLI sibling path, and native model-owned bypass behavior, and understand the behavior implemented here.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Aug 4, 2026
@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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 4, 2026
@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 8, 2026, 11:40 AM ET / 15:40 UTC.

ClawSweeper review

What this changes

The PR carries the selected agent’s existing context-token cap into embedded-run prechecks, safeguard compaction, and direct or Gateway-started compaction while retaining model-limit clamping.

Merge readiness

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

This is a coherent root-cause repair for a real embedded-run budget inconsistency, but it should remain open for maintainer selection between two same-root-cause PRs and stronger exact-head behavior proof before merge.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and well-covered at helper boundaries, but merge confidence remains limited by missing full-path behavior proof and the competing repair.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The supplied terminal probe invokes policy and safeguard helpers, but it does not demonstrate an after-fix embedded agent session or compaction execution through the production boundary. 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 supplied terminal probe invokes policy and safeguard helpers, but it does not demonstrate an after-fix embedded agent session or compaction execution through the production boundary. 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 defect: The embedded policy resolves its context window without supplying the selected agent’s merged contextTokens value, even though the resolver accepts such a cap.
Canonical config and working sibling: resolveAgentConfig merges an entry cap over the default, and the CLI sibling resolves and passes that selected-agent value into context-window resolution.
Patch ownership path: The PR resolves the selected agent after the native-model-owner early exit and propagates the resulting budget to normal sessions, safeguard factories, and both compaction entry points.
Findings None None.
Security None None.

How this fits together

The embedded runner converts a selected agent and model into an effective context budget for each agent attempt. That budget also controls compaction and low-context safeguards, so every consumer must use the same prepared value.

flowchart LR
  A[Selected agent configuration] --> B[Embedded model policy]
  C[Model context limit] --> B
  B --> D[Attempt context budget]
  D --> E[Prompt precheck]
  D --> F[Safeguard compaction]
  D --> G[Direct and Gateway compaction]
Loading

Decision needed

Question Recommendation
Which of this PR and #120343 should be the canonical selected-agent context-cap repair after an exact source comparison and full embedded-session proof? Choose one canonical repair after proof: Compare the two exact heads, keep the more complete owner-boundary implementation and regression coverage, and require a full embedded-session after-fix trace.

Why: Both branches address the same owner-boundary invariant, but their exact diffs could not be compared and the chosen patch changes upgrade-visible session thresholds.

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The supplied terminal probe invokes policy and safeguard helpers, but it does not demonstrate an after-fix embedded agent session or compaction execution through the production boundary. 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) - Existing embedded sessions with per-agent caps different from the global default will change precheck and compaction thresholds after upgrade.
  • Resolve merge risk (P1) - A second open PR, fix(agents): apply per-agent contextTokens cap to embedded run context budget #120343, addresses the same invariant; merging both without an exact-diff comparison risks duplicated repair paths.
  • Resolve merge risk (P1) - The native model-owned bypass remains source-preserved, but the required sibling Codex source was unavailable for direct contract verification.
  • Complete next step (P2) - A maintainer must select one of two same-root-cause PRs and require full-path proof; there is no narrow mechanical repair remaining on this branch.
Agent review details

Security

None.

PR surface

Source +21, Tests +190. Total +211 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 9 40 19 +21
Tests 4 192 2 +190
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 232 21 +211

Review metrics

Metric Value Why it matters
Production versus test LOC production +40/-19 (net +21); tests +192/-2 The production growth is justified by carrying one already-resolved context-budget fact across independently resolving runtime owners.

Merge-risk options

Maintainer options:

  1. Prove the selected-agent path before merge (recommended)
    Run an exact-head embedded session with a per-agent cap distinct from the default and record the attempt and compaction budgets before selecting the canonical PR.
  2. Pause for duplicate consolidation
    Do not merge either branch until maintainers compare it with fix(agents): apply per-agent contextTokens cap to embedded run context budget #120343 and choose one implementation path.

Technical review

Best possible solution:

Select one canonical repair that resolves the selected-agent cap once and carries the prepared, model-clamped budget through every embedded and compaction consumer, then retain the stronger regression coverage from the other proposal.

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

Yes—current main is source-reproducible: the CLI supplies merged selected-agent contextTokens while the embedded policy omits it and falls back to the global/default model resolution path.

Is this the best way to solve the issue?

Yes for the architectural shape: resolving the selected agent once and carrying the prepared model-clamped budget to all consumers is preferable to separate fallback calculations; the canonical branch still needs selection.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The supplied terminal probe invokes policy and safeguard helpers, but it does not demonstrate an after-fix embedded agent session or compaction execution through the production boundary. 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.
  • remove proof: sufficient: Current real behavior proof status is insufficient, not sufficient.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: 📣 needs proof.

Label justifications:

  • P2: Incorrect embedded context limits can cause ordinary agent attempts and compaction to use the wrong configured threshold, but the impact is limited to configured per-agent caps.
  • merge-risk: 🚨 compatibility: Existing installations with per-agent contextTokens values different from the global default will begin observing those values in embedded runs.
  • merge-risk: 🚨 session-state: The repair changes the context ceiling used to decide prechecks and compaction for persisted embedded sessions.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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 supplied terminal probe invokes policy and safeguard helpers, but it does not demonstrate an after-fix embedded agent session or compaction execution through the production boundary. 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:

Likely related people:

  • Patrick-Erichsen: The PR timeline records an assignment, and this review needs a choice between competing fixes rather than a mechanical patch correction. (role: assigned reviewer and likely decision owner; confidence: medium; files: src/agents/embedded-agent-runner/run/setup.ts, src/agents/embedded-agent-runner/compaction-runtime-context.ts)
  • Alix-007: The available shallow-history blame names this author on the implicated current-main lines, but the graft boundary prevents stronger ownership attribution. (role: current-line attribution; confidence: low; commits: 50ec5570ae89; files: src/agents/embedded-agent-runner/run/setup.ts, src/agents/agent-scope-config.ts)

Rank-up moves

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

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 (23 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-05T04:14:05.065Z sha e14f920 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T06:38:40.472Z sha ca9251b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T12:21:15.996Z sha ef1c8d0 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T13:13:14.961Z sha ef1c8d0 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-06T14:32:33.322Z sha aa4eb59 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-07T07:36:39.712Z sha 954ebca :: needs maintainer review before merge. :: none
  • reviewed 2026-08-07T07:43:59.275Z sha 954ebca :: needs maintainer review before merge. :: none
  • reviewed 2026-08-08T11:48:14.185Z sha f33429f :: needs maintainer review before merge. :: none

@wenrizc

wenrizc commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@wenrizc

wenrizc commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@wenrizc

wenrizc commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated the PR relationship to Related: #71136 because this PR addresses the embedded selected-agent cap portion while the broader issue remains open.

@wenrizc

wenrizc commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Inspectable real-behavior proof for current head 7b9a11af2e47ae16f7d446afd9c1048a15d39fb8:

Command: a local node --import tsx --input-type=module probe invoking resolveEmbeddedRuntimeModelPolicy for agent specialist and then buildEmbeddedExtensionFactories with the resolved budget. The probe uses a configured selected-agent cap of 64,000, a default cap of 128,000, and a model-config cap of 1,000,000.

{
  "selectedAgent": "specialist",
  "configuredAgentContextTokens": 64000,
  "resolvedContextWindowInfo": {
    "tokens": 64000,
    "referenceTokens": 1000000,
    "source": "agentContextTokens"
  },
  "normalEmbeddedEffectiveContextWindow": 64000,
  "safeguardCompactionContextWindowTokens": 64000
}

This is a redacted local runtime transcript: the selected-agent cap reaches both the normal embedded effective model and the safeguard-compaction runtime.

@wenrizc

wenrizc commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added inspectable redacted runtime transcript to the PR body and comments for the selected 64,000-token cap reaching both normal embedded policy and safeguard-compaction runtime.

@clawsweeper clawsweeper Bot added 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed 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. 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 4, 2026
@wenrizc

wenrizc commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated current head 670ef413127edb7bfcf5af697d8ab10fef316c87 with the direct-compaction cap repair, exact-head proof for selected-agent 500,000 over default 128,000, and gpt-5.5 Pi autoreview evidence. Current-head checks are complete with no failures.

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 5, 2026
@wenrizc

wenrizc commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Synced branch with latest upstream main (merge-only; none of this PR's 13 files were touched by the merge). Current head ef1c8d0fc55:

  • Focused tests re-run on head: 4 files, 93 tests passed (src/agents/context-window-guard.test.ts, compaction-runtime-context.test.ts, extensions.test.ts, run/setup.test.ts).
  • oxlint, oxfmt, max-lines ratchet, git diff --check upstream/main...HEAD: all passed on head.
  • Gateway no-caller-budget transcript re-run on head, byte-identical to the recorded proof.
  • CI on head: openclaw/ci-gate SUCCESS; Real behavior proof SUCCESS; remaining checks passed or skipped by path filters.

No re-review requested: the author diff is unchanged from the last reviewed head (e14f920d2f7); this is a pure upstream sync.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 6, 2026
@Patrick-Erichsen Patrick-Erichsen self-assigned this Aug 6, 2026
@wenrizc

wenrizc commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Current head 7b36cc8b57359201224ec8b13a74b9b76c546a64 has complete CI with no failures; PR body Evidence is updated for this head.

@clawsweeper

clawsweeper Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 7, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 8, 2026
@Yigtwxx

Yigtwxx commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

The maintainer decision that the ClawSweeper block on this PR asks for has been made, and the canonical repair has landed.

#120343 merged 2026-08-09 00:56Z as af9b872604bec8e3c6a41ba5f822032a38212a88, and the maintainer evidence comment states the selection explicitly:

The batch's maintainer authority selects #120343 as the canonical fix over #119277. [...] #119277's alternative request precedence is therefore not the selected contract.

The same comment also leaves this branch's disposition open: "#119277 remains open for separate orchestrator disposition; no close authority was exercised here." So the call here is yours. What follows is only the measurement I would want if it were my branch.

Overlap, measured now

This head acd01cb5 against landed af9b8726, added non-blank lines, tests excluded:

this PR landed #120343
production files changed 9 9
shared production files 9 9
added production lines 40 47
byte-identical added lines, matched within the same file 20 20

Where this branch's remaining 20 lines go:

  • extensions.ts (12), run/attempt-session.ts (1), compaction-session-execution.ts (1), prepared-compaction-runtime.ts (1): identical on both sides, so all of this branch's lines in those files are on main.
  • run/setup.ts (7 here): same effect, different seam. This branch resolves the cap inside resolveEmbeddedRuntimeModelPolicy; main takes agentContextTokens as a parameter and resolves it in the caller, run/model-harness.ts (+11 there, resolveSessionAgentIds then resolveAgentConfig).
  • context-window-guard.ts (3): superseded by a strictly more specific message. main now names agents.list[].contextTokens, agents.entries.<id>.contextTokens, and agents.defaults.contextTokens, where this branch says "an agent contextTokens setting".
  • compact.queued.ts (1): the same argument added at the same call, supplied from a different local (runtimePolicyAgentId here, runtimeTarget.agentId on main).
  • compaction-runtime-context.ts (9): the one behavioural difference, below.

The difference is the line that was ruled on, and it reaches one step further than precedence

This branch:

agentContextTokens: requestedTokenBudget ?? configuredAgentTokenBudget,

main:

const agentContextTokens = params.agentId
  ? resolveAgentConfig(params.config ?? {}, params.agentId)?.contextTokens
  : undefined;

resolveContextWindowInfo treats that field as a cap and falls back to config (src/agents/context-window-guard.ts:92-97):

const capTokens =
  normalizePositiveInt(params.agentContextTokens) ??
  normalizePositiveInt(params.cfg?.agents?.defaults?.contextTokens);
if (capTokens && capTokens < baseInfo.tokens) {
  return { tokens: capTokens, referenceTokens: baseInfo.tokens, source: "agentContextTokens" };
}

So routing the caller's requested budget into that field does two things rather than one: the requested value replaces the agent cap, and because of the ?? it also suppresses the agents.defaults.contextTokens fallback. Probe with model window 400,000 and a requested budget of 500,000:

arm resolved tokens source final budget
agent cap 200,000, main shape 200,000 agentContextTokens 200,000
agent cap 200,000, this branch's shape 400,000 model 400,000
no agent-specific cap, agents.defaults.contextTokens 150,000, main shape 150,000 agentContextTokens 150,000
same config, this branch's shape 400,000 model 400,000
control, no requested budget, main shape 200,000 agentContextTokens 200,000

The source flip matters beyond the number. formatContextWindowWarningMessage and formatContextWindowBlockMessage only tell the operator that a cap is in play when source === "agentContextTokens", so in rows two and four the operator also loses the very message this branch rewrites.

One stale artifact

The ClawSweeper review on this PR was last written 2026-08-08 15:40Z against head acd01cb5, before the merge. Its Decision needed question ("Which of this PR and #120343 should be the canonical selected-agent context-cap repair") and its P1 item "a second open PR [...] addresses the same invariant" both predate the answer quoted above, so the queue still reads this branch as an undecided candidate.

Scope: main at c708b41af4f. The probe called resolveContextWindowInfo as it stands on main — the landed commit changed only the two message formatters in that file, not the resolver — and included a control arm with no requested budget. I did not run an embedded agent session.

@wenrizc wenrizc closed this Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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.

3 participants