Skip to content

fix(agents): prevent recursive task execution during model fallback - #92011

Merged
steipete merged 1 commit into
openclaw:mainfrom
MertBasar0:fix/fallback-recursive-task-execution
Jul 17, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
MertBasar0:fix/fallback-recursive-task-execution

Conversation

@MertBasar0

@MertBasar0 MertBasar0 commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes #92271

What Problem This Solves

Fixes an issue where a fallback model handling an internal completion report could interpret that report as fresh work and recursively delegate it again.

Why This Change Was Made

The run now derives a typed report_only delegation capability only when a fallback handles completion provenance. The shared OpenClaw tool boundary removes or action-gates delegation surfaces while preserving reporting, status, history, and cleanup tools. Codex app-server runs additionally disable both native collaboration feature generations on a transient thread, because loaded Codex threads ignore resume-time config overrides. Normal thread bindings remain unchanged.

This replaces the original sessions_spawn-only guard and covers sessions_send, system-agent delegation, LLM tasks, Codex session steering, cron/media launch actions, the Pi/Copilot/Codex shared tool surfaces, and native Codex collaboration.

User Impact

Fallback completion reports can summarize and verify completed work without launching or redirecting more work. Normal user turns, non-fallback completion reports, and ordinary verification/reporting tools retain their existing behavior.

Evidence

  • node scripts/run-vitest.mjs src/agents/delegation-capability.test.ts extensions/codex/src/app-server/thread-lifecycle.test.ts extensions/codex/src/app-server/thread-lifecycle.binding.test.ts extensions/codex/src/app-server/dynamic-tool-build.test.ts extensions/copilot/src/tool-bridge.test.ts — 3 core tests, 223 Codex tests, and 77 Copilot tests passed.
  • node scripts/check-changed.mjs -- <15 touched files> — Blacksmith Testbox changed gate passed (tbx_01kxq0tacnrjjj6vpd3h3x22c5): https://github.com/openclaw/openclaw/actions/runs/29551712547
  • Autoreview accepted and fixed the loaded-Codex-thread bypass. Final branch review's only reported concern referenced a nonexistent subagents.steer action; current source and schema expose only list and cancel, so no hypothetical branch was added.

Contributor credit preserved in the rewritten commit. Thanks @MertBasar0.

@MertBasar0
MertBasar0 requested a review from a team as a code owner June 10, 2026 19:46
@openclaw-barnacle openclaw-barnacle Bot added app: ios App: ios scripts Repository scripts agents Agent runtime and tooling size: XL triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 10, 2026
@MertBasar0
MertBasar0 force-pushed the fix/fallback-recursive-task-execution branch from d122371 to c18b02b Compare June 10, 2026 20:52
@openclaw-barnacle openclaw-barnacle Bot added size: XS and removed app: ios App: ios scripts Repository scripts size: XL labels Jun 10, 2026
@vincentkoc vincentkoc self-assigned this Jun 11, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Cross-harness review: not landable yet.

The patch only injects a fallback identity prompt into CLI backends. It does not establish one invariant across OpenClaw's embedded runtime, Claude/Codex CLI backends, or Codex's native spawn_agent surface. OpenClaw already has actual recursive-spawn enforcement at sessions_spawn via stored depth and maxSpawnDepth; Codex separately owns native collaboration tools (spawn_agent) in its tool registry. A prompt saying “do not re-execute” neither disables those tools nor proves recursion is prevented.

Best-fix requirement before merge: define the forbidden recursion state at the shared fallback/run boundary, then enforce it in every harness that can spawn work (or explicitly prove a harness cannot), with regression coverage for embedded OpenClaw, CLI/MCP exposure, and Codex native collaboration. I checked Codex ownership in codex-rs/core/src/tools/handlers/multi_agents_spec.rs and codex-rs/core/src/tools/spec_plan.rs; this PR does not control that surface.

@MertBasar0
MertBasar0 marked this pull request as draft June 11, 2026 22:09
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Thanks for the cross-harness review — you're right on all three counts. The pushed diff was also structurally broken (the injection landed after the return path), so the prompt never executed; I'm treating this as a rewrite, not a patch.

Converting to draft while I rework it along the lines you outlined:

  1. Shared invariant first: define the forbidden state ("a fallback turn replying to completion announcements must not re-execute or re-spawn reported work") at the fallback/run boundary, not per-backend prompts.
  2. Enforcement + coverage matrix: embedded runtime, CLI/MCP exposure, and Codex native spawn_agent — enforce or explicitly document non-exposure, each with regression tests. The incident evidence shows the duplicate work was spawned at depth 1, so maxSpawnDepth doesn't catch it; this needs an idempotency/evidence rule, not a depth rule.
  3. One scoping question: do you want the Codex-native spawn_agent control handled in this PR, or as a follow-up in codex-rs since that tool registry lives there? Happy to do either.

Will mark ready once CI and the behavior-proof job are green.

@clawsweeper

clawsweeper Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 16, 2026, 11:59 PM ET / July 17, 2026, 03:59 UTC.

Summary
The branch introduces a typed report-only delegation capability for fallback completion-report turns, filters or action-gates shared delegation tools, and disables native Codex collaboration on transient restricted threads.

PR surface: Source +137, Tests +205. Total +342 across 15 files.

Reproducibility: no. independent current-main reproduction was completed in this review, but the incident record, provenance path, and production-boundary tests provide a clear source-level reproduction model.

Review metrics: 1 noteworthy metric.

  • Delegation restriction surface: 5 tools removed, 4 tool families action-gated, 2 Codex feature flags disabled. The breadth is intentional but compatibility-sensitive because one provenance classification changes the available authority across several harnesses.

Stored data model
Persistent data-model change detected: serialized state: src/sessions/input-provenance.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #92271
Summary: This PR is the active candidate fix for the semantic fallback-recursion issue; the unrelated transcript-cache PR does not share this root cause.

Members:

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

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster ✨ media proof bonus
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Inspect and cite the exact pinned Codex feature registry, native collaboration registration, and loaded-thread resume behavior.

Risk before merge

  • [P2] Report-only mode intentionally suppresses otherwise legitimate new delegation during a fallback turn whose input is classified as a completion report; maintainers should explicitly own this compatibility tradeoff.
  • [P1] The exact Codex dependency revision still needs direct source verification that both collaboration feature flags govern all native delegation entry points and that loaded threads ignore the relevant resume-time overrides as assumed.

Maintainer options:

  1. Verify the pinned Codex contract (recommended)
    Confirm every native delegation surface and loaded-thread override behavior in the exact Codex revision before merging the compatibility-sensitive restriction.
  2. Accept the restricted-turn policy
    Merge with explicit ownership that fallback completion-report turns may not start or redirect delegated work, even when such work would otherwise be legitimate.

Next step before merge

  • [P2] A reviewer should complete the mandatory exact pinned-Codex source inspection; no narrow code defect is currently available for an automated repair lane.

Maintainer decision needed

  • Question: Does an exact inspection of the pinned Codex revision confirm that disabling features.multi_agent and features.multi_agent_v2 on a newly started transient thread removes every native delegation entry point and that resuming a loaded thread cannot apply those restrictions reliably?
  • Rationale: The patch is otherwise review-clean, but repository policy makes this direct dependency-contract verification mandatory before a Codex behavior verdict.
  • Likely owner: steipete — Authored the current rewritten head and touched both the shared agent boundary and Codex integration, making them the clearest owner for the final contract check.
  • Options:
    • Complete pinned Codex check (recommended): Inspect the exact sibling Codex revision, record the controlling registry and resume-config paths, and merge if they match the patch assumptions.
    • Pause for Codex adjustment: Keep the PR open and revise the OpenClaw integration if the pinned Codex revision exposes another delegation feature or supports safe resume-time restriction.

Security
Cleared: The diff adds authorization restrictions without changing dependencies, workflow permissions, secret handling, package resolution, or downloaded code execution.

Review details

Best possible solution:

Land the shared capability design only after checking the exact pinned Codex source and recording that its native collaboration registration and thread-config semantics match the two feature flags and transient-thread strategy used here.

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

No independent current-main reproduction was completed in this review, but the incident record, provenance path, and production-boundary tests provide a clear source-level reproduction model.

Is this the best way to solve the issue?

Yes, conditionally: a typed capability enforced at shared tool construction is substantially safer than prompt-only or sessions_spawn-only guards, provided the exact pinned Codex contract confirms the native restriction assumptions.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P1: The patch addresses a real agent workflow that can recursively repeat completed work and push unintended changes during model fallback.
  • merge-risk: 🚨 compatibility: Merging intentionally removes delegation authority from classified fallback completion-report turns and starts transient Codex threads instead of resuming existing bindings.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The submitted production-path output and linked Blacksmith changed-surface run demonstrate the restricted fallback behavior, and the latest completed review already validated that proof against the rewritten head lineage.
  • proof: sufficient: Contributor real behavior proof is sufficient. The submitted production-path output and linked Blacksmith changed-surface run demonstrate the restricted fallback behavior, and the latest completed review already validated that proof against the rewritten head lineage.
Evidence reviewed

PR surface:

Source +137, Tests +205. Total +342 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 10 139 2 +137
Tests 5 205 0 +205
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 344 2 +342

What I checked:

Likely related people:

  • steipete: Authored and force-pushed the rewritten current commit spanning the shared agent boundary and Codex/Copilot integrations. (role: current-head author and likely follow-up owner; confidence: high; commits: 386d56a5ddbf; files: src/agents/delegation-capability.ts, src/agents/agent-tools.ts, extensions/codex/src/app-server/thread-lifecycle-run.ts)
  • vincentkoc: The initial review identified the prompt-only and single-tool shortcomings, required one shared invariant, and explicitly traced the native Codex collaboration surface. (role: reviewer and cross-harness invariant owner; confidence: medium; files: src/agents/agent-tools.ts, extensions/codex/src/app-server/thread-requests.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-09T08:16:53.419Z sha 3ef11980b2750dea6caf3b4d4d857da2bda9b2a4 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-12T19:27:40.690Z sha 74e8fd921852143b249946b05a9722475e7975b1 :: needs changes before merge. :: [P1] Propagate the fallback bit through runAgentAttempt
  • reviewed 2026-07-12T19:37:28.193Z sha 74e8fd921852143b249946b05a9722475e7975b1 :: needs changes before merge. :: [P1] Forward the fallback flag through the agent-command path
  • reviewed 2026-07-12T19:56:19.952Z sha cb3a338aaf4e0bd88f088ff9859e8e4207a29462 :: found issues before merge. :: [P1] Preserve legitimate spawns after completion announcements
  • reviewed 2026-07-12T20:05:11.095Z sha cb3a338aaf4e0bd88f088ff9859e8e4207a29462 :: found issues before merge. :: [P1] Preserve legitimate spawns after completion announcements
  • reviewed 2026-07-13T20:49:06.329Z sha cb3a338aaf4e0bd88f088ff9859e8e4207a29462 :: found issues before merge. :: [P1] Preserve legitimate spawns after completion reports
  • reviewed 2026-07-16T03:10:00.266Z sha 4d061dde2e3c252bd02a0fa83e3d2d22a36f13d0 :: found issues before merge. :: [P1] Preserve legitimate spawns after completion announcements
  • reviewed 2026-07-17T03:39:17.272Z sha c1e9fb876e33ed094d9e9c928de38dbc7673c856 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. label Jun 11, 2026
@MertBasar0
MertBasar0 force-pushed the fix/fallback-recursive-task-execution branch from a0039dd to 46d93c4 Compare June 12, 2026 16:53
@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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 12, 2026
@MertBasar0
MertBasar0 marked this pull request as ready for review June 12, 2026 17:17
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Reworked per the cross-harness review and marking ready: the invariant is now defined at the shared fallback/run boundary and enforced mechanically at the sessions_spawn choke point (subagent + ACP runtimes), with the announcement content hardened for every harness. The updated description includes the coverage matrix, regression tests, and a Real behavior proof section with live after-fix output (CI is green, including the proof gate).

One open scoping question from before still stands: should the Codex-native spawn_agent control land in this PR or as a codex-rs follow-up? Happy to do either.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 3, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 8, 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 Jul 8, 2026
@MertBasar0
MertBasar0 force-pushed the fix/fallback-recursive-task-execution branch from 83ce64f to 53b8496 Compare July 8, 2026 07:34

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main (7e0324263b) to clear the stale/conflicting state and force-pushed the PR branch.

Verification on the rebased head 53b849699e:

node scripts/run-vitest.mjs run \
  src/agents/model-fallback.test.ts \
  src/agents/model-fallback.probe.test.ts \
  src/agents/outcome-fallback-runtime-contract.test.ts \
  src/agents/tools/sessions-spawn-tool.test.ts \
  src/sessions/input-provenance.test.ts \
  src/agents/subagent-announce.format.e2e.test.ts
→ passed 3 Vitest shards

oxfmt --check on the 20 changed files
→ clean

I also attempted the repo typecheck locally, but this checkout's dependency set is currently missing unrelated workspace deps such as @openclaw/uirouter, @openclaw/libterminal, ghostty-web, and markdown-it-cjk-friendly, so local tsgo does not get to this PR's changed surface. CI should be the source of truth for that after the push.

Scope is unchanged: this PR is still intentionally limited to the embedded runtime sessions_spawn guard. #92271 stays open for gateway loopback sessions_spawn, sessions_send/cron scheduling, and codex-rs native spawn_agent follow-ups.

Requesting maintainer scope decision: is landing this as a scoped embedded-runtime mitigation acceptable, or should one of the follow-up surfaces be pulled into this PR?

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 8, 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: the existing ClawSweeper review comment will be edited in place when the review finishes.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@MertBasar0

Copy link
Copy Markdown
Contributor Author

Merged current main into the branch (single conflict in src/agents/agent-tools.ts — kept main's new mergeRingZeroTools structure, re-inserted this PR's fallback options) and repaired the P1 propagation gap from the last review: main's newer CLI-to-embedded attempt path (agent-command.ts → command/attempt-execution.ts) dropped the fallback bit before tool construction, so that route bypassed the guard. runEmbeddedAgent now receives isFallback: true for CLI-origin fallback retries only (primary option shapes unchanged), with focused regression coverage for both directions.

Verification on head cb3a338aaf4:

run-vitest: model-fallback (126) / probe (20) / outcome-fallback-runtime-contract (10) /
            sessions-spawn-tool (57) / input-provenance → 213 passed
            attempt-execution.cli → 67 passed (incl. 2 new regressions)
tsgo core + core-test → 0 errors, oxlint clean
CI: 72 pass / 0 fail, Real behavior proof included

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 13, 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: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 15, 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: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: codex extensions: copilot merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M stale Marked as stale due to inactivity 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.

Fallback turns can re-execute work already reported as completed (semantic recursive task execution)

3 participants