Skip to content

refactor(agents): replace tool-loop detectors with an arguments-only repeat guard - #199591

Merged
obviyus merged 1 commit into
mainfrom
refactor/loop-guard-arguments-only
Nov 16, 2026
Merged

obviyus merged 1 commit into
mainfrom
refactor/loop-guard-arguments-only

Conversation

@obviyus

@obviyus obviyus commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The tool-loop guard was 12 files and about 1,700 lines. It hashed tool outcomes, had name checks for single tools (exec, message, wait, memory_search, computer, progress_card, write, process), and had four separate detectors plus a post-compaction guard. Rolling detection was opt-in, so most installs did not use it.

One part was always on: after 3 identical failing calls, the next identical call ended the turn. The model got no chance to answer, and the user got a stop message in place of an answer.

Fix

One guard in packages/agent-core/src/tool-repeat-guard.ts (105 lines), used by the agent loop:

  • It compares each tool call with the call before it. It compares the tool name and the canonical arguments only. It never compares outcomes.
  • 3rd identical call in a row: the call runs, and a redirect note is added to its result. The note names the tool and tells the model to change its approach.
  • 20th identical call in a row: the call does not run. The turn ends with the typed reason tool_repeat_limit and this message: OpenClaw stopped this turn: the model called <tool> with the same arguments 20 times in a row. Send a new message to continue.
  • Tools declare repeatable themselves and skip the check: Code Mode wait, process poll/log/list, agents_wait, sessions_yield, subagents list/wait, computer screenshot/wait. The declaration is plain data (true or { actions: [...] }), so it crosses the worker wire.
  • Worker turns (cloud and node workers) run the same guard over all their tools. The Gateway resolves tools.loopDetection.enabled (agent over global) into the worker tool-surface policy as toolRepeatGuard, and each tool definition carries its repeatable exemption. Two optional fields are added to the closed worker tool-surface schema (definition.repeatable, policy.toolRepeatGuard); worker bundles are build-bound to the Gateway.
  • Calls to an unknown tool are keyed by name.
  • New user input resets the streak.

Removed: outcome hashing, per-tool checks, argument churn, ping-pong, the rolling history, batch admission and recovery state, the post-compaction guard, the "3 identical failures" hard stop and its error code. Repeated identical failing calls now get the same note and cap as any other repeat.

Config:

  • tools.loopDetection.enabled stays. false turns the guard off. Unset or true keeps it on. This also folds the rolling detection that was opt-in into the one default rule.
  • The Codex appServer.loopDetectionPreToolUseRelay key is retired. openclaw doctor --fix removes it.
  • The tool.loop diagnostic event stays, with detector: "tool_repeat".

Proof

Check Tier Base (5d5ca9d2) Head (ecb05477)
Unit: note at 3rd identical call, stop at 20th with tool_repeat_limit, repeatable tools skip, unknown tool keyed by name, guard off when disabled (tool-repeat-guard.test.ts) vitest-source n/a (new) 10/10 pass
Regression: 4 identical failing calls, then the model answers vitest-source fails: turn ends after 3 failures, no answer pass
Real Gateway, mock model repeats one failing read (tool-loop-global-breaker, step 1) dist-nodts fails: Gateway logs OpenClaw stopped this turn: the same read call failed 3 times, run ends in error with no answer pass: note on 3rd read, model recovers with its final answer
Real Gateway, mock model ignores the note (step 2) dist-nodts n/a pass: exactly 20 reads, 20th not run, user sees the tool_repeat_limit message
Regression: worker turn with loop detection on, progress_card called 3 times with {"markdown":"Still working"} gets the redirect note on the 3rd result; with tools.loopDetection.enabled: false it gets none (worker.runtime.test.ts, real worker runtime + fake Gateway) vitest-source fails on a3f26f46 (worker forced enabled: false) pass
Gateway policy: toolRepeatGuard: false only when loop detection is off; agent setting overrides global (prepared-tool-surface.test.ts) vitest-source n/a (new) pass
Upgrade: config written by latest stable 2026.11.3 (tools.loopDetection.enabled, Codex appServer.loopDetectionPreToolUseRelay + requestTimeoutMs) plus the old sub-keys (windowSize, historySize, warningThreshold, criticalThreshold, globalCircuitBreakerThreshold, detectors, postCompactionGuard, which stable already rejects, as left by older releases); stable Gateway runs turn 1 on a mock model; head openclaw doctor --fix; head Gateway starts and runs turns 2 and 3 on the same session (fresh HOME, throwaway ports) ocx src pass: doctor removes every retired key and keeps enabled and requestTimeoutMs; head Gateway starts on the migrated config; turn 2 answers; turn 3's provider request contains turn 1's reply, so the session survives
CI checks-node-changed-compact-large-41: code-mode-engine-parity.test.ts "continues immediate required replies without serializing retained guest state" (['exec','resume'] vs ['exec']) vitest-source fails 2/2 on merge base db05f080; still red on rebased base (ocx base merge-base --src) fails 3/3, same assertion: inherited, not caused by this PR
CI checks-node-changed-compact-large-13: openclaw-tools.sessions-send-child-coordination.test.ts "retains only the live requester's required delivered witness" (expected { …(4) } to not have property "error") vitest-source fails on merge base b237d3e5 (ocx base merge-base --src) fails, same assertion: inherited, not caused by this PR
packages/agent-core vitest-source 29 files, 343 tests pass
51 touched unit test files + 2 before-tool-call e2e files vitest-source pass
pnpm check:test-types, pnpm tsgo:scripts, tsgo:core, tsgo:extensions type pass
ocx build --dts + packed tarball (check-openclaw-package-tarball) full pass; guard in package, old symbols absent
rg for every removed symbol across src/ scripts/ test/ extensions/ packages/ static 0 hits

Net lines

209 files changed, 1275 insertions(+), 9989 deletions(-) (net -8,714)

  • Source: +815 / -3,585 (net -2,770; includes the regenerated predicates.js validator)
  • Tests: +391 / -6,198 (net -5,807)
  • Docs: +69 / -206 (net -137)

@clawsweeper

clawsweeper Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: diagnostics-otel Extension: diagnostics-otel scripts Repository scripts docker Docker and sandbox tooling agents Agent runtime and tooling extensions: qa-lab extensions: codex labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces outcome-based loop detection with one shared guard that warns on the third identical consecutive tool call and stops the twentieth.

Example: A model calls read with {"path":"LOOP_MISSING.txt"} four times, then answers.

  • Before: The third identical failure quarantines the action, and the unchanged fourth attempt ends the turn.
  • After: The third result includes a redirect note, the fourth attempt runs, and the model can answer.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, coherent simplification with production-entry-point and upgrade evidence, no blocking finding, and one low-value added test.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied evidence exercises the production Gateway and provider transport with deterministic repeated-read responses, showing recovery and the terminal cap; a latest-stable upgrade preserves unrelated config and session history.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: An unchanged retry after repeated tool failures can end the turn before the model produces its eventual answer.
Reason: The maintainer-authored proposal explicitly accepts a simpler protection policy and removes substantial outcome-specific machinery while retaining bounded repetition.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR makes a deliberate, useful simplification, and no blocking correctness defect was identified; current-head CI remains in progress.

Priority: P2
Reviewed head: ecb054779a07b1892c8311e51e29039c2bfdec28

Before merge

None.

Findings

None.

Tests

  • Low-value test src/agents/bash-tools.process.poll-timeout.test.ts: Remove the added declaration-only test: it asserts a fixed repeatable metadata object without exercising process calls through the guard.
Agent review details

How this fits together

The agent loop receives model-authored tool calls, applies repeat policy before execution, and publishes tool results or a typed terminal response; Gateway preparation supplies equivalent policy to workers.

flowchart TD
  A[Model tool calls] --> B[Shared repeat guard]
  C[Gateway policy and tool metadata] --> B
  C --> D[Worker agent loop]
  D --> B
  B --> E[Tool execution]
  E --> F[Results and redirect note]
  B --> G[Typed turn stop]
Loading

Technical review

Best possible solution:

Use the shared agent-loop guard with tool-owned exemptions, consistent worker policy, and Doctor migration for the retired Codex setting.

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

Current-main source shows the third-failure quarantine and unchanged-retry termination, and the PR records a before/after Gateway reproduction; this review executed no target code.

Is this the best way to solve the issue?

The shared guard is a coherent implementation of the approved simplification: it removes competing detectors while preserving ordinary authorization, ordered settlement, worker policy, and actionable terminal output.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Rolling and outcome-based loop detection changes intended behavior with a stated reason (feat: add stuck loop detection and exponential backoff infrastructure for agent polling #17118: Bound runaway polling and resource consumption; later changes distinguished actual progress from volatile result metadata.)
  • Identical-failure quarantine and recovery changes intended behavior with a stated reason (fix(agents): allow bounded recovery after repeated identical tool errors #186853: Let the model replan after three identical failures while blocking the quarantined action and retaining one shared recovery allowance.)
  • Post-compaction guard changes intended behavior with a stated reason (2a702f9: Stop repeated identical outcomes after compaction fails to break a loop; this PR explicitly removes that separate policy.)
  • Config enable semantics changes intended behavior with a stated reason (076df94: Make rolling loop detection configurable; the proposal deliberately repurposes the retained switch for the default-enabled shared guard.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduction: The reviewed edits are the verified merge-base-to-head change; collaborator authorship supplies the direction decision and independently prevents closure. (ecb054779a07)
  • Single repeat owner: The guard compares canonical arguments, handles unavailable tools by name, honors repeatable declarations, and produces the documented note and stop thresholds. (packages/agent-core/src/tool-repeat-guard.ts:45, ecb054779a07)
  • Earlier worker findings addressed: Gateway preparation projects plain-data repeatable declarations and the resolved opt-out; worker session creation installs that policy, addressing the previous worker-protection and configuration findings. (src/worker/embedded-agent.runtime.ts:359, ecb054779a07)
  • Config migration and upgrade evidence: The Codex Doctor contract removes only appServer.loopDetectionPreToolUseRelay; the PR records a v2026.11.3 upgrade preserving enabled, requestTimeoutMs, and the existing session across subsequent Gateway turns. (extensions/codex/doctor-contract-api.ts:186, ecb054779a07)
  • Production entry-point proof: The PR records real Gateway runs using the mock-openai transport: repeated failed reads recover after the third-result note, while an uncooperative model reaches the twentieth-call stop and visible recovery message. (qa/scenarios/runtime/tool-loop-global-breaker.yaml:1, ecb054779a07)
  • Current main retains the replaced behavior: Current main still implements outcome-based failure quarantine, rolling detectors, and post-compaction protection; the proposed shared guard is not already implemented there. (src/agents/tool-loop-detection.ts:449, c3653666d673)

PR surface

PR surface statistics unavailable: the file list is incomplete.

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Configuration and worker contract 0 new user config keys; 1 retired Codex key; 2 optional worker fields The existing enable switch changes default semantics, while repeatable metadata and resolved worker policy cross the closed worker schema.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.

Label justifications:

  • P2: This improves repeated-tool recovery and simplifies runtime policy without evidence of an urgent widespread outage.
  • merge-risk: 🚨 compatibility: The PR deliberately changes default protection, removes older detector behavior, adds optional tool metadata, and retires a Codex config key; its maintainer-authored direction and recorded upgrade proof address the tradeoff.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (7 earlier review cycles)
  • reviewed 2026-11-15T12:18:46.941Z sha 50bf6f8 :: blocked before merge. :: [P1] [P1] Keep runtime repeatability metadata out of the worker wire projection | [P2] [P2] Propagate the configured repeat-guard opt-out to workers
  • reviewed 2026-11-15T13:54:45.194Z sha 5c4734e :: blocked before merge. :: [P2] [P2] Preserve enabled repetition protection on worker turns
  • reviewed 2026-11-15T14:10:46.120Z sha cec65b7 :: blocked before merge. :: [P2] [P2] Preserve enabled repetition protection on worker turns
  • reviewed 2026-11-15T14:50:08.732Z sha a3f26f4 :: blocked before merge. :: [P2] [P2] Preserve enabled repetition protection on worker turns
  • reviewed 2026-11-15T16:04:11.589Z sha f0fc19a :: needs changes before merge. :: none
  • reviewed 2026-11-15T16:12:50.756Z sha 0f936b9 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-15T16:53:45.168Z sha fc644e2 :: needs maintainer review before merge. :: none

Reviewed November 15, 2026, 10:46 PM ET / November 16, 2026, 03:46 UTC (Revision 8).

@obviyus
obviyus force-pushed the refactor/loop-guard-arguments-only branch from 50bf6f8 to 5c4734e Compare November 15, 2026 13:47
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 16, 2026
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: two required jobs are red on head ecb054779a07. This PR does not cause either failure.

  • check-lint-core-2 fails with one oxlint error: src/agents/tool-search-prepared-catalog.ts:118 unicorn(prefer-structured-clone). That line comes from fix(agents): snapshot shareable MCP catalog metadata as JSON #199909 (f4d2e455), which is already on main. This PR does not change the file. oxlint on that file reports the same error on merge base 8862ffc7.
  • checks-node-changed-extensions-bundle-6 fails in extensions/codex/src/app-server/run-attempt.context-engine.test.ts:631 ("persists the admitted u…": expected "vi.fn()" to not be called at all, but actually been called 1 times). ocx test fails 2/2 the same way on merge base 8862ffc7.

The first run also showed checks-fast-baseline-ratchets (runner lost its log), checks-ui-e2e (2/5) and checks-node-changed-compact-large-13. All three pass after one gh run rerun --failed. All other required checks passed. ClawSweeper rates this exact head ready.

@obviyus
obviyus merged commit 3a3eed8 into main Nov 16, 2026
359 of 370 checks passed
@obviyus
obviyus deleted the refactor/loop-guard-arguments-only branch November 16, 2026 04:59
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 3a3eed8.

  • Bug: after 3 identical failing tool calls, the next one ended the turn, so the user got a stop message instead of an answer. Worker turns had no repeat protection at all.
  • Fix: one arguments-only repeat guard for local and worker turns. It adds a redirect note on the 3rd identical call and ends the turn with tool_repeat_limit on the 20th. Polling tools declare repeatable. tools.loopDetection.enabled: false turns it off. About 8,700 lines of outcome-based detectors are removed.
  • Proof: regression tests fail on the base and pass on the head (failing-call recovery and worker progress_card repeats). Real-Gateway mock-model runs cover recovery and the 20-call cap. A config created by 2026.11.3 with the retired keys loads after openclaw doctor --fix, and the session carries on through a head Gateway turn.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…repeat guard (openclaw#199591)

## Problem

The tool-loop guard was 12 files and about 1,700 lines. It hashed tool outcomes, had name checks for single tools (exec, message, wait, memory_search, computer, progress_card, write, process), and had four separate detectors plus a post-compaction guard. Rolling detection was opt-in, so most installs did not use it.

One part was always on: after 3 identical failing calls, the next identical call ended the turn. The model got no chance to answer, and the user got a stop message in place of an answer.

## Fix

One guard in `packages/agent-core/src/tool-repeat-guard.ts` (105 lines), used by the agent loop:

- It compares each tool call with the call before it. It compares the tool name and the canonical arguments only. It never compares outcomes.
- 3rd identical call in a row: the call runs, and a redirect note is added to its result. The note names the tool and tells the model to change its approach.
- 20th identical call in a row: the call does not run. The turn ends with the typed reason `tool_repeat_limit` and this message: `OpenClaw stopped this turn: the model called <tool> with the same arguments 20 times in a row. Send a new message to continue.`
- Tools declare `repeatable` themselves and skip the check: Code Mode `wait`, `process` poll/log/list, `agents_wait`, `sessions_yield`, `subagents` list/wait, `computer` screenshot/wait. The declaration is plain data (`true` or `{ actions: [...] }`), so it crosses the worker wire.
- Worker turns (cloud and node workers) run the same guard over all their tools. The Gateway resolves `tools.loopDetection.enabled` (agent over global) into the worker tool-surface policy as `toolRepeatGuard`, and each tool definition carries its `repeatable` exemption. Two optional fields are added to the closed worker tool-surface schema (`definition.repeatable`, `policy.toolRepeatGuard`); worker bundles are build-bound to the Gateway.
- Calls to an unknown tool are keyed by name.
- New user input resets the streak.

Removed: outcome hashing, per-tool checks, argument churn, ping-pong, the rolling history, batch admission and recovery state, the post-compaction guard, the "3 identical failures" hard stop and its error code. Repeated identical failing calls now get the same note and cap as any other repeat.

Config:

- `tools.loopDetection.enabled` stays. `false` turns the guard off. Unset or `true` keeps it on. This also folds the rolling detection that was opt-in into the one default rule.
- The Codex `appServer.loopDetectionPreToolUseRelay` key is retired. `openclaw doctor --fix` removes it.
- The `tool.loop` diagnostic event stays, with `detector: "tool_repeat"`.

## User impact

- A model that repeats a failing call now gets a note and can still answer, instead of the turn ending after 3 failures.
- A model stuck on one call is stopped after 20 identical calls with a clear message, on local and worker turns alike.
- `tools.loopDetection.enabled: false` still turns the guard off. Existing configs keep loading; `openclaw doctor --fix` removes the retired keys.

## Proof

| Check | Tier | Base (`5a640d63`) | Head (`ecb05477`) |
|---|---|---|---|
| Unit: note at 3rd identical call, stop at 20th with `tool_repeat_limit`, repeatable tools skip, unknown tool keyed by name, guard off when disabled (`tool-repeat-guard.test.ts`) | vitest-source | n/a (new) | 10/10 pass |
| Regression: 4 identical failing calls, then the model answers | vitest-source | **fails**: turn ends after 3 failures, no answer | pass |
| Real Gateway, mock model repeats one failing read (`tool-loop-global-breaker`, step 1) | dist-nodts | **fails**: Gateway logs `OpenClaw stopped this turn: the same read call failed 3 times`, run ends in error with no answer | pass: note on 3rd read, model recovers with its final answer |
| Real Gateway, mock model ignores the note (step 2) | dist-nodts | n/a | pass: exactly 20 reads, 20th not run, user sees the `tool_repeat_limit` message |
| Regression: worker turn with loop detection on, `progress_card` called 3 times with `{"markdown":"Still working"}` gets the redirect note on the 3rd result; with `tools.loopDetection.enabled: false` it gets none (`worker.runtime.test.ts`, real worker runtime + fake Gateway) | vitest-source | **fails** on `a3f26f46` (worker forced `enabled: false`) | pass |
| Gateway policy: `toolRepeatGuard: false` only when loop detection is off; agent setting overrides global (`prepared-tool-surface.test.ts`) | vitest-source | n/a (new) | pass |
| Upgrade: config written by latest stable `2026.11.3` (`tools.loopDetection.enabled`, Codex `appServer.loopDetectionPreToolUseRelay` + `requestTimeoutMs`) plus the old sub-keys (`windowSize`, `historySize`, `warningThreshold`, `criticalThreshold`, `globalCircuitBreakerThreshold`, `detectors`, `postCompactionGuard`, which stable already rejects, as left by older releases); stable Gateway runs turn 1 on a mock model; head `openclaw doctor --fix`; head Gateway starts and runs turns 2 and 3 on the same session (fresh HOME, throwaway ports) | source CLI | | pass: doctor removes every retired key and keeps `enabled` and `requestTimeoutMs`; head Gateway starts on the migrated config; turn 2 answers; turn 3's provider request contains turn 1's reply, so the session survives |
| `packages/agent-core` | vitest-source | | 29 files, 343 tests pass |
| 51 touched unit test files + 2 before-tool-call e2e files | vitest-source | | pass |
| `pnpm check:test-types`, `pnpm tsgo:scripts`, `tsgo:core`, `tsgo:extensions` | type | | pass |
| Full build with declarations + packed tarball check | full | | pass; guard in package, old symbols absent |
| `rg` for every removed symbol across `src/ scripts/ test/ extensions/ packages/` | static | | 0 hits |

## Net lines

`209 files changed, 1275 insertions(+), 9989 deletions(-)` (net -8,714)

- Source: +815 / -3,585 (net -2,770; includes the regenerated `predicates.js` validator)
- Tests: +391 / -6,198 (net -5,807)
- Docs: +69 / -206 (net -137)

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa pushed a commit that referenced this pull request Nov 17, 2026
…ns start at once (#192534)

## What Problem This Solves

Fixes: a Gateway using the Claude CLI runtime can push its host into memory exhaustion when several conversations start new Claude processes close together.

On an 8 GB Linux VM without swap, several Slack/Teams turns arrived within about 3 minutes. The Gateway went from 3 to 7 warm Claude CLI processes, available memory fell from ~3.8 GB to ~250 MB and stayed there, and the VM thrashed (no OOM kill, CPU ~5%) until a reboot about 2 hours later. The only limit on warm processes was a fixed count of 16; idle warm processes were kept even while the host ran out of memory.

## User Impact

User impact: when host memory is low, a new Claude CLI conversation first closes idle warm processes (least recently used first). If memory is still low and every warm process is busy, that turn fails over instead of starting another process, and a channel reply says: "⚠️ This host is low on memory, so it could not start another session. Try again after active conversations finish." (Before, any such failure would have shown the generic "AI service needs a short break" rate-limit copy.) Hosts with enough free memory behave as before; turns that reuse their own warm process are unaffected; busy turns are never closed.

## Why This Change Was Made

Before a turn starts a new warm process, the live-session registry reads host free memory through the existing `readHostFreeMemoryBytes()` helper (`os.freemem()`, which is `MemAvailable` on Linux; `process.availableMemory()` on macOS). It walks the warm processes once in least-recently-used order: while memory is below 1 GiB, it closes each idle process and waits for it to exit before the next reading. If memory is still below the floor after that pass, the turn fails over with the `rate_limit` category the 16-session cap already uses, plus a distinct `cli_live_session_host_memory` code. The existing failover-code copy (`renderFailoverCodeUserCopy`) owns its user text, and the rate-limit reply renderer now returns a host-authored code's copy before generic rate-limit text (auth-profile cooldown keeps its expiry-aware copy). The registry map is now kept in least-recently-used order, so both the memory path and the existing count cap close the conversation that has waited longest.

The 1 GiB floor comes from measurements of one warm session:

| Measurement | RSS |
| --- | --- |
| Claude Code 2.1.314, Linux arm64 container, stream-json, idle after start | ~180 MiB |
| Same, after one Haiku turn / three concurrent Sonnet turns | ~195–198 MiB each |
| Full warm session under a Gateway (macOS): Claude Code + two Node supervisor helpers | ~490 MiB (264 + 138 + 87) |

1 GiB leaves room for about two more warm sessions before the kernel has to reclaim. The 16-session cap stays as the upper bound. No config key is added.

## Evidence

- Two `executePluginOwnedProcess` tests (an entry point on both `main` and this branch), with host memory simulated at `readHostFreeMemoryBytes`:
  - Low memory, new conversation: the least recently used idle process closes; the busy one and the recently used one stay. On `main` this fails on behavior (`recent.close` not called).
  - Low memory, only a busy process: the turn rejects with `rate_limit` / `cli_live_session_host_memory` before the plugin runs, the busy process stays, and `resolveReplyFailureSummary` returns the host-memory copy. On `main` this fails on behavior (the turn runs: `reason: "exit"`).
- `src/agents/cli-runner/`, `extensions/anthropic`, and the CLI attempt-execution tests: 1479 passed on the candidate; the registry and `execute-plugin` tests pass on the exact head (108). One failure, `extensions/anthropic/session-catalog.test.ts` ("reports the discovery frontier…"), also fails alone on this host and does not touch the changed files.
- Real path on the previous head `a646b6b8` (the repair batch after it adds the failover code and copy and makes eviction one bounded pass; the tests above cover both): isolated Gateway (own state, config and Claude config dir, test API key from env only), `anthropic/claude-haiku-4-5` with `agentRuntime.id: "claude-cli"`, turns sent with `openclaw agent`. Memory pressure was simulated at the same seam the code reads (`os.freemem` / `process.availableMemory`), with each live Claude process under the Gateway counted as 700 MiB, so closing a process really raises the reading.
  - Real memory: 4 concurrent sessions start (`activeSessions=1…4`), no closures.
  - Low memory, new 5th session: `free-memory read: live claude processes=4 reported=424MiB` → `memory pressure: closing idle session activeSessions=4` → `processes=3 reported=1124MiB` → `cli live session start … activeSessions=4`; the turn replied.
  - Low memory, existing session: reused its warm process, no memory read, no closure; replied.
  - Low memory, all four warm sessions busy with long turns, new session: failed over in 54 ms (`Host memory is too low for another CLI live session.`); all four busy turns completed.

## Limits

- Admission only. A warm process that grows during a long turn after it started is not limited here.
- `readHostFreeMemoryBytes()` reads host memory on Linux, not a container cgroup limit; that helper is shared and unchanged.
- Turns that start at the same instant can each read the same free-memory value before any process exists; the floor's headroom covers a small burst, and the 16-session cap still holds.
- The failover category stays `rate_limit`, as the existing count cap uses; the distinct code carries the cause.
- The live check ran on macOS with a simulated reading; the Linux numbers come from an isolated Claude Code container run.

## Merge danger

Two-way door: a revert restores the previous behavior. No config, schema, stored state or published contract changes.

Blast radius: Gateways using a CLI runtime with warm live sessions (today Claude CLI). If the floor is wrong for a host, the effect is more closed idle sessions (a cold start on the next turn) or a failover when memory is below 1 GiB and every warm session is busy. Other runtimes and channels are not affected.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit de07e00)

Release adaptation: revalidate the existing current-run authority between awaited idle-process cleanup and before capability creation; use the abort-race lazy factory so an already-aborted request starts no close. Preserve baseline cleanup-finally repair. Add one execution-boundary regression for revoked requester authority; no unrelated follow-ups.

# #192534 companion dispositions

Signed baseline e13cf15; audit bd692e9. Working base 8b3ca5d lacks the memory floor and activation LRU refresh; 16-count limit exists. Mechanical probe: clean, six touched files. Exact merged source de07e00.

Later same-path commits, each reviewed in saved relevant-followups.patch / other-followups.patch:
- 30e9d3e #200073: not-applicable, listed model chat rejection code/copy independent of host memory.
- 3a3eed8 #199591: not-applicable, tool loop policy refactor independent of memory admission.
- 8fc58f8 #199226: not-applicable, app naming copy independent of memory.
- 8ccba17 #198426: not-applicable to this admission change, warm callback async-context repair independent; do not silently absorb. Existing requestToolPermission is bound; no callback change required by memory.
- 2110db5 #198288: not-applicable, model chat eligibility and code/copy independent.
- 4527846 #198324: not-applicable, provider rate-limit reset deadlines; host-local memory refusal has no provider deadline.
- 4f8df80 #198224: present-equivalent, baseline registry remove already uses finally and releases retired map after failed cleanup.
- 8cd7d87 #197655: not-applicable, main test allocation pruning; retain this release allocation.
- 5dc6683 #197163: present-equivalent, buildHarnessHostRequester used in baseline; separate tool hook metadata.
- 7786960 #197051: not-applicable, managed WebSearch availability, independent tool policy.
- ac7e941 #196677: not-applicable, expired API-key copy independent of host admission.
- 4d6205c #194439: not-applicable, provider failure/tool warning handling independent of pre-execution host refusal.
- 4845a0f #193508: not-applicable, native credential removal propagation; no new credentials accessed by memory policy. Existing live assertion retained/rechecked.
- 6f69195 #193250: not-applicable, exhausted upstream credit failover category independent of local resource refusal.
No later #192534 mentions.

Prerequisites: readHostFreeMemoryBytes exists unchanged in baseline; @openclaw/retry abort race accepts lazy factory; createCliFailoverError preserves explicit code; FailoverError carries code; existing rate-limit reply renderer consumes it; registry closeRecord joins process exit and owned cleanup. These are present-equivalent.

Neighbor tests: cli-live-session-registry.test.ts, execute-plugin.test.ts, execute-plugin.policy.test.ts, execute-plugin.steering.test.ts, failover/user-copy.test.ts are existing consumers, not missing implementation companions. execute-plugin.warm-context.test.ts exists only after the independent #198426 change and is not applicable to this baseline or memory fix. Run focused registry/execution/copy siblings. Selected-file references: broad generic filename inventory is mostly incidental error/execute references; traced actual owners/imports above. Docs and allocation are non-runtime references; no generated exports or workflow changes needed.

Focused proof: baseline 2 failed/36 passed (LRU eviction missing; busy-only admission incorrectly exits successfully). Green 135 passed across five existing owner/consumer files, including host-memory failure copy and revoked-requester preservation. Format and diff checks clean. Type-aware lint blocked by the established shared TypeScript declaration-confinement boundary; no bypass/install. Parent owns integration and broad release qualification.

Co-authored-by: RomneyDa <[email protected]>

Parent qualification: corrected the authority regression's required braces and matching test allocation (102 lines); no production change from worker. Combined 145/145 tests across seven files passed; post-braces changed suite 39/39 passed. Supported parent type-aware lint and formatting passed six files, executable syntax and diff checks passed. Worker dependency-layout lint limitation resolved. Parent self-review and source/companion comparison recorded in cli-resources-parent-review.md. Full stable/FRV remains pending; publication held.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: codex extensions: diagnostics-otel Extension: diagnostics-otel extensions: qa-lab gateway Gateway runtime 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. scripts Repository scripts size: XL 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