Skip to content

refactor(agents): deslop embedded agent runner fourth pass - #160906

Merged
steipete merged 2 commits into
mainfrom
deslop/l152-embedded-runner4
Sep 29, 2026
Merged

steipete merged 2 commits into
mainfrom
deslop/l152-embedded-runner4

Conversation

@steipete

@steipete steipete commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The embedded runner still contains duplicate result projections, unused argument plumbing, forwarding helpers, and repetitive commentary after the previous cleanup passes.

Related: #159597

User Impact

No user-visible behavior change. Run and attempt lifecycles, cancellation ordering, authority revalidation, prompt/transcript bytes, tool dispatch and schemas, provider request shaping, usage accounting, and persisted state remain unchanged.

Why This Change Was Made

This maintainer-requested fourth pass combines the remaining sound simplifications within src/agents/embedded-agent-runner:

  • Reuse the existing stage tracker, deferred primitive, path-escape predicate, string normalization, and owner types instead of maintaining local forwarding or duplicate definitions.
  • Share equivalent finalizer, retry, candidate, sender, and provider-context projections. Context builders still run at their original points across awaited work.
  • Remove unused orphan-trigger, budget-agent, auth-plan, and preparation result plumbing after checking callers and public exports.
  • Keep truncation allocation facts together instead of coordinating parallel arrays; preserve weighted budgets, notices, and frozen replay projections.
  • Collapse redundant typed branches and shorten commentary while retaining ownership, lifecycle, platform, and protocol constraints.

Measured production change: 641 net lines removed (361 added / 1,002 removed). Tests/support: 19 net lines removed. The assertion-safety baseline contains only the four exact shrink updates required by the removed assertions. Production changes remain inside the embedded runner; the command-test repair is described below.

The full production census covered 274 files / 65,765 lines. This fourth pass is below the requested 1,000-line target after implementing the sound opportunities found; the required coverage log for every production file over 200 lines follows below.

Fixes Found Along the Way

No independently established product bug or flaky-test repair is claimed in this refactor.

Evidence

Exact-head CI: approved pre-existing-failure exception

CI run 36529548540 completed on repair head f3483a23eba8c10c6edfc45a50765c60892c5e72: 127 jobs passed and 21 skipped. The only failed execution job was checks-node-compact-small-18 (job 109280246068); the aggregate openclaw/ci-gate failed because of that job. Security-fast and all CodeQL Security High checks passed; there are no pending checks or required reviews.

The tooling shard core-tooling-16-hosted-3 failed test/scripts/ci-node-worker-owner-boundary.test.ts, cases modern-corrupt and modern-unshared, with ERR_MODULE_NOT_FOUND: fixture scripts/lib/vitest-build-prerequisites.mts is absent when imported by fixture scripts/ci-run-node-test-shard.mts.

Pre-existence is proven by unrelated PR #160075 at its verified current head 4710cc9857949f295e3baf92b39d452de6874dde: its latest CI run 36528303180, same failed job failed the same two cases with the same missing prerequisite at 06:00:54 UTC, before this PR's 06:15:17 UTC failure. That PR changes Windows session/cron handling and Windows test selection; its package script edit changes no dependencies or the failing Linux path.

Independence was checked against the actual tested merge ed8fac598fd5d29b26f09517976bffbe983f2413 and its main parent 4735f663f61425b98fed9ae54550699a323e7db5: there are no PR changes under scripts/, test/, .github/, or in package.json / pnpm-lock.yaml. The sparse fixture omits the prerequisite; inherited prebuilt-mode configuration reaches its missing import before the intended worker owner or any changed agent code executes. None of this PR's changed files are in the failing test/import path. Main CI repair remains with the coordinator.

The PR's own Testbox proof and fresh review passed as recorded above. Under the operator's explicit September 27/28 pre-existing-failure rule, submit the squash merge pinned to f3483a23eba8c10c6edfc45a50765c60892c5e72; this exception does not claim green CI.

Repair of the PR-owned command-test failure at f3483a23eba8c10c6edfc45a50765c60892c5e72:

  • On main 863e377524a970787dfb2540b32722810c512cff, the missing provider map returned early; no TypeError was part of the behavior. The refactor delegates to the real findNormalizedProviderValue, which also returns undefined before normalization. Prompt-alias preparation for the colliding Google alias reaches this lookup. The command fixture's complete module mock omitted that export.
  • Reproduced the original PR failure on Blacksmith Testbox: 137 passed, one failed with the reported missing export. Main's original file passes all 138 tests. With model-selection.js fully unmocked in a temporary copy of the existing scenario, both main and the PR retain cloudflare-ai-gateway/gemini-2.5-flash-lite and requestedRouteResolution: "resolved".
  • The fix uses importOriginal to preserve real exports before applying the existing scenario overrides. No production behavior or assertions changed; production remains 361 added / 1,002 removed, net -641 lines.
  • Repaired file: 138/138 passed. Measured pnpm test src/agents/agent-command.live-model-switch.test.ts --maxWorkers=1: 48.59s wall on the final repair. The existing 138-case command/lifecycle suite remains intact; no cases were added.
  • All 20 tests mocking the agent model-selection facade plus the embedded runner directory passed: 355 files / 5,827 tests, 443.64s. The line-cap gate then required moving the unchanged collision configuration into the existing fixture helper; the affected 138-case file and fully unmocked collision were rerun successfully afterward.
  • Final node scripts/check-changed.mjs --base fd1467d466924a42f64cd00618e0f8e332b8e16f --timed: passed in 1,359.91s. Formatting, line-cap, core/test types, dead exports, lint, and all selected guards passed.
  • Independent Codex autoreview of the repair delta through P2: scoped-clean.

Local attempts were blocked by host load (worker preparation reached the no-output deadline, then the command import exceeded the existing hook deadline); the exact reproduction and comparisons above ran on Testbox without changing deadlines. The initial comparison lease expired during slow local source staging before any comparison test ran; the replacement used a 90-minute idle window.

Final repair proof lease: blacksmith-testbox, tbx_01m3ns27ctv8xqxgyr1zvsb0ed, controller run. The wrapper verifies source bytes; the controller status alone is not the proof result.

Blacksmith Testbox validation (Linux, Node 24.19). git range-diff confirms the cleanup patch is identical after the clean pre-readiness rebase at 225c629730c7e7df1cc14cba2b307892481cb9c1. On that pushed head, node scripts/check-changed.mjs --base fd1467d466924a42f64cd00618e0f8e332b8e16f --timed passed in 1,637s, the four focused OpenRouter/CLI/compaction files passed 143 tests in 67s, and pnpm build passed in 349s. The wrapper verified the frozen source and reported exit 0. The patch-identical candidate also has this earlier proof:

  • Runner directory plus importers discovered across src/, extensions/, and packages/: 606 files / 12,535 tests passed, 27 shards, 1,713s.
  • Final node scripts/check-changed.mjs: passed, 1,428s. This includes core/test types, lint, dead exports, formatting, and ratchets.
  • Final focused owner tests: 3 files / 48 tests passed, 34s; earlier replay/compaction correction checks passed 234 tests.
  • Import-boundary tests, including src/infra/fs-safe-import-boundary.test.ts and sibling boundaries: 20 files / 112 tests passed, 77s on the reviewed candidate before rebase.
  • pnpm build: passed, 337s on the reviewed candidate before rebase.
  • Agent/Gateway E2E selection: 436/437 tests passed across 12 files. Both full Gateway compaction and session-handoff flows passed. The remaining failure is described below.

Pre-rebase final lease: blacksmith-testbox, tbx_01m3ncs0hg8q4grpz44da3xpgv, controller run. Post-rebase lease: blacksmith-testbox, tbx_01m3ngcma7jxwmm87jk797p0tj, controller run. Both leases were stopped after proof. The repository wrapper verified the frozen source before running each command; the controller run alone is not the test-result claim. The post-rebase provider portal sync timed out after successful command completion; the reported test/build results and exit 0 were retained.

Changed-test cost, measured with pnpm test <file> --maxWorkers=1: stage timing 2s/6 tests; prompt helpers 39s/7 tests; attempt 29s/54 tests; transcript repair contract 42s/4 tests; session boundary 43s/30 tests. No new tests were added. Hosted CI cost will be available on the attached PR run.

Existing E2E failure: agent-runner.runreplyagent.e2e.test.ts threw AgentDatabaseRegistryChangedError at openclaw-agent-db-registry-listing.ts:287 in the adoption callback case. Replaying the identical 12-file selection on clean main 27de2f87db284610f8deb3312318fa9934cb7182 also passed 436/437, failing with the same exception/stack in the immediately preceding cancellation case. This establishes a pre-existing fixture-group failure, not exact-case reproduction or a claimed fix. The fixture mocks embedded execution; its mock never supplies context-engine attempt facts, so the changed run-entry discard path is not executed. The relevant fixture/storage sources are unchanged. Per campaign direction, existing main failures remain with the coordinator; no retry, timeout increase, skip, or assertion weakening was added.

Initial candidate validation caught type inference, obsolete fixture fields, and lint issues; these were corrected before the final passing checks. A stopped Testbox/SSH connection interrupted one check attempt, so its partial output was not counted as a passing gate.

Fresh independent Codex review of the final candidate completed scoped-clean at P0-P2. Earlier findings were checked against complete source context; no accepted actionable finding remains.

Marked ready for review at the exact pushed head above. Hosted CI run 36517130819 attached to that head and was still running at readiness; pending hosted checks are not counted as passing proof.

Fourth-pass coverage: every production file over 200 lines, sorted by original size

Embedded agent runner fourth-pass coverage

Base: ed5cddeae5269386b7b4469a02758994691eecc5. All 274 production files were read across non-overlapping worker slices. The lead inspected the combined diff. Sizes are before edits.

Lines Production file Outcome
1796 runs.ts READ — Reuse createDeferredCore for completion-claim registration. Keep synchronous abort, exact-handle claims, retained authority checks, pending-input eligibility, and forced-terminal persistence ordering intact.
1595 tool-result-truncation.ts READ — Combined small-block and suffix budget facts per block, replacing parallel index-correlated arrays and repeated aggregation. Frozen projections, weighted cuts, spill recovery, notices, and persisted byte rewrites retain their existing owners.
879 replay-history.ts READ — Reused canonical object coercion, removed redundant array revalidation after normalization, simplified custom-entry projection and blank-user filtering while retaining sparse-array identity behavior. Provider ordering and usage-accounting decisions remain unchanged.
816 extra-params.ts READ: shortened narration while retaining MiMo and non-native DeepSeek wire-format constraints. Alias precedence, wrapper ordering, and request shaping unchanged.
739 run-orchestrator.ts READ — Construct fallback runtime descriptors once with the existing conditional runtime field. Retain all generation, admission, disposal, and transcript-settlement boundaries.
736 run/attempt-session-prepare.ts READ — Removed unused orphan trigger plumbing; retain permission/replay generations and session ownership publication.
730 run/terminal-resolution.ts READ — share the identical reasoning/empty retry fact projection; combine duplicate stop-reason metadata projection; retain retry precedence, prompt bytes, transcript controls, usage, and terminal payload selection.
715 run/images.ts READ — No further sound cut: slot/fact ownership, sandbox versus admitted attachment roots, video byte budgets, and current-turn failure reporting have distinct contracts. Previous-pass shared materialization already removes the duplicate replay/provider flow.
714 compaction-session-execution.ts READ — Retained the distinct endpoint/client commit accounting, before/after hook metrics, replay repair, thinking retry, and retirement order; no further sound structural cut found.
713 model.static-catalog.ts READ: retained generation-pinned manifest/dynamic catalogs, complete prepared-provider coverage, conflict/suppression policy, and distinct context-only resolver. Replacing these with one broad resolver would conflate owners.
711 run-entry.ts READ — Combine repeated context-engine attempt discard with clearing its unsettled marker. Retain finalization/cleanup order and failure propagation; use existing custody, turn-finalization, and cyber-failover coverage.
708 run/run-attempt-dispatch.ts READ — Retain explicit attempt projection: merged spread would forward additional authority, model, or option fields.
707 model.configured-overrides.ts READ: removed redundant missing-provider-map guard; findNormalizedProviderValue already owns it. Exact-key-first behavior and configured/discovered route, pricing, media, and sizing precedence retained.
697 run/auth-controller.ts READ — remove an alternate profile-list parameter whose sole explicit caller always supplied the controller's existing candidates; remove a redundant classifier intermediate. Runtime credential generation checks, timers, rotation, and bookkeeping remain unchanged.
693 run-loop.ts READ — No sound further collapse: dispatch, recovery, normalization, finalization, and retry paths have distinct budgets and ownership fences.
685 compact.queued.ts READ — Removed a duplicate resolved-model alias and two casts/projections; removed the unused budget agentId argument and module narration. Every awaited preparation revalidation remains.
673 run/settled-turn-finalization.ts READ — unify the four original-terminal result projections, preserving late usage reads, and inline the one-use session-target overlay helper. Every await, authority assertion, writer fence, abort check, and control cleanup remains in its original order.
657 compact.queued-execution.ts READ — Retained separate native admission and engine writer ownership; same-target completion, accepted successor, late cancellation, and secondary native diagnostics have different contracts.
653 run/attempt-stream-settle.ts READ — Retain ordered async completion, timeout snapshots, usage selection, and stream wrappers with distinct contracts.
644 run/attempt-stream-prepare.ts READ — Retain steering admission, finalization checks, queue registration and post-await current-owner fences.
638 run/attempt.tool-call-argument-repair.ts READ — No sound cut: bounded malformed-JSON parser deliberately treats ordinary strings, smart-quoted keys, freeform values, edit arrays, and tool-specific successors differently; merging these would broaden repair.
635 run/attempt-llm-boundary.ts READ — Retain prompt projections and identity matching; branches preserve historical/transcript and thinking-signature bytes.
621 prepared-compaction-runtime.ts READ — Share a fresh prompt-context builder at each original invocation point; preserve post-await field reads and independent objects. Retain original sequential disposer lookup timing. Remove unused budget agentId and module narration.
603 run/attempt-finalize.ts READ — Retain separate completion and abort paths, error precedence, callback order and after-turn settlement.
591 run/runtime-preparation.ts READ — Use canonical stage tracker directly; preserve credential-scoped model materialization and fallback ordering.
591 run/attempt.ts READ — Use canonical stage tracker and one prepared retry-settings snapshot; preserve tool-resource transfer and cleanup ordering.
590 compact.ts READ — Inlined one-use explicit-model/fallback-list predicates and failure-result forwarding; retained fallback route/auth ownership and physical generation cleanup.
584 thinking.ts READ: replaced manual error-candidate any-match loop with some; shortened comments retaining opaque-signature authority and latest-turn recovery constraints. Recovery/notification/stream-settlement ordering unchanged.
583 google-prompt-cache.ts READ: removed redundant Model intersection, inlined one-use tool projection, removed null guard dominated by the earlier falsy guard, and removed module narration. Cache payloads, tool schemas, persisted entry shapes, expiry/backoff, and writer-claim propagation retained.
581 run/compaction-runtime.ts READ — Retain durable/memory successor paths and exact owner rechecks; consolidation would hide distinct persistence authority.
566 run/attempt-recovery.ts READ — Retain ordered recovery classifications and bounded retry effects; settled-tool continuation differs from replay.
548 run/attempt-prompt-helpers.ts READ — collapsed three queued-marker matching branches already subsumed by line-delimited text matching; removed unused merge trigger and duplicate narration. Retained SDK-exposed fs-policy adapter, durable injection retry cache, structured-media bounds, and context-engine runtime projection.
546 run/attempt-prompt-build.ts READ — removed unused orphan merge trigger arguments. Remaining sequencing distinguishes transient/provider prompts from persisted transcript prompts and preserves post-await authority checks, exact-mode runs, and steering ownership.
536 model.ts READ: shortened error-hint commentary only. Kept all authority checks after awaits, catalog/auth ownership, selected-ID handling, and model-facing error text.
530 run/assistant-failure.ts READ — no safe further change: thinking repair, invisible-error retries, profile rotation, and asynchronous failed-profile settlement have distinct failure precedence; existing outcome builder already owns shared projection.
527 run/llm-idle-timeout.ts READ — Remove redundant first-arm latch; one existing consumed flag owns pre-stream tool timestamp bridging.
519 delivery-evidence.ts READ — No sound further collapse: unknown external evidence requires validation and separate aggregate, visible, partial, source-final, and committed evidence contracts.
504 run/attempt-prompt-phase.ts READ — no further sound simplification: this owner publishes each failure/admission transition before fallible phases and retains distinct compaction, steering, and yield cleanup.
498 tool-result-context-guard.ts READ — Removed the single-use enforceToolResultLimit forwarding function; the installed guard now owns its estimate cache and calls the existing projection/truncation owners directly. Context-engine lifecycle and all abort checks remain untouched.
495 run/attempt-setup.ts READ — Replace local relative-path escape predicate with fs-safe owner; use canonical stage tracker directly.
494 run/payloads.ts READ — no safe further change: streamed/canonical text, reply directives, stored TTS facts, source mirrors, cron silence, and error suppression each protect distinct output-byte and delivery contracts; the third pass already owns source-reply extraction.
489 run/session-bootstrap.ts READ — Retain legacy marker resolution and writer claim/admission fences; storage migration would exceed this deslop contract.
479 run/types.ts READ — Retain public harness/result contracts, own-property semantics, and documented upgrade fields.
475 run/attempt-tool-prepare.ts READ — No sound cut: construction options are an explicit projection, while generation retirement, approval revocation, and live permission refresh preserve ordering and ownership.
474 model.registry-resolution.ts READ: retained async auth settlement/revalidation, explicit model precedence, suppression/runtime comparison, and configured fallback. Consolidating hook contexts only to reduce LOC would obscure the preparation boundary.
469 run/lane-controller.ts READ — Retain session/global lane and attempt ownership separation, live fences, capacity waiting, and abort precedence.
462 run/attempt-stream.ts READ — Retain provider wrapper ordering and repair settlement; stream-specific fields require the existing narrow adaptation.
451 run/overflow-context-recovery.ts READ — Retain compaction, truncation and continuation gates with independently observed effects and authority rechecks.
447 run/attempt-system-prompt-prepare.ts READ — shared provider prompt-context construction while invoking the builder separately at the original preparation points, preserving reads across awaits. Retained permission/tool-generation cache and every active-authority check.
443 run-state.ts READ — No sound further collapse: global maps preserve hot-reload compatibility, while duplicate-looking authority checks bracket reentrant probes and must remain.
437 run/attempt.model-diagnostic-lifecycle.ts READ — Retain separate public hook and private diagnostic projections, request-body observer ordering and terminal once semantics.
436 run/attempt-tool-call-replay-sanitization.ts READ — No sound cut: completed replay tools, displaced result pairing, signed-thinking preservation, provider-specific ID policy, and fresh live tool availability cannot share one permissive decision.
429 run/attempt-result.ts READ — Retain field-presence projection and post-hook evidence snapshots; shared broad spreads would alter result contracts.
415 run/attempt-queue-message.ts READ — Retain steering receipts, terminal cleanup, exact-message cancellation and optional-argument adaptation.
413 run/attempt-settle.ts READ — Retain transcript writes, captured binding assertions, incognito path and committed-error reporting boundaries.
407 direct-compaction-preparation.ts READ — Inlined single-use model materialization/resolution adapters so inference comes from the auth owner; removed their duplicated parameter type and unused returned start time.
407 context-engine-maintenance.ts READ — Removed module narration. Retained coalescing, per-engine resource custody, signal reraising, and shutdown cleanup. The wait wrapper has out-of-lane CLI callers and cannot be fully retired inside this lane.
402 run/attempt-history.ts READ — shared sender text projection across string and structured content while retaining identity/no-op behavior and media blocks. Retained identity-before-structural pairing and provenance-first projection.
399 run/incomplete-turn-recovery.ts READ — no safe further change: settlement requires both persisted call/result identity and lifecycle completion; retry and silence deliberately differ on side effects, accepted spawns, output budget, and terminal ownership.
393 prompt-cache-observability.ts READ: simplified cache-affinity fallback and delegated map capacity checks to existing pruneMapToMaxSize. Kept fingerprint bounds, unreadable/getter defenses, field order, diagnostic text, usage baseline, and cache-break thresholds.
387 run/attempt.model-diagnostic-observation.ts READ — Retain unknown-value and getter-safe observation, stream-byte accounting, terminal precedence, and diagnostic capture policy; the third pass already extracted the observation owner.
386 run/failover-retry-controller.ts READ — no safe further change: provider Retry-After floors, run-owned cancellation, separate count/outage budgets, profile health, and rotation caps are already centralized in this controller.
384 compaction-runtime-context.ts READ — Replaced local trim/lowercase implementation with the canonical string normalizer and removed unused budget agentId input. Nullable context projection and alias/literal precedence remain explicit.
383 run/preemptive-compaction.ts READ — Retain distinct outgoing-provider and unwindowed diagnostic pressure, cache checkpoints, and truncation thresholds; merging those branches would change compaction decisions.
383 run/params.ts READ — Retain public caller option surface and inherited command contracts; narrowing or deleting fields needs external caller cutover.
379 compaction-successor.ts READ — No change: legacy successor support has an explicit shipped contract; expected-entry checks, commit facts, and lifecycle publication guard distinct failure stages.
378 run/prompt-failure.ts READ — no safe further change: precheck-only replay refresh, CLI stop precedence, deferred failed-profile bookkeeping, and thinking fallback differ intentionally from assistant failure recovery.
365 run/incomplete-turn-resolution.ts READ — pass the existing continuation evidence directly to the canonical delivery predicate, which already handles missing arrays; remove the duplicate three-field/default-array projection. Historical tool-result roles, error copy, and liveness classification remain intact.
358 types.ts READ — Remove narrating result-field comments and redundant module header; retain notes about cumulative accounting, visibility, and source ownership.
358 run/terminal-preparation.ts READ — no safe further change: current-attempt attribution, usage accumulator ownership, terminal receipt, partial answer recovery, and media provenance have separate consumers. Replacing result fields with broad spreads would weaken boundaries.
354 run/attempt-prompt-support.ts READ — no further sound simplification: concrete tool baseline and capability intersection serve live permission refresh; observability fields and hooks describe separate retained boundaries.
353 run/model-setup.ts READ — Retain pinned native ownership, operator policy, catalog failure propagation, and post-await assertions; the native and host-auth paths have different contracts.
344 run/tool-media-payloads.ts READ — No sound cut: carried batches retain separate trust/voice/source-suppression provenance; collapsing their selection and delivery projection would combine authority.
331 run/attempt-prompt-submit.ts READ — no further sound simplification: provider transform installation, persistence waits, steering assertions, dispatch accounting, and nested cleanup ordering each protect distinct lifecycle contracts.
318 run/history-image-prune.ts READ — No sound cut: fact-owned projection replacement and pre-MediaFact legacy hygiene intentionally differ; the completed-turn fence prevents active tool-loop prefix edits.
315 stream-resolution.ts READ: retained session/runtime ownership, native versus boundary-aware transport selection, credential revalidation, and weak activity bridging for composed abort signals. These wrappers enforce distinct contracts.
308 result-fallback-classifier.ts READ — No sound further collapse: priority-ordered refusal, delivery, incomplete-turn, and silent-response decisions own different retry contracts; descriptor proposals did not simplify the code.
307 compaction-hooks.ts READ — Removed repeated validation of the parsed post-index mode and module narration; kept mode-dependent settlement and every authority assertion.
301 run/attempt-tool-call-stream-normalization.ts READ — No sound cut: generated IDs are response-local and partial/final alias counting prevents duplicate retry increments. Branch merging obscures threshold and malformed-name behavior.
297 run/attempt-session-runtime-prepare.ts READ — Retain ordered session creation, persistence wait, boundary preparation, guard/transport wiring, and immediate resource capture for cleanup.
294 cli-backend-dispatch.ts READ — Condense repeated dispatch documentation while preserving subscription-billing, tool-policy, transcript, and timeout ordering rationale.
291 run/tool-error-warning.ts READ — No sound cut: timeout, process, shell, and general tool errors use distinct existing user-facing formats; Markdown command/context parsing is required to preserve literal commands.
289 run/attempt-normalization.ts READ — no further sound simplification: usage chronology, context mutation, interruption ownership, and retry finalization cannot share one undifferentiated path without changing behavior.
287 compaction-runtime-preparation.ts READ — Removed module narration. Auth convergence and profile-scoped materialization cannot be collapsed without changing route/provider ownership.
279 run/attempt-tool-construction-plan.ts READ — No sound cut: construction is a superset admitted by final runtime policy; MCP namespace discovery and LSP matching differ. Existing shared construction and intersection owners are already used.
278 run-entry-terminal.ts READ — No sound further collapse: terminal metadata's own-property rules intentionally differ by delivery behavior, and receipt ownership must remain explicit.
277 run/incomplete-turn-classification.ts READ — no safe further change: loose message/usage parsing is an actual boundary; signatureless thinking versus empty content and pre-tool commentary versus composed answers have distinct recovery contracts.
276 openrouter-model-capabilities.ts READ: callers now rely on triggerFetch for refresh deduplication; collapsed awaited-miss refresh branches. Cache persistence, schemas, parsing, timeout/body cleanup, and skip-next-miss semantics unchanged. SDK exports remain needed.
273 run/attempt-prompt-preflight.ts READ — no further sound simplification: diagnostic-only pressure, canonical replay pressure, and truncation recovery have intentionally different effects. The small shared budget snapshot already owns duplicate projection.
269 run/setup.ts READ — APPLIED: reuse the hook runner owner types for context, runner methods, and hook results instead of three local contract declarations.
269 run/auth-profile-success.ts READ — use canonical isStringOption for model API validation, remove duplicate plugin-harness runtime-owner branches, and pass existing input to the narrow sentinel-resolution helper. Fingerprinting/materialization precedence and asynchronous success bookkeeping are unchanged.
266 run/attempt-bundle-tools.ts READ — Removed the redundant empty-client-list branch before filtering through the runtime matcher. MCP/LSP cleanup and live permission projections are retained.
264 model.manifest-alias.ts READ: retained activated/trusted owner arbitration, endpoint/API compatibility, ambiguity handling, and generation-owned metadata. Prior-pass alias work is not duplicated.
261 run/session-prompt-state.ts READ — Retain single initial-writer owner, commit-edge successor bookkeeping, internal prompt byte construction, and runtime persistence settlement.
258 model.provider-hooks.ts READ: retained lazy hook ownership and route normalization. Apparent duplicate cost normalization cannot use normalizeResolvedPricing: that would change tier metadata and object identity.
256 run/attempt-history-prepare.ts READ — no further sound simplification: raw-mode reset, quota-resume hierarchy restoration, replay limits, and context-engine assembly preserve separate invariants; transcript repair reapplication after windowing is necessary.
252 run/auth-plan.ts READ — remove the unused usesOpenAIAuthRouting return field after a full src/extensions/packages/ui/apps/scripts/test reference scan; the local routing decision is unchanged. Native binding auth, provider-scoped overlays, and one harness convergence retry have different route ownership.
252 run/attempt.model-diagnostic-events.ts READ — Retain separate iterator/result settlement, unopened-generator closure, bounded provider cleanup, and proxy invariants for nonconfigurable streams.
249 run/attempt-tool-catalog.ts READ — No sound cut: visible/live/capability names replace current sets while replay names grow monotonically; preserved set identities are consumed by retained callbacks.
242 cli-backend-dispatch-transcript.ts READ — Keep one explanation for immediate tool mirroring versus buffered assistant text; preserve exact record bytes and write serialization.
241 transcript-rewrite.ts READ — No sound cut: entry-type replay preserves branch links, pending-input relocation, historical identity, and compaction checkpoint invalidation. Removing specialized append paths changes persisted history.
241 run/failover-policy.ts READ — consolidate identical surface-error results; inline the one-use retry-limit predicate so the proven non-null reason needs no fallback; reuse the existing concrete-non-timeout predicate for assistant fallback reason. Prompt/assistant/run-budget/external-abort precedence remains unchanged.
240 run/attempt-client-tools.ts READ — No sound cut: client slot reservation, raw trusted-media names, concrete replay-safe tool identities, and side-effect owner ambiguity each protect distinct runtime contracts.
239 run/attempt-async-tasks.ts READ — Retain cron-only completion policy, registry fallback, dynamic approval deadline, and named abort errors; generic abortable uses a different error marker.
239 model.inline-provider.ts READ: retained inline duplicate-row merging before defaults, secret-marker filtering, and legacy Foundry modality compatibility. Transport API vocabulary differs from config's newer pi-messages value; no behavior change without entry-point evidence.
236 model.configured-fallback.ts READ: retained fallback-specific omission of unknown output caps, authored pricing, route support checks, and provider-owned transport. It cannot safely share the discovered-model overlay wholesale.
232 run/provider-review-continuation.ts READ — no safe further change: payload and metadata checks protect the acknowledged user-input suffix; acceptance, dispatch, and post-await live-authority checks are necessary distinct edges.
228 run/attempt-transcript-lifecycle.ts READ — Retain nested serialization, error precedence and deferred AsyncLocalStorage disposal; generic queue would change lifecycle.
227 message-visibility.ts READ — No sound cut: payload displayability, terminal source delivery, silent turns, and intermediate transcript progress have distinct trust/visibility contracts. Cyclic attachment protection is real in-process boundary handling.
225 run/provider-review-run.ts READ — no safe further change: admission, attempt claiming, refusal recording, queue cleanup, and continuation terminal classification own separate state transitions.
223 run/deferred-lifecycle-owner.ts READ — Retain CLI/embedded handoff owners and release order; retained callbacks must not target replacements.
222 history.ts READ — No sound cut: account/thread/linked-peer interpretation cannot use only current dmScope; turn eviction preserves prelude summaries and cache-stable batches.
217 session-prompt-state.ts READ — No sound further collapse: cloning, LRU, frozen projections, and serialized TTL markers have distinct state contracts; transcript bytes and snapshot hashing remain untouched.
209 sandbox-skills.ts READ — No sound further collapse: lexical host-path mapping and Linux container path normalization differ; library-selection failure and explicit-empty snapshot semantics are necessary.
209 provider-prompt-state.ts READ: retained ordinary-data structured-clone eligibility checks, worker failure fallback, exact request digests, and byte-identical retry admission. Removing the clone guards would change custom payload serialization.
204 run/pre-persisted-user-turn.ts READ — Retain live writer checks and exact persisted message/anchor/version witnesses on both preparation and later replay admission.
203 run/attempt-execution-phase.ts READ — Retain context replacement authority, history-failure cleanup, callback transcript binding, and timeout/stream installation order.
202 run/attempt-tool-call-name-resolution.ts READ — Replaced hand-written minimum-offset reduction with Math.min and removed redundant loop-length guard; exact/alias/case-insensitive precedence and ambiguous inference remain unchanged.
202 run/attempt-context-engine-helpers.ts READ — Retain distinct bootstrap completion, compaction-scoped usage fallback, and stable prompt-cache result projection; these are independent policies.

Reuse canonical helpers and owner types, consolidate equivalent result and
prompt projections, and remove unused argument plumbing and narration.
Preserve lifecycle, cancellation, authority, transcript, request, and usage
contracts. Shrink only the assertion baseline entries affected by this cleanup.
@clawsweeper

clawsweeper Bot commented Sep 29, 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 agents Agent runtime and tooling size: XL labels Sep 29, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 29, 2026, 2:18 AM ET / 06:18 UTC (Revision 3).

ClawSweeper review

What this changes

The branch removes duplicate helpers and unused plumbing from OpenClaw’s embedded agent runner and adjusts command-test fixtures while aiming to preserve runtime behavior.

Merge readiness

⛔ Blocked before merge - 3 items remain

The cleanup remains distinct from the merged third pass and is absent from current main. One newly added broad partial mock conflicts with the scoped agent test policy and has a narrow repair.

Priority: P3
Reviewed head: f3483a23eba8c10c6edfc45a50765c60892c5e72

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Substantial focused validation supports the cleanup, but the newly introduced broad test mock needs a narrow repair.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The maintainer-authored cleanup is exempt from the external-contributor proof gate. The PR reports Testbox command, runner, and Gateway validation; the introduced diff does not change a stored-data contract, so migration proof is not applicable.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored cleanup is exempt from the external-contributor proof gate. The PR reports Testbox command, runner, and Gateway validation; the introduced diff does not change a stored-data contract, so migration proof is not applicable.
Evidence reviewed 9 items Introduced test mock: The final PR commit replaces an explicit model-selection mock with an importOriginal partial mock that exposes the whole real facade.
Scoped test policy: The agent test guide calls for explicit mock factories and says to avoid broad importOriginal partial mocks in hot agent tests.
Narrow lookup owner: The needed normalized provider lookup is a small export that delegates to the model catalog core helper.
Findings 1 actionable finding [P2] Keep the model-selection mock explicit in this hot test
Security None None.

How this fits together

The embedded agent runner takes admitted requests through model selection, provider calls, tool execution, and transcript handling to produce a final reply. The changed command test exercises model selection at that boundary.

flowchart LR
  A[Inbound request] --> B[Run admission]
  B --> C[Model selection]
  T[Command test fixture] --> C
  C --> D[Embedded agent attempt]
  D --> E[Provider and tools]
  E --> F[Transcript and reply]
Loading

Before merge

  • Keep the model-selection mock explicit in this hot test (P2) - The new importOriginal() spreads every real model-selection export into this 138-case command fixture, so unlisted calls can bypass its controlled doubles and the full facade is loaded. The newly needed provider lookup has a narrow owning helper; expose that lookup explicitly in the existing mock instead. This concern was introduced after the earlier reviewed head.
  • Complete next step (P2) - Replace the broad model-selection partial mock with an explicit normalized-lookup export and rerun the 138-case command test before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P2] Keep the model-selection mock explicit in this hot test — src/agents/agent-command.live-model-switch.test.ts:666-668
Agent review details

Security

None.

PR surface

Source -641, Tests -19, Other -2. Total -662 across 76 files.

View PR surface stats
Area Files Added Removed Net
Source 67 361 1002 -641
Tests 8 33 52 -19
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 4 -2
Total 76 396 1058 -662

Review metrics

Metric Value Why it matters
Command-test wall time 48.59 s / 138 cases The new partial mock sits in an import-bound agent suite, making its dependency boundary relevant to review.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/embedded-agent-runner/run/attempt-orphan-repair.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep the smaller runner while preserving explicit test isolation and the existing admission, provider, transcript, and reply contracts.

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

Not applicable to a reported product defect. The newly introduced partial mock is directly visible in the pinned test diff; the PR body reports that the command suite passes after the fixture repair.

Is this the best way to solve the issue?

No, not quite: the production simplifications appear coherent, but the command fixture can supply the one real normalized lookup through an explicit mock without importing the full model-selection facade.

Full review comments:

  • [P2] Keep the model-selection mock explicit in this hot test — src/agents/agent-command.live-model-switch.test.ts:666-668
    The new importOriginal() spreads every real model-selection export into this 138-case command fixture, so unlisted calls can bypass its controlled doubles and the full facade is loaded. The newly needed provider lookup has a narrow owning helper; expose that lookup explicitly in the existing mock instead. This concern was introduced after the earlier reviewed head.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The maintainer-authored cleanup is exempt from the external-contributor proof gate. The PR reports Testbox command, runner, and Gateway validation; the introduced diff does not change a stored-data contract, so migration proof is not applicable.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P3: This is an internal cleanup with no claimed user-visible behavior change and one narrow test-fixture repair.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The maintainer-authored cleanup is exempt from the external-contributor proof gate. The PR reports Testbox command, runner, and Gateway validation; the introduced diff does not change a stored-data contract, so migration proof is not applicable.

Evidence

Acceptance criteria:

  • [P1] pnpm test src/agents/agent-command.live-model-switch.test.ts --maxWorkers=1.
  • [P1] node scripts/check-changed.mjs --base fd1467d --timed.

What I checked:

Likely related people:

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

Rank-up moves

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

  • Replace the broad partial mock with an explicit export of the real normalized provider lookup, then rerun the command test.

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 (2 earlier review cycles)
  • reviewed 2026-09-29T02:49:20.159Z sha 225c629 :: blocked before merge. :: none
  • reviewed 2026-09-29T03:36:22.151Z sha 225c629 :: blocked before merge. :: none

@steipete
steipete marked this pull request as ready for review September 29, 2026 03:26
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: f3483a23eba8c10c6edfc45a50765c60892c5e72
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/embedded-agent-runner/effective-tool-policy.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/embedded-agent-runner/run/auth-controller.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/embedded-agent-runner/run/auth-plan.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/embedded-agent-runner/run/auth-profile-success.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/embedded-agent-runner/sandbox-info.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) September 29, 2026 03:30
Use a partial mock so missing provider maps reach the real normalized lookup. Keep the collision fixture and assertions intact, moving its config into the existing helper to satisfy the line-cap ratchet.
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Sep 29, 2026
@steipete
steipete merged commit 46147f5 into main Sep 29, 2026
222 of 225 checks passed
@steipete
steipete deleted the deslop/l152-embedded-runner4 branch September 29, 2026 06:36
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 30, 2026
…160906)

Consolidate equivalent embedded-runner projections and owner helpers, remove unused plumbing, and simplify redundant branches while preserving run authority, cancellation, prompt/transcript bytes, tool policy, transport shaping, and usage accounting. Production change: 361 added / 1,002 removed, net -641 lines.

Preserve real model-selection exports in the command test mock. Missing provider maps return undefined on both main and the refactor; the legacy automatic fallback still wins over the colliding alias. Keep the unchanged collision configuration in the existing fixture helper to satisfy the line-cap ratchet.

Validation: main/PR comparison with model-selection fully unmocked; 138 command tests; all 20 facade-mocking siblings plus embedded runner tests (355 files / 5,827 tests); final check-changed; independent autoreview through P2. No production behavior change is claimed.

Related: openclaw#159597

Exact-head CI exception: checks-node-compact-small-18 has the same two sparse-runner missing-prerequisite failures as unrelated PR openclaw#160075 run 36528303180. All other execution jobs passed or skipped. See PR Evidence.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant