Skip to content

refactor(agents): consolidate lifecycle and tool execution - #166691

Merged
steipete merged 8 commits into
mainfrom
deslop/d06b-agents-subagents-tools-20261007
Oct 7, 2026
Merged

steipete merged 8 commits into
mainfrom
deslop/d06b-agents-subagents-tools-20261007

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Related: #166550

What Problem This Solves

Consolidates repeated subagent lifecycle and tool execution logic, and fixes two adjacent owner-validation defects found during the pass.

User Impact

All existing features, tool descriptions, prompts, configuration and protocol shapes remain intact. Watched children using raw keys such as global recover under their recorded agent; whitespace-only computer target references no longer bypass screenshot-frame validation. No migration or operator action is required.

Why This Change Was Made

Shared cores now own registry/completion write admission and receipt settlement, requester mutations, cleanup finalization, scoped reads, prepared spawn facts, media dispatch, and question prompt lifecycle. Real differences remain explicit, including authority checks, recovery/replay rules, await boundaries, and the distinct HTML rendering and visibility grammars.

The two bug fixes are separate commits. Restart recovery ignored childAgentId and omitted the explicit agent read scope. Computer frame admission tested raw reference truthiness even though request construction discarded blank references.

Net production reduction: 1,686 lines (3,911 added / 5,597 deleted), 1.89% of the original 89,099-line subsystem. This includes replacement helpers and excludes tests, fixtures, test support, generated output and declarations. Every original production file was covered; alternatives that grew code or obscured ownership were measured and rejected. Existing assertions remain intact; test changes adapt removed private seams or add regressions. All three canonical baseline updates only shrink allowances.

Evidence

  • Both complete subsystem directories and 17 affected outside targets passed: 5,538 tests across 352 files, two existing skips, 12 Vitest shards, 1,347.17 seconds on Linux/Hetzner, head 459d1757d2e13c1d3d5ac90fd86082b239dee4c3. The conflict-only rebase preserved main's scheduler-slot aliases and Gateway authority forwarding; all affected integration tests plus lint-suppression tests passed on rebased head 6137ef76df0217ae0f60bc5646a7e9dc76f0f5d8 (900.59 seconds wrapper wall time).
  • The pre-rebase correction tree d287c11728d9d19336ae6ced258d53f572e7c176 has 650 additional focused tests passing across 12 files (220.86 seconds), a fresh core typecheck, and runtime/Madge cycle counts of 0. That committed tree matches its tested and reviewed tree. The complete changed-file packet passed all source guards, production types, all 27 test type graphs, and all three Knip scans. Its final lint stage found nine lane issues; those were corrected and independently reviewed with no findings. The full core lint rerun has no remaining lane findings; only the four untouched size violations listed below remain, waived by the campaign rule.
  • Restart recovery's new real-SQLite regression failed before the fix (deferred instead of terminal); all 30 integration tests passed after it (896.33 seconds wrapper wall time). Both blank-reference regressions dispatched stale-frame clicks before the fix; all 58 computer tests passed after it (221.22 seconds). These times include compiler preparation; hosted CI timing will be visible in the attached exact-head run.
  • Baseline comparisons passed: 3,808 ordered message schemas; 11,785 HTML cases; 2,610 numeric-reader cases; 270 progress/timer traces; 270 Workshop cases; automation and decision schema/validation cases; 945 media comparisons; 166,679 connected-wave cases; and 4,116 exact active-subagent prompt comparisons. The text audit found no unexplained model-facing or user-visible byte differences.
  • Full Linux build passed on the frozen production candidate. SDK comparison found no entrypoint additions/removals or direct export declaration changes. Its 130 reachable-export flags were audited to three internal declaration changes; public callable/type shapes are unchanged (digest 77d2f0d5). The earlier parameter-type correction emits identical JavaScript; final lint corrections and rebase integration have fresh focused, type, and cycle proof without import or public declaration changes.
  • Independent review completed. Initial review returned five findings and the rebased review returned three; all were rejected after checking exact caller guards and owning worker contracts. Fixture and final lint corrections received separate clean reviews. No accepted findings remain.

The full packet initially exposed two fixture seams after shared-reader/runtime consolidation. They now preserve the real exports and use the same test-owned reader; the existing cancellation and announcement assertions pass unchanged. The old-base changed checker also found an untouched UI test type error; main commit 1d10375ee56, included in this rebase, fixes it.

The separate raw-key reconciliation path still needs worker reads and owner-aware cleanup routing. That repair is being prepared for a separate sequential bug-fix PR; this PR does not claim to fix it.

The standalone core lint rerun reports pre-existing max-lines violations in ui/src/components/session-organizer-operations.runtime.ts, src/cli/update-cli/update-command-service-maintenance.ts, src/agents/worktrees/service-preparation.ts, and src/agents/tools/message-tool-execution.ts. All four files are untouched and byte-identical to origin/main. No cap, ignore, or suppression was added; the obsolete sessions-send max-lines allowance was removed through the canonical ratchet.

The first hosted run found one lane-owned fixture issue: the reservation test wrapped the same mutable spy installed by beforeEach after two mutation APIs were consolidated. It now captures the existing implementation, preserving the settlement-failure wrapper and every assertion. The original-order negative control reproduced the stack overflow/missing retry deadline; the complete 35-case E2E file and 3 lint-suppression tests pass after repair (482.07 seconds including cold build). Its scoped lint/typecheck and fresh P2 review pass.

Current head is 9eb0658df94b62de8af8d338823824fdf9d95a4f, rebased onto d449d77dd1cbd9aad682b25ef92f1d4afc052c81 to incorporate upstream Discord fix 9df0cd095766ff05864aa67aa91b627a347a4d1a. That separate hosted failure reproduced on clean main before the fix; the same whole 30-case file passes after it. All eight lane commits are patch-identical through the rebase. Fresh core types, runtime/Madge cycle checks (both zero), and lint-suppression tests (3) pass on the rebased head. The two cancelled auxiliary runs from the first hosted attempt were rerun successfully; exact-head CI is required again after this push.

@clawsweeper

clawsweeper Bot commented Oct 7, 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.

@steipete
steipete marked this pull request as ready for review October 7, 2026 18:12
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 7, 2026
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 9eb0658df94b62de8af8d338823824fdf9d95a4f
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/subagents/requester-cron-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/tools/sessions-operator-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 7, 2026, 3:22 PM ET / 19:22 UTC (Revision 2).

ClawSweeper review

What this changes

Consolidates subagent lifecycle and tool execution logic, fixes recorded-agent restart recovery, and rejects stale screenshot frames when computer target references are blank.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: both focused fixes remain absent from the pinned main, and the related merged listing fix does not supersede this work. No blocking introduced defect was found.

Priority: P2
Reviewed head: 9eb0658df94b62de8af8d338823824fdf9d95a4f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful consolidation with focused regressions and substantial reported validation; no blocking patch defect was found.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary contributor proof gate does not apply to this maintainer-authored PR. Inspected recovery and computer regressions supplement the captured validation reports; the reviewed changes preserve stored formats and do not establish a material authority expansion requiring additional final-effect proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary contributor proof gate does not apply to this maintainer-authored PR. Inspected recovery and computer regressions supplement the captured validation reports; the reviewed changes preserve stored formats and do not establish a material authority expansion requiring additional final-effect proof.
Evidence reviewed 9 items Pinned change ownership: Reviewed introduced changes from d449d77 to the recorded PR head. Raw test-merge parent records identify the pinned main first and this exact head second; endpoint drift was not attributed to the PR.
Restart recovery remains necessary: Pinned main derives the child agent solely from the session key and omits agentId from the worker read scope. The branch uses the recorded childAgentId and supplies that scope explicitly, preserving current-owner and final-commit checks.
Computer frame validation remains necessary: Pinned main checks raw target-reference truthiness, although request construction trims those references. The branch uses the same string reader for frame admission; its regression cases reject stale-frame clicks for both blank reference fields and accept the current frame.
Findings None None.
Security None None.

How this fits together

Subagents execute delegated work and return results to their requesting session. Their lifecycle owners coordinate SQLite persistence, recovery, cancellation, and delivery, while agent tools validate requests before dispatch.

flowchart TD
  A[Agent tool request] --> B[Validate target and current owner]
  B --> C[Execute delegated work]
  C --> D[Lifecycle and completion owner]
  D --> E[Worker write admission]
  E --> F[SQLite state and committed receipts]
  F --> D
  D --> G[Requester result and cleanup]
Loading

Before merge

  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: src/agents/tools/session-status-session-resolve.ts, unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep shared lifecycle and dispatch owners while preserving existing authority, receipt, protocol, and persisted-state contracts.

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

Yes, from source: a raw child key lacks the agent prefix required by main's recovery reader, and whitespace-only computer references bypass its raw-truthiness frame check. The focused regressions cover both paths; this review did not execute them.

Is this the best way to solve the issue?

Yes. The fixes reuse recorded ownership and existing string normalization, while the consolidation preserves variant-specific authority and settlement behavior without adding public configuration or parallel APIs.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded internal consolidation with two source-supported recovery and validation fixes, without evidence of an urgent widespread regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary contributor proof gate does not apply to this maintainer-authored PR. Inspected recovery and computer regressions supplement the captured validation reports; the reviewed changes preserve stored formats and do not establish a material authority expansion requiring additional final-effect proof.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-07T18:25:52.845Z sha d287c11 :: blocked before merge. :: none

Share registry and completion write admission, requester mutations, cleanup
finalization, scoped reads and prepared spawn facts. Carry existing owners
and parameters through tool, media and question lifecycles while keeping
variant-specific authority, replay and settlement behavior explicit.

Consolidate HTML attribute scanning with distinct render and visibility
grammars, plus repeated tool schema and result construction. Keep model
prompts, descriptions, protocol shapes and existing test assertions intact.
@steipete
steipete force-pushed the deslop/d06b-agents-subagents-tools-20261007 branch from d287c11 to 9eb0658 Compare October 7, 2026 19:15
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head CI attribution for 9eb0658df94b62de8af8d338823824fdf9d95a4f:

  • checks-node-changed-compact-small-12-1 (run 37673327738, attempt 2, job 112979702999) fails only src/wizard/setup.finalize.trusted-proxy.test.ts:461, “keeps real health authentication on the setup Gateway despite ambient endpoints”: expected completed to be true, received false. This identical assertion and helper stack reproduced once in the whole five-case file on clean main 7e16a229e3ea5fef602db2b09604bec3d1329412 (1 failed / 4 passed; 86.80 seconds wrapper time). No preceding shard file is needed to reproduce it.
  • The test, setup finalizer, health/readiness implementations, Gateway call/auth path, and real-Gateway fixture helpers are byte-identical between the PR and that main. None is changed by this PR. The child Gateway initializes the empty subagent registry during boot, but that initialization completes before the failing post-startup health call. No lane tool execution participates in the assertion's path. The exact swallowed health exception is still unresolved; this is evidence for the named inherited failure, not a claim of a general authentication outage.
  • The aggregate openclaw/ci-gate (job 112984445010) fails because the selected Node shard above failed. Both previously cancelled shards now passed: checks-node-changed-extensions-bundle-6-1 (job 112979702894) and checks-node-changed-compact-large32-1-2 (job 112979703109).

The earlier requester-wake fixture recursion was ours and was repaired in this exact head; its complete 35-case file passes. The older Discord preview failure was inherited and fixed upstream by 9df0cd095766ff05864aa67aa91b627a347a4d1a, included in this head; it is not used as a current exception.

Final exhaustive commits/<head>/check-runs census: 197 checks: 143 success, 51 skipped, 1 neutral, 2 failure; zero cancelled or pending. The neutral CodeQL aggregate reflects 15 unselected baseline configurations; all selected security and quality checks passed. The two failures are individually attributed above. The inspected failure-path files remain unchanged on freshly fetched main 05e6660fdbc0f62ff994a41ce77b6b49ad5ea9b0. No failing changed-file finding is waived. Merging the exact head under the coordinator-authorized inherited-failure exception.

@steipete
steipete merged commit d8e684e into main Oct 7, 2026
336 of 345 checks passed
@steipete
steipete deleted the deslop/d06b-agents-subagents-tools-20261007 branch October 7, 2026 20:01
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 7, 2026
…b [step 2/5]

Upstream "consolidate lifecycle and tool execution" (openclaw#166691). Thirteen
conflicting files (24 hunks) in the subagent registry and spawn code. The
feature's structure is kept, with upstream's semantic changes carried over:

- lifecycle-announce-cleanup: upstream re-indented the cleanup driver
  (runCleanup). The feature's fence placement (onBeforeDispatch at the
  sessions.delete handoff) is re-applied in upstream's block. The announce
  params take upstream's `...pendingPayload` spread, plus the feature's
  legacy-row requesterAgentId fallback.
- run-launch: failed queued launches use upstream's createFailedQueuedRun
  and then clear the feature's launchDispatch marker. The imports of both
  sides are reconciled.
- queries/read: upstream retired resolveRequesterForChildSessionFromRuns
  (read uses getLatestSubagentRunForChild); the feature's
  listAncestorSessionKeysFromRuns is kept.
- sweeper/registry: upstream dropped the resumedRuns and contextCleanup
  params; the feature keeps its shouldDeferArchive / callGatewayForSweep and
  its extracted collector-group sweep. The extracted mutators follow
  upstream's void mutateCleanup contract (no `return draft`).
- run-liveness: the feature's tunable stale cutoff and liveness verdict are
  kept, and upstream's new isYieldedSubagentRun is added.
- session-cleanup: the feature's continuation guard block is kept, with
  upstream's destructure.
- attachments: the feature's shared inline-attachment validation is kept.
  Upstream had inlined the attachment limits, which auto-merged past the
  feature's tighten-only clamp; the call to resolveAttachmentLimits is
  restored.
- spawn-request/spawn: upstream flattened the resolved request; the
  feature's continuation fields are added flat, and the feature helpers that
  read the old nested shape (spawn-continuation, spawn-registration) now
  read the flat one.
- subagent-announce: hasUsableSessionEntry now lives upstream in
  subagent-announce-delivery.runtime, so the local copy is dropped.
- Tests: the feature's tests move to upstream's consolidated
  mutateRequesterCompletionBatch (rejection-write, requester-agent), and
  restore-recovery no longer passes hasUsableSessionEntry through its mock.

Checks: typecheck clean for core and every core test shard plus
extensions-test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
…166691)

* fix(subagents): honor recorded owners during restart recovery

* fix(computer): require current frames for blank target references

* refactor(agents): consolidate subagent lifecycles and tool dispatch

Share registry and completion write admission, requester mutations, cleanup
finalization, scoped reads and prepared spawn facts. Carry existing owners
and parameters through tool, media and question lifecycles while keeping
variant-specific authority, replay and settlement behavior explicit.

Consolidate HTML attribute scanning with distinct render and visibility
grammars, plus repeated tool schema and result construction. Keep model
prompts, descriptions, protocol shapes and existing test assertions intact.

* fix(agents): preserve shared reader fixture coverage and type contracts

* test(agents): preserve real exports in consolidated mocks

* test(subagents): preserve announce runtime predicates in fixtures

* refactor(agents): satisfy lint in consolidated tool paths

* test(subagents): preserve composed requester-wake mutation spies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed 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