Skip to content

fix(agent-core): bound runaway loops with turn/error-batch/idle-repeat guards (#120962) - #121063

Closed
Papilionidae wants to merge 1 commit into
openclaw:mainfrom
Papilionidae:fix/br-120962
Closed

Papilionidae wants to merge 1 commit into
openclaw:mainfrom
Papilionidae:fix/br-120962

Conversation

@Papilionidae

@Papilionidae Papilionidae commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #120962

[AI-assisted]

What Problem This Solves

Fixes an issue where a worker agent could enter an unbounded retry loop inside the native runLoop: an external service returning HTTP 429 (masked inside a "successful" tool output) drove 219 assistant turns / 177 tool calls / ~15M tokens over 6h42m, stopped only by the global stuckSessionAbortMs timeout rather than by any active guardrail.

Why This Change Was Made

Adds three opt-in hard cutoffs to the agent-core runLoop, each activating independently when set to a positive integer in tools.loopDetection:

  • turnLimit — max assistant turns per run; ends gracefully with a terminal message instead of another provider request.
  • maxConsecutiveErrorBatches — max consecutive all-error tool batches; any success resets the streak.
  • maxIdleRepeatCalls — max consecutive identical tool calls (same name + args); catches errors hidden inside successful output. Steering-skipped calls are excluded.

enabled: true alone does not engage hard cutoffs (preserves upgrade contract). enabled: false disables both layers. Resolved config propagates through sessions, compaction, and worker launch descriptors. The launcher fences guard-enabled turns on worker bundles lacking the worker-loop-guard-v1 capability; configless and enabled:false turns are unaffected.

User Impact

Operators who want the guardrails set at least one guard key (e.g. turnLimit: 200) in a tools.loopDetection block. Existing configurations gain no new hard termination behavior unless a guard key is explicitly set. Public package consumers see no change unless they opt in.

Evidence

image

Focused tests (all pass):

  • packages/agent-core/src/agent-loop.guard.test.ts — 23 tests: maxTurns, error-batch, idle-repeat, steering-skip exclusion (sequential + parallel), steering requeue
  • src/agents/sessions/agent-session-loop-guard-transport.test.ts — real AgentSession through local HTTP/SSE transport, 3 repeated calls → graceful termination, no 4th request
  • src/agents/tool-loop-detection-config.test.ts — 9 tests: per-key activation, enabled:false kill switch, per-agent cascade
  • src/gateway/worker-environments/worker-turn-launcher.loop-guard.test.ts — 6 tests: launcher fence, serialization, guard-off compatibility
  • packages/gateway-protocol/src/schema/worker-admission.test.ts — 25 tests: loop-guard capability in worker protocol features

@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Aug 9, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. 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 9, 2026
@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR adds opt-in limits on assistant turns, consecutive all-error tool batches, and repeated tool calls across native sessions and remote workers.

Example: An operator sets maxIdleRepeatCalls to 3, and query_mam_status repeatedly returns HTTP 429 inside successful tool output.

  • Before: Without enabled rolling detection, identical successful-looking calls can continue until another termination condition occurs.
  • After: The proposed guard stops after three repeated decisions and emits a terminal assistant message.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Meaningful harness coverage supports the idea, but unchanged correctness findings and unresolved product direction prevent readiness; latest-stable upgrade compatibility is not demonstrated.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 5 actionable review findings remain.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A background agent can repeatedly retry an action whose successful-looking output contains a service failure, consuming time and tokens.
Reason: The problem has value, but three new tuning settings and argument-only cutoffs are a product choice beyond the existing detection contract.

Merge readiness

⛔ Blocked before merge - 10 items remain

Keep open: this PR contains distinct, maintainer-engaged work that current main does not fully replace, but five previously reported defects remain.

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

Decision needed

  • Question: Should OpenClaw add these three opt-in numeric hard budgets, or address demonstrated successful-output loops through the existing outcome-aware protection?
  • Recommendation: Extend existing outcome-aware protection: Establish the masked-429 failure at the native runner boundary and repair the existing protection while preserving useful polling.
  • Why: Current main deliberately limits configuration surface and now has narrower always-on error protection; the member clarification establishes distinct scope without approving new settings or argument-only termination.

Before merge

  • Add real behavior proof - The inspected screenshot and discussion show passing Vitest runs, including a real AgentSession using a real HTTP client against a simulated SSE upstream, but no recorded request/response trace or shipped-flow output demonstrates the changed cutoffs and remote-worker path; provide redacted terminal output or logs showing those outcomes, removing IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Restore drained follow-ups to exactly one queue (P1) - With maxTurns=1, let the first response stop naturally while a follow-up is queued. The outer loop drains that follow-up into pendingMessages before the next limit check. This callback prepends it to steeringQueue but removes it only from steeringQueue.inFlight; its original followUpQueue.inFlight entry survives and finishRun restores it too. Continuing can therefore process the same user request twice. Restore it through its original queue or transfer ownership out of both queues exactly once.
  • Count streamed tool-call prefixes in idle repeats (P2) - When an async tool call executes from toolcall_end, streamAgentResponse commits its prefix and removes it from the returned terminal fragment. Scanning only message.content therefore misses those executed calls. A provider repeatedly streaming the same async call followed by a text-only terminal fragment never advances maxIdleRepeatCalls. Count executed calls across the complete provider response, retaining the existing per-response deduplication and steering exclusions.
  • Exclude skipped-only fragments from error aggregation (P2) - A streamed response can contain an executed failing prefix followed by a separate fragment whose calls are all skipped by steering. allErrorOfBatch correctly returns false for that skipped-only fragment, but batches.every then treats it as a successful fragment and resets the consecutive-error counter. Repeating this shape prevents the configured breaker from firing despite every executed call failing. Aggregate non-skipped finalized outcomes across the response before deciding whether the batch was all-error.
  • Document activation when enabled is omitted (P2) - The resolver activates turnLimit:1 even when enabled is omitted, and the new resolver test explicitly requires that behavior. This paragraph instead promises every guard remains off when enabled is unset, contradicting the activation rule immediately above it. An operator following that statement can unexpectedly terminate a run after its first tool turn. Correct the equivalent claims throughout both documentation pages to say only explicit enabled:false disables configured guards.
  • Remove the unused worker supervisor import (P2) - getProcessSupervisor is newly imported but never referenced in this module. The production tsconfig enables noUnusedLocals and includes this file, so this introduces an unused-import compiler diagnostic; the configured lint rule also rejects unused variables. Remove the import. This source-level defect is independently verified, although the blocked CI logs do not establish which failed job reported it.
  • Complete next step - Resolve the GitHub-reported merge conflict while preserving current-main loop protections.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Queued input lifecycle - unknown: The original base explicitly retains drained messages in their queue until message_end commits them and restores uncommitted input at teardown; broader historical blame encountered unavailable old blobs.

Findings

  • [P1] Restore drained follow-ups to exactly one queue — packages/agent-core/src/agent.ts:672-674
  • [P2] Count streamed tool-call prefixes in idle repeats — packages/agent-core/src/agent-loop.ts:430-435
  • [P2] Exclude skipped-only fragments from error aggregation — packages/agent-core/src/agent-loop.ts:605

Provenance

  • Queued input lifecycle changes intended behavior without addressing why it exists (unknown: The original base explicitly retains drained messages in their queue until message_end commits them and restores uncommitted input at teardown; broader historical blame encountered unavailable old blobs.)

Tests

  • Missing end-to-end proof: Supply observable native-session and worker traces for configured cutoffs, queued-input preservation, and legacy-worker behavior, including a latest-stable upgrade with settings intact; base-failing regression evidence is not shown.
Agent review details

How this fits together

Agent-core drives provider responses and tool execution; resolved operator settings enter through session factories or worker launch assignments, and guard termination leaves transcript events and a user-visible message.

flowchart TD
  A[Operator configuration] --> B[Loop configuration resolver]
  B --> C[Native session factory]
  B --> D[Worker capability fence]
  D --> E[Worker launch assignment]
  E --> C
  C --> F[Agent core run loop]
  F --> G[Transcript and terminal message]
Loading

Technical review

Best possible solution:

Have the loop-policy owner choose the remaining cutoff contract, then implement it through existing loop and queue owners with correct streamed-response accounting.

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

Source establishes the missing general budgets and the introduced queue/accounting failures; no current-main execution of the historical masked-429 incident was performed.

Is this the best way to solve the issue?

Hard budgets can bound work, but the new policy needs owner sponsorship and the implementation must preserve single queue ownership and account for all streamed tool fragments.

Full review comments:

  • [P1] Restore drained follow-ups to exactly one queue — packages/agent-core/src/agent.ts:672-674
    With maxTurns=1, let the first response stop naturally while a follow-up is queued. The outer loop drains that follow-up into pendingMessages before the next limit check. This callback prepends it to steeringQueue but removes it only from steeringQueue.inFlight; its original followUpQueue.inFlight entry survives and finishRun restores it too. Continuing can therefore process the same user request twice. Restore it through its original queue or transfer ownership out of both queues exactly once.
    Confidence: 0.99
  • [P2] Count streamed tool-call prefixes in idle repeats — packages/agent-core/src/agent-loop.ts:430-435
    When an async tool call executes from toolcall_end, streamAgentResponse commits its prefix and removes it from the returned terminal fragment. Scanning only message.content therefore misses those executed calls. A provider repeatedly streaming the same async call followed by a text-only terminal fragment never advances maxIdleRepeatCalls. Count executed calls across the complete provider response, retaining the existing per-response deduplication and steering exclusions.
    Confidence: 0.99
  • [P2] Exclude skipped-only fragments from error aggregation — packages/agent-core/src/agent-loop.ts:605
    A streamed response can contain an executed failing prefix followed by a separate fragment whose calls are all skipped by steering. allErrorOfBatch correctly returns false for that skipped-only fragment, but batches.every then treats it as a successful fragment and resets the consecutive-error counter. Repeating this shape prevents the configured breaker from firing despite every executed call failing. Aggregate non-skipped finalized outcomes across the response before deciding whether the batch was all-error.
    Confidence: 0.97
  • [P2] Document activation when enabled is omitted — docs/tools/loop-detection.md:133-135
    The resolver activates turnLimit:1 even when enabled is omitted, and the new resolver test explicitly requires that behavior. This paragraph instead promises every guard remains off when enabled is unset, contradicting the activation rule immediately above it. An operator following that statement can unexpectedly terminate a run after its first tool turn. Correct the equivalent claims throughout both documentation pages to say only explicit enabled:false disables configured guards.
    Confidence: 0.99
  • [P2] Remove the unused worker supervisor import — src/worker/embedded-agent.runtime.ts:38
    getProcessSupervisor is newly imported but never referenced in this module. The production tsconfig enables noUnusedLocals and includes this file, so this introduces an unused-import compiler diagnostic; the configured lint rule also rejects unused variables. Remove the import. This source-level defect is independently verified, although the blocked CI logs do not establish which failed job reported it.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Critical-loop recovery keeps the original intent (1f10ef8: Allow one bounded recovery after a critical tool denial, then terminate a second critical loop without removing normal tools.)
  • Loop configuration surface changes intended behavior with a stated reason (783a5d2: Remove internal numeric tuning knobs to reduce configuration and compatibility burden; this PR explains distinct opt-in budgets for runaway work but lacks an owner decision.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit a637374 adds packages/agent-core/src/agent-loop.ts:13 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a637374e4352; files: packages/agent-core/src/agent-loop.ts)
  • Onur Solmaz: Raw commit 1f10ef8 adds packages/agent-core/src/agent-loop.ts:417 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1f10ef8050a9; files: packages/agent-core/src/agent-loop.ts)

PR surface

Source +676, Tests +2476, Docs +136, Generated 0. Total +3288 across 43 files. Added test files: 7.

View PR surface stats
Area Files Added Removed Net
Source 22 685 9 +676
Tests 17 2490 14 +2476
Docs 2 156 20 +136
Config 0 0 0 0
Generated 2 3 3 0
Other 0 0 0 0
Total 43 3334 46 +3288

Review metrics

Metric Value Why it matters
New configuration surface 3 numeric limits, each global and per-agent Adds six configurable paths plus optional worker launch transport for their resolved values.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #120962
Summary: This PR explicitly implements the three-cutoff request; merged comparison-identity and identical-error fixes cover narrower behavior.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Useful runaway-execution protection remains distinct, but it is optional new policy with bounded implementation defects rather than a demonstrated urgent current-main regression.
  • merge-risk: 🚨 compatibility: Adds public configuration and worker launch fields, including rejection and reprovisioning for guard-enabled turns on older worker bundles.
  • merge-risk: 🚨 session-state: Guard termination can restore one queued follow-up into both steering and follow-up queues, causing duplicate processing.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

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 (53 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-24T12:11:56.181Z sha b3fa58c1d5380ca7f44ab198e62981cef82424aa :: needs changes before merge. :: [P3] Replace stale built-in-default wording
  • reviewed 2026-08-24T12:57:26.347Z sha ef756653654629ba18eba6ebd6f1f3f9f90532b4 :: found issues before merge. :: [P2] Remove the unsupported maintainer-approval assertion
  • reviewed 2026-08-24T13:23:08.263Z sha 2d3b5bdb2970c6df99d5fce9fd065f105682b00d :: found issues before merge. :: [P2] Do not self-approve the new product policy | [P3] Correct the layer count in the configuration reference
  • reviewed 2026-08-25T01:07:49.976Z sha 68126d7c6f64404e1dec96da564aad20f8d98cd7 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T20:30:02.262Z sha 68126d7c6f64404e1dec96da564aad20f8d98cd7 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T09:05:58.026Z sha 077fc8a :: blocked before merge. :: [P1] [P1] Restore drained follow-ups to exactly one queue | [P2] [P2] Include streamed tool-call prefixes in idle-repeat accounting | [P2] [P2] Exclude skipped-only fragments from error aggregation | [P2] [P2] Document activation when enabled is omitted
  • reviewed 2026-09-27T10:59:01.759Z sha 077fc8a :: blocked before merge. :: [P1] Restore drained follow-ups to exactly one queue | [P2] Count streamed tool-call prefixes in idle repeats | [P2] Exclude skipped-only fragments from error aggregation | [P2] Document activation when enabled is omitted | [P2] Remove the unused worker supervisor import
  • reviewed 2026-10-03T13:21:56.898Z sha 077fc8a :: blocked before merge. :: [P1] [P1] Restore drained follow-ups to exactly one queue | [P2] [P2] Count streamed tool-call prefixes in idle repeats | [P2] [P2] Exclude skipped-only fragments from error aggregation | [P2] [P2] Document activation when enabled is omitted | [P2] [P2] Remove the unused worker supervisor import

Reviewed October 17, 2026, 6:42 PM ET / 22:42 UTC (Revision 54).

@openclaw-barnacle openclaw-barnacle Bot added size: XL triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed size: L labels Aug 9, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Aug 9, 2026
@Papilionidae
Papilionidae marked this pull request as ready for review August 9, 2026 15:25
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 9, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 9, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Aug 10, 2026
@openclaw-barnacle openclaw-barnacle Bot added the app: web-ui App: web-ui label Aug 10, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 10, 2026
@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The P1 finding is resolved: WORKER_LOOP_GUARD_PROTOCOL_FEATURE is restored in WORKER_PROTOCOL_FEATURES so new worker builds advertise the capability. The launcher's per-turn fence (supportsWorkerLoopGuardLaunch) still protects guard-enabled turns on bundles lacking the capability; configless and enabled:false turns are unaffected.

Rebased on upstream/main (a435cf6840c). All 57 tests pass. Format/lint clean. Config baseline regenerated.

The CI failure on the previous head (38c59007a6d) was ui/src/pages/chat/chat-pane-terminal.test.ts EnvironmentTeardownError — a pre-existing flaky UI test unrelated to this PR's changes.

@clawsweeper

clawsweeper Bot commented Aug 24, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Shiny media proof attached: focused test run output showing the idle-repeat guard terminating a real AgentSession transport run after 3 repeated calls (no 4th provider request), plus all 23 agent-loop guard tests passing.

Rebased on upstream/main (7a7bb1f6709). All tests pass. Format/lint clean.

The CI failure on the previous head was src/node-host/node-worker-supervisor.container.test.ts — a Docker container isolation test that is flaky on CI (13 tests, 1 failed, the rest passing). This test does not exercise any code path changed by this PR.

@clawsweeper

clawsweeper Bot commented Aug 24, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased on upstream/main (7a7bb1f6709). Head: b3fa58c1d53.

Proof artifact — focused test run output:

$ node scripts/run-vitest.mjs run --config test/vitest/vitest.agents-support.config.ts src/agents/sessions/agent-session-loop-guard-transport.test.ts

 RUN  v4.1.10 /media/vdc/ai-agents/github/openclaw

 ✓ |agents-support| src/agents/sessions/agent-session-loop-guard-transport.test.ts (1 test) 1235ms
     ✓ maxIdleRepeatCalls terminates the run after 3 real transport round trips  1230ms

 Test Files  1 passed (1)
      Tests  1 passed (1)

$ node scripts/run-vitest.mjs run packages/agent-core/src/agent-loop.guard.test.ts

 RUN  v4.1.10 /media/vdc/ai-agents/github/openclaw

 ✓ |unit| packages/agent-core/src/agent-loop.guard.test.ts (23 tests) 255ms

 Test Files  1 passed (1)
      Tests  23 passed (23)

The transport test exercises a real AgentSession through local HTTP/SSE transport with an injected fault source, observing graceful idle-repeat termination after 3 repeated calls with no 4th provider request. The guard test suite covers maxTurns, maxConsecutiveErrorBatches, maxIdleRepeatCalls, steering-skip exclusion (sequential + parallel), and steering requeue on guard termination.

CI note: The failure on the previous head (48a5b8078ae6) was src/node-host/node-worker-supervisor.container.test.ts — a Docker container isolation test that is flaky on CI (13 tests, 1 failed). This test does not exercise any code path changed by this PR. The new head b3fa58c1d53 is rebased on the latest main.

@clawsweeper

clawsweeper Bot commented Aug 24, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

P3 finding resolved: all stale "built-in default" / "200/3/3" wording replaced with the explicit configured-value activation rule across 6 files:

  • src/agents/sessions/sdk.ts:109-115 — comment now says "per-key guard values" instead of "200/3/3"
  • src/agents/tool-loop-detection-config.test.ts:42 — test name now says "configured value" instead of "built-in default"
  • src/agents/sessions/sdk.loop-guard.test.ts:117-120 — comment now says "engage any guard" instead of "built-in defaults"
  • src/agents/sessions/agent-session-loop-guard-transport.test.ts:180-182 — comment now says "configured values" instead of "200/3/3"
  • src/agents/embedded-agent-runner/run/attempt-session-prepare.ts:210-211 — comment now says "explicit guard keys activate each guard" instead of "built-in defaults"
  • src/worker/embedded-agent.runtime.test.ts:1-5 — comment now says "guards off" instead of "built-in defaults, guards on"

Rebased on upstream/main (97b13b1735d). All tests pass. Format/lint clean.

@clawsweeper

clawsweeper Bot commented Aug 24, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

P2 finding resolved: removed the unsupported maintainer-approval assertion from docs/tools/loop-detection.md. The "Product policy" section now states the opt-in design plainly without claiming a specific maintainer approval date.

Rebased on upstream/main (9ee238dd450). All tests pass. Format/lint clean. PR body retains the screenshot proof in the Evidence section.

@clawsweeper

clawsweeper Bot commented Aug 24, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Both findings resolved:

  1. [P2] Do not self-approve the new product policy — Removed the "product decision record" paragraph from docs/tools/loop-detection.md. The opt-in behavior is now documented as plain product behavior without any self-approval assertion.

  2. [P3] Correct the layer count in the configuration reference — Fixed docs/gateway/config-tools.md from "two layers" to "three layers" (RunLoop guards, rolling-history detectors, post-compaction guard).

All tests pass. Format/lint clean.

@clawsweeper

clawsweeper Bot commented Aug 25, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Head 68126d7c6f6 supersedes the previously reviewed 2d3b5bdb297. Both findings on the old head are resolved:

  1. [P2] Do not self-approve the new product policy — The "product decision record" paragraph at docs/tools/loop-detection.md:197-200 is removed. No self-approval language remains.

  2. [P3] Correct the layer count — docs/gateway/config-tools.md:290 now says "three layers" (RunLoop guards, rolling-history detectors, post-compaction guard).

Rebased on upstream/main (3b0cad5d708). mergeable=true. All tests pass. Format/lint clean.

@clawsweeper

clawsweeper Bot commented Aug 25, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

…t guards (openclaw#120962)

Add opt-in runLoop guards (maxTurns, maxConsecutiveErrorBatches,
maxIdleRepeatCalls) to the native agent loop, configuration resolver,
session factories, and worker launch contract. Guards are opt-in: configless
and enabled:false sessions preserve pre-guard behavior. The launch-time fence
requires the loop-guard worker capability only for guard-enabled turns, so
legacy bundles can still serve guard-off turns. Recovery does not reclaim
workers solely for lacking the loop-guard capability — the launcher decides
per turn.

[AI-assisted]
@Papilionidae

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Sep 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@LamplighterPaul LamplighterPaul left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Tested this at head 077fc8a because it targets exactly the failure I reported in #110337 (comment: #110337 (comment)): one rejected sessions patch re-sent 223 times over 36 minutes with loop detection unset.

What I ran (isolated container, no network, Node 24, vitest 5, pnpm install --frozen-lockfile on the branch):

Suite Result
packages/agent-core/src/agent-loop.guard.test.ts 23/23 pass
src/agents/tool-loop-detection-config.test.ts 9/9 pass
added regression test mirroring the #110337 shape (below) 3/3 pass

The regression test drives Agent with a sessions tool that throws the real ToolInputError text and a stream that re-issues the identical call 25 times:

Config Tool executions Provider requests Ends with
no guard keys 25 26 model's own text
maxIdleRepeatCalls: 5 5 5 terminal "identical arguments 5 times in a row"
maxConsecutiveErrorBatches: 4 4 4 terminal "ended in errors"

So the guards do stop this shape, and the unguarded row shows the baseline. Happy to push the test onto the branch if you enable maintainer edits, or open it against your fork.

CI is red for a reason inside the PR: check-prod-types fails on
src/worker/embedded-agent.runtime.ts(38,10): error TS6133: 'getProcessSupervisor' is declared but its value is never read.
That import is added by this PR and unused in the file. The other lanes look like the same run cascading. The branch is also ~2600 commits behind main, so a rebase is needed before maintainers can evaluate it.

One design comment, non-blocking: with only tools.loopDetection.enabled: true, none of the three guards engage (resolveLoopGuardRuntimeConfig returns all-undefined). I understand the upgrade-contract reasoning, but it means the #110337 shape still runs to exhaustion under this PR unless the operator knows to set a key. An identical call that returns an identical error is deterministic, so a conservative default for maxIdleRepeatCalls when enabled is true (or at least a documented recommended value) would make the fix reach the people it's for. Maintainers' call.

Regression test (packages/agent-core/src/agent-loop.guard.incident.test.ts)
// Reproduces openclaw/openclaw#110337 (comment 2026-09-11): a model re-sent one
// rejected `sessions` patch (ToolInputError) 223 times in a run. Checks the PR
// guards stop that shape, and shows the unguarded baseline for contrast.
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { Agent } from "./agent.js";
import {
  type AssistantMessage,
  createAssistantMessageEventStream,
  type Message,
  type Model,
} from "./llm.js";
import type { AgentMessage, AgentTool, StreamFn } from "./types.js";

const model: Model = {
  id: "test-model",
  name: "Test Model",
  api: "test-api",
  provider: "test-provider",
  baseUrl: "https://example.test",
  reasoning: false,
  input: ["text"],
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  contextWindow: 1000,
  maxTokens: 1000,
};

const TEST_USAGE = {
  input: 0,
  output: 0,
  cacheRead: 0,
  cacheWrite: 0,
  totalTokens: 0,
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};

const REJECTION =
  "targets is only valid for patch and cannot be combined with sessionKey or expectedSessionId";

// The exact shape the model sent (redacted ids): top-level session AND a
// one-entry targets array for the same session, every optional field emptied.
const INCIDENT_ARGS = {
  action: "patch",
  sessionKey: "agent:main:dashboard:11111111-1111-1111-1111-111111111111",
  targets: [
    {
      sessionKey: "agent:main:dashboard:11111111-1111-1111-1111-111111111111",
      expectedSessionId: "22222222-2222-2222-2222-222222222222",
    },
  ],
  expectedSessionId: "22222222-2222-2222-2222-222222222222",
  deleteTranscript: true,
  label: "OpenClaw Android",
  icon: "",
  color: "",
  group: null,
  statusNote: "",
  attention: "clear",
  ttlMinutes: 30,
  pinned: false,
  archived: false,
  model: "",
  thinkingLevel: "",
  ownerType: "agent",
  ownerId: "",
  names: [],
  name: "",
  to: "",
};

function rejectingSessionsTool(calls: { count: number }): AgentTool {
  return {
    name: "sessions",
    label: "Sessions",
    description: "sessions",
    parameters: Type.Any(),
    execute: async () => {
      calls.count += 1;
      throw new Error(REJECTION);
    },
  };
}

function makeStream(turns: AssistantMessage["content"][], requests: Message[][]): StreamFn {
  let turnIndex = 0;
  return (_activeModel, context) => {
    requests.push(context.messages.slice());
    const content = turns[turnIndex];
    turnIndex += 1;
    if (!content) {
      throw new Error(`unexpected provider request ${turnIndex}`);
    }
    const stream = createAssistantMessageEventStream();
    queueMicrotask(() => {
      const message: AssistantMessage = {
        role: "assistant",
        content,
        api: "test-api",
        provider: "test-provider",
        model: "test-model",
        usage: TEST_USAGE,
        stopReason: content.some((item) => item.type === "toolCall") ? "toolUse" : "stop",
        timestamp: 1,
      };
      stream.push({ type: "done", reason: message.stopReason === "toolUse" ? "toolUse" : "stop", message });
      stream.end();
    });
    return stream;
  };
}

function identicalRejectedTurns(n: number): AssistantMessage["content"][] {
  const turns: AssistantMessage["content"][] = [];
  for (let i = 1; i <= n; i += 1) {
    turns.push([{ type: "toolCall", id: `call-${i}`, name: "sessions", arguments: INCIDENT_ARGS }]);
  }
  turns.push([{ type: "text", text: "gave up" }]);
  return turns;
}

function lastAssistantText(messages: AgentMessage[]): string {
  const last = messages.at(-1);
  if (!last || last.role !== "assistant") {
    return "";
  }
  return last.content
    .filter((part): part is Extract<typeof part, { type: "text" }> => part.type === "text")
    .map((part) => part.text)
    .join("");
}

describe("incident #110337: identical rejected sessions patch", () => {
  it("baseline without guards: every identical rejected call is executed", async () => {
    const requests: Message[][] = [];
    const calls = { count: 0 };
    const agent = new Agent({
      initialState: { model, systemPrompt: "", tools: [rejectingSessionsTool(calls)] },
      streamFn: makeStream(identicalRejectedTurns(25), requests),
    });
    await agent.prompt("OpenClaw Android is enough");

    expect(calls.count).toBe(25);
    expect(requests).toHaveLength(26);
    expect(lastAssistantText(agent.state.messages)).toBe("gave up");
  });

  it("maxIdleRepeatCalls stops the identical rejected call after N turns", async () => {
    const requests: Message[][] = [];
    const calls = { count: 0 };
    const agent = new Agent({
      initialState: { model, systemPrompt: "", tools: [rejectingSessionsTool(calls)] },
      streamFn: makeStream(identicalRejectedTurns(25), requests),
      maxIdleRepeatCalls: 5,
    });
    await agent.prompt("OpenClaw Android is enough");

    expect(calls.count).toBe(5);
    expect(requests).toHaveLength(5);
    expect(agent.state.messages.at(-1)).toMatchObject({ role: "assistant", stopReason: "stop" });
    expect(lastAssistantText(agent.state.messages)).toContain("identical arguments 5 times in a row");
  });

  it("maxConsecutiveErrorBatches also stops it, since every batch is all-error", async () => {
    const requests: Message[][] = [];
    const calls = { count: 0 };
    const agent = new Agent({
      initialState: { model, systemPrompt: "", tools: [rejectingSessionsTool(calls)] },
      streamFn: makeStream(identicalRejectedTurns(25), requests),
      maxConsecutiveErrorBatches: 4,
    });
    await agent.prompt("OpenClaw Android is enough");

    expect(calls.count).toBe(4);
    expect(requests).toHaveLength(4);
    expect(lastAssistantText(agent.state.messages)).toContain("ended in errors");
  });
});

@VACInc

VACInc commented Sep 27, 2026

Copy link
Copy Markdown
Member

Merged #159864 repairs Code Mode repeated-work identity; it does not add this PR’s opt-in RunLoop turn, error-batch, or idle-repeat cutoffs. These are independent safeguards, so this PR is not superseded.

@SPM-OS

SPM-OS commented Oct 4, 2026

Copy link
Copy Markdown

Nice work on the runaway guards — we're building Tammo (tammo.ai) around the same problem from the budget side: pre-call budget gate (worst-case estimate vs remaining), hard deny, signed spend ledger for every decision. Complementary to turn/error guards. Running a free 30-day pilot — would love your take as someone building guards. — uu (operator, Tammo)

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@steipete

Copy link
Copy Markdown
Contributor

Thanks for the PR. We're closing older pull requests that have gone stale against current main.

This XL PR has failing CI, still needs real behavior proof, and has had no commits since September 7; main already stops identical-error loops. If a specific runaway pattern still escapes current loop detection, please open a focused issue or a smaller PR.

If this change is still needed, please open a fresh PR against current main and we'll review it there.

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 docs Improvements or additions to documentation gateway Gateway runtime 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. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL stale Marked as stale due to inactivity 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.

Bug: 219-Turn Agent Death Spiral (Missing maxTurns, isError Breaker, and Idle Loop Detector in runLoop)

5 participants