Skip to content

refactor(agents): consolidate runner, compaction, and delivery flow - #167325

Merged
steipete merged 4 commits into
mainfrom
deslop/d03-p3-20261007
Oct 8, 2026
Merged

steipete merged 4 commits into
mainfrom
deslop/d03-p3-20261007

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The embedded agent runner and its immediate compaction, delivery, and failover owners repeat operations across closely related paths, making behavior harder to maintain consistently.

User Impact

No user-visible behavior change. Features, prompt and error text, configuration, CLI and protocol shapes, persisted data, authority checks, recovery, replay, and plugin SDK declarations remain unchanged.

Why This Change Was Made

Shared code now handles cancellation settlement, checkpoint prompt scaffolding, tool-payload traversal, delivery receipt projection, ordered failover classification, stream construction, and chunk metadata emission. Real differences remain explicit, including abort-error construction, redaction mode, omitted versus undefined fields, and transport/recovery behavior. Single-use forwarding and redundant internal parameter threading are removed where ownership already supplies the value.

This is d03's third and final PR, submitted under the coordinator's 500–999-line exception with complete coverage: 643 net production lines removed (1,069 added / 1,712 deleted), across 103 production files. Counts use git diff --numstat origin/main...HEAD, excluding tests, fixtures, test support, generated files and declarations. Of this reduction, 314 lines are inside the runner directory and 329 are in its immediate owners/callers.

The largest-file-first pass covers all 285 runner production files and 26 assigned subscriber files, then adjacent owners. It implemented and measured shared-core alternatives, including rejected prototypes that were longer or obscured behavior. The implementation window exceeded two hours. Complete per-file decisions and measured alternatives: part 1, part 2, part 3.

Evidence

  • Final native plugin SDK comparison at 34e39db29179ceb9b7f2ce09f727c2aeded0b83a: zero added/removed entrypoints and zero changed exports or reachable declarations. Testbox run, verified source tree a1f1b52fe5b6607bfea3089ad3e036b947425d21; comparison command completed in 567.6 seconds.
  • Full Testbox proof: 529 files / 8,682 tests passed, covering the complete runner directory and 184 exact adjacent/caller test files, across 14 Vitest groups. Run; source commit 328c9d7c559ba43c08b4338fdcd68f6efe98ef14, verified tree cec7c62a0837da6e52597fafb1691cb0eacd2597. Runtime/E2E build passed in 341.9 seconds; test wrapper took 2,262.99 seconds. The task-owned Testbox lease was stopped after proof.
  • Follow-up proof for later lint and SDK-contract restorations passed: four lint-repair test files, then 12 SDK-correction files / 223 tests in 108.76 seconds. Existing SDK-visible aliases, private declarations, live-edit counters, and delivery lifecycle operations were restored when the first API comparison detected declaration drift. A further chunker declaration restoration passed 87 owner tests plus the three mandatory suppression tests in 110.62 seconds, along with core types, scoped lint, and fresh independent review. No API acknowledgment or waiver is used.
  • Core production types, all core test-type shards, scoped lint, and every remaining selected architecture/auth guard passed. Runtime import cycles: 0. Madge components: 0 on candidate and clean main. Mandatory lint-suppression tests passed; no suppressions added.
  • All three compaction prompt byte comparisons passed. Differential checks covered 15,841 model/stream cases and 10,065 chunker cases. Independent review of the complete change and subsequent corrections found no actionable P0–P2 issues.
  • Changed tests only adapt fixtures to moved internal parameters; no assertions were removed or weakened. The four-file cost run passed 94 tests in 608.83 seconds including cold worker preparation, using pnpm test <exact files> --maxWorkers=1; the final diff retains three of those fixture changes. No test timeout, retry, skip, or worker budget changed. The assertion-safety baseline shrinks only.
Local changed-check attribution

node scripts/check-changed.mjs passed core production/test types and its preceding checks, then stopped at two untouched branch-base dead exports:

  • SessionPendingInputState in src/config/sessions/session-accessor.sqlite-pending-inputs.ts, fixed upstream by 19f37f076862830f9b8953287f94a4725e3b8908.
  • discardStreamSegmentIndexes in ui/src/pages/chat/stream-segment-pruning.ts, fixed upstream by e8e341ecebf70a0d3802b3f52deecb4d53ec1ebb.

Both files are byte-identical to this branch's base. Fresh target main ea7cc1066568fbbeece9151c497ecab15923bd2a passed all three native deadcode scans with zero findings. All eight checks after that stop were run separately and passed. These are resolved branch-base findings, not a current-main-red waiver; exact-head hosted PR checks remain the landing gate.

@clawsweeper

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

Copy link
Copy Markdown
Contributor Author

Coverage log, part 1 of 3.

Per-file decisions: rows 1–132 of 380

Base b3196dfda33555857eae9cd52ea29367a91bd9ea → final head 34e39db29179ceb9b7f2ce09f727c2aeded0b83a (tree a1f1b52fe5b6607bfea3089ad3e036b947425d21).

643 net production lines removed (1,069 added / 1,712 deleted) across 103 changed or new production files. Tests, fixtures, test support, generated files, and declarations are excluded from that count.

All 285 assigned runner files and 26 assigned subscriber files have recorded decisions. This complete table also includes adjacent owners, for 380 unique files in total. There are no decision gaps or changed-file focused-test-target gaps. The entries record implementation and differential evidence; validation results belong to the PR's proof summary.

File Scope Base lines Final lines Decision and evidence
packages/agent-core/src/harness/compaction/branch-summarization.ts compaction 272 256 Retained byte-identical shared checkpoint prompt scaffold. Restored caller-specific summary error construction and the extractSummaryText public API: the API-safe shared response-classifier aggregate was two lines longer (357 vs 355).
packages/agent-core/src/harness/compaction/compaction.ts compaction 1029 979 Shared exact Markdown checkpoint structure with branch/updating variants; shared token-fit predicate while preserving lazy summary getter reads; inlined the single-use file-operation collector at its existing call point, retaining fresh prior-details reads and history-before-prefix order.
packages/agent-core/src/harness/compaction/summarization-completion.ts compaction 99 99 Restored caller-specific typed error branches around the existing shared extractSummaryText API. The API-safe classifier and owner aggregate measured 357 versus 355 lines; prompt scaffolding and other compaction reductions remain elsewhere.
packages/agent-core/src/harness/compaction/summarization-prompts.ts compaction 23 23 Retained one existing system/provenance prompt owner; its runtime timestamp and user context carrier remain unchanged.
packages/agent-core/src/harness/compaction/summary-checkpoint-prompt.ts compaction 0 28 New internal scaffold owner for the three existing checkpoint prompts. Introduction and section text remain explicit variants; only the identical Done text is a shared default. Public compaction entrypoints and prompt bytes are unchanged.
packages/agent-core/src/harness/compaction/utils.ts compaction 342 342 Restored the existing exported extractSummaryText API exactly. An API-safe shared response classifier prototype measured 357 lines across its owners versus 355 retaining this extraction core and caller-specific typed error branches, so the longer shared classification form was rejected.
src/agents/compaction-planning-projection.ts compaction 282 282 Retained P2 SameValue (Object.is) identity derivation, including malformed NaN. Existing rejected shared-entry closure costs extra per-container state and saves only two lines versus the direct key-budget loops; all bounded-read/CJK behavior stays explicit.
src/agents/compaction-planning-worker-runtime.ts compaction 64 64 Re-read the two new workerClass: compute lines since P2. Shared versus private pool ownership and caller-abort identity are still separate. No changes.
src/agents/compaction-planning-worker.ts compaction 149 149 Retained P2 shared planner input contracts and the existing common runtime pipeline. More generic factories need a cast through the discriminated request union or longer typed build-input callbacks.
src/agents/compaction-planning.ts compaction 344 344 Retained P2 simplifications and the original two-pass atomic batch selection. A batch can drop assistant/results while preserving a displaced user; aligned estimates and destructive pruning need separate owning indexes.
src/agents/compaction-planning.worker.ts compaction 111 111 Retained worker protocol and exact unknown-input validation. Result discriminants have different shapes; existing indexer already shares all index-returning branches.
src/agents/compaction-real-conversation.ts compaction 116 116 Retained P2 shared anchor vocabulary and precise 20-message aging. Non-text blocks must not bypass later text reads in the same message; content and provenance checks remain unchanged.
src/agents/compaction-replay.ts compaction 10 10 Retained ten-line shared usage-before-thinking replay composition.
src/agents/compaction-usage.ts compaction 56 56 Retained both real production modes: in-place subscriber cleanup and identity-preserving replay cleanup. Missing-summary behavior and timestamp fallback remain distinct used policies.
src/agents/compaction.ts compaction 339 339 Retained P2 shared summary-failure recording and empty single-stage dispatch. Source is byte-identical to P2; no new sound duplicate remained after re-evaluating those paths against the lower-level harness owner.
src/agents/embedded-agent-block-chunker.ts root 750 742 Shared source metadata emission and exact lazy maximum calculation; combined equivalent tail-stop predicates. Retained resolveBreakResult and original pickPreferredBreakIndex signature/defaults because both appear in the exported class SDK declaration. Restoring them costs 23 lines (31-line prototype reduction becomes 8); no API waiver. The initial prototype passed 10,065 differential cases covering chunks, metadata, source/state/array identity, replacement, emitter reentrancy and mutable budgets; the restored implementation passed 87 owner tests. Cleanup-core alternative grew +4.
src/agents/embedded-agent-error-observation.ts root 197 197 Read complete owner/tests/callers. Runtime parsing, redaction and fingerprinting already have one owner; text observations delegate to it. Formatted common-return-fields prototype: 197 to 195 (-2), rejected as less clear because it adds an intersection alias across public annotations without simplifying any runtime work. Explicit optional property presence, bound-before-hash and fail-closed behavior retained.
src/agents/embedded-agent-helpers/anthropic-api.ts model_prompt 3 3 Re-read full three-line re-export. Existing shared provider predicate owner serves callers; deleting facade would only move imports outside scope, not eliminate implementation.
src/agents/embedded-agent-helpers/assistant-message-failures.ts model_prompt 57 57 Re-read full module. Auth/billing/rate predicates are each two-line exports required by callers, with one specific classifier each. Terminal guard and prepared provider owner belong to shared failover classifier. Generic higher-order predicate adds a factory plus three calls without removing the public wrappers.
src/agents/embedded-agent-helpers/bootstrap.ts model_prompt 463 460 Applied common per-file append/budget update with explicit personal-metadata inclusion. Missing-file markers still omit personalUser; Unicode slicing, warning text, budget bounds and original getter counts preserved. 450 differential budget/file cases. Initial append-only prototype 463 -> 462; retained combined file 463 -> 460.
src/agents/embedded-agent-helpers/context-file.ts model_prompt 7 7 Re-read full seven-line shared data type. All fields used, including authenticated personal-user marker; shape unchanged.
src/agents/embedded-agent-helpers/context-overflow-observation.ts model_prompt 49 49 Re-read full module. Input, max-token, effective-context and provider-limit facts have distinct sources; one derived observation shape feeds downstream recovery. No repeated selection core.
src/agents/embedded-agent-helpers/error-text.ts model_prompt 326 326 Re-read full module and provider-owner test. Already delegates provider classification to canonical failover owner. Message categories retain ordered, exact user text and redaction/formatting boundaries; data table would still require category-specific parameter projections and return shapes. No additional duplicated computation found.
src/agents/embedded-agent-helpers/google.ts model_prompt 13 13 Re-read full module. Public re-export preserves import ownership and one three-API predicate; table adds a constant/import without simplifying runtime control flow.
src/agents/embedded-agent-helpers/image-errors.ts model_prompt 45 45 Re-read full module. Image dimensions and image count are independent limits, with distinct parse and user-message contracts. Existing optional-number coercion is shared; no duplicate owner.
src/agents/embedded-agent-helpers/images.ts model_prompt 107 107 Re-read full module. Two message roles use the same content visitor, retaining lazy changed-array copying, original identity, limits and role-specific wrappers. No second transform core remains to extract.
src/agents/embedded-agent-helpers/messaging-dedupe.ts model_prompt 78 78 Re-read full module. Shared normalizer and length guards serve message comparison; substring direction and target/channel equivalence intentionally differ. No redundant retained state or second decision owner found.
src/agents/embedded-agent-helpers/openai.ts model_prompt 327 320 Applied identical malformed-block guard in the owning assistant-content mapper rather than in both callbacks. Sparse array holes, NaN identity and untouched message identity preserved; no ID/pairing rules changed. 676 differential replay cases using actual normalization/compaction helpers.
src/agents/embedded-agent-helpers/provider-runtime-failure.ts model_prompt 217 208 Applied ordered OAuth pattern/kind table; inlined single-use sandbox, schema and timeout predicates. Keep replay predicate invocation order and schema-options getter boundary deliberately intact. 5632 classification/imported-call/getter differential cases.
src/agents/embedded-agent-helpers/sanitize-user-facing-text.ts model_prompt 294 294 Re-read full module. Separate tool-call dumps, model wrappers, thinking tags and final user-visible rendering use distinct delimiters and malformed-input handling. Existing sanitation pipeline already shares its repeated parsing core; exact bytes/order retained.
src/agents/embedded-agent-helpers/thinking.ts model_prompt 48 41 Applied identical malformed-block guard in the owning assistant-content mapper rather than in both callbacks. Sparse array holes, NaN identity and untouched message identity preserved; no ID/pairing rules changed. 676 differential replay cases using actual normalization/compaction helpers. | Shared caller decision; count comes from its separate final row. Inlined the sole supported-value parser into fallback-level selection. Empty fragments still normalize to an empty list via the existing pure normalization owner. Mandatory reasoning, unsupported-off, quoted/unquoted values and attempted-level ordering preserved in 1280 differential cases.
src/agents/embedded-agent-helpers/turns.ts model_prompt 363 337 Applied common consecutive-turn append path, flattened Anthropic unchanged-message guards, and inlined the sole aborted-turn predicate. Truthy-role tracking and stopReason getter count unchanged. 4394 consecutive merge cases plus 2016 Anthropic malformed/signed/unsigned/result-alias/aborted cases pass.
src/agents/embedded-agent-helpers/user-facing-text.ts model_prompt 19 19 Re-read full module. Two differently scoped sanitizer entry points import their actual owners; tiny constants/types are shared with callers. No internal duplicate computation.
src/agents/embedded-agent-live-edit-diff.ts attempt_prepare 122 122 Restored to base after the SDK checker proved emittedAdded/emittedRemoved are reachable declaration fields. The measured two-line mirror removal passed runtime differentials but changes an existing SDK contract, so it is not retained.
src/agents/embedded-agent-message-delivery.ts registry_history 433 428 Shared receipt delivery projection and envelope traversal remain. Moved the identical status normalizer into a value-only leaf module so this existing module preserves its exact reachable SDK declaration.
src/agents/embedded-agent-message-tool-source-reply.ts registry_history 172 163 Shared envelope signal predicate remains; consumes the identical blank-preserving status normalizer from the new value-only leaf, preserving SDK declarations and result order.
src/agents/embedded-agent-messaging-extraction.ts registry_history 450 431 Inlined the single-use target adapter into extractMessagingToolSend, retaining options getter timing, direct target/alias/fallback precedence, numeric alias normalization and provider lookup order (-15). One local ordered copyText core now handles text/mediaUrl/idempotencyKey nullish fallback and truthy projection (-4), without changing field order. Extraction/shared thread evidence and native-provider differences remain explicit. 2,592 extraction and 2,880 source-payload extracted-source cases match outputs, JSON field order and getter/dependency traces.
src/agents/embedded-agent-messaging-history.ts registry_history 2 2 Read complete. Two-line constant already owns the bound shared by subscriptions and refreshed runtimes; removing or moving it would duplicate ownership or shift lines without reduction.
src/agents/embedded-agent-messaging-status.ts root 0 3 New value-only internal shared status normalizer. Its exact former body preserves blank strings versus undefined; placing it outside declaration-reachable modules keeps the existing SDK surface unchanged without duplicating the normalizer.
src/agents/embedded-agent-messaging.ts registry_history 134 134 Read complete implementation and action-classification callers/tests. Actual shared target-evidence/delivery core with explicit delivery parameter measures 134 to 137 (+3): rejected. A flattened provider-delivery boolean return measures 134 to 135 (+1): rejected. Original source retained. Case-sensitive send action set, lowercase conversation variants and repeated plugin lookup timing remain unchanged.
src/agents/embedded-agent-messaging.types.ts registry_history 39 39 Read complete. Shared metadata consists only of public send and source-reply shapes; type intersection would obscure the separately optional fields and remove no runtime owner. The actual payload logic was consolidated in its implementation instead; public fields and SDK shapes unchanged.
src/agents/embedded-agent-runner/abort.ts registry_history 16 16 Revisited complete owner and its responsibility boundaries. Exact error-name matching and normalized string-message matching have different coercion rules, so merging them would broaden accepted errors.
src/agents/embedded-agent-runner/active-run-projections.ts registry_history 57 57 Shared exact deduplication and locale ordering across key/id projections; source collections remain explicit. Net LOC is unchanged. Count projection retains duplicate reply-only IDs and its original lookup order.
src/agents/embedded-agent-runner/cache-ttl-checkpoint.ts model_prompt 211 211 Re-evaluated P3: complete source re-read. Schema and persisted full/delta marker shape stay untouched; all fields participate in change application in canonical order, with damaged-delta poisoning. Generic change core already shared.
src/agents/embedded-agent-runner/cache-ttl.ts model_prompt 94 94 Re-read P3 and retained the prior P2 consolidation: Inlined the single-use context matcher into the backward marker scan, retaining ordered provider/model normalization, missing context permissiveness and caught malformed history.
src/agents/embedded-agent-runner/cli-backend-dispatch-eligibility.ts registry_history 86 86 Revisited complete owner and its responsibility boundaries. One backend lookup and ordered credential selection. Pinned, ordered subscription, metadata fallback and unreadable-store acceptance remain separate existing decisions; no parallel implementation to merge.
src/agents/embedded-agent-runner/cli-backend-dispatch-transcript.ts registry_history 200 200 Revisited and retained the earlier consolidation: one await settles finalize regardless of whether text was admitted; flatMap owns normalized result projection instead of mutable push/continue bookkeeping. Taint snapshot and enqueue ordering preserved.
src/agents/embedded-agent-runner/cli-backend-dispatch.ts registry_history 236 224 Inlined both single-use allowlist and result-binding adapters into the only dispatch owner, removing the unused general RunEmbeddedAgentParams helper surface. Maintained the exact gates, named projection, return identity, callback order and finally cleanup. 80 extracted dispatcher cases match complete dependency traces and ordered output JSON.
src/agents/embedded-agent-runner/compact-reasons.ts compaction 148 148 Retained existing shared failure construction and ordered classification table. Summary timeout unwrapping, abort provenance and terminal model-fallback stop remain one owner; shortening them would collapse distinct error semantics.
src/agents/embedded-agent-runner/compact.foreground-work.ts compaction 130 130 Retained. P2 actual null-sentinel prototype (130 -> 128) conflates absence with transferred engine custody; three work scopes still have different admission/drain/dispose boundaries. Source is byte-identical to the inspected P2 merge.
src/agents/embedded-agent-runner/compact.queued-execution.ts compaction 665 660 Use the existing failure-result constructor for backend and secondary-native failures; exact field order and failure/log order remain. A further shared successor-match prototype with recovery/successor owner measured 1590 -> 1605 (+15), so retained the direct projection.
src/agents/embedded-agent-runner/compact.queued.ts compaction 703 703 Retained after P2 shared-failure cutover. Native admission precedes generic auth; prepared generation, original policy selection and resolved storage identity stay separate. Shared writer/comparison prototypes grew (+1 in P2; +15 for this pass’s recovery comparison).
src/agents/embedded-agent-runner/compact.runtime.ts compaction 12 12 Retained cached lazy import. Removing the boundary eagerly imports the compaction graph or duplicates the loader in callers.
src/agents/embedded-agent-runner/compact.ts compaction 529 524 Choose the control-operation promise once before awaiting it, preserving receiver and rejection handling; derive the fallback reason behind the existing success guard so successful results do not read reason. Every auth admission, fallback and cancellation boundary remains.
src/agents/embedded-agent-runner/compact.types.ts compaction 140 140 Retained SDK-reachable contracts. Optional caller fields versus required runtime session identity and shipped raw sessionFile compatibility remain independently used.
src/agents/embedded-agent-runner/compaction-diagnostics.ts compaction 69 68 Derive estimate validity directly from number | undefined rather than a parallel failed boolean. Later estimation stops at the first failure while every contributor is still collected; NaN and infinite numeric estimates remain preserved.
src/agents/embedded-agent-runner/compaction-duplicate-user-messages.ts compaction 81 81 Retained. Consecutive retry-batch reset, normalized sender/text tuple, persisted media exemption and newest timestamp are distinct facts. NaN timestamps must not become normal dedupe windows.
src/agents/embedded-agent-runner/compaction-hooks.ts compaction 348 345 Express the post-compaction estimate as one guarded returned value after the existing undefined early return. All request-budget handling, observed-vs-estimated baseline selection and NaN behavior stay unchanged. Memory refresh and hook owners retain their distinct live gates and settlement.
src/agents/embedded-agent-runner/compaction-runtime-context.ts compaction 361 352 Pass the admitted thinking-policy input to its existing resolver with cfg and requested level aliases explicit. Reviewed both production callers: no sessionEntry or other resolver-only field is present. Retained the ordered public runtime-context projection and its profile-specific omissions.
src/agents/embedded-agent-runner/compaction-runtime-preparation.ts compaction 284 275 Share the prepared selection record with target resolution and credential metadata policy, retaining forced defaults and metadata-provider alias explicitly. Reviewed actual callers and named consumer projections; no harnessRuntime or extra policy field enters from those prepared records.
src/agents/embedded-agent-runner/compaction-safety-timeout.ts compaction 106 106 Retained. The cancellation latch protects once-only hooks across two abort sources; a timed-out request also has a separate ceiling and a delegated reset owner. No extra watchdog or forwarding path remains.
src/agents/embedded-agent-runner/compaction-session-agent.ts compaction 102 102 Retained consumer, now fed from its prepared owner by compaction-session-execution. Stream choice, key resolution, provider text transforms and extra-parameter/web-search policy stay in order.
src/agents/embedded-agent-runner/compaction-session-execution.ts compaction 714 706 Pass the prepared runtime record to session-stream preparation and retain the effective retry thinking level, composed signal, resolved auth key and config as explicit overrides. Removed the now-unused authStorage destructuring. Caller audit confirms the prepared record has no extra stream-consumed fields.
src/agents/embedded-agent-runner/compaction-successor.ts compaction 382 382 Retained. Current validation, resolution, commit-edge recording, MCP retirement and lifecycle delivery each have one owner. Fresh shared successor-comparison prototype adds 21 lines here and saves only six across consumers, aggregate +15. Existing structured/legacy resolution prototype remains +2 on the unchanged owner.
src/agents/embedded-agent-runner/context-engine-capabilities.ts compaction 42 42 Retained. One lazy runtime import keeps fresh config and normalized identity coupled to each completion; capability authority is projected explicitly.
src/agents/embedded-agent-runner/context-engine-maintenance-execution.ts compaction 130 130 Retained. Foreground can use the caller manager and rewrite lock; background must reacquire its own target. Their mutation and publication core is already shared, and every post-await authority check stays attached to its effect.
src/agents/embedded-agent-runner/context-engine-maintenance-work.ts compaction 129 129 Retained. Existing settle helper collects all cleanup failures; idle and close barriers intentionally surround resource release at different times. Set unions must mutate their existing owner sets rather than replacing identity.
src/agents/embedded-agent-runner/context-engine-maintenance.ts compaction 381 381 Retained the P2 inlined deferred worker. Coalesced reruns share resource custody but keep distinct active/pending params; disposal cannot manufacture a live rerun after shutdown.
src/agents/embedded-agent-runner/context-engine-maintenance.types.ts compaction 34 34 Retained. Each resource, cancellation, completion and failure callback is consumed by a different named phase of the same maintenance owner.
src/agents/embedded-agent-runner/context-truncation-notice.ts registry_history 4 4 Revisited complete owner and its responsibility boundaries. Four-line shared formatter with multiple callers and exact visible bytes; already one owner.
src/agents/embedded-agent-runner/delivery-evidence.ts registry_history 482 482 Fresh common messaging-evidence core with explicit target predicate was implemented as a prototype and formatted: 482→486 (+4). It adds a private type/core plus per-variant callbacks; kept the shorter direct expressions and every delivery evidence distinction.
src/agents/embedded-agent-runner/direct-compaction-preparation.ts registry_history 370 370 Revisited complete owner and its responsibility boundaries. Authentication attempts and provider auth exchange fail identically but moving them under one catch requires lifting inferred auth/model bindings or a new result wrapper; their lifecycle and external-auth boundaries remain explicit. Workspace/sandbox snapshots already share prepared runtime.
src/agents/embedded-agent-runner/direct-compaction.ts registry_history 100 100 Revisited complete owner and its responsibility boundaries. Revisited idle barriers: a generic callback wrapper adds another owner without collapsing the required work-only versus work-plus-cleanup phases. runWhenIdle is not interchangeable because it tracks its own callback; cancellation cleanup remains explicit.
src/agents/embedded-agent-runner/effective-tool-policy.ts registry_history 64 64 Revisited complete owner and its responsibility boundaries. Re-read canonical policy adapter and warn/drop path plus scoped tests. Optional-tool subset deliberately retains WeakMap metadata and suppresses only validated-core unavailability warnings. No competing policy owner.
src/agents/embedded-agent-runner/embedded-cyber-failover.ts registry_history 121 121 Revisited complete owner and its responsibility boundaries. Selection context already shared. Eligibility, retry usefulness and committed-work evidence intentionally answer separate questions with distinct error/refusal/public-delivery policies.
src/agents/embedded-agent-runner/empty-assistant-turn.ts registry_history 35 35 Revisited complete owner and its responsibility boundaries. Existing normalized zero-presence plus all-zero test is minimal and preserves nullish total fallback and nonnumeric usage handling.
src/agents/embedded-agent-runner/execution-phase.ts registry_history 25 25 Revisited complete owner and its responsibility boundaries. Stable phase map is the complete external vocabulary; deriving labels from unchecked strings would accept unknown phases. Runtime key validation plus replace costs more than current table.
src/agents/embedded-agent-runner/extensions.ts registry_history 137 137 Revisited complete owner and its responsibility boundaries. Safeguard registration and tool-result middleware are different responsibilities, not variants. Delivery receipt precedes middleware, final presentation follows it; merging these observations would alter authority/evidence timing.
src/agents/embedded-agent-runner/extra-params.ts model_prompt 705 692 Applied typed-param forwarding, shared cached-content resolver, ordered numeric temperature/topP table, and inline request-scoped-key predicate. Alias precedence, numeric NaN acceptance, option key order and getter order preserved; 121 alias and 72 numeric projection cases.
src/agents/embedded-agent-runner/failure-signal.ts registry_history 38 38 Revisited complete owner and its responsibility boundaries. Cron/tool/code gates are minimal and ordered. Generic merging with terminal-tool-failure would broaden persisted diagnostics and conflate fatal denial with a safe catalog-miss message.
src/agents/embedded-agent-runner/google-prompt-cache.ts model_prompt 505 496 Applied shared explicit cached-content resolver with extra-params. No request construction, policy, sentinel, digest, persistence or cache-lifecycle behavior changes.
src/agents/embedded-agent-runner/history.ts registry_history 186 186 Revisited complete owner and its responsibility boundaries. Turn eviction already uses bounded reverse selection without an extra message-index array; account-level map replacement and route disambiguation are separate policies, not duplicated readers.
src/agents/embedded-agent-runner/lanes.ts registry_history 46 46 Revisited complete owner and its responsibility boundaries. Retained shared lane selection: sessions normalize their queue key, nested cron work avoids its outer slot, and subagent lanes bind to immediate-parent capacity. These are different queue-ownership contracts.
src/agents/embedded-agent-runner/legacy-compaction-session-key.ts registry_history 22 22 Revisited complete owner and its responsibility boundaries. complete source re-read. This is the PR1 shared successor selection; raw retained and normalized lookup keys remain distinct.
src/agents/embedded-agent-runner/logger.ts registry_history 3 3 Revisited complete owner and its responsibility boundaries. Three-line concrete subsystem logger is already the sole owner.
src/agents/embedded-agent-runner/message-injection-target.ts registry_history 487 487 Revisited complete owner and its responsibility boundaries. One shared return type replaces the duplicate legacy/V2 injection shape. Tried a shared nonthrowing authority probe but reverted: the original resolve try also contains rejection logging, and narrowing that catch changes exceptional behavior.
src/agents/embedded-agent-runner/message-visibility.ts registry_history 218 218 Revisited complete owner and its responsibility boundaries. Attachment recursion owns a cycle guard; visible payload and terminal assistant contracts differ on malformed arrays, explicit metadata and silent text. Broad shared record guards would change accepted values. Direct gates are shorter than named callback strategies.
src/agents/embedded-agent-runner/model-resolution.ts model_prompt 88 88 Re-evaluated P3: complete source re-read. Already one provider iteration shared between dynamic and static tiers; final tier owns errors, preserving prepared-model authority and initial discovery miss fallback.
src/agents/embedded-agent-runner/model.compat.ts model_prompt 39 36 Applied a single absent-input return. Surviving object identity and nested image merging unchanged; 64 differential cases.
src/agents/embedded-agent-runner/model.configured-fallback.ts model_prompt 208 208 Re-evaluated P3: Header, endpoint, params, reasoning, media and auth facts have different ordered precedence. Existing attachment owners preserve model identity and hidden metadata; the prior shared attachment prototype saved only two aggregate lines while adding a type-heavy export.
src/agents/embedded-agent-runner/model.configured-overrides.ts model_prompt 642 633 Applied direct typed-param forwarding into the private transport projector at three sites; provider-default resolution explicitly sets modelId undefined so wider caller records cannot leak it. External hook/context keys are still reconstructed explicitly. 48 differential default/configured/alias transport projection cases pass. Broader shared service-attachment prototype was zero net; see measured rejection below.
src/agents/embedded-agent-runner/model.inline-provider.ts model_prompt 201 201 Re-evaluated P3: complete source re-read. Sanitized headers exclude secret markers, model/request authority preserves configured precedence. Inline model completion is a separate public projection with omitted values filled only there.
src/agents/embedded-agent-runner/model.manifest-alias.ts model_prompt 175 175 Re-read P3 and retained the prior P2 consolidation: Applied: inline sole-use suppression wrapper after provider/model admission, removing repeated normalization and oversized plugin type mirror. Canonical manifest planner still owns suppression rules, and target API lookup remains lazy.
src/agents/embedded-agent-runner/model.provider-hooks.ts model_prompt 211 211 Re-read P3 and retained the prior P2 consolidation: Inlined single-use final legacy-id projection into final normalized model handoff. Identity, id/name comparison, route facts, hook order and timeout restoration unchanged. Cost helper retains separate nonrecord default/valid identity semantics.
src/agents/embedded-agent-runner/model.provider-hooks.types.ts model_prompt 25 25 Re-evaluated P3: Hooks deliberately use unknown at plugin implementation boundaries while preserving shared parameter types. No unused caller generality or alternate runtime implementation remains.
src/agents/embedded-agent-runner/model.provider-transport.ts model_prompt 35 35 Re-evaluated P3: Re-read outer hook/context projections. Shared record spreading would change outer-vs-context key insertion order (provider/model first outside; config/workspace first inside) or duplicate a reconstruction. Preserve exact plugin contract projection.
src/agents/embedded-agent-runner/model.registry-resolution.ts model_prompt 407 407 Re-evaluated P3: complete source re-read. Configured/static/dynamic model and auth admission preserve tier and call order; suppression error and normalization inputs already shared. Stale auth retry keeps exact selected auth owner.
src/agents/embedded-agent-runner/model.static-catalog-row.ts model_prompt 27 27 Re-evaluated P3: Sole explicit projection intentionally excludes unknown fields and selectively clones window/thinking data. Table/spread would change own keys or require unsafe assertions.
src/agents/embedded-agent-runner/model.static-catalog.ts model_prompt 636 636 Re-read P3 and retained the prior P2 consolidation: Applied: cache hit and freshly selected donor now share one model projection; donor lookup writes its final row/null directly to the existing cache. Removed single-use findDonor closure and early cached projection. Preserve first-match route checks, ambiguity/conflict stop, suppressions, cached misses and fresh returned objects.
src/agents/embedded-agent-runner/model.static-catalog.types.ts model_prompt 8 8 Re-evaluated P3: Eight-line shared catalog state shape; every member has different owner semantics. Merging with implementation changes import dependency direction without reducing fields.
src/agents/embedded-agent-runner/model.static-id.ts model_prompt 67 67 Re-evaluated P3: complete source re-read. Exact and normalized lookup indexes own different precedence with first-row retention and pinned metadata generation; no duplicate cache owner.
src/agents/embedded-agent-runner/model.ts model_prompt 401 401 Re-evaluated P3: Retained after actual 401 -> 396 inlining prototype. Success scheduling matched, but a synchronous normalization rejection reached the outer observer one microtask earlier; restoring that boundary needs explicit rejection plumbing and is less clear than the existing named async owner.
src/agents/embedded-agent-runner/openrouter-model-capabilities.ts model_prompt 323 323 Re-read P3 and retained the prior P2 consolidation: Applied: remove one-use synchronous SQLite opener and create its store at the caught read site. Main's asynchronous catalog persistence registration, pre-network captured store and close-join lifecycle remain unchanged. SDK surface unchanged.
src/agents/embedded-agent-runner/plugin-runtime-refresh-delivery.ts registry_history 125 125 Revisited complete owner and its responsibility boundaries. Retained after actual 125 -> 135 shared-evidence-selector prototype. Explicit text/media fallback controls need three arguments per call; the abstraction grows code and hides which delivery evidence is selected. Partial/block/reasoning callbacks have distinct suppression and mirror contracts.
src/agents/embedded-agent-runner/plugin-runtime-refresh.ts registry_history 141 141 Revisited complete owner and its responsibility boundaries. Continuation messages must reuse original array when no new messages exist. Generation, delivery, pending media and successful tools each reset differently. Looping resets requires generic setters and would obscure ownership; no duplicate current-state owner found.
src/agents/embedded-agent-runner/post-compaction-loop-guard.ts registry_history 144 144 Revisited complete owner and its responsibility boundaries. Attempt count is already derived from history. Baseline signatures, mutable observation identities and captured repeated tool names protect different invariants; repeated false verdicts must remain fresh objects.
src/agents/embedded-agent-runner/prepared-compaction-runtime.ts compaction 578 578 Retained after full re-read. The old +4 host-facts prototype remains applicable byte-for-byte. A tempting attempt: params shortcut is unsound because prepareEmbeddedSkills would newly receive contextTokenBudget, changing prompt skill selection; the explicit skill input is the intended boundary.
src/agents/embedded-agent-runner/prompt-cache-observability.ts registry_history 386 383 Inlined the one-use tracker publisher into beginPromptCacheObservation. Stage the fully constructed typed record before delete/prune/set, preserving getter evaluation, LRU order and publication before assertion failures.
src/agents/embedded-agent-runner/prompt-cache-request-observer.ts registry_history 75 75 Revisited complete owner and its responsibility boundaries. complete source re-read. Started-request count, unconsumed current request, and last completed observation cannot be derived from one another; all three have distinct lifetimes.
src/agents/embedded-agent-runner/prompt-cache-retention.ts model_prompt 73 83 Added shared cached-content resolver consumed by Google cache and extra-params. Existing marker aliases and provider eligibility remain distinct. Extra lines here remove duplicate parsing from both consumers.
src/agents/embedded-agent-runner/provider-prompt-serialization.ts registry_history 20 20 Revisited complete owner and its responsibility boundaries. Digest-only stable-value and encoded-body digest use different encoders; merging requires a wider union and branches for byte semantics. Existing 20-line owner is already complete.
src/agents/embedded-agent-runner/provider-prompt-state.ts registry_history 202 202 Revisited complete owner and its responsibility boundaries. Re-read worker eligibility, byte estimate, payload observation, exact snapshot rejection and transport encoding. Observation model comes from the payload callback while encoding uses stream model; one shared record owner already handles both. A callback-binding helper adds another forwarding layer with no responsibility removed.
src/agents/embedded-agent-runner/provider-prompt-state.worker.ts registry_history 7 7 Revisited complete owner and its responsibility boundaries. Re-read sole typed worker adapter and transfer-list ownership. Seven-line boundary is already minimal; no interface or transfer behavior change.
src/agents/embedded-agent-runner/replay-history.ts registry_history 709 706 Combined consecutive null/incomplete-reasoning exits using short circuit evaluation; normalization, inference and duplicate-mirror calls retain their prior order and invocation conditions. Broad policy-parameter forwarding rejected because the downstream owner also reads directApiKey/runtimeHandle fields deliberately excluded by this projection.
src/agents/embedded-agent-runner/replay-session-state.ts registry_history 114 114 Revisited complete owner and its responsibility boundaries. complete source re-read. Legacy sync methods swallow non-incognito failures; V2 async method propagates, awaits, and asserts again. They share current-owner assertion already. Model snapshot handling deliberately forgets partial reads on failure.
src/agents/embedded-agent-runner/replay-state.ts registry_history 52 52 Revisited complete owner and its responsibility boundaries. Two fields merge monotonically and no-next returns exact object; create-through-merge prior measured 52 to 52 with added indirection. Current file remains 52.
src/agents/embedded-agent-runner/result-fallback-classifier.ts registry_history 272 272 Fresh Set-based provider-error policy prototype measured 272→273 (+1), so retained the shorter switch. No error classification, visible copy or fallback precedence changed.
src/agents/embedded-agent-runner/run-entry-cli.ts run_control 88 88 Read complete admission/read/settlement owner. Writable latest reads and read-only reads require different argument records; settlement binds exact admission and optional preserved native binding. No semantic read-policy unification.
src/agents/embedded-agent-runner/run-entry-runtime.ts run_control 36 36 Read two route variants. Explicit pinned runtime can deliberately make a CLI provider non-CLI execution; deriving useCliExecution from the returned provider would change that contract. Shared return construction requires extra temporary state.
src/agents/embedded-agent-runner/run-entry-terminal.ts run_control 266 266 Read full trace/receipt/terminal projection. Outer failed attempts, inner errors and final successful winner have different ordering and precedence. Terminal metadata policy distinguishes own key, defined value and literal true; replacing it with one table loses clear field policy or requires additional type projection.
src/agents/embedded-agent-runner/run-entry.ts run_control 708 708 Read full 708-line candidate/turn/context/custody owner. No edit: the measured P2 optional-callback cutover still requires prohibited cron caller, so it is not reintroduced and no shim added. Cyber policy restoration/accepted-work logic remains separate from ordinary fallback and exact failure settlement.
src/agents/embedded-agent-runner/run-loop.ts run_control 617 609 Applied passing the already-owned finalizedTerminal record to the terminal resolver (-6) and removing private duplicated dispatch provider/model fields (-2). Resolver/auth-copy callees only read named fields and return explicit projections; extra private finalized fields do not cross a result boundary. Selected identity parity audited: sole rebind from preparedRuntime before loop, no later production mutation.
src/agents/embedded-agent-runner/run-orchestrator.ts run_control 730 730 Read full 730-line owner and cleanup/caller paths. Cleanup nesting preserves all three failures/finalizers and parent abort-listener lifetime. Prepared-generation leases and logical terminal publication have different lifetimes. Direct CLI, pre-reply hook and embedded loop remain distinct owners with existing shared admission.
src/agents/embedded-agent-runner/run-permissions.ts run_control 65 65 Read full dispatcher. Retained apply function, run owner, generation and delegated authority intentionally differ; ownership checks before/after awaited apply and before revocation remain. P2 exact close/new-owner differential already established no re-registration path; no further redundant permission state.
src/agents/embedded-agent-runner/run-state.ts run_control 488 488 Verified the previously read full owner is unchanged except new ten-line run-ID human-input adapter, then read that adapter and its registration owner. No registration, lifecycle, callback revalidation or multi-index cleanup gate can be removed. Exact source instance and post-callback checks remain separate authority facts.
src/agents/embedded-agent-runner/run.ts registry_history 4 4 Revisited complete owner and its responsibility boundaries. Four-line public export boundary contains no implementation duplication; removing it moves consumers with no feature-internal reduction.
src/agents/embedded-agent-runner/run/abortable.ts attempt_execute 107 111 Added narrow shared withAbortListener(signal,start,errorFactory) core used by provider abortable and async-task sleep. Existing retry package racePromiseWithAbortSignal is not equivalent: it adds race/finally microtasks and removes listeners after settlement. Local common core preserves cleanup-first timing.
src/agents/embedded-agent-runner/run/agent-end-context.ts attempt_execute 114 114 Read full foreground and hook context projection. Shared message context owner already removes repeated fields; remaining public fields preserve explicit own-key presence, while cron caller origin is conditionally omitted. Broad spread is not equivalent.
src/agents/embedded-agent-runner/run/agent-hook-context.ts attempt_execute 43 43 Read hook identity and audience fencing. Audience closure intentionally rereads run.memoryAudience; captured local would alter later mutation behavior. Existing channel/identity projectors own common fields.
src/agents/embedded-agent-runner/run/assistant-failure.ts run_control 523 523 Revalidated byte-identical complete P2 owner. Same failed-profile closure supports overload-cap and normal rotation; prompt/assistant failure logging and failure marks differ in detach/await/catch behavior. Further catch wrapper requires extra callback/type parameters and risks moving exception boundaries.
src/agents/embedded-agent-runner/run/attempt-async-tasks.ts attempt_execute 201 185 Shared listener registration, cleanup-before-settlement and rejection normalization with abortable.ts via withAbortListener. Sleep retains pre-start throwIfAborted and named abort factory; provider wrapper retains already-running rejection consumption and marker/cause semantics.
src/agents/embedded-agent-runner/run/attempt-before-agent-run.ts attempt_execute 79 79 Read gate and redacted-message persistence. Hook result classification, append+flush and post-write sanitized projection are ordered effects; the existing gate owner already shares block semantics.

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Coverage log, part 2 of 3.

Per-file decisions: rows 133–261 of 380

Base b3196dfda33555857eae9cd52ea29367a91bd9ea → final head 34e39db29179ceb9b7f2ce09f727c2aeded0b83a (tree a1f1b52fe5b6607bfea3089ad3e036b947425d21).

643 net production lines removed (1,069 added / 1,712 deleted) across 103 changed or new production files. Tests, fixtures, test support, generated files, and declarations are excluded from that count.

All 285 assigned runner files and 26 assigned subscriber files have recorded decisions. This complete table also includes adjacent owners, for 380 unique files in total. There are no decision gaps or changed-file focused-test-target gaps. The entries record implementation and differential evidence; validation results belong to the PR's proof summary.

File Scope Base lines Final lines Decision and evidence
src/agents/embedded-agent-runner/run/attempt-bootstrap-prepare.ts attempt_prepare 192 190 Applied: the lazy completed-bootstrap cache returns its nullish assignment directly. Identity, execution and prompt workspaces remain separate; pre/post-remap bootstrap filters consume different arrays and cannot be unified by path alone.
src/agents/embedded-agent-runner/run/attempt-bundle-tools.ts attempt_prepare 277 275 Applied: delete the impossible absent cronCreatorToolAllowlistCaptureRef branch. The inferred required field is always allocated as {} by prepareEmbeddedAttemptToolBase; attempt.ts is the sole production caller and forwards that result. Updated one fixture field in attempt-bundle-tools.test.ts; all assertions remain unchanged. MCP/LSP acquisition and disposal retain separate resource owners.
src/agents/embedded-agent-runner/run/attempt-client-tools.ts attempt_execute 243 243 Re-read reserved client slots, tool surface construction and refresh. Generic array/set update owners already shared; object-keyed replay-safe sets and owner Maps require distinct operations. No broader container API introduced.
src/agents/embedded-agent-runner/run/attempt-compaction-thinking.ts attempt_execute 45 45 Read model capability projection and provider conversion. Existing route record shares provider/catalog/runtime fields; concrete model levels still pass through provider and runtime mappings separately.
src/agents/embedded-agent-runner/run/attempt-context-engine-helpers.ts attempt_prepare 182 182 Retained. Bootstrap skip and completed-marker gates serve different state; private current-attempt usage scan is shared by two callers and excludes zero-usage aborts. Public observation projection intentionally excludes runtime-only fields.
src/agents/embedded-agent-runner/run/attempt-context-summary.ts attempt_prepare 66 53 Applied actual single-use helper inlining: 66→53 (-13). Aggregate owner now counts each message directly, with one local text counter and the existing aggregate image counter. Removed per-message result objects, empty-result branches and private helper. Image blocks still exclude text fields, unknown objects are ignored, role sorting and 100-message snapshot stay identical.
src/agents/embedded-agent-runner/run/attempt-decision-context.ts attempt_execute 251 247 Applied one bounded text-block admission path for string and block-array user messages; preserves initial content snapshot, char/block bounds, newline joining, envelope stripping and media exclusion.
src/agents/embedded-agent-runner/run/attempt-decision-diagnostics.ts attempt_execute 81 81 Read measurement and publication. Definitions omit tool runtime fields; diagnostic output contains intentionally explicit metadata and null/default semantics. Existing measuring owner used by baseline and final dispatch.
src/agents/embedded-agent-runner/run/attempt-decision-prefilter.ts attempt_execute 175 175 Re-read full bounded rubric/evaluation/current-selection flow. Skip result is already shared; proposed result carries live authority unlike retained/unavailable records. Rubric bytes and thresholds untouched.
src/agents/embedded-agent-runner/run/attempt-delivery-state.ts attempt_execute 57 57 Read delivery projection. Already shares capped append core; source reply arrays preserve undefined when no previous generation, while spawns remain uncapped and duplicate sends preserved.
src/agents/embedded-agent-runner/run/attempt-exec-approval-continuation.ts attempt_execute 42 42 Read prompt resizing and transcript update. Existing resize closure already shares budget and default range. Raw prompt and transcript fallback/omission are separate contract values.
src/agents/embedded-agent-runner/run/attempt-execution-phase.ts attempt_execute 209 209 Re-read stream/history/subscription/timeout assembly. Current transcript binding is already shared; independent repaired-replay latch and late idle-timeout callback cannot derive from terminal state.
src/agents/embedded-agent-runner/run/attempt-execution-types.ts attempt_execute 84 84 Read complete phase contract. Existing Prepared type already derives most owner returns; changing one remaining spelling offers no LOC reduction. Phase callbacks and yield facts are distinct lifetimes.
src/agents/embedded-agent-runner/run/attempt-finalize.ts attempt_execute 569 564 Inlined sole-use abortCompaction closure at its live-run abort edge; preserves isCompacting read after controller abort, caught compaction error, exact warning, probe behavior, active-session abort and abandonment order. The external-controller preparation path remains separately classified.
src/agents/embedded-agent-runner/run/attempt-gateway-tools.ts attempt_execute 73 73 Read preparation and current-host fencing. Gateway identity is captured then revalidated after awaited availability. Source identity projection and detached/disabled gates are separate; no duplicate lookup retained.
src/agents/embedded-agent-runner/run/attempt-history-prepare.ts attempt_prepare 190 190 Retained. Replay context is a function because model/config reads remain live across awaits. Quota resumption fences, canonical patch callback and finalization filtering are distinct; common parameter projection already exists.
src/agents/embedded-agent-runner/run/attempt-history.ts attempt_prepare 351 350 Applied: remove the empty-envelope special case (slice at zero yields the original string), inline normalized sender return, and replace the dense-undefined callback assertion with an explicit return type. Rejected dropping the callback entirely because inherited numeric properties could populate the synthetic source object. Pairing still reserves exact identities before timestamp/content fallback; output remains dense.
src/agents/embedded-agent-runner/run/attempt-http-runtime.ts attempt_execute 14 14 Read two ordered bootstrap calls. Proxy must install before stream timeout wrapper. Already minimal owner adapter, no ordering-safe removal.
src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts attempt_execute 671 650 Applied canonical object normalization for prompt keys and blocked metadata, preserving array-backed objects. Inlined the sole active-user replacement adapter into its prompt-transform owner, retaining transcript-text snapshot, first-match semantics, object/array identity and restoration.
src/agents/embedded-agent-runner/run/attempt-memory-audience.ts attempt_execute 70 70 Read delegated versus acquired memory audience custody. Existing log-level selection already collapses three variants; delegated leases cannot share release ownership with newly acquired ones.
src/agents/embedded-agent-runner/run/attempt-nested-tool-activity.ts attempt_execute 81 81 Read accepted-range hydration and revalidation. Before/after checks fence the awaited maintenance read; first/last scans and scope filtering serve different evidence boundaries. No storage changes allowed or needed.
src/agents/embedded-agent-runner/run/attempt-normalization.ts attempt_execute 305 305 Re-read compaction accounting before cancellation, usage precedence, breaker and final outcomes. Returned compaction count lacks event ordering; carried usage and current usage retain different precedence. No shared return constructor saves lines without moving reads across log/hook boundaries.
src/agents/embedded-agent-runner/run/attempt-orphan-repair.ts attempt_execute 112 112 Read full ancestry scan, metadata replay and repair planner. Replay switch preserves subtype-specific call arity and label remapping against prior writes; table form would require casts or callback wrappers. The sole-use type predicate supplies real container narrowing.
src/agents/embedded-agent-runner/run/attempt-permission-prompt.ts attempt_execute 214 214 Re-read complete generation replacement loop and current prompt admission. Each generation comparison follows distinct awaited work; previous +1-line fence-helper prototype adds no clarity. Prompt admission and continuation intentionally differ.
src/agents/embedded-agent-runner/run/attempt-preparation.ts attempt_execute 44 44 Read concurrency admission and synchronous-work accounting. Queue tail serializes starts only; timer/counter yield budgets are independent. Awaiting stage before charging would include async latency, so current return/finally required.
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts attempt_prepare 634 632 Applied: always use the truncation owner's returned messages. The identity comparison remains solely for unchanged logging policy; assigning an identical reference needs no branch. Prompt/transcript/origin/steering projections retain distinct provenance and byte order.
src/agents/embedded-agent-runner/run/attempt-prompt-helpers.ts attempt_prepare 516 503 Applied: inline the sole drain-cache insertion helper using delete→canonical prune→set (same LRU order and 256-entry bound); merge identical orphan rejection results with original short-circuit predicates; inline the string trim return. Retained the original flatMap call on unknown content arrays: map/filter draft was 503→497 (-6) but changes which caller-owned array methods/species are invoked and adds a traversal. Kept SDK-exported resolveAttemptFsWorkspaceOnly despite no local production caller. JSON budgets, prompt bytes and authority ordering unchanged.
src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts attempt_execute 557 557 Re-read full assembly/budget/primary-dispatch/persistence flow. Initial prompt refresh and primary request restoration have different commit/admission return contracts. Existing authority checkpoint and owned-write callbacks retain their separate awaited boundaries.
src/agents/embedded-agent-runner/run/attempt-prompt-preflight.ts attempt_execute 261 261 Re-read raw-history normalization, projection checkpoint budget and diagnostic-only overflow route. Existing three-field recovery-budget projection is already shared and deliberately excludes other input fields.
src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts attempt_execute 445 445 Re-read history transform, primary projection repair, steering acknowledgment and yield/precheck error handling. Runtime carrier installation and model prompt transformation have different capture/queue contracts; lazy installation and reverse cleanup retained.
src/agents/embedded-agent-runner/run/attempt-prompt-support.ts attempt_execute 390 390 Implemented/formatted shared Decision baseline reader 390→390, rejected at zero reduction because it adds a callback without simplifying the required baseline-before-measurement ordering. See prototype-attempt-prompt-support.ts.
src/agents/embedded-agent-runner/run/attempt-queue-message.ts attempt_execute 452 450 Applied one cancellation sentence with explicit acceptance/delivery suffix; exact output bytes retained. Revisited observer errors and preserved ordered AggregateError causes rather than the previously lint-rejected consolidation.
src/agents/embedded-agent-runner/run/attempt-recovery.ts attempt_execute 568 568 Re-read full classification/retry/compaction control flow. Recovery decisions can emit diagnostics before live snapshots and retries; common generic result constructor would evaluate those snapshots too early. Existing retry and blocked-result factories already own equivalent work.
src/agents/embedded-agent-runner/run/attempt-result.ts attempt_execute 400 400 Re-read result snapshot, carryover, finalization and source progress promotion. Carryover owns independent copied values after returned objects mutate; deriving from prior result would change that contract. Exact current-attempt/kept-answer/terminal evidence distinctions retained.
src/agents/embedded-agent-runner/run/attempt-session-identity.ts attempt_prepare 151 151 Retained. Marker and keyed lookup branches reuse successor identity operations but have distinct current-binding/read fences. Final normalized-path validation cannot replace initial exact-field authority checks. All post-await assertions retained.
src/agents/embedded-agent-runner/run/attempt-session-prepare.ts attempt_prepare 682 682 Restored ClientToolPreparation alias and its annotation to preserve the exact reachable SDK declaration. The five-line inline type prototype was implemented and typechecked, then rejected by the API surface gate.
src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts attempt_prepare 357 357 Retained. Read complete prompt-series retirement, manager/session publication, context guards and transport setup. restartRecorded is the outcome of awaited durable retirement and cannot derive from prepared.restart. Current image count and prompt cache are owning state consumed by later callbacks, not redundant mirrors.
src/agents/embedded-agent-runner/run/attempt-session-settle.ts attempt_prepare 216 215 Applied: the same abort-cleanup-failure recorder now serves the immediate owner-context check and post-settlement callback. Both invocations remain, including late failure publication in the joining scope. Initial/post-drain/final terminal snapshots and mandatory disposal/first-error precedence are retained.
src/agents/embedded-agent-runner/run/attempt-sessions-yield.ts attempt_prepare 120 120 Retained. One durable suffix predicate preserves trailing metadata; live suffix bounds assistant removals while custom interrupt removal remains independently eligible. Publication stays after the awaited durable removal and retains a pre-await message snapshot.
src/agents/embedded-agent-runner/run/attempt-settle.ts attempt_execute 404 404 Fresh full P3 read of event drain, revision rewind, stream settle and failed-media note path. Drain requires pre/post ownership reads; current and rewound snapshots differ across settlement. Persistent-note branches retain distinct durable/incognito/local writer custody and committed-message error semantics.
src/agents/embedded-agent-runner/run/attempt-setup.ts attempt_execute 476 476 Re-read all setup/context-guard/diagnostic functions. Cache pruning, context-engine loop hooks, image pruning and computer frame transforms already share their maintained owner APIs; ordered restore chain is required. No new shared variant implementation found.
src/agents/embedded-agent-runner/run/attempt-stage-timing.ts attempt_execute 69 69 Read stage tracker, emitter and warning policy. Trace prefix remains lazy; same formatter already serves both levels. No duplicate thresholds or authoritative timing state.
src/agents/embedded-agent-runner/run/attempt-steering-admission.ts attempt_execute 76 76 Read steering lifecycle. Accepting, paused and closed encode valid phases; stream release is cleared before stop to survive reentrancy. Catch/finally owners preserve original preparation error and ordered releases.
src/agents/embedded-agent-runner/run/attempt-stop-reason-recovery.ts attempt_execute 145 144 Simplified missing/present normalized stop-reason text to one conditional result, preserving exact message. Kept stream creation, iterator synthesis and result recovery separate because microtask timestamp and single-terminal latch are distinct.
src/agents/embedded-agent-runner/run/attempt-stream-prepare.ts attempt_execute 629 629 Re-read entire finalizer hook, subscriber, injection capability and queue registration owner. Claimed source authority, session registration and run registration remain independent live checks; V1/V2 share existing internal closures.
src/agents/embedded-agent-runner/run/attempt-stream-runtime.types.ts attempt_execute 25 25 Read stream phase contract. Types derive owner callbacks/return values; no repeated runtime work. Preserve complete phase shape.
src/agents/embedded-agent-runner/run/attempt-stream-settle.ts attempt_execute 657 657 Re-read full async wait, snapshot, cache accounting and transport preparation. Snapshots before and after writer settlement must differ in timing; transport wrapper order and credential custody retained.
src/agents/embedded-agent-runner/run/attempt-stream.ts attempt_execute 439 439 Re-read wrapper chain and callback owners. Compaction/thinking replay repair already shares writer-lock/error/log core; result joins, early return and pre-output retry are distinct lifetimes. No wrapper order or lazy provider boundary changed.
src/agents/embedded-agent-runner/run/attempt-subscription-cleanup.ts attempt_execute 89 89 Read bounded abort settle and ordered resource teardown. Sync guard/session release and awaited flush/MCP/LSP disposal differ in timing; existing MCP/LSP loop already shares homogeneous cleanup.
src/agents/embedded-agent-runner/run/attempt-system-prompt-additions.ts attempt_prepare 32 32 Retained. Progress/incognito compose once before awaited coauthor preparation. Coauthor receives an intentionally narrow five-field input and retains its own output field/placement.
src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts attempt_prepare 469 466 Applied: construct refreshed embedded prompt inputs once, directly including the awaited prepared tool-context fields, instead of creating then mutating the same private object with Object.assign. Evaluation order, permission capture, report refresh and post-await assertion retained.
src/agents/embedded-agent-runner/run/attempt-system-prompt.ts attempt_prepare 94 94 Retained. Stable/dynamic/permission regions share renderAttemptPromptSection. Permission notice replacement tracks whether an older hook prompt carried the region; it cannot derive from output text without conflating user-authored content.
src/agents/embedded-agent-runner/run/attempt-terminal-anchor.ts attempt_execute 18 18 Read tail metadata walk. Missing entries return null while custom TTL-only entries continue; generic ancestor helper would need predicate/signature plumbing larger than this local loop.
src/agents/embedded-agent-runner/run/attempt-terminal-evidence.ts attempt_execute 185 185 Fresh P3 full read complete. Current-attempt assistant fallback, replay-safe evidence, terminal output and delegated-media continuation have distinct acceptance sets. Existing primitive evidence owners are shared; a strategy object cannot remove the remaining specific exclusions.
src/agents/embedded-agent-runner/run/attempt-thread-helpers.ts attempt_execute 81 81 Read hook-context composition, spawn workspace and TTL persistence. Functions have separate prompt, sandbox and transcript contracts, and TTL eligibility short-circuiting avoids unnecessary provider calls. No common structural work.
src/agents/embedded-agent-runner/run/attempt-timeout-prepare.ts attempt_execute 141 141 Re-read deadline/approval pause/compaction grace machine. Bounded, paused, unlimited and closed are distinct valid states; timer owner identity prevents stale callbacks, and required warning-before-abort ordering retained.
src/agents/embedded-agent-runner/run/attempt-tool-call-block-type.ts attempt_prepare 14 14 Retained. Shared record normalization plus three literal discriminants is already the compact runtime/type predicate; an allocation or Set-based lookup would not improve clarity or narrow types.
src/agents/embedded-agent-runner/run/attempt-tool-call-name-resolution.ts attempt_prepare 198 196 Applied: exact spelling and ID-derived-name resolution share one success return, in their original short-circuit order. Ambiguous-name scans preserve empty-string versus null differences and the malformed-counter fence stays after both attempts.
src/agents/embedded-agent-runner/run/attempt-tool-call-replay-sanitization.ts attempt_prepare 428 416 Applied: narrow the private Anthropic sanitizer optional one-property options object to its sole required boolean; infer the private two-field report from its returned owner record; combine nullable name resolution with trimming before the existing validity guard. Signed-thinking versus ordinary replay rules and public signatures remain unchanged.
src/agents/embedded-agent-runner/run/attempt-tool-call-stream-normalization.ts attempt_prepare 297 297 Retained. Provider IDs are collected before fallback assignment, shared partial/final objects reuse per-index IDs, and a separate historical set prevents reused IDs across responses. Guard calls must execute even after streamAttemptAlreadyCounted is true; reducing through short-circuit assignment would skip rewrites.
src/agents/embedded-agent-runner/run/attempt-tool-call-text-promotion.ts attempt_prepare 155 155 Retained. Package owner serves scrub/promotion parsing; this wrapper owns stable promoted IDs and unopened-iterator return. Promotion and scrub differ in allowed terminal reasons and partial-block retention. Factoring the shared checkpoint call would need an extra tagged-result binding/branch.
src/agents/embedded-agent-runner/run/attempt-tool-catalog.ts attempt_prepare 271 271 Retained. Existing buildCatalog owns construction and refresh; shared prompt-plan keys drive policy/refresh traversal. Host prompt sets are snapshots, while live/replay sets preserve externally held identity and intentional replay accumulation.
src/agents/embedded-agent-runner/run/attempt-tool-construction-plan.ts attempt_prepare 267 267 Retained. Existing shouldCreateBundleRuntimeForAttempt owns MCP/LSP common policy, while namespaces/globs and LSP patterns remain explicit strategies. Public SDK-exported signatures and alias/intersection semantics remain unchanged.
src/agents/embedded-agent-runner/run/attempt-tool-prepare.ts attempt_prepare 498 496 Applied: accumulate the retained-cleanup-failure fact with an OR assignment. Completed cleanup ownership and retirement joins remain unchanged. Dynamic conversation context is rebuilt at permission refresh; broad static copying would freeze live attempt fields.
src/agents/embedded-agent-runner/run/attempt-tool-run-context.ts attempt_prepare 130 130 Retained. Exact projection excludes caller-only session/authority fields, renames chatId, derives prepared requesterModel and freezes trace. Broad spreads are not equivalent; tuple projection needs a cast and an equally long field inventory. Captured reply owner provides live accepted-audio state.
src/agents/embedded-agent-runner/run/attempt-tool-search-executor.ts attempt_prepare 169 169 Retained. The two abort races own implementation/acceptance versus outer lifecycle settlement. One preparer/immediate execution core already serves native/deferred tools. Tool receipt recording must precede accepted-result projection; durable activity rechecks authority after both admissions.
src/agents/embedded-agent-runner/run/attempt-tool-search-run-plan.ts attempt_prepare 111 111 Retained. Visible/replay/live/capability sets have distinct policies. Controls excluded from visible tools are absent from deferred catalog names; prior replay tools survive revocation. Existing collectAllowedToolNames owns shared normalization.
src/agents/embedded-agent-runner/run/attempt-trajectory-flush.ts attempt_execute 24 24 Read trajectory cleanup adapter. Existing runAgentCleanupStep owns bounds/warnings; async callback preserves Promise and absent-recorder behavior. Inlining would duplicate cleanup policy at callers.
src/agents/embedded-agent-runner/run/attempt-trajectory-status.ts attempt_execute 104 104 Read success/error/interruption and text fallback classification. Tool-use requires explicit delivery, length stops require visible/delivered output, and timeout/error flags have precedence. Shared evidence predicates already own common checks.
src/agents/embedded-agent-runner/run/attempt-trajectory.ts attempt_execute 107 97 Shared four-field trajectory session-target projection with dispatch. Explicit omitMissing preserves dispatcher omission versus embedded attempt own-undefined field. Projection remains at original read/effect positions and excludes extra target authority fields.
src/agents/embedded-agent-runner/run/attempt-transcript-helpers.ts attempt_prepare 174 170 Applied: infer the single-field transcript-presence result rather than maintaining a private one-use mirror alias. Runtime paths unchanged. Midturn cleanup, compaction recovery and quota maintenance retain distinct canonical owners and post-await checks.
src/agents/embedded-agent-runner/run/attempt-transcript-lifecycle-prepare.ts attempt_prepare 124 124 Retained. Lifecycle disposal adds generation release in finally; initial-writer wrapper carries separate inherited admission. Common write function already composes both owners. Removing either wrapper loses authority or settlement.
src/agents/embedded-agent-runner/run/attempt-transcript-lifecycle.ts attempt_prepare 192 189 Applied: shared final failure selection after optional primary-error cause attachment, plus inlined the transient child-owner and queue-tail forwarding bindings. Native promise handlers retain registration order and microtask structure; primary/frozen/already-caused errors, descendant admission, drain-before-ALS-disable and teardown budget unchanged.
src/agents/embedded-agent-runner/run/attempt-user-transcript-context-registry.ts attempt_execute 32 32 Read registry and owner test. Array identity remains live across list/clear; a Map would require new snapshots and change that contract. Upsert already shares record/list behavior.
src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.ts attempt_execute 243 243 Re-read iterator factory, early/late cleanup, result observer and proxy paths. Unopened generators skip finally, so explicit unopened return is required. Shared result and error observers already remove duplicated lifecycle publication.
src/agents/embedded-agent-runner/run/attempt.model-diagnostic-lifecycle.ts attempt_execute 385 382 Applied one response-payload observation callback for synchronous and Promise-like results. Preserved synchronous returns, thenable-owned then invocation, replacement identity and byte-accounting timing.
src/agents/embedded-agent-runner/run/attempt.model-diagnostic-observation.ts attempt_execute 403 380 Applied inline single-use usage projection and semantic-progress publication at their owning observation methods. Exact usage shape, terminal precedence, one-shot latch and FIFO diagnostic publication preserved.
src/agents/embedded-agent-runner/run/attempt.tool-call-argument-repair.ts attempt_execute 584 581 Applied direct bounded tool-name normalization expression. Re-read complete parser/state machine; object and edits-array parsing already share comma-separated body; malformed quote and ordinary JSON rules remain explicit.
src/agents/embedded-agent-runner/run/attempt.ts attempt_execute 560 560 Re-read full preparation/cleanup/permission refresh pipeline. Shared exact phase prefix is only five fields and a new record plus two spreads does not improve the already-grouped calls; expanding its fields would change input key placement and preparation-read timing. MCP/LSP cleanup already shares a loop.
src/agents/embedded-agent-runner/run/auth-controller.ts run_control 648 648 Read full initialization, refresh and rotation owner plus 1,007-line owner tests. Fresh eligible-profile iterator prototype 648→657 (+9): preserving initial rereads after admission callbacks, rotation exhaustion, cooldown policy and identical await boundaries requires an initial/rotation strategy and extra iterator state. Retained explicit paths; no moved lastProfileId assignment across the AWS exception boundary.
src/agents/embedded-agent-runner/run/auth-plan.ts run_control 233 232 Applied one materialize/select convergence loop replacing two copies (-1). It performs at most the same two preparations, allows one harness change, marks prepare-plan only on the first pass, and throws identical nonconvergence copy. Existing public/internal function contract unchanged; source differential compares ordered callbacks, mutations and thrown steps.
src/agents/embedded-agent-runner/run/auth-profile-failure-policy.ts run_control 38 38 Read complete exclusion policy. A Set membership table cannot narrow the returned AuthProfileFailureReason union without an assertion; local transient and timeout-started exceptions require explicit predicates. Existing ordered null gate is the smallest clear typed form.
src/agents/embedded-agent-runner/run/auth-profile-failure-policy.types.ts run_control 4 4 Read four-line shared/local/local_transient contract and consumers. All variants used; moving it into the policy implementation neither removes responsibility nor saves production lines after imports.
src/agents/embedded-agent-runner/run/auth-profile-success.ts run_control 257 257 Revalidated byte-identical full P2 owner. Nonblocking success bookkeeping, credential/class-specific fingerprints and materialized route facts remain independent. Sharing local log formatting moves work across trace gates; credential fingerprints already share the canonical owner.
src/agents/embedded-agent-runner/run/auth-store.ts run_control 51 51 Read full scoped store and key dispatch. Preserve authoritative empty external IDs, normalized requested IDs, retained credential object identity and empty store version. A generic collection adapter would obscure the only two distinct shape variants.
src/agents/embedded-agent-runner/run/backend.ts attempt_execute 88 88 Read attachment preparation, admitted authority and backend result projection. Callback rechecks current admission after awaited attachment work. Backend model/provenance removal and prepared-owner model selection must remain explicit; no equivalent duplicate core remains.
src/agents/embedded-agent-runner/run/blocked-run-result.ts attempt_execute 28 28 Read complete blocked result owner. It is already the single parameterized constructor for visible error and metadata. Further spreading would change public result fields.
src/agents/embedded-agent-runner/run/codex-app-server-recovery.ts attempt_execute 66 66 Read retry budget and precedence-ordered reason classifier without changing Codex behavior. Different reasons and side-effect gates are intentional; table form would evaluate checks eagerly or add predicate closures.
src/agents/embedded-agent-runner/run/compaction-accounting-bridge.ts attempt_execute 41 41 Read WeakMap custody. Runtime identity stores private accounting independently from portable public metadata; narrow attach/read functions are already minimal.
src/agents/embedded-agent-runner/run/compaction-live-model-selection.ts attempt_execute 32 32 Read model/profile inheritance. No request returns current by identity; same-provider inherits profile; provider change drops profile and resets source. Shared selection record already covers variant fields.
src/agents/embedded-agent-runner/run/compaction-retry-aggregate-timeout.ts attempt_execute 63 63 Read reflected retry promise and aggregate timer. Each extension owns a fresh timer; late rejection remains observed. A single race/finally cannot preserve repeated active-work extension.
src/agents/embedded-agent-runner/run/compaction-runtime.ts compaction 548 548 Retained shared before/after hook envelope from P2. The fresh comparison helper prototype saves only three lines here while growing the shared owner by 21. Memory-manager and durable-successor adoption retain their distinct authority, commit and disposal order.
src/agents/embedded-agent-runner/run/compaction-timeout.ts attempt_execute 92 89 Replaced mutable reverse-tail cursor with findLastIndex at the same continuation predicate. Preserves sparse/undefined entries, reverse visitation and fresh prefix-array identity. Boolean timeout-return prototype measured 92 to 92 and was reverted; direct guard remains clearer.
src/agents/embedded-agent-runner/run/context-engine-admission.ts attempt_execute 55 55 Read lease acquisition, turn begin and disposal. Supplied leases stay caller-owned; newly acquired leases dispose both on failed begin and owner release. A local disposer adds callback declaration without reducing the two short branches.
src/agents/embedded-agent-runner/run/context-recovery-state.ts attempt_execute 48 48 Read ordered accounting and marker ownership. Unknown-current-context snapshot must differ from no observation, and marker clear-before-restore prevents reuse. Compaction totals and latest context are distinct facts.
src/agents/embedded-agent-runner/run/deferred-lifecycle-owner.ts attempt_execute 221 221 Re-read pending owner, retry wait, sync discard, async complete and CLI handoff. Existing retry-release and owner-replacement cores already shared; flattening async complete into sync discard changes cleanup order.
src/agents/embedded-agent-runner/run/execution-context.ts run_control 70 68 Applied removal of duplicated provider/modelId from private PreparedEmbeddedAttemptDispatchInput (-2), coordinated with attempt_execute. Those immutable selected values already belong to preparedRuntime. Original PreparedEmbeddedRunInput pre-hook identity stays unchanged.
src/agents/embedded-agent-runner/run/execution-phase-diagnostics.ts run_control 39 39 Read full captured-callback/current-session owner. Current session ID cannot derive from original mutable params; callback bindings are captured while diagnostic identity fields remain intentionally read at event time. Inlining closures into the returned record retains all code and grows annotations.
src/agents/embedded-agent-runner/run/failover-observation.ts run_control 111 111 Read full sanitized capture and live decision logger. Structured raw-error projection, own undefined fields and optional trace-level formatting are separate surfaces. Table-driven projection would need casts and would expose fields the current explicit projection intentionally excludes.
src/agents/embedded-agent-runner/run/failover-policy.ts run_control 197 197 Read current source and revalidated P2 shared prompt predicate. Prompt, assistant and retry-limit modes retain different action sets and authority/timeouts. Common action result selection already owns the actual shared core.
src/agents/embedded-agent-runner/run/failover-retry-controller.ts run_control 407 407 Read complete owner and existing focused contracts. Auth fingerprint invalidation, profile mutation, transient retry count, output-limit count, outage time window and rate-limit-history cap have different reset conditions. P2 already owns ordinary/rate-limit dispatch; no remaining shared retry budget can remove one of these facts.
src/agents/embedded-agent-runner/run/helpers.ts run_control 186 186 Read complete usage/model/text helpers. Model identity intentionally ignores OpenClaw synthetic assistants; latest usage distinguishes recorded zero and unavailable contexts. Public raw/visible text projections need different extractor behavior; generalized text helper would only add callback plumbing.
src/agents/embedded-agent-runner/run/history-image-prune.ts attempt_prepare 319 319 Retained on first pass. Canonical fact ownership and factless legacy regex cleanup have distinct provenance; lazy message/content copies preserve sparse slots and metadata-only fresh-array guarantees. Cutoff tracking preserves recent completed turns and ignores the active loop.
src/agents/embedded-agent-runner/run/idle-timeout-breaker.ts attempt_execute 26 26 Read independent output-progress and timeout counters. Non-timeout failures preserve count while completed progress resets; state survives retries by design and cannot derive from latest attempt.
src/agents/embedded-agent-runner/run/images.media-refs.ts attempt_prepare 92 92 Retained. One local-reference resolver handles media URI, safe file URL and ordinary path; aliases and CLI-image-cache exclusion have different roles. Full map-before-some intentionally resolves every fact; replacing it with a short-circuit mapper could omit later validation.
src/agents/embedded-agent-runner/run/images.ts attempt_prepare 635 635 Retained after actual common loadWebMedia call prototype 635→637 (+2), saved as prototypes/attempt_prepare/images-shared-loader.ts. Parameterizing sandbox/localRoots/maxBytes into one nested variant object grew under formatting. Image ownership, exact slot order, per-entry sanitizer failure accounting and provider/canonical metadata projections remain separate contracts.
src/agents/embedded-agent-runner/run/incomplete-turn-classification.ts run_control 250 249 Applied canonical positive-finite-number coercion for output token evidence (-1), deleting duplicate finite/positive composition. Answer-segment and provenance classifiers retain all ownership/empty/error distinctions.
src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts run_control 430 427 Applied combining consecutive settled-continuation null-return guards (-3). Delivery and model-policy checks remain after all earlier safety checks with identical short circuit. Other reasoning/empty/tool-rejection variants need different output evidence and retain their exact instructions.
src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts run_control 377 372 Applied one ordered null-return guard for existing terminal and delivery exemptions (-5). Same short-circuit property/helper reads; no reason/message branch removed. Fresh blocked-liveness return prototype 372→372 (0) retained separately; it only trades two readable returns for a multiline OR.
src/agents/embedded-agent-runner/run/internal-params.ts attempt_execute 90 90 Read private run and attempt parameters. Fields represent separate live authority, preparation and accounting contracts; no unused owner projection identified. Public config/SDK/persisted shapes untouched.
src/agents/embedded-agent-runner/run/lane-controller.ts attempt_execute 464 464 Revisited both enqueue settlement paths and deadline callbacks. Native global admission tracks counter settlement on synchronous enqueue throws; session admission additionally owns awaited foreground maintenance and queued context retirement. Prior +2-line shared wrapper remains an extra thunk; no new common lifetime identified.
src/agents/embedded-agent-runner/run/lane-runtime.ts attempt_execute 57 57 Read queue note, timeout and priority mapping. Foreground trigger classification and recovery override are distinct because resume permission depends on both. Existing timer coercion owner handles numeric policy.
src/agents/embedded-agent-runner/run/llm-idle-timeout.ts run_control 451 448 Applied explicit container-host allowlist Set in place of a one-use three-branch hostname predicate (-3). Exact hostname matching, model cloud override, local/private parsing and first-event/idle timer policies preserved. Stream creation/progress/consumer cleanup logic untouched.
src/agents/embedded-agent-runner/run/message-tool-terminal.ts attempt_execute 123 123 Read both tool-completion hooks. Host-authored capability evidence is per-batch; message-tool-only delivery is post-call receipt evidence. Args are deliberately reread after delivery callback before terminal decision, so cached args would alter callback-observable state.
src/agents/embedded-agent-runner/run/message-transform-stream-wrapper.ts attempt_execute 56 56 Read transform identity and one-shot context handoff. Handoff clears capture before awaiting and checks abort before materialization; eager conversion or blanket copying would break ownership/identity.
src/agents/embedded-agent-runner/run/midturn-precheck.ts attempt_execute 50 50 Read local overflow signal and assistant exclusion. Constructor preserves request reference and name; signal instance check and stable assistant text check apply to distinct representations. No unused branch.
src/agents/embedded-agent-runner/run/model-admission.ts run_control 55 55 Read full admission gates. Configless fallback resolves only when neither requested provider/model exists; pinned native sessions defer model ownership to their runtime. The two different selection stages cannot be collapsed into one authority check.
src/agents/embedded-agent-runner/run/model-harness.ts run_control 132 132 Read full shared model-provider plan and selectors. Empty prepared-attempt array must still select prepared-provider mode; native pinned harness error text and authored context budget source remain unchanged. Common two-field return would add an adapter.
src/agents/embedded-agent-runner/run/model-setup.ts run_control 449 448 Applied fresh-catalog membership predicate used both before lazy native catalog loading and after it. Measured fresh prototype 449→448 (-1), so implemented despite prior estimate. Entries/route variants still short-circuit in order; catalog remains live across loading. Native session authority/read-retry path unchanged.
src/agents/embedded-agent-runner/run/overflow-context-recovery.ts attempt_execute 447 447 Re-read full overflow detector, compaction/truncation retries and guidance. Budget-only precheck and provider failures retain different diagnostics, checkpoint rejection and active-session recovery. Existing shared truncator and retry closure are the smallest common execution cores.
src/agents/embedded-agent-runner/run/params.ts run_control 351 351 Read full public run/foreground parameter contract. Shared context intersections already own cross-entry fields; optional authored controls, runtime grants, lifecycle callbacks and configuration options remain unchanged.
src/agents/embedded-agent-runner/run/payloads.ts run_control 444 444 Read complete segment/payload producer. Shared source mirror and segment projection already consume existing records. Canonical assistant media, streamed text, TTS facts, error formatting and terminal tool warnings differ in presence/provenance. A data-driven payload copy would require key casts and lose visible property-order clarity.
src/agents/embedded-agent-runner/run/permission-change.ts run_control 116 116 Revalidated byte-identical previously read full owner and close/new-factory proof. Registry now owns liveness, Deferred owns pending completion; revision remains independent current request state. No further duplicate state or safe narrowing.
src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts attempt_execute 266 266 Re-read transcript source witness, replay preparation and one-time consumption. Every assertion closes a distinct source/writer/await gap. No schema/storage owner changes made.
src/agents/embedded-agent-runner/run/preemptive-compaction.ts compaction 372 372 Retained the P2 derived route. The comparison still begins overflowTokens > 0, preserving NaN; current-window pressure owns behavior while larger unwindowed pressure is diagnostic only.
src/agents/embedded-agent-runner/run/preemptive-compaction.types.ts attempt_execute 8 8 Read four-state route contract. Pure union matches all used recovery states; no runtime LOC to simplify.
src/agents/embedded-agent-runner/run/preparation-timing.ts attempt_execute 21 21 Read timing adapter. It names the agent.prepare span and stage attributes on shared diagnostics owner; removing adapter repeats literal policy at many callers.
src/agents/embedded-agent-runner/run/prepared-runtime-context.ts attempt_execute 91 91 Read generation-workspace resolution and committed runtime rebinding. Lazy metadata resolution and admitted-generation bypass have different load boundaries; requested execution workspace and runtime workspace are not duplicate state.
src/agents/embedded-agent-runner/run/progress-controller.ts attempt_execute 151 151 Re-read all global event, callback and user progress paths. Global emission is synchronous while two callback sends are awaited; distinct logs and reset ownership preserved. Existing progress payload formatter is shared.

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Coverage log, part 3 of 3.

Per-file decisions: rows 262–380 of 380

Base b3196dfda33555857eae9cd52ea29367a91bd9ea → final head 34e39db29179ceb9b7f2ce09f727c2aeded0b83a (tree a1f1b52fe5b6607bfea3089ad3e036b947425d21).

643 net production lines removed (1,069 added / 1,712 deleted) across 103 changed or new production files. Tests, fixtures, test support, generated files, and declarations are excluded from that count.

All 285 assigned runner files and 26 assigned subscriber files have recorded decisions. This complete table also includes adjacent owners, for 380 unique files in total. There are no decision gaps or changed-file focused-test-target gaps. The entries record implementation and differential evidence; validation results belong to the PR's proof summary.

File Scope Base lines Final lines Decision and evidence
src/agents/embedded-agent-runner/run/prompt-failure.ts run_control 379 379 Revalidated byte-identical complete P2 owner. Recorded-stop guards precede auth/thinking repair. Detached failure mark after selecting a replacement and awaited mark before fallback are separate lifetime contracts; trace defaults and optional status keys remain unchanged.
src/agents/embedded-agent-runner/run/prompt-image-metadata.ts attempt_execute 53 53 Read persisted image indices/layout decoding. Existing integer owner is shared; map-to-null for positional indices differs from filter-out for suppressed indices. Valid slot discriminants preserve typed shape and missing-key omission.
src/agents/embedded-agent-runner/run/prompt-image-preparation.ts attempt_execute 82 82 Read prompt hydration and native image/media cutover. Skip, embedded and plugin paths preserve different own keys and failure behavior; native filtering intentionally resolves persisted facts after hydration. Existing image owner handles common work.
src/agents/embedded-agent-runner/run/provider-refusal.ts attempt_execute 30 30 Read refusal diagnostic projection. Existing coercion owner is reused; provider/category admission and optional review/native identifiers preserve different absence rules.
src/agents/embedded-agent-runner/run/provider-review-continuation.ts attempt_execute 222 222 Revisited full P2-read source, unchanged. Before/after payload validation straddles hook awaits; dispatch and accepted-response latches fence reentry rather than duplicate one state.
src/agents/embedded-agent-runner/run/provider-review-run.ts attempt_execute 228 228 Re-read source only; unchanged. Synchronous Incognito capture and awaited durable review recording remain separate storage contracts; before/after authority checks and final queue settlement must retain precedence.
src/agents/embedded-agent-runner/run/recovery-message-action-capability.ts attempt_execute 78 78 Read capability reconstruction. Trusted-ingress gate precedes minting; source-turn correlation does not replace current authority. Explicit field projection preserves the existing private capability shape.
src/agents/embedded-agent-runner/run/retry-budget.ts run_control 39 39 Read all retry state/mutations/callers in run-loop. Dispatched and charged counts differ on legitimate progress continuation; maxAttempts is the configured owner bound. No duplicate count is derivable without replacement state.
src/agents/embedded-agent-runner/run/retry-limit.ts run_control 47 47 Read fallback throw and terminal payload owner. Those actions differ in exception identity and metadata rather than only message copy; shared construction adds a variant layer with no common lifecycle owner.
src/agents/embedded-agent-runner/run/run-attempt-dispatch.ts attempt_execute 683 664 Shared active-run assertion acquisition and trajectory target projection with distinct abort signals and missing-key policy. Reads route provider/modelId from the existing prepared runtime after proving exact production value parity and no mutation. Two dispatch fixtures migrated without assertion changes; run_control owns caller/type field removal.
src/agents/embedded-agent-runner/run/run-attempt-result.ts attempt_execute 78 78 Read normalization, idle progress and trace summaries. Continuation forces unsafe replay while absent plugin arrays normalize independently; successful names need sorted nested names but ordered direct names. No interchangeable branch.
src/agents/embedded-agent-runner/run/run-settlement.ts attempt_execute 136 136 Re-read committed accounting and ordered teardown. Original/accepted writer fields differ by identity; prior shared writer-record prototype grew two lines. Accounting publication remains ahead of fallible cleanup.
src/agents/embedded-agent-runner/run/runtime-context-prompt.ts attempt_prepare 252 252 Retained. Carrier builder is already shared by system updates and legacy custom messages. Typed fragments versus fallback text and fresh carrier versus existing-message update require distinct branches; symbol retention and provider flags are named contracts.
src/agents/embedded-agent-runner/run/runtime-preparation.ts attempt_prepare 537 532 Applied: initialize transport ownership only after actual harness selection; use one typed context-token metadata constructor at initial preparation and model commit. resolveEmbeddedRunEffectiveModel returns an ordinary spread-created record, so captured numeric metadata is stable; fresh metadata object creation and property omission occur at the same two points, preserving snapshot identity between commits. Native/direct auth authority, refresh and commit branches unchanged.
src/agents/embedded-agent-runner/run/runtime-resolution.ts attempt_execute 131 131 Read complete route/default/think/trajectory projection. Manifest normalization is deliberately deferred until runtime preparation; requested aliases, configured default and actual model attribution have different fallback contracts. No repeated execution core remains.
src/agents/embedded-agent-runner/run/session-bootstrap.ts attempt_prepare 541 539 Applied: share the identical candidate-session-key result across the matching-entry and absent-entry conditions in their original short-circuit order. Legacy marker validation, initial-writer admission, pending-write drain and replacement fencing unchanged.
src/agents/embedded-agent-runner/run/session-boundary-prompt-cache-key.ts attempt_execute 21 21 Read cache identity key. Explicit trim has priority; provider gate prevents unrelated suffixing; truncateCodePoints preserves 64-code-point contract. No duplicated construction.
src/agents/embedded-agent-runner/run/session-context-limits.ts attempt_execute 7 7 Read bounded context projection. Shared fixed event count and token-derived byte limits; both bounds intentional. Already minimal.
src/agents/embedded-agent-runner/run/session-prompt-state.ts attempt_execute 316 316 Re-read source/target/fence, commit notification and continuation owners. Persisted input, adopted target, accepted successor and projection-settlement flags encode separate facts. No safe derivation merges them.
src/agents/embedded-agent-runner/run/settled-turn-finalization.ts run_control 659 659 Read full finalization/retry/transcript producer and tests/callers. Finalizer-local replay state, original tool evidence and fallback error preservation remain separate. Candidate shared abort/assert helper grows code for three independent return-before-assert boundaries; unchanged.
src/agents/embedded-agent-runner/run/setup.ts attempt_execute 233 233 Re-read model-hook admission, public attachments and context policy. Source-sensitive context cap and native-model ownership have distinct output absence rules. Provider/model override branches remain two clear field-specific updates.
src/agents/embedded-agent-runner/run/shared-run-context.ts attempt_execute 20 37 Shared pure four-field trajectory session-target projection here alongside existing message-context projection, preserving missing-key strategy. Dispatcher already imports this runtime-free owner, avoiding a new eager trajectory-preparation module edge. Table-based message projection remains larger than fixed fields.
src/agents/embedded-agent-runner/run/source-reply-payloads.ts attempt_execute 93 93 Read full payload/mirror/evidence builder. Runtime delivery and transcript mirror shapes intentionally differ, including empty text, index-based idempotency key and transcript ownership. Existing source media resolver and evidence owner are shared.
src/agents/embedded-agent-runner/run/stream-wrapper.ts attempt_execute 111 111 Read settlement and event-transform composition. Error/return/throw paths preserve iterator ownership and settle-versus-close differences. Adjacent transforms already coalesce; opened-iterator snapshots prevent retroactive reordering.
src/agents/embedded-agent-runner/run/terminal-outcome.ts run_control 75 75 Read full terminal projection. Public helper callers need timeout/cancellation/interrupted separately; computing a new shared classification record would add projection plus migration code. Refusal safe-copy and captured signal interruption remain at their current producer.
src/agents/embedded-agent-runner/run/terminal-preparation.ts run_control 330 330 Revalidated byte-identical to previously read complete P2 owner. Completed answer, current model attribution, timeout recovery, usage totals and partial payload identity intentionally come from separate facts. Common terminal envelope still requires more projection/type code than it removes.
src/agents/embedded-agent-runner/run/terminal-resolution.ts run_control 715 706 Applied one terminal-facts record to the four recovery classifiers and one immutable recovery-admission predicate to ordered retry branches. Local snapshots and same-order classifier calls remain; result projections and visible copy unchanged. Fresh visible-answer retry helper prototype 706→716 (+10), rejected: callback/counter/diagnostic parameters outweigh two explicit branches.
src/agents/embedded-agent-runner/run/terminal-retry-state.ts run_control 26 26 Read complete counter defaults and optional completion-check interface/callers. The counters have different limits/reset semantics. Inferring type from defaults removes optionality; deriving count tables needs a cast and grows definitions.
src/agents/embedded-agent-runner/run/terminal-timeout.ts run_control 102 102 Read full timeout producer and compare with terminal resolution. Shared metadata is interleaved differently with final timeout/error and trace fields; a shared constructor needs more typed projection inputs. Existing copyAttemptDeliveryState already owns the actual common delivery projection.
src/agents/embedded-agent-runner/run/timeout-context-recovery.ts attempt_execute 139 139 Re-read exact-marker capture/transfer/reinstatement and compaction recovery. Failure restores the original timeout marker, success transfers cleanup; a blanket finally would alter that authority boundary.
src/agents/embedded-agent-runner/run/tool-activity-heartbeat.ts attempt_prepare 54 54 Retained. Direct execution, preparation and ready execution each need their own interval lifetime; metadata-copy recursion preserves source identity. Shared generic heartbeat owner already wraps all three paths.
src/agents/embedded-agent-runner/run/tool-error-warning.ts attempt_prepare 281 272 Applied: flatten the final recognized-run-summary return and infer the private raw-command-context record instead of a one-use mirror. Rejected eager shared detail suffix: combined draft 281→270 (-11), final 272 (-9). It redundantly formatted/read error details on full-verbose generic failures; preserving branch-local evaluation is clearer. Literal command parsing, terminal punctuation and approval-timeout behavior remain exact.
src/agents/embedded-agent-runner/run/tool-loop-recovery.ts attempt_prepare 63 63 Retained after actual inline-admission-destructure prototype 63→65 (+2), saved under prototypes/attempt_prepare/tool-loop-recovery.ts. Typed result/lifecycle callbacks and fail-closed first-call intervention are already concise.
src/agents/embedded-agent-runner/run/tool-media-payloads.ts attempt_prepare 331 326 Applied actual conditional payload-list prototype 331→326 (-5): host-owned and auto-delivery entries share one ordered list/filter/append path while keeping explicit independent audio/trusted flags and source-suppression marking. Carried/current selection, batch ownership, metadata transfer and returned-array identity when no owned media stay unchanged.
src/agents/embedded-agent-runner/run/transcript-tail-metadata.ts attempt_execute 10 10 Read metadata preservation predicate. Four entry categories are explicit; last category delegates transcript-only message policy. No redundant guard.
src/agents/embedded-agent-runner/run/turn-taint-state.ts run_control 14 14 Read sticky network taint projection. Clean results cannot clear earlier untrusted content; presentation-only observations do not taint. This independent run-owned state has no other owning representation.
src/agents/embedded-agent-runner/run/types.ts run_control 479 479 Read complete 479-line published attempt/result types. Required attempt fields, omitted caller fields, current-vs-legacy assistant evidence, provider failure diagnostics and tool provenance are actual consumers/contracts. No semantic SDK signature change or speculative type mirror replacement.
src/agents/embedded-agent-runner/runs.abort-target.ts registry_history 52 52 Revisited complete owner and its responsibility boundaries. Not covered in P2 log
src/agents/embedded-agent-runner/runs.probes.ts registry_history 68 68 Revisited complete owner and its responsibility boundaries. Retained explicit compaction/abort/supersede probes: warning deduplication, unknown compaction result and fail-closed boolean results differ. A fresh generic read/fallback/error strategy prototype grew 68 to 82 lines (+14).
src/agents/embedded-agent-runner/runs.session-index.ts registry_history 42 42 Revisited complete owner and its responsibility boundaries. Re-read exact-key vs full-index clear and stable parent-realpath normalization. Existing shared deletion loop preserves aliases. Scheme checks are readable ordered predicates; no additional ownership consolidation.
src/agents/embedded-agent-runner/runs.ts registry_history 1687 1676 Removed the sole private abandonment-publication helper and its duplicate ID validation. The active-handle owner now captures the same parameter snapshot and run ID, clears prior indexes, and publishes the same fields in the same order. 216 extracted cases retain results, map order and path-normalizer trace.
src/agents/embedded-agent-runner/sandbox-info.ts model_prompt 119 119 Re-read P3 and retained the prior P2 consolidation: Applied: common unavailable-result projection uses explicit blockedByPolicy decision. Host policy still short-circuits elevation availability and custom blocked-reason reads.
src/agents/embedded-agent-runner/sandbox-skills.ts registry_history 257 257 Revisited complete owner and its responsibility boundaries. Physical/host/runtime references use one shared mapping owner and first-occurrence index. Resolved versus discovery selections differ in completeness checks; sourceReadPath first pass and physical-target second pass intentionally preserve replacement precedence.
src/agents/embedded-agent-runner/server-endpoint-compaction.ts registry_history 131 131 Revisited complete owner and its responsibility boundaries. The committed flag cannot derive from endpoint success: rewrite, observer and release failures have different fallback rights. Apparent owner type checks supply TypeScript narrowing after a compound findLast predicate; removing them requires a longer explicit type guard.
src/agents/embedded-agent-runner/session-prompt-state.ts registry_history 410 410 Revisited and retained the earlier consolidation: one state selection/publication path owns creation and LRU promotion; only newly created states trigger pruning, as before. No persisted series/checkpoint changes.
src/agents/embedded-agent-runner/skill-runtime.ts registry_history 145 145 Revisited complete owner and its responsibility boundaries. Snapshot and fresh-entry env paths feed existing shared runtime preparation; they consume different source contracts, while final authority gates and rollback remain single-owned.
src/agents/embedded-agent-runner/skills-prompt.ts registry_history 65 65 Revisited complete owner and its responsibility boundaries. new owner since PR1, read complete. Shared skill-entry preparation already owns host-vs-sandbox eligibility and map; runtime prompt owner controls loading and usage paths. No policy equivalence for collapsing different truthiness/enabled tests.
src/agents/embedded-agent-runner/stream-resolution.ts model_prompt 286 284 Shared credentialed stream constructor for provider/native/boundary routes, retaining explicit options/strategy and separate Vertex/custom auth/identity contracts. Restored explicit default-option guards after the 283-line loop variant violated no-accumulating-spread; the valid callback-core prototype measured 285, one line longer than the retained 284-line form. Differential option/getter and route/credential/cancellation cases remain required.
src/agents/embedded-agent-runner/terminal-tool-failure.ts registry_history 60 60 Revisited complete owner and its responsibility boundaries. Exact allowlist regex protects persisted diagnostic content; sharing generic failure-signal parsing would combine distinct safe-data policies. Every literal and first-line gate kept.
src/agents/embedded-agent-runner/thinking-replay-repair.ts model_prompt 114 114 Re-evaluated P3: Durable rewrite effects are already shared. Thinking repair maps every affected message; checkpoint repair selects only the latest exact checkpoint. A selector strategy would duplicate the current concise replacement builders.
src/agents/embedded-agent-runner/thinking.ts model_prompt 480 474 Applied shared thinking-recovery eligibility/start owner for request/stream/iterator rejection, explicit stage and yielded-output parameters; shared producer-completed handler; direct success predicate. No async boundary added. Exact retry cap, output veto, logs and notifications match in 96 differential cases.
src/agents/embedded-agent-runner/tool-call-argument-decoding.ts registry_history 60 60 Revisited complete owner and its responsibility boundaries. Object assignment versus Object.fromEntries differs for literal proto; this behavior-change proposal remains outside the lane. Stream result and partial events share the decode owner already.
src/agents/embedded-agent-runner/tool-name-allowlist.ts registry_history 27 27 Revisited complete owner and its responsibility boundaries. Retained canonical reserved names, shared trimmed-name collection, and the deduplicated sorted session allowlist; each adapter serves its existing caller contract.
src/agents/embedded-agent-runner/tool-result-char-estimator.ts registry_history 169 167 Inlined the one-use image predicate at its exact fallback condition, retaining object/array and malformed block acceptance. No estimator algorithm or JSON fallback changed.
src/agents/embedded-agent-runner/tool-result-context-guard.ts registry_history 469 468 Derived whether the first text block was restored from replacement-message identity, eliminating a duplicate boolean without changing map traversal or sparse slots. 36 extracted cases preserve output and cache identity. Fresh cleanup-only shared adapter measured 468→473 (+5); retained direct installation cleanup.
src/agents/embedded-agent-runner/tool-result-text-budget.ts registry_history 113 113 Revisited complete owner and its responsibility boundaries. Head/tail share the same binary-search core with explicit direction. Separate public adapters preserve caller signatures. Prepared text memo belongs to block identity/revision; no redundant cache owner found.
src/agents/embedded-agent-runner/tool-result-truncation.ts registry_history 1483 1480 Narrowed the private two-boolean projection API to the only real variant, recovering:true. Dispatch always records sources and applies available replacements; recovery selects frozen replacements and permits reduction. All three callers migrated together. 48 extracted mode/state cases match branch identity and source-map mutations.
src/agents/embedded-agent-runner/tool-schema-runtime.ts model_prompt 91 91 Re-read P3 and retained the prior P2 consolidation: Inlined single-use diagnostics summary owner. Six-tool and twelve-violation bounds, pluralization, untrimmed provider label and exact structured diagnostics retained. Shared plugin params builder still serves inspection and normalization.
src/agents/embedded-agent-runner/tool-send-receipts.ts registry_history 53 53 Revisited complete owner and its responsibility boundaries. Re-read shallow receipt snapshots, consume-once registry deletion and optional field presence. One existing weak session registry owns lifetime. Generic field-table transformation would add typing/projection machinery for two fields.
src/agents/embedded-agent-runner/transcript-byte-preflight-authority.ts registry_history 90 90 Revisited complete owner and its responsibility boundaries. Re-read mint/release/consume flow. Claims are consumed even when the exact session/harness/trigger fails; one-shot authority differs from reusable admission. All identity and current-native-compaction checks retained.
src/agents/embedded-agent-runner/transcript-rewrite.ts registry_history 222 219 Flattened the private empty-ID lookup branch into an equivalent conditional return. Append dispatch, pending-input relocation, branch selection, commits and persisted fields unchanged; 15 extracted ID/map cases agree.
src/agents/embedded-agent-runner/types.ts registry_history 341 341 Revisited complete owner and its responsibility boundaries. This file declares distinct public result/diagnostic/compaction/sandbox contracts, with no runtime duplication. Shape intersection proposals would share only provider/model fields while obscuring optionality and individual ownership.
src/agents/embedded-agent-runner/usage-accumulator.ts registry_history 121 120 One ordered cache-counter loop records cacheRead/cacheWrite presence under their existing Reported fields. It retains write order, including reported zero, and changes no normalized/persisted field.
src/agents/embedded-agent-runner/utils.ts registry_history 37 37 Revisited complete owner and its responsibility boundaries. Positive finite budget flooring permits positive fractions to become zero; generic positive-integer normalization changes behavior. Thinking adapters encode distinct product/runtime mode contracts.
src/agents/embedded-agent-runner/wait-for-idle-before-flush.ts registry_history 56 56 Revisited complete owner and its responsibility boundaries. complete source re-read. Immediate timeout bypasses optional idle work, while cancellation never bypasses required transcript persistence. Reordering local async wait would change the promise boundary.
src/agents/embedded-agent-subscribe.callback.ts subscriber 34 34 No retained change. The 34-line owner already shares failure handling while preserving distinct synchronous and promise callback timing, pending task ownership and success/error behavior.
src/agents/embedded-agent-subscribe.handlers.compaction.runtime.ts subscriber 34 34 Complete runtime floor reconciler and compaction tests read. One accessor callback owns max(current, observed), zero floor, no-op detection and monotonic updatedAt. The async callback and outer await retain the existing store contract; no persistence or semantic change allowed or needed.
src/agents/embedded-agent-subscribe.handlers.compaction.ts subscriber 220 217 Inlined the sole reason normalizer at compaction start and removed its unused type alias. Captured evt.reason once before the same manual/threshold/overflow decision. Unknown reason fallback, every visible string, hook timing, persistence event and authority/liveness guard retained.
src/agents/embedded-agent-subscribe.handlers.lifecycle.ts subscriber 405 386 Retained inlined terminal wrappers and acceptance-hook callback, preserving sync/Promise timing and once reservation. Suppression still calls the restored SDK-reachable clearDeferredBlockReplies operation.
src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts subscriber 376 375 Removed only the redundant final return undefined. The source/current snapshots serve distinct mutation phases, and asynchronous flush versus synchronous flush must retain their different optional-callback/error/finalizer timing. Reasoning decisions are deliberately captured before delivery; no broad shared callback wrapper adopted. Complete finalization and source suppression order retained.
src/agents/embedded-agent-subscribe.handlers.messages.replies.ts subscriber 238 234 Selected explicit-media or pending-media payload in the existing branch order, then used one common cleanup/return. Inlined the now-single-use clear helper. Explicit selection keeps attachment alignment and trust narrowing; reasoning and empty pending media keep original payload/state identity. Source-reply metadata and audio directive counters unchanged.
src/agents/embedded-agent-subscribe.handlers.messages.snapshot.ts subscriber 286 286 No retained change. Prefix/source reconciliation uses distinct old/new coordinates, code crossings and prepared boundaries. A generic boundary-pair helper would require two snapshots, two offsets, scope and code-end modes and obscure the short-circuit read order; existing prefixAt/crossesCode already share the repeated work.
src/agents/embedded-agent-subscribe.handlers.messages.stream.ts subscriber 399 389 Shared the exact object-backed text-block predicate across stream item and content-index selection, preserving array-shaped malformed blocks and signature lookup conditions. Removed the redundant accumulated-prefix branch: includes already covers that case; the initial content-prefix suffix extraction still wins. Stream, commentary, reasoning and directive contracts remain unchanged.
src/agents/embedded-agent-subscribe.handlers.messages.update.ts subscriber 620 608 Reused the any-object event coercer, inlined immediate commentary aliases, and shared the outer source-reply suppression guard between mutually exclusive reasoning transitions. Kept raw/rendered/source coordinates and transport phase custody separate.
src/agents/embedded-agent-subscribe.handlers.tools.completion.ts subscriber 657 651 Reused the existing any-object coercer for terminate and heartbeat result facts; arrays remain accepted and details are read at the same point. Inlined patch event ID/title helpers, retaining their exact strings and evaluation point.
src/agents/embedded-agent-subscribe.handlers.tools.progress.ts subscriber 168 162 Shared the two tool-update data projections through an explicit includeResult parameter, returning a fresh object each time. Preserved field order, parent/hide optional presence, detailed event before item event before callback, and the omission of raw results from callback events. Throttle timestamps, sanitizer calls and typed public progress gating unchanged.
src/agents/embedded-agent-subscribe.handlers.tools.results.ts subscriber 561 560 Inlined sole approval-delivery failure callback into its catch. Warning/observer strings, payload and ordering preserved. A shared approval-detail reader prototype grew 12 to 15 lines (+3), so retained separate readers.
src/agents/embedded-agent-subscribe.handlers.tools.start.ts subscriber 555 547 Removed two one-use patch ID/title exports and inlined into completion caller. Shared active-key generator prototype was 14 to 14 lines before extra generator/call overhead; rejected as no reduction and less direct iteration.
src/agents/embedded-agent-subscribe.handlers.ts subscriber 131 129 Shared identical synchronous and asynchronous event-error logging through a local callback. Kept the dispatcher switch, event-specific narrowing and detached-versus-returned scheduling unchanged; the event chain still clears only if it owns the active promise. No extra promise layer introduced.
src/agents/embedded-agent-subscribe.handlers.types.ts subscriber 351 351 Restored to base: clearDeferredBlockReplies is reachable in SDK declarations and is a required retained operation.
src/agents/embedded-agent-subscribe.model-state.ts subscriber 226 226 Complete owner/tests inspected. Pending streamed usage, last positive call usage, retry fallback and completed assistant copies have different lifetimes and cannot derive from one another. Actual billed-cost predicate prototype measured 226 to 227 (+1); rejected. Provider-billed zero and error/retry context-accounting rules remain explicit.
src/agents/embedded-agent-subscribe.raw-stream.ts subscriber 43 43 Complete owner, raw-stream tests and Incognito boundary tests read. Environment and Incognito gates must precede path resolution and factory evaluation; one-time directory attempt, synchronous factory/JSON containment and asynchronous append containment are different phases. Existing code already owns each once. No change.
src/agents/embedded-agent-subscribe.reply-delivery.ts subscriber 613 611 Retained inlined one-use delivery success/failure callbacks. Restored clearDeferredBlockReplies and its return slot to preserve the reachable SDK contract and owner operation.
src/agents/embedded-agent-subscribe.run-state.ts subscriber 111 111 No retained change. Fresh collections and exact property/default presence are required; reset state intentionally retains attempt authority and mutation facts. Shared deferral predicate prototype was 16 to 16 lines before at least two new imports (+2 overall), so rejected.
src/agents/embedded-agent-subscribe.shared-types.ts subscriber 27 27 Read complete. Closed rendering modes and the event extension shape are shared API declarations; changing them or replacing explicit typed fields with a generic record would widen the contract. No runtime duplication or removable field.
src/agents/embedded-agent-subscribe.stream-rendering.ts subscriber 728 725 Shared hidden-code reset for entering and closing reasoning. Nested opens, orphan closes, scanner carry state and final-tag behavior stay intact.
src/agents/embedded-agent-subscribe.tool-lifecycle.ts subscriber 104 92 Moved completion into the owning invocation closure, eliminating repeated ctx/toolParams/outcome threading while retaining both existing awaits and the execution-only catch boundary. Snapshot executionStarted before flushing, exactly as the old outcome argument did, so reentrant flush callbacks cannot change the event fact. Removed the one-use runner alias and inlined the one-use implementation-start callback. Error identity, no-start branding, sanitization reuse and terminal result shape unchanged.
src/agents/embedded-agent-subscribe.tool-text-diagnostics.ts subscriber 91 91 Complete owner and lifecycle diagnostic tests inspected. Implemented a shared warning-context prototype preserving normalization, registration lookup, session lookup and field order: 91 to 90 (-1). Rejected as less clear: it needs a three-argument callback interface, including two lazy metadata readers, to replace two direct warning constructions. The direct warnings make private-text exclusion and each safe metadata field easier to inspect.
src/agents/embedded-agent-subscribe.trajectory.ts subscriber 38 38 Complete capture owner and subscribed/nested ordering tests inspected. Start sanitizes args while end consumes an already-prepared result; their field and callback evaluation order differs. One existing try/catch already contains both capture variants and protects live delivery from recorder failure. No duplicated owner to remove.
src/agents/embedded-agent-subscribe.ts subscriber 542 538 Retained inlined sole final-text re-filter helper. Restored the SDK-reachable clearDeferredBlockReplies operation and its wiring/callers. Promise-return optimization was also rejected: valid void adapter 537 lines versus retained explicit wait 536 before API restoration. Exact public wait behavior and microtask timing retained.
src/agents/embedded-agent-subscribe.types.ts subscriber 129 129 Read complete and traced runtime consumer interface. This is the public subscription contract and canonical Pick of attempt fields; remaining members carry distinct callback, delivery, authorization or lifecycle semantics. No runtime implementation to consolidate; no fields or signatures changed.
src/agents/embedded-agent-tool-authored-source-reply.ts attempt_prepare 32 32 Retained. Single extraction then exact idempotency fallback and sourceReplyFinal/toolAuthored projection already constitutes one owner. Capability/error/direct-call authority remains with callers; changing flags, fallback key or moving persistence here would change contracts.
src/agents/embedded-agent-tool-media.ts attempt_prepare 296 285 Applied: scalar media aliases share one ordered key list for envelope and attachment records, and redundant false/undefined branches collapse without changing reads or trust gates. Exact-name registration, core-TTS provenance, external-tool exclusions, attachments and metadata allowlist remain unchanged. No trusted-policy consolidation across repeated observations.
src/agents/embedded-agent-tool-result-preparation.ts attempt_prepare 106 106 Retained after full owner/cache/reuse test read and actual common descriptor-reader prototype 106→110 (+4). Capture and match still need distinct traversal/results, so the shared guard adds indirection. Input/output snapshots independently reject mutations; sparse arrays, proxies, nonplain prototypes, functions/accessors remain ineligible; Object.is preserves NaN/signed zero.
src/agents/embedded-agent-tool-results.ts attempt_prepare 469 446 Applied: one recursive payload walker parameterized by args/result mode replaces two traversal owners. Args preserve scalar-key field masking but reset keys inside arrays; structured results retain array credential keys, result-only bigint conversion and binary/opaque omission. Shared-reference/circular handling, Object.entries getter order and proto data properties preserved. Text versus structured fallback share final join/cap; denial codes use one ordered find; remove proven unreachable non-object checks after readToolResultDetails; all three truncation variants use one limit/suffix core with unchanged constants and text. Public signatures unchanged.
src/agents/embedded-agent-utils.ts root 446 428 Applied reviewed prototype: shared deferred phase finalization, one thinking-tag transition cursor/core and combined native-thinking guard. 11,467 source differentials passed, including exported regexp state, callback/getter order, identity and replay-checkpoint effects. Full source and patch reviewed; existing SDK signatures unchanged.
src/agents/failover/assistant-request-failure-copy.ts failover 279 279 Copy-specific redaction, nested parsing, depth and byte limits stay explicit. Storage-message sharing prototype 279 -> 280 (+1), rejected. Provider/storage/user copy tables already parameterize the distinct messages. Broad renderer merge would obscure the different trusted-fact versus raw-text boundaries.
src/agents/failover/classification-rules.ts failover 427 422 Shared the four reason values preserved by both 404 and 410; 410 still precedes context overflow, 404 still additionally preserves format. Separate structured-code alias-map prototype 422 -> 416 (-6) rejected as less clear: replaces short switch labels with a 134-character symbol list plus splitting/flattening machinery. Existing grouped switch expresses each code directly.
src/agents/failover/classify-core.ts failover 452 435 Unified five early semantic matchers and three provider-pattern matchers into one ordered priority table. Same original ordering; context, recovery, plugin discovery, HTTP mapping and approval exclusion remain in their original positions. Prototype 452 -> 435 (-17), applied.
src/agents/failover/classify.ts failover 38 38 38 lines; two public wrappers preserve provider preparation and lazy core separation, plus compatibility exports. Removing them needs caller or SDK changes beyond owned scope; no extra private state or unreachable path.
src/agents/failover/context-overflow-tables.ts failover 55 54 Combined adjacent false-return exclusions, preserving TPM/size before reasoning order and all downstream classifier calls.
src/agents/failover/context-overflow.ts failover 64 62 Folded terminal successful-classifier guard into short-circuit OR with the heuristic. Request-size ceiling and quota/reasoning exclusions still run first.
src/agents/failover/error.ts failover 194 191 Combined consecutive false-return AbortError guards with identical short-circuit order. Constructor field list retained: Object.assign would publish extra supplied fields and change getter/cause semantics. Direct code precedence and recursive error-before-cause traversal retained.
src/agents/failover/message-patterns.ts failover 390 390 Complete pattern inventory and ordered matching reviewed. Factory prototype 390 -> 383 (-7) adds a wrapper owner and replaces named exported function declarations with unnamed returned closures, changing function names and stack diagnostics; no demonstrated readability improvement. Retained direct named matchers and exact regex bytes.
src/agents/failover/probe-status.ts failover 20 20 20 lines; complete reason-to-probe-status lookup. Already data-driven; omitting default entries would alter exported lookup shape.
src/agents/failover/provider-patterns.ts failover 39 39 39 lines; explicit null blocks discovery, prepared owner changes provider attribution, missing owner lazily dispatches runtime. Shared invocation across these branches would require a strategy adapter longer than the existing 22-line operation and obscure the null authorization/discovery boundary.
src/agents/failover/request-error-facets.ts failover 58 58 58 lines; one classifier with explicit precedence and one private conversation-state predicate. The distinct quota-429, conversation-state, 503 and generic-internal facets already share normalized text; no redundant owning state or duplicate operation found.
src/agents/failover/request-error-facts.ts failover 33 33 33 lines; one explicit reply projection combines typed failure facts with raw fallbacks. reason, code, provider, status and auth facts remain individually projected; spreading source objects would leak fields or change fallback precedence.
src/agents/failover/retry-evidence.ts failover 219 204 Grouped five duration units with their exact aliases in a private expanded Map, preserving all 23 entries and insertion order. Final replay decision returns the negated rejection condition directly; all prior evidence checks and short-circuit calls unchanged.
src/agents/failover/signal-details.ts failover 66 55 Shared trimming, UTF-16 truncation, deduplication and append logic for scalar candidates, removing the obsolete append wrapper. Strings alone retain bounded JSON traversal; record order, visited set and candidate limit unchanged.
src/agents/failover/signal.ts failover 28 28 28 lines; canonical protocol reason alias and public classification/signal shapes. No production policy duplication; shape changes prohibited.
src/agents/failover/user-copy.ts failover 630 628 Shared ordered command/exec/disk copy rendering; same lazy calls and first nonempty return. Partial cooldown-table prototype measured 628 -> 621 (-7), rejected after source-isolated input with invalid reason changed TypeError into generic copy. Full table preserved.
src/agents/sessions/agent-session-compaction.ts compaction 692 692 Restored to base. The measured three-line shared emitter changed a private member name present in reachable SDK class declarations. Preserve the existing declaration rather than add another forwarding member or misname the broader emitter.
src/agents/sessions/compaction/compaction.ts compaction 50 50 Retained the SDK throwing adapter. Its usageSink argument occupies the slot that agent-core uses for runtime dependencies; a raw rest forwarding signature would change the public API rather than remove a duplicate implementation.
src/agents/sessions/compaction/index.ts compaction 5 5 Retained the public/session import barrel; it contains no duplicate runtime path.
src/agents/sessions/compaction/request-budget.ts compaction 175 175 Retained after reviewing all budget consumers and tests. Fixed/tool serialization is deliberately once per owner; pending-user overlap, additive context and queued context are independent facts with exact joint-margin rounding. Existing estimation helpers already own shared arithmetic.
src/agents/sessions/compaction/runtime.ts compaction 11 11 Retained the eleven-line usage-sink adapter. It returns the canonical runtime unchanged without a sink and creates one private overlay only when requested.
src/agents/sessions/manual-compaction-preflight.ts compaction 37 37 Retained the two ordered core-planner attempts and exact no-op reasons. The manual zero-retention retry remains distinct from the configured-budget first attempt; public compactable result shape is unchanged.
src/agents/sessions/session-compaction-persistence.ts compaction 100 100 Retained after actual shared-scope factory prototype measured 100 -> 110 (+10). Preserving public function declarations, distinct global AsyncLocalStorage namespaces, same-manager checks, and sync versus awaited revocation leaves the shorter existing two wrappers. No storage/global-state shape changed.

@steipete
steipete marked this pull request as ready for review October 8, 2026 16:28
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL labels Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 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: 34e39db29179ceb9b7f2ce09f727c2aeded0b83a
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • 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.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 8, 2026, 12:36 PM ET / 16:36 UTC.

ClawSweeper review

What this changes

This PR consolidates repeated agent execution, cancellation, conversation summarization, delivery, and provider-failure handling while preserving existing contracts.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful consolidation with no concrete finding, supported by extensive reported checks but limited independently verified runtime evidence.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: This area-owner-authored internal refactor is exempt from ordinary contributor runtime proof. Reported tests and differential checks support cancellation, summarization, delivery, and stream equivalence, but do not establish a shipped-entry-point run. The diff does not materially change authority or stored-data contracts.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: Repeated operations create maintenance cost across closely related runtime paths. The area's prior merged history supports this consolidation direction, and the proposal reduces duplication without introducing a new product surface.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this owner-authored consolidation open. The introduced diff contains useful remaining work, and review found no concrete correctness or security regression. Confidence in runtime equivalence rests mainly on source inspection and reported differential/unit validation.

Priority: P3
Reviewed head: 34e39db29179ceb9b7f2ce09f727c2aeded0b83a

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.

Findings

None.

Provenance

  • src/agents/embedded-agent-runner/run/auth-plan.ts and stream-resolution.ts: original intent not found (unknown: Exact original introduction could not be recovered because string-history searches required unavailable promisor blobs; recent merged consolidation explicitly preserves auth, authority, and transport contracts.)
  • src/agents/embedded-agent-runner/run/abortable.ts and attempt-async-tasks.ts: original intent not found (unknown: Older blob availability prevented complete introduction research; current source and coverage discussion establish cleanup-before-settlement and distinct abort-error contracts.)
  • src/agents/failover/classify-core.ts and cache parsing: original intent not found (unknown: Available file history identifies recent maintenance, but older content required by introduction searches is unavailable.)

Tests

  • Missing end-to-end proof: No supplied run exercises the consolidated behavior through a shipped CLI, Gateway, or real channel; the reported suites and differential checks are supplemental. This maintainer-authored internal refactor is exempt from the ordinary external-contributor proof gate.
Agent review details

How this fits together

The agent runtime turns user requests and conversation history into model requests, tool execution, and delivered replies. Its summarization and cancellation paths keep conversations within model limits and settle interrupted work.

flowchart TD
  A[User request and conversation history] --> B[Prepared model and credentials]
  B --> C[Agent attempt runner]
  C --> D[Model stream and tools]
  C --> E[Conversation summarization]
  D --> F[Reply delivery and completion]
  E --> C
  G[Cancellation or provider failure] --> C
Loading

Technical review

Best possible solution:

Keep the consolidation within the existing runtime owners and preserve its explicit differences in cancellation, redaction, delivery, prompt bytes, and public declarations.

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

Not applicable: this PR proposes behavior-preserving consolidation rather than a reported malfunction.

Is this the best way to solve the issue?

Yes: sharing repeated operations in their existing owners is a maintainable direction, and the reviewed hunks retain the relevant ordering and variant-specific contracts.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • packages/agent-core/src/harness/compaction/ keeps the original intent (refactor: internalize OpenClaw agent runtime #85341: Internalize reusable agent runtime and compaction primitives under OpenClaw ownership while keeping compatibility at public boundaries.)
  • src/agents/embedded-agent-tool-results.ts and messaging extraction keeps the original intent (refactor(agents): split subscribe leaf ownership #122249: Split oversized subscriber handling into canonical result, media, and messaging owners while preserving SDK exports and event ordering.)
  • src/agents/embedded-agent-subscribe.handlers.lifecycle.ts keeps the original intent (895dccd: Gate finalize hooks before delivery; subsequent history preserves kept answers and deferred reply semantics.)
  • src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts and dispatch keeps the original intent (refactor(agents): consolidate embedded runner execution paths #166690: Reuse prepared runtime records and share execution operations while retaining ordering, replay safety, cancellation, and run authority.)
  • src/agents/embedded-agent-runner/run/attempt-transcript-lifecycle.ts keeps the original intent (refactor(agents): consolidate embedded runtime variants #167186: Share repeated runtime operations while preserving transcript ownership, cancellation, persisted shapes, and public contracts.)

Testing

Proof path: unit tests only. Added test files: 3.

Security

None.

Evidence

What I checked:

  • Pinned introduction reviewed: Read the complete introduced diff, including files omitted from the supplied file inventory; changes consolidate existing operations rather than add configuration, dependencies, or protocol surfaces. (34e39db29179)
  • Auth convergence remains bounded: The consolidated loop retains initial materialization, one allowed harness change, a second confirmation, and the existing nonconvergence error. (src/agents/embedded-agent-runner/run/auth-plan.ts:200, 34e39db29179)
  • Credential authority preserved: The shared stream constructor keeps the credential wrapper that checks current authority both before and after awaited credential resolution, before invoking the transport. (src/agents/embedded-agent-runner/stream-resolution.ts:274, 34e39db29179)
  • Distinct redaction contracts retained: The shared recursive walker preserves argument-array free-text handling, result-array credential keys, result-only bigint conversion, circular handling, and binary/header omission. (src/agents/embedded-agent-tool-results.ts:293, 34e39db29179)
  • Merge candidate preserves newer main behavior: Raw commit records confirm the test merge has the pinned base followed by the exact PR head. Its tool-result context guard contains both this PR's transcript restoration and main's newer system/reserve-token accounting in separate hunks. (src/agents/embedded-agent-runner/tool-result-context-guard.ts:359, e400e1866f3d)
  • Live mergeability: GitHub REST reports the pinned head open and mergeable; mergeable_state is blocked. Changes between its base and fetched main do not touch the introduced paths. (34e39db29179)

Likely related people:

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

PR surface

PR surface statistics unavailable: the file list is incomplete.

Stored data model

Persistent data-model change detected: unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Labels

Label changes:

  • add P3: This is internal maintenance with no intended user-visible change or demonstrated urgent defect.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P3: This is internal maintenance with no intended user-visible change or demonstrated urgent defect.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Compatibility review for exact head 34e39db29179ceb9b7f2ce09f727c2aeded0b83a is complete. The review identifies no concrete config or data-model change and records unknown-truncated-pull-files for its incomplete inventory. The complete inventory and contract review below resolve both checklist items.

I fetched every page of the PR files API and compared its 107 unique paths with git diff --name-only origin/main...HEAD; the sets match exactly. The only changed path under config/, src/config/, src/state/, or a schema/migration directory is config/assertion-safety-baseline.txt. That is a shrink-only static-analysis baseline: 16 existing type-assertion allowances removed, with no configuration key, default, permission, or runtime behavior change.

No schema, migration, persisted-data shape, protocol shape, or upgrade path changes are introduced. Existing transcript and delivery operations remain with their owners; the shared code retains field omission, ordering, recovery, and replay behavior. The final native SDK comparison also reports zero added/removed entrypoints and zero changed signatures or reachable declarations. All three compaction prompt byte comparisons are identical.

The PR body records the full 529-file / 8,682-test run, focused proof after the SDK restorations, and exact source identities. The complete 380-file coverage log is linked there. No compatibility waiver or migration is needed; these two compatibility checklist items are resolved by the complete file inventory and contract proof. The review reports no concrete correctness or security findings. Exact-head hosted CI remains the landing gate.

@steipete
steipete merged commit 7d59b5b into main Oct 8, 2026
234 of 238 checks passed
@steipete
steipete deleted the deslop/d03-p3-20261007 branch October 8, 2026 16:46
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…penclaw#167325)

* refactor(agents): consolidate embedded runner and delivery mechanics

* refactor(agents): keep defaults and compaction setup explicit

* refactor(agents): preserve reachable SDK contracts

* refactor(agents): preserve chunker SDK declaration
steipete added a commit that referenced this pull request Oct 16, 2026
## What Problem This Solves

Routine diagnostic instrumentation builds state and performs message/tool-schema work with no product consumer. The chat pane keeps a separate timing buffer that is only written; the Debug page reads the Gateway event log instead. Agent preparation also recounts compaction messages and serializes tool definitions solely for routine debug summaries.

## User Impact

No user-visible behavior, configuration, protocol, or SDK change. Routine successful operations no longer produce the retired trace summaries; operator failures, lifecycle events, and documented slow-stage diagnostics remain available.

## Why This Change Was Made

Remove the pane-local timing buffer, correlation map, timing-only paint callback, hydration timing events, and their mechanism-only tests. Keep the real after-paint hydration scheduler, send/progress/request clocks, queue state, recovery, and Gateway timing protocol unchanged.

Remove CLI argv/environment/session trace formatting, Decision tool-surface measurement and its first-primary-request observer, compaction debug recounts, the now-orphaned provider routing log formatter, and routine prompt/run/memory-preflight success traces. Authentication/environment policy, Decision pruning, compaction execution, failure logs, OTel IDs/events, and documented slow-stage warnings stay with their existing owners. No config, protocol, SDK, persistence, dependency, or release change.

Net production removal: **868 lines** (+4/-872 against the branch base, excluding tests, fixtures, test support, generated files, and declarations). Test reductions only remove assertions for retired instrumentation; retained behavior coverage stays.

## Best-effort tradeoffs accepted

- Pane timing history and cross-ACK diagnostic correlation disappear rather than retaining a bounded map for an unread buffer. The latest bound fix [#171146](#171146) describes diagnostic metadata, not an activation/foundation. Actual outbox/progress clocks and Gateway timing fields remain; slow startup remains diagnosed by the Gateway.
- CLI per-invocation argv, auth-key-name inventories, and hashed resume summaries are no longer logged. The extracted owner came through [#166711](#166711); its real auth/environment operations remain unchanged. Operators retain failures and existing content-free process outcome metadata.
- Decision debug schema-size counters and the first-request observation callback disappear. [#153340](#153340) used the counters for experiment verification; the feature is implemented and its permission/pruning/restoration tests remain. No model quality, token-cost, or performance claim depends on these normalized-character counters.
- Compaction no longer walks/re-estimates all messages before and after work just to print debug deltas/top contributors. The extracted diagnostics owner came through [#167325](#167325); real conversation detection, model-call IDs, hooks, failures, fallback warnings, and usage accounting stay. No recovery or durability guard is removed.
- Routine successful prompt/run lifecycle and memory preflight traces are quiet. Canonical lifecycle events, failure logs, slow-stage warnings, and actual policy decisions stay. No security, live-authority, concurrency, or data-integrity guard is removed.

## Evidence

Initial exact-head CI on b2922ae (run 38857825275) exposed two stale test expectations for the deliberately removed logs. The repair removes only the CLI info-log spy/assertion and the Decision diagnostic-record assertion/setup. All three CLI purposes retain output/trigger/spawn assertions; all four recorded-carrier cases retain request, budget, compaction, usage, and error assertions. No production code changes in this CI repair. Independent P0-P2 review of the complete two-file repair is scoped-clean, with final unchanged-source verification complete; formatting and diff checks pass.

| Initial failing job | Attribution |
| --- | --- |
| checks-node-changed-compact-large-1-1 (116833564544) | Ours: three CLI utility cases asserted the retired trace. Assertions for actual execution remain. |
| checks-node-changed-compact-large-1-2 (116833564644) | Ours: two recorded-carrier cases asserted the retired Decision log. All four behavioral combinations remain. |
| check-prod-types (116833927964) | Unrelated unused LitContent import in ui/src/pages/chat/chat-view.tsx:16. Identical TS6133 actually reproduced on unrelated PR #173879, head 5ad6fb8, run 38859044898, [job 116838613238](https://github.com/openclaw/openclaw/actions/runs/38859044898/job/116838613238). This PR does not change that file. |
| check-lint-core-2 (116833927918) | Same untouched import; identical eslint(no-unused-vars) actually reproduced in the independent run, [job 116838613165](https://github.com/openclaw/openclaw/actions/runs/38859044898/job/116838613165). |
| openclaw/ci-gate (116835410676) | Summary of the four jobs above, not a separate product failure. |

Focused local replays of the recorded-carrier cases and CLI utility suite were stopped after more than ten minutes without assertion results on the saturated host (exit 143). These are incomplete proof, not passing tests or evidence of a product defect. The fresh suppression run completed with 2 passed / 1 failed: the untouched scripts/lib/control-ui-warm-reload-probe.ts unbound-method allowlist mismatch. Vitest duration 350.15s, wrapper 476.06s; no test, timeout, retry, skip, or suppression change. The next exact-head hosted CI is the broad gate; no CI rerun or unchanged-head push was requested.

Independent isolated review completed with no accepted/actionable P0-P2 findings; final unchanged-source verification passed. Exact-head hosted CI is pending. No merge or green CI gate is claimed yet.

Completed local boundary proof: nine UI files, 231 tests; provider attribution policy, 19 tests; production core and UI typechecks, exit 0; runtime value cycles: 0; Madge cycles: 0; mock-export and assertion-safety shrink ratchets pass. Every runtime/test command uses a task-owned HOME/OpenClaw/XDG environment.

The changed checker completed: core-test graph types (29 graphs), formatting, core lint, UI style checks, cycles and architecture/security guards passed. Its earlier attributable core/UI type and ratchet failures were repaired and those exact gates replayed successfully. Dead-export findings remain in untouched subagent/session/Gateway/UI owners; they are not claimed inherited solely by path.

Agent-focused proof remains incomplete: the memory-fallback private-buffer case timed out at 120 seconds; the following usage-accounting case passed at 119 seconds. Host load was about 177 on 16 cores. The task-owned run was stopped rather than extending timeouts or changing tests; no passing or product-defect conclusion is drawn from it. Exact-head CI must cover those agent suites. If CI fails in a changed graph, attribution/replay/drop rules apply.

Initial UI fork startup timeout left five files unexecuted, not failed assertions; all five subsequently passed in the recorded focused runs with unchanged timeouts. An initial agent build was invalidated by the orphan-formatter cleanup during artifact preparation; final frozen-source proof replaces that attempt. The local suppression suite reports an untouched warm-reload-probe expected-entry mismatch; the diff adds no suppression. The broad local check also reports an untouched chat-message max-lines suppression against moving main. Neither is represented as a successful gate or an exact-head hosted CI attribution.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
## What Problem This Solves

Routine diagnostic instrumentation builds state and performs message/tool-schema work with no product consumer. The chat pane keeps a separate timing buffer that is only written; the Debug page reads the Gateway event log instead. Agent preparation also recounts compaction messages and serializes tool definitions solely for routine debug summaries.

## User Impact

No user-visible behavior, configuration, protocol, or SDK change. Routine successful operations no longer produce the retired trace summaries; operator failures, lifecycle events, and documented slow-stage diagnostics remain available.

## Why This Change Was Made

Remove the pane-local timing buffer, correlation map, timing-only paint callback, hydration timing events, and their mechanism-only tests. Keep the real after-paint hydration scheduler, send/progress/request clocks, queue state, recovery, and Gateway timing protocol unchanged.

Remove CLI argv/environment/session trace formatting, Decision tool-surface measurement and its first-primary-request observer, compaction debug recounts, the now-orphaned provider routing log formatter, and routine prompt/run/memory-preflight success traces. Authentication/environment policy, Decision pruning, compaction execution, failure logs, OTel IDs/events, and documented slow-stage warnings stay with their existing owners. No config, protocol, SDK, persistence, dependency, or release change.

Net production removal: **868 lines** (+4/-872 against the branch base, excluding tests, fixtures, test support, generated files, and declarations). Test reductions only remove assertions for retired instrumentation; retained behavior coverage stays.

## Best-effort tradeoffs accepted

- Pane timing history and cross-ACK diagnostic correlation disappear rather than retaining a bounded map for an unread buffer. The latest bound fix [openclaw#171146](openclaw#171146) describes diagnostic metadata, not an activation/foundation. Actual outbox/progress clocks and Gateway timing fields remain; slow startup remains diagnosed by the Gateway.
- CLI per-invocation argv, auth-key-name inventories, and hashed resume summaries are no longer logged. The extracted owner came through [openclaw#166711](openclaw#166711); its real auth/environment operations remain unchanged. Operators retain failures and existing content-free process outcome metadata.
- Decision debug schema-size counters and the first-request observation callback disappear. [openclaw#153340](openclaw#153340) used the counters for experiment verification; the feature is implemented and its permission/pruning/restoration tests remain. No model quality, token-cost, or performance claim depends on these normalized-character counters.
- Compaction no longer walks/re-estimates all messages before and after work just to print debug deltas/top contributors. The extracted diagnostics owner came through [openclaw#167325](openclaw#167325); real conversation detection, model-call IDs, hooks, failures, fallback warnings, and usage accounting stay. No recovery or durability guard is removed.
- Routine successful prompt/run lifecycle and memory preflight traces are quiet. Canonical lifecycle events, failure logs, slow-stage warnings, and actual policy decisions stay. No security, live-authority, concurrency, or data-integrity guard is removed.

## Evidence

Initial exact-head CI on b2922ae (run 38857825275) exposed two stale test expectations for the deliberately removed logs. The repair removes only the CLI info-log spy/assertion and the Decision diagnostic-record assertion/setup. All three CLI purposes retain output/trigger/spawn assertions; all four recorded-carrier cases retain request, budget, compaction, usage, and error assertions. No production code changes in this CI repair. Independent P0-P2 review of the complete two-file repair is scoped-clean, with final unchanged-source verification complete; formatting and diff checks pass.

| Initial failing job | Attribution |
| --- | --- |
| checks-node-changed-compact-large-1-1 (116833564544) | Ours: three CLI utility cases asserted the retired trace. Assertions for actual execution remain. |
| checks-node-changed-compact-large-1-2 (116833564644) | Ours: two recorded-carrier cases asserted the retired Decision log. All four behavioral combinations remain. |
| check-prod-types (116833927964) | Unrelated unused LitContent import in ui/src/pages/chat/chat-view.tsx:16. Identical TS6133 actually reproduced on unrelated PR openclaw#173879, head 5ad6fb8, run 38859044898, [job 116838613238](https://github.com/openclaw/openclaw/actions/runs/38859044898/job/116838613238). This PR does not change that file. |
| check-lint-core-2 (116833927918) | Same untouched import; identical eslint(no-unused-vars) actually reproduced in the independent run, [job 116838613165](https://github.com/openclaw/openclaw/actions/runs/38859044898/job/116838613165). |
| openclaw/ci-gate (116835410676) | Summary of the four jobs above, not a separate product failure. |

Focused local replays of the recorded-carrier cases and CLI utility suite were stopped after more than ten minutes without assertion results on the saturated host (exit 143). These are incomplete proof, not passing tests or evidence of a product defect. The fresh suppression run completed with 2 passed / 1 failed: the untouched scripts/lib/control-ui-warm-reload-probe.ts unbound-method allowlist mismatch. Vitest duration 350.15s, wrapper 476.06s; no test, timeout, retry, skip, or suppression change. The next exact-head hosted CI is the broad gate; no CI rerun or unchanged-head push was requested.

Independent isolated review completed with no accepted/actionable P0-P2 findings; final unchanged-source verification passed. Exact-head hosted CI is pending. No merge or green CI gate is claimed yet.

Completed local boundary proof: nine UI files, 231 tests; provider attribution policy, 19 tests; production core and UI typechecks, exit 0; runtime value cycles: 0; Madge cycles: 0; mock-export and assertion-safety shrink ratchets pass. Every runtime/test command uses a task-owned HOME/OpenClaw/XDG environment.

The changed checker completed: core-test graph types (29 graphs), formatting, core lint, UI style checks, cycles and architecture/security guards passed. Its earlier attributable core/UI type and ratchet failures were repaired and those exact gates replayed successfully. Dead-export findings remain in untouched subagent/session/Gateway/UI owners; they are not claimed inherited solely by path.

Agent-focused proof remains incomplete: the memory-fallback private-buffer case timed out at 120 seconds; the following usage-accounting case passed at 119 seconds. Host load was about 177 on 16 cores. The task-owned run was stopped rather than extending timeouts or changing tests; no passing or product-defect conclusion is drawn from it. Exact-head CI must cover those agent suites. If CI fails in a changed graph, attribution/replay/drop rules apply.

Initial UI fork startup timeout left five files unexecuted, not failed assertions; all five subsequently passed in the recorded focused runs with unchanged timeouts. An initial agent build was invalidated by the orphan-formatter cleanup during artifact preparation; final frozen-source proof replaces that attempt. The local suppression suite reports an untouched warm-reload-probe expected-entry mismatch; the diff adds no suppression. The broad local check also reports an untouched chat-message max-lines suppression against moving main. Neither is represented as a successful gate or an exact-head hosted CI attribution.
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: 👀 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