Skip to content

refactor(agents): consolidate embedded runtime variants - #167186

Merged
steipete merged 7 commits into
mainfrom
deslop/d03-p2-20261007
Oct 8, 2026
Merged

steipete merged 7 commits into
mainfrom
deslop/d03-p2-20261007

Conversation

@steipete

@steipete steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

The embedded agent runtime still repeated preparation, recovery, streaming, and compaction work after the first consolidation pass.

User Impact

No user-visible change. Features, text, authority checks, cancellation, replay, configuration, SDK contracts, and persisted shapes are preserved.

Why This Change Was Made

Shared implementations now handle repeated provider matching, compaction preparation, subscriber delivery, and transcript metadata while keeping variant-specific inputs and ordering explicit. Internal preparation interfaces are narrower, and all callers and mocks have migrated from the removed tool-handler forwarding barrel.

This second d03 pass removes 766 net production lines (1,240 added / 2,006 removed across 105 production paths). The 128-minute implementation pass records 357 per-file decisions, including measured rejected prototypes, in the accompanying coverage comments. It uses the campaign’s 500–999-line exception. Tests changed only for removed internal seams; assertions and scenarios remain intact.

Together with the first merged pass, the lane removes 2,173 runner lines (3.25%) and 2,477 production lines including adjacent owners. Independently landed upstream reductions are excluded. A further 39-line run-entry cutover remains a proposal because it requires a prohibited cron caller.

Evidence

  • Full build and focused/full subsystem proof: 441 unique files / 5,816 tests, including every runner-directory file (345 files / 4,387 cases) at 4e1055ae779. Three normally excluded live-provider files are not counted as proof.
  • The five lint corrections passed changed checks, production types, all 27 core test-type graphs, dead-export scans, all selected guards, zero runtime/Madge cycles, and 8 files / 258 focused tests at verified tree 262890b6665f47ed73535312a1646f377fae1317 (7954898a206).
  • Conflict-only integration at final head d12224379b2729e2bff6500f63b2b962f457db46 preserves main’s image-decoding and interactive-payload fixes. 8 files / 172 tests, production and affected agent test types, formatting, lint, and both zero-cycle checks passed. Whole-branch independent review completed scoped-clean at P3.
  • Native SDK comparison found no public compatibility change: 131 conservative reachability notices, all five distinct internal declaration deltas assessed, and zero direct declaration, export-kind, or entrypoint changes. The initial parallel attempt exceeded the 32-GiB host’s memory and was OOM-killed; the same tool’s existing serial path completed with four available CPUs.
  • Single-worker cost command: node scripts/run-vitest.mjs <18 changed/seam-consumer files> --maxWorkers=1. 18 files / 432 tests passed; summed Vitest duration 133.11s, wrapper wall 626.71s including runtime artifact preparation. This used CI mode on an 8-vCPU Linux host.

The mandatory lint-suppression test was run and is inherited red: 2 passed / 1 failed. It reports two unlisted typescript/prefer-promise-reject-errors suppressions in untouched src/config/sessions/session-transcript-lock-settlement.ts (79 actual entries versus 78 expected). A fresh frozen install of current main 9c763cb168e9461f76e9c3a9059c7b38838a7d3b reproduces the identical failure. Both that file and test/scripts/lint-suppressions.test.ts are byte-identical across base, head, and current main. This lane adds no suppressions and does not change the allowlist or its assertions.

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

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL labels Oct 8, 2026
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Per-file implementation coverage (1/2)

Base d3309e5760116877852a800c2ed21f9d15864c8e; candidate d12224379b2729e2bff6500f63b2b962f457db46. 766 net production lines removed (1,240 added / 2,006 deleted), 105 production paths and 357 preserved decisions. Tests, fixtures/support, generated declarations and tooling baselines excluded. Implementation: 128 minutes.

P1 merged reductions plus this candidate contribute 2,173 runner-only lines (3.2521% of the original 66,818-line baseline) and 2,477 production lines including adjacent code. PR2 contributes 453 runner lines and 766 total; independently landed upstream changes are excluded.

Conflict resolution preserved main’s verifyDecodability: true and conditional tool-ID sanitizer in the image helper, plus the lane’s sanitizeImages closure. Automatic upstream integration also preserved parseJsonMessageParam(payload, "interactive") in tool results. No new implementation scope was added.

Retained full-test receipt: 441 files / 5,816 cases at 4e1055ae779e5f851d051e6ee3d7cddc6e8433c5, including all 345 runner files / 4,387 cases. Correction proof passed at 7954898a20622fbb67f094c82ab59c275c9900ad: changed checks including core plus 27 test type graphs, dead code and guards; zero runtime/Madge cycles; mandatory lint 3/3; focused tests 8 files / 258 cases. Its single-worker cost run passed 18 files / 432 cases, with 133.11s summed Vitest duration and 626.71s wall time including runtime artifact preparation. Repeated summaries were excluded; separate receipts are not summed into full-suite coverage.

At final head d12224379b2729e2bff6500f63b2b962f457db46, rebase format/lint passed for three files (zero warnings/errors), focused tests passed 8 files / 172 cases, core plus three affected agent test type graphs passed, and runtime/Madge cycles were both 0. Whole-branch review was scoped-clean P3. Native SDK comparison completed with 131 reachable records, no added/removed entrypoints and no public SDK shape changes after assessment of five internal declaration deltas. The initial parallel render hit a kernel-confirmed OOM; four-CPU affinity selected the existing serial render path, which completed successfully.

The final mandatory lint-suppression test FAILED: 2 passed / 1 failed. The exact same missing allowlist record for two typescript/prefer-promise-reject-errors suppressions in untouched src/config/sessions/session-transcript-lock-settlement.ts reproduced on current main 9c763cb168e9461f76e9c3a9059c7b38838a7d3b (79 actual records versus 78 expected). That owner and test/scripts/lint-suppressions.test.ts are byte-identical across base, head and current main, and neither is changed by this lane. No new lint suppressions were added. The earlier correction-head lint pass does not supersede this final failure.

Unprefixed paths are relative to src/agents/embedded-agent-runner/. Positive net values are removals; negative values are shared-owner costs. Historical prototype measurements remain distinct from current diff counts.

File Net removed Implementation or retained responsibility
runs.ts 31 Shared registry removal and exact idle diagnostics for ordinary/forced cleanup, preserving optional sessionFile presence. Shared claim revocation only around the existing binding/assertion guards; kept prior-handle cleanup outside both catches.
tool-result-truncation.ts 4 Shared one bounded suffix-finishing closure between head-only and head/tail truncation, retaining late option reads and every suffix invocation. Projection/recovery retain distinct frozen-byte, spill-source and canonical-write contracts.
packages/agent-core/src/harness/compaction/compaction.ts 17 Applied: one prepared summary invocation for history and turn-prefix variants; flattened exact context-barrier, turn-start and sparse-entry guards. Ask-truncation shared-core prototype was actually built and formatted: 22→27 lines (+5), so retained shorter original math/adapters.
run-orchestrator.ts 6 Retained single-use admission-wrapper consolidation (-6 lines). Rejected map Object.assign-to-spread prototype under no-map-spread: mapped block 10 to 9 lines, restored to 10. Whole file 736 to 729 with both edits, then 730 after restoring Object.assign; cleanup precedence and optional runtime-field omission stay unchanged.
src/agents/embedded-agent-subscribe.stream-rendering.ts 8 Applied shared final-tag transitions: self-closing tags choose the same opening/closing transitions as explicit tags; nested ignored tags still leave the source cursor untouched.
replay-history.ts 14 Implemented one current replay-history binding through ordered transforms, plus inlined the single-use legacy string-content normalizer. Provider IDs, before/after pairing, snapshot persistence, cleanup, strict invariant checks and text handling retain their order.
run/terminal-resolution.ts 0 Retained after two fresh formatted prototypes: shared incomplete completion 715→713 (-2) adds mutable error/count state and a deeper diagnostic branch solely to remove one projection; prepared-runtime/captured-snapshot parameter grouping 715→724 (+9) and caller 617→608 (-9), aggregate 0 before an explicit terminal-auth projection adds four more lines. Keep explicit retry gates, terminal count variants, and current think-level timing.
compaction-session-execution.ts 0 Sanitization/validation already share live replay context; pre/post hooks share live context. Endpoint and client compaction retain explicit request authority, watchdog ownership and result variants.
extra-params.ts 8 one normalized model-ID membership core replaces separate DeepSeek and MiMo predicates; family membership stays explicit and wrapper order unchanged.
run-entry.ts 2 Implemented a single awaited direct/measured preparation dispatch. Full optional-callback cutover was prototyped: owner 710 -> 688 (-22), command caller 666 -> 661 (-5), fallback caller 363 -> 357 (-6), memory caller 1416 -> 1414 (-2), cron caller 826 -> 824 (-2), repair caller 479 -> 477 (-2): combined -39. Rejected for scope: complete cutover requires prohibited src/cron/isolated-agent/run-executor.ts lines 278/306.
compact.queued.ts 4 Applied shared failure-result construction for locked runtime, active run, auth preparation, and failed deferral; every reason/failure value and property order stays identical. Native-before-auth admission and all post-await live assertions remain explicit.
run/run-attempt-dispatch.ts 0 Measured ordered-key projection table 689→698 (+9) after formatting; it adds a generic cast and indirection while retaining the same literal key inventory. Explicit projection remains clearer.
run/attempt-session-prepare.ts 0 Shared persisted/suppressed media callback prototype measured 682 to 683 (+1), with an extra callback and unchanged registry-only-on-persist distinction. Rejected.
run/attempt-llm-boundary.ts 0 Re-read complete projection, identity, timestamp, transform and restoration paths. Existing text transformer cannot replace runtime-context escaping without changing the fresh-array identity of non-text-only content and malformed content behavior; preserving that requires a second independent cloning policy.
compact.queued-execution.ts 0 Retained measured prototype: extracted exact latest-row writer check across native/context-engine admission; 665 to 666 (+1). Typed helper and callback wrapping cost more than removed bodies, while adding an authority indirection.
src/agents/embedded-agent-subscribe.handlers.tools.completion.ts 8 Applied direct contextual-typed activity construction at the canonical emitter; remove single-use event locals and mirrored type imports. Event keys, order, optional spreads and emission sequence remain unchanged.
run/attempt-stream-settle.ts 6 Made the caller-owned settlement state the sole prompt-error/source owner; removed duplicate local mirrors and the unused sessionIdUsed input. Preserves error publication before rejection, compaction precedence, and cancellation read-only snapshot.
run/settled-turn-finalization.ts 3 Implemented passing the already-owned initial terminal record to the terminal preparation owner, matching its existing completion-record call. Consumer reads known fields and never spreads the input.
run/auth-controller.ts 5 Shared the three profile-unavailability projections through one unknown-default owner. Initial selection versus later rotation still differ in cooldown probing, first-error provenance, and think-level reset; those effects stay in their existing order.
src/agents/session-tool-result-guard.ts 9 adjacent owner read end to end with wrapper, payload, transcript-sequence and raw-append dependencies plus all three guard suites. Applied: inline one-use transcript-only role normalization under existing narrowed caller; share minimal receipt return while keeping committed-callback timing; reuse absent-hook result path.
model.configured-overrides.ts 0 Transport source selection already shared. No second core remains between no-provider, untouched provider and configured-model paths: exact metadata provenance, optional auth-header presence and lazy catalog lookup differ.
model.static-catalog.ts 4 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.
run/images.ts 3 Applied: owned inline-image entries always normalize factIndex to number|null. Remove the impossible undefined-equality special case and use the same exact-match lookup.
run/attempt-stream-prepare.ts 6 Threaded the prepared session record into its subscriber, retaining runtime channel, global hooks, active session, authority, and callbacks as explicit overrides. Seven tool-set/map projections now use their existing prepared owner.
src/agents/embedded-agent-subscribe.handlers.messages.update.ts 15 Applied one lazy raw-stream payload factory shared by commentary/thinking/text variants. Exact field insertion order, timestamp timing, Incognito gate and branch-specific text remain unchanged.
run/attempt-prompt-build.ts 0 Retained distinct user, transcript, hook-system, steering-receipt and origin projections. Shared prepend/append strategy prototype grew 634 to 638 lines (+4) while preserving text/log order.
run-loop.ts 2 remove mutable thinking mirror. The attempt snapshot continues to own initial thinking; assistant-failure result owns later thinking passed to terminal handling.
run/attempt.tool-call-argument-repair.ts 16 Inlined the single-use edits-array reader at its value discriminator; consolidated mutually exclusive delimiter cases and closing return. Complete parser differential 229,400 cases matches arguments, offsets and JSON order.
prepared-compaction-runtime.ts 0 Schema projection already shares the core/bundle differences explicitly. Measured host-facts prototype: ordinary owner 80 -> 77, compaction owner 578 -> 572, new helper 13, combined 658 -> 662 (+4). Rejected growth and extra fact-owner API. Memory/watched ownership is separate and was measured +19 in PR1; no semantic gates removed.
src/agents/embedded-agent-subscribe.handlers.tools.results.ts 10 Applied one delivery/load/failure boundary for pending/unavailable approval variants, retaining only pending suppression and strict-vs-optional callback behavior. Reuse canonical object normalization and combine equivalent package-runner option branches. Automatic upstream integration retains parseJsonMessageParam(payload, "interactive").
src/agents/embedded-agent-subscribe.handlers.tools.start.ts 15 Applied inline sole-use execution-phase forwarding, common exec eligibility guard and ordered flag list. Logging label, callback payload, sync/Promise behavior and source ordering remain identical.
run/attempt-finalize.ts 0 Recorder event data already shares terminal/model/evidence projections. External preparation abort and accepted live-run abort have different failure recording, callback ordering and reason normalization. A common reason expression remains larger (prior implemented prototype 7 to 9 lines).
run/attempt-recovery.ts 0 Retry projection, shared compaction input and blocked-result cores already consolidated. Remaining branches own distinct replay-safe/settled-tool/native retry gates; no dead mutable state.
src/agents/embedded-agent-subscribe.reply-delivery.ts 7 Applied one text-admission guard with original short-circuit order; shared final baseline publication across flushed-partial and ordinary finalization paths. Asynchronous coalescing and delivery ownership untouched.
run/attempt.ts 0 Resource cleanup already shares MCP/LSP disposal. Kept lifecycle ownership transfer, late-bound yield callbacks and independent retained-tool cleanup.
run/attempt-prompt-phase.ts 0 Revisited the two prepareToolPrompt invocations: the initial path returns rendered text; guarded primary dispatch reasserts current authority and installs projection commit. Sharing a callback would add declaration/return plumbing to two three-line invocation blocks and cannot absorb the distinct cancellation/publication boundaries.
src/agents/embedded-agent-subscribe.ts 11 Applied one live committed-message evidence closure consumed by tool suppression, compaction recovery and public observation. Inline sole-use output formatter in its actual emission owner, preserving whitespace/Markdown/empty text bytes.
run/compaction-runtime.ts 4 Merged before/after owning-engine hook gating, error handling and post-hook assertion. The phase-specific payload, successful-after requirement, successor resolution, and exact text remain explicit; 1,536 source differential scenarios agree.
compact.ts 20 Shared exact failure result constructor with queued compaction; inlined one-use locked-harness and fallback-result wrappers. Retained auth-profile ternary at its original evaluation point after plugin buildPrompt instead of moving a read across plugin code.
run/session-bootstrap.ts 8 Implemented direct forwarding of the typed prepared identity record into its local backfill owner, removing a four-field mirror.
run/runtime-preparation.ts 0 Re-read preparation and refresh end to end. Runtime model, effective model and context metadata share the existing prepared owner.
run/attempt-prompt-helpers.ts 19 derive truncated-key count from one traversal counter; inline the single-use target projection into the runtime context owner. Preserve exact target fallback/key order, empty-vs-undefined and thread zero.
run/assistant-failure.ts 11 Applied: controller owns reason-based ordinary/rate-limit profile advance; shared local trace constructor keeps timeout classification, omitted status, stage and reason key order. Preserve trace/log/bookkeeping order and post-rotation thinking read.
google-prompt-cache.ts 22 Inlined the private request-header and managed-config wrappers into their single request/preparation callers; deleted their unused type aliases. Parsing/sentinel protection, request key/order, sort/digest work, and pre-try error boundary remain unchanged.
thinking.ts 28 Applied: one per-request recovery record replaces repeated five-argument threading across stream/result recovery. Derive unsigned-thinking failure immediately rather than carrying a redundant flag.
run/attempt-tool-prepare.ts 0 Permission refresh observes new fields while retiring old tool generations. Tool-construction projection intentionally omits caller-only authority; broad attempt spread is not equivalent.
message-injection-target.ts 5 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.
delivery-evidence.ts 0 Other delivery kinds retain distinct count/visibility/route evidence.
run/types.ts 0 These are SDK-reachable and intentionally narrower/required in attempt-vs-caller contexts; no type widening, config or protocol changes.
run-state.ts 0 Re-read registrations, personal-tool authority, human-input waits, recovery probes, both registry indices and lifecycle eviction. Rechecks before/after callbacks are live-authority fences, not duplicate state; session/run eviction already shares one traversal with explicit variant work.
run/attempt-setup.ts 0 Re-read preparation and full context-guard stack. Cache, context-engine, image and computer transforms run in a fixed sequence and restore exact previous functions. Prior generic installer grew 13 lines; no narrower shared owner arises here.
src/agents/embedded-agent-helpers/bootstrap.ts 9 Shared one result-metadata constructor across unchanged, AGENTS-policy and ordinary head/tail results; AGENTS text trimmer now returns only its owned text. All original warnings, content bytes, field order and limits preserved.
run/attempt-system-prompt-prepare.ts 2 Applied: share the exact signal-then-authority preparation checkpoint across initial sandbox preparation, watched-session callback, initial report and refresh publication. Input snapshot cache remains unchanged.
tool-result-context-guard.ts 0 Revisited shared installer: upstream transform invocation in the context-engine path has abort checks before and after, while tool truncation does not. Cursor reset, rollback, deferred history, per-message identity cache and mid-turn fences remain distinct state. PR1 measured faithful generic installer +9.
src/agents/embedded-agent-messaging-extraction.ts 17 Implemented one final send-evidence projection for generic and native message tools, retaining explicit route, thread, suppression, account and implicit-thread facts; derived private options type from the existing public declaration, leaving public source signature unchanged.
run/lane-controller.ts 0 Implemented shared queue settlement prototype preserving synchronous throws, async finally/catch and generic result types: 464 to 466 (+2). Rejected additional thunk layer.
src/agents/embedded-agent-utils.ts 18 Implemented one thinking/text block appender with explicit whitespace policy, consolidated ordered no-tag/bypass gates, and derived private prepare-callback type from its public owner. The phase selector was retained: shared chat-message-content owner prohibits unphased fallback when explicit phases exist, whereas this owner intentionally permits selected fallback and retains content indices plus callback timing.
run/llm-idle-timeout.ts 9 Removed a dot/colon guard already guaranteed by the bare-hostname regex; simplified exact-or-normalized provider lookup; delegated repeated-abort idempotence to the locally created native AbortController. Timing and every watchdog budget remain unchanged.
run/payloads.ts 10 Threaded the existing payload inputs into source-mirror construction and the final segment owner; aliases and final text slice remain explicit. Consumers project only their named fields and no user-visible payload shape changes.
run/attempt-queue-message.ts 0 Rejected observer-catch consolidation: file 452 to 444 lines (-8), restored to 452. The consolidated catch fails preserve-caught-error; changing the AggregateError cause to satisfy it would violate the required outer-error cause and ordered [outer, observer] error list. Retained main’s deferred throw outside the observer catch; final diff is zero.
run/incomplete-turn-recovery.ts 20 Applied: inline two single-use tool-call classification wrappers into their named owner predicates. Conditions, short-circuit order and continuation strings remain unchanged; settled-batch evidence stays separate.
run/model-setup.ts 0 Native authority reader, host-auth tuple pinning, mutable native model getter and one-race retry remain necessary. Shared selected-model membership accessor needs three lines to replace two duplicated pairs, gaining no LOC.
run/overflow-context-recovery.ts 0 In-attempt compaction retry and new compaction share budget checks but require different transcript custody, logs and counters before async maintenance. Terminal provider-size ceiling, parked work, truncation and zero-history recovery retain independent decisions; moving all branches into a strategy table adds callbacks and obscures visible order.
run/attempt-prompt-submit.ts 0 All repeated authority assertions are already one closure. The long local stream-transform installer owns ordered save/install/restore and late operator updates; inlining only moves the same statements across preparation ordering.
run/attempt-stream.ts 0 Retained the existing shared wrapper installer and ordered transport pipeline. Thinking/compaction repair, tool-call normalization, output transforms, timeout guards and diagnostic hooks require their current order.
run/attempt-tool-call-replay-sanitization.ts 5 Applied: remove two redundant changed writes and zero-length-result branch from embedded Anthropic result filter; the owning post-filter length check already records every removal. Signed thinking and ordinary replay still retain distinct validation and preservation behavior.
src/agents/session-tool-result-guard.payload.ts 0 Recursive redaction, bounded-size summaries and fallback shape have distinct public data/security contracts. Existing copy-fields owner is shared; no schema/retention/redaction change permitted.
run/attempt-settle.ts 7 Unified bounded pending-event joins through an explicit afterRunBudgetTimeout strategy; retained no-argument ordinary wait, queue-only salvage wait, exact abort-signal property presence, live terminal re-read and final flush gate. Removed unused stream-settle state input.
session-prompt-state.ts 1 Applied: 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-subscribe.handlers.messages.stream.ts 10 Shared assistant API discrimination across Responses/Anthropic/completions predicates; replaced reverse matching-index loop with native findLastIndex. 132 classifier and 40,000 malformed/mixed block differential cases identical.
model.registry-resolution.ts 0 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-subscribe.handlers.lifecycle.ts 2 Shared synchronous/Promise terminal-hook containment with explicit error observers; failure observer return values are discarded. Preserves synchronous completion, async catch/then sequence, callback error copy and terminal-once state.
run/failover-retry-controller.ts -3 Applied: private rate-limit owner plus single advanceAuthProfile(reason, context) public internal operation replaces callers' repeated selection. Ordinary path returns the original runtime Promise directly; rate-limit counter, cap, logs, error fields and await ordering stay unchanged. This owner grows five lines while its two callers shrink.
run/attempt.model-diagnostic-observation.ts 0 Chunk/result projection already shares response observation. Getter containment, large-string JSON accounting, terminal activity, result fallback capture and FIFO semantic progress are distinct contracts.
model.ts 0 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.
run/attempt-result.ts 0 Carryover writes must preserve fresh-attempt precedence and per-field assignment ordering. Key-loop prototype would require union assignment casts or per-key object allocations.
src/infra/agent-activity-events.ts 0 Made the unused AgentPatchSummaryEventData export module-private; the emitter still consumes the same type and payload fields. This removes an unused internal export with no emitted runtime change and zero net LOC.
src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts 17 Shared lazily evaluated raw message-end diagnostic envelope and repeated reply emission eligibility; normal path retains its cached text accessor and commentary retains direct text extraction. Eligibility rereads silentExpected at each original checkpoint.
run/attempt-prompt-support.ts 0 Retained ordered baseline capture and Decision-surface measurement: refresh callbacks can observe the newly installed baseline. Sharing observation payloads moves property reads across recorder calls. The single-use equality-helper prototype was equal size.
prompt-cache-observability.ts 0 Fingerprint buckets, snapshot variation table and bounded tracker owner already shared. A one-use tracker setter removal requires staging the constructed object before map eviction to preserve ordering, producing no simpler core.
run/attempt.model-diagnostic-lifecycle.ts 0 Request-start and terminal output already share one emitter; lifecycle and diagnostic completion have distinct ownership. Terminal notification is intentionally separate from iterator diagnostic exhaustion, while plugin and timeline payloads deliberately project different fields.
run/prompt-failure.ts 5 Applied: profile-advance reason and failure context passed directly to the controller. Preserve recorded-stop precedence, prompt classification, retry bookkeeping and detached failure marking.
context-engine-maintenance.ts 2 Inlined the one-use deferred worker into its admitted maintenance scope, preserving the captured worker parameter snapshot, background mode, matching-abort classification, callback/log order and scheduler error boundary.
compaction-successor.ts 0 Retained measured prototype: unified structured and legacy resolution through one request record and final result projection; 383 to 385 (+2). Additional variant state and conditional clone obscures structured thread preservation and legacy object identity.
run/incomplete-turn-resolution.ts 0 Retained after prototype: merged the two blocked returns, formatted 377 -> 377 (0); no reduction, so restored. Incomplete payload, silent tool tail, source delivery and replay gates retain distinct side-effect and authored-silence behavior.
run/preemptive-compaction.ts 2 derive the route once from the original ordered numeric predicates instead of mutating initialized state. NaN still follows the original overflowTokens > 0 guard.
direct-compaction-preparation.ts 0 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-helpers/turns.ts 6 Signed and ordinary tool-use cleanup retain their different validity predicates but now share one final replacement/append path driven by content identity. A flatMap draft saved 11 LOC, but final loop saves 6 LOC while avoiding a fresh wrapper array for every message.
src/agents/session-tool-result-guard-wrapper.ts 0 Shared queued-recorder branch prototype grew +3 after formatting; reverted to original explicit branches. Callback-specific transformation/persistence projections are intentionally separate.
compaction-runtime-context.ts 0 Profile-specific field omission already parameterizes full/after-turn/recovery. Table-generated projection requires an assertion or extra field-key/type layer without reducing the explicit single output shape.
run/attempt-history.ts 6 Collapsed redundant text-array and sparse-message guard branches without changing identity reservation, timestamp fallback or active tool-continuation rules.
run/attempt-session-runtime-prepare.ts 0 Prepared session record already shared across manager/session/guards/trajectory. System-prompt restart commit state records awaited durable retirement and cannot derive solely from prepared.restart; public resource callbacks publish ownership before awaits.
run/params.ts 0 All public optional fields and shared composed contexts have consumers. Existing type composition removes duplicate channel/message fields; further removal would alter public SDK/config/runtime signatures.
src/agents/embedded-agent-subscribe.handlers.types.ts 0 One typed state/context owner; tool-media trust, source-reply delivery and parser positions are distinct facts. No competing duplicate state identified; public callback field shapes retained.
compaction-hooks.ts 0 Internal hook message forwarding settles before plugin hooks; native memory provider refresh and search-index sync have distinct close/admission semantics.
packages/agent-core/src/harness/compaction/utils.ts 5 Applied: inlined the one-use conversation-speaker adapter at its user/tool-result-only call site, removing the unused assistant fallback while preserving every output byte and provenance call.
src/agents/compaction-planning.ts 3 Removed a one-use sanitization variable and repaired-drop alias; removed the lower clamp proven redundant after the finite parts > 1 gate. Atomic tool occurrence grouping, aligned sanitized estimates, ordered repair/pruning, and oversized-batch two-pass behavior remain unchanged.
src/agents/compaction.ts 5 Shared full/partial summary failure recording, preserving abort-first handling, exact log text, arbitrary partial-summary value behavior, and suffix preference. Empty history now selects the existing single-stage path without invoking the worker.
types.ts 0 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-helpers/openai.ts 7 The existing identity-preserving replay traversal now also owns stale-reasoning filtering through an explicit private drop sentinel. Preserves malformed input entries, unchanged array/message identity and checkpoint rewrite calls.
src/agents/embedded-agent-helpers/error-text.ts 5 Inlined the one-use missing-tool-input predicate; both regular expressions, truthiness guard and exact visible copy stay in the same priority position.
run/tool-media-payloads.ts 0 Selection is already shared across current/carried batches. Host-owned, TTS-owned and assistant media differ in provenance and flags, and the existing mergeSelectedToolMedia is the shared core.
run/terminal-preparation.ts 0 Re-read usage, receipt, payload, timeout and partial replacement paths. Final text uses kept answer while attribution uses current completed/latest assistant; merging their projections would conflate real evidence boundaries.
openrouter-model-capabilities.ts 2 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.
run/history-image-prune.ts 3 Inlined single-use structural-pruned marker read. Existing turn-cutoff state and lazy array copying retain sparse slots, frozen input, caption ownership and metadata-only fresh-array guarantees.
run/session-prompt-state.ts 0 Existing capture/notify/internal-prompt helpers already own shared transitions. Current target, committed successor, persisted input, internal continuation and next-attempt suppression are independent facts; combining them would lose commit-edge versus notification timing.
run/attempt-normalization.ts 0 Re-read accounting, cancellation after persistence, terminal projection, idle breaker and context recovery. Last-call usage candidates carry precedence; compaction observed count and returned count guard different accounting.
run/attempt-tool-call-stream-normalization.ts 5 Implemented one unavailable-tool rewrite decision after optional deduplicated count update.
src/agents/embedded-agent-helpers/sanitize-user-facing-text.ts 2 One ordered marker table now serves both cheap activation and verified line ownership scans; filtering/provenance decisions and streaming state remain unchanged.
result-fallback-classifier.ts 24 Inlined single-use generic-external failure branch at its existing precedence point and passed route context separately to shared harness result classifier. Exact messages, format codes, trusted provider metadata and exhaustion priorities retained.
src/agents/compaction-planning-projection.ts 11 Derived content-block changed state from returned identity and named the remaining JSON budget before recursion. Initial shared-entry helper prototype was 293 -> 280; final 282-line form retains direct array/object loops because the common closure saved only two more lines while obscuring key-cost ordering and allocating at each nested container.
stream-resolution.ts 5 Applied: inline sole-use lifecycle runtime resolver at stream selection. Prior result-constructor prototype was zero net; five strategy branches preserve distinct credential, cache, signal and identity contracts.
src/agents/embedded-agent-subscribe.handlers.messages.snapshot.ts 0 Actual flattened shared gate prototype expanded 286 to290 (+4) under formatter; reverted. Prefix/suffix alignment, code-region crossing and signature fallback own different offset facts; common-position helpers already serve both frames.
compaction-runtime-preparation.ts 0 Auth-store selection and harness-selection parameter core already shared. Ordered second auth attempt exists only after a selected-harness change; converting to a generic convergence loop adds state and a loop counter for the same two bounded passes.
packages/agent-core/src/harness/compaction/branch-summarization.ts 10 Applied: shared summary request envelope, one expression for default/additive/replacement instructions, and direct final string assembly without mutable summary state. Branch-only token budgeting/error classes remain explicit.
run/tool-error-warning.ts 0 All warning variants retain exact punctuation/details defaults. Parser preserves literal command/context boundaries; no generic formatting rewrite selected without differential proof.
run/attempt-bundle-tools.ts 3 Removed redundant pre-filter client-tool variable. Re-evaluated shared MCP/LSP eligibility record: 277 to 278 (+1), rejected.
run/attempt-tool-catalog.ts 7 Implemented one agent policy label prefix, preserving every user-visible label. Prototyped tuple strategy table: 276 -> 275 (-1), then replaced it with clearer shared prefix: 276 -> 269 (-7).
run/attempt-tool-construction-plan.ts 5 Shared the repeated MCP/LSP/common-bundle input contract. A separate inlining prototype for the sole MCP-name predicate measured 272 -> 272 after formatting and was rejected; the named namespace discriminator remains clearer.
run-entry-terminal.ts 0 Terminal metadata loops already share key assignment, with explicit own-key versus defined-value versus literal-true policies. Receipt and trace projections have different return shapes; one shared table would obscure policy and not reduce declarations.
run/pre-persisted-user-turn.ts 0 Source identity, writer witness, preparation and one-time consumption are separate facts. All asserts fence distinct callback or await boundaries.
run/attempt-prompt-preflight.ts 0 Budget snapshot helper projects only the three owner-approved fields; inline broad spread leaks routing/details. A shared rejection constructor needs callback/type plumbing for two result shapes, without reducing formatted production size.
run/auth-profile-success.ts 0 Re-read OAuth/profile/harness/AWS binding paths and SQLite bookkeeping. Different credential ownership branches are deliberate; PR1 already unified resolved-profile fingerprinting.
sandbox-skills.ts 0 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.
run/runtime-context-prompt.ts 3 One custom-message envelope constructor now serves legacy context and system updates, with content/type/details as explicit variations. Property insertion order, fragments identity and timestamp timing retained.
src/agents/embedded-agent-subscribe.handlers.messages.replies.ts 16 Inlined single-use aligned media reader into canonical pending-reply reader; removed one-use media predicate. Original first URL occurrence, attachment index, stripped untrusted metadata, trusted-map owner and explicit undefined property shapes retained.
run/attempt-decision-context.ts 0 Conversation scan pairs duplicate tool IDs by counts and keeps return/error totals independently. Nontext limits, envelope exclusion and full-exchange budgets are separate guards.
run/incomplete-turn-classification.ts 0 Composed answer ownership and payload provenance filters already converge at their shared predicates. Provider/API eligibility constants are data-driven; no parallel duplicate classifier remains.
run/attempt-client-tools.ts 0 Collection refresh already parameterized by arrays and homogeneous name sets. Replay-safe object set and side-effect Map require distinct element types/operations; one container abstraction adds dispatch and loses strict types.
run/attempt.model-diagnostic-events.ts 0 Error publication and shared result observation already centralized. Opened/unopened iterator returns differ in finally execution and cleanup ownership; merging into an async wrapper adds a microtask and changes unopened return timing.
run/auth-plan.ts 8 Passed existing preparation records to the external-auth scope, credential metadata policy and model materializer, keeping config/agent/requested-profile aliases explicit. Retained the narrower dynamic-provider lookup because adding modelId there would change plugin selection.
cli-backend-dispatch.ts 0 The CLI argument projection deliberately omits caller tool flags, callbacks, channel authority and other CLI-supported names. A broad spread would change features; a whitelist table still needs 49 explicit fields plus conditional requester model plus a new generic projector.
run/setup.ts 0 Re-read durable harness admission, guarded hook dispatch, attachment shape and context policy. Provider/model override updates have distinct fields and log text; table form adds mapping entries without eliminating a common owner.
src/agents/embedded-agent-subscribe.model-state.ts 6 Shared context-accounting projection for successful turn completion and ordinary message-end observations; success flag explicit. Optional observer still guards usage work and model/cost/reset ordering retained.
src/agents/embedded-agent-subscribe.handlers.compaction.ts 10 Composed external start event from canonical event with widened optional reason instead of subsumed duplicate union; selected info/warn once for identical failure log payload.
run/provider-review-run.ts 0 Sync incognito capture and awaited durable recording have distinct exception/finalizer behavior. Failure wrapper overloads would introduce optional-cause presence variants, not replace a duplicated owner.
run/provider-review-continuation.ts 0 Payload-before/after checks intentionally straddle async contributor work; dispatch-before/after checks fence reentrant callbacks. Metadata parsing already uses canonical JSON owner.
transcript-rewrite.ts 0 Shared append already preserves replacement-specific replay, original metadata projection, ID relocation, writer transaction and exact suffix order. An appender table must encode unlike arities/async return shapes and adds types versus the switch.
run/deferred-lifecycle-owner.ts 0 Retry and owner replacement already share release operations. discard is synchronous; complete owns awaited trajectory flush before active-run release. A common async terminal path would change sync disposal and exception propagation.
message-visibility.ts 0 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.
model.provider-hooks.ts 7 Inlined single-use final legacy-id projection into final normalized model handoff. Identity, id/name comparison, route facts, hook order and timeout restoration unchanged.
src/agents/embedded-agent-helpers/provider-runtime-failure.ts 0 Combined structured and textual refresh-contention exits with the same short-circuit order. Net LOC unchanged; one redundant branch removed.
run/attempt-session-settle.ts 0 Initial, post-drain, and final terminal snapshots serve different observable boundaries. The two cleanup error catches preserve first-failure precedence and independently mark retained work; merging them would skip mandatory disposal on failure.
run/attempt-permission-prompt.ts 0 Measured generation-fence closure 214→215 (+1). It adds a retry-local closure while preserving three await fences and replacement retry; direct fences are shorter and clearer.
cache-ttl-checkpoint.ts 0 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.
run/attempt-execution-phase.ts 0 Owned transcript callback binding already shared. Prompt abort guard must precede fresh loop creation; guarded-fetch scope and prompt-settle tracker preserve nested async authority.
model.configured-fallback.ts 0 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.
cli-backend-dispatch-transcript.ts 5 Applied: 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.
run/failover-policy.ts 6 Applied: remove single-use prompt rotation helper and derive rotate eligibility from the same format-admitted failover predicate. Timeout and TLS still skip profile rotation; all prompt/assistant terminal policy differences remain explicit.
provider-prompt-state.ts 0 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.
model.inline-provider.ts 0 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.
model.manifest-alias.ts 26 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.
run/attempt-async-tasks.ts 0 Lazy metadata/registry enumeration already shares discovery; sleep cleanup occurs before each settle edge, and a Promise.race/finally replacement changes abort-listener settlement timing. Deadline and metadata must be reread; waited IDs and terminal records have distinct ordering/deduplication responsibilities.
run/attempt-tool-call-name-resolution.ts 0 Fresh common-uniqueness prototype: 198→199 (+1). Keeping empty-string behavior distinct from infer's truthy match plus callbacks/type contract consumes the shared loop reduction.
run/attempt-transcript-lifecycle.ts 4 Derived cleanup reuse directly with nullish assignment to cleanupDrain, deleting duplicate await/return branch. Descendant admission, actual-drain ALS disposal, primary-error precedence and timeout bound preserved.
run/attempt-context-engine-helpers.ts 11 Narrowed bootstrap callback to canonical resolveBootstrapContextForRun return type; removed unused generic file-kind flexibility and duplicate result declaration. Sole production caller and all test callers fit existing concrete file types; runtime statements unchanged.
run/attempt-bootstrap-prepare.ts 0 Bootstrap identity workspace, execution workspace and prompt workspace differ deliberately. Existing routing/files callbacks already share the repeated core; the two filters inspect different owning arrays before and after remapping.
run/attempt-history-prepare.ts 0 Replay context is already shared; compaction variant has different live model capture, trace checkpoint and post-sanitize normalization. Quota resumption writer checks and heartbeat filtering retain their owners.
run/helpers.ts 4 latest usage selection uses the existing ordered hasNonzeroUsage selection form. Both production callers supply newly-created ordinary records; result identity, unavailable context, reported zero and fallback precedence retained. .
history.ts 0 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.
run/attempt-terminal-evidence.ts 0 Terminal state, replay safety and delegated completion share primitive evidence owners while using intentionally different acceptance sets. Media delegation must bypass progress evidence without relaxing non-media terminal custody.
run/attempt-transcript-helpers.ts 7 Implemented shared suffix predicate across precheck, compaction recovery and yield cleanup. The third duplicate in sessions-yield now consumes new narrow transcript-tail-metadata.ts; all three call sites share exactly the original predicate. Combined helpers/yield/new leaf: 181 + 124 = 305 -> 174 + 120 + 10 = 304 (-1), with no new runtime dependency beyond the original assistant-marker leaf.
run/attempt-decision-prefilter.ts 0 Skipped-result constructor already shared. Remaining outcome records have intentional property presence/order and distinct proposed isCurrent callback.

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Per-file implementation coverage (2/2)

Base d3309e5760116877852a800c2ed21f9d15864c8e; candidate d12224379b2729e2bff6500f63b2b962f457db46. 766 net production lines removed (1,240 added / 2,006 deleted), 105 production paths and 357 preserved decisions. Tests, fixtures/support, generated declarations and tooling baselines excluded. Implementation: 128 minutes.

P1 merged reductions plus this candidate contribute 2,173 runner-only lines (3.2521% of the original 66,818-line baseline) and 2,477 production lines including adjacent code. PR2 contributes 453 runner lines and 766 total; independently landed upstream changes are excluded.

Conflict resolution preserved main’s verifyDecodability: true and conditional tool-ID sanitizer in the image helper, plus the lane’s sanitizeImages closure. Automatic upstream integration also preserved parseJsonMessageParam(payload, "interactive") in tool results. No new implementation scope was added.

Retained full-test receipt: 441 files / 5,816 cases at 4e1055ae779e5f851d051e6ee3d7cddc6e8433c5, including all 345 runner files / 4,387 cases. Correction proof passed at 7954898a20622fbb67f094c82ab59c275c9900ad: changed checks including core plus 27 test type graphs, dead code and guards; zero runtime/Madge cycles; mandatory lint 3/3; focused tests 8 files / 258 cases. Its single-worker cost run passed 18 files / 432 cases, with 133.11s summed Vitest duration and 626.71s wall time including runtime artifact preparation. Repeated summaries were excluded; separate receipts are not summed into full-suite coverage.

At final head d12224379b2729e2bff6500f63b2b962f457db46, rebase format/lint passed for three files (zero warnings/errors), focused tests passed 8 files / 172 cases, core plus three affected agent test type graphs passed, and runtime/Madge cycles were both 0. Whole-branch review was scoped-clean P3. Native SDK comparison completed with 131 reachable records, no added/removed entrypoints and no public SDK shape changes after assessment of five internal declaration deltas. The initial parallel render hit a kernel-confirmed OOM; four-CPU affinity selected the existing serial render path, which completed successfully.

The final mandatory lint-suppression test FAILED: 2 passed / 1 failed. The exact same missing allowlist record for two typescript/prefer-promise-reject-errors suppressions in untouched src/config/sessions/session-transcript-lock-settlement.ts reproduced on current main 9c763cb168e9461f76e9c3a9059c7b38838a7d3b (79 actual records versus 78 expected). That owner and test/scripts/lint-suppressions.test.ts are byte-identical across base, head and current main, and neither is changed by this lane. No new lint suppressions were added. The earlier correction-head lint pass does not supersede this final failure.

Unprefixed paths are relative to src/agents/embedded-agent-runner/. Positive net values are removals; negative values are shared-owner costs. Historical prototype measurements remain distinct from current diff counts.

File Net removed Implementation or retained responsibility
src/agents/sessions/compaction/request-budget.ts 0 Inherited equivalent from main; zero PR2 credit. The initial pass shared the standalone token-delta core across history and prompt estimates. Main independently landed the equivalent change in #166954; this candidate keeps its request-budget.ts byte-identical to the rebased base.
tool-result-char-estimator.ts 3 Removed the undefined early return already implemented by native JSON serialization plus the non-string result guard (20-input differential agrees). Rejected a shared serializer prototype at 172 -> 176: two fallback values plus lazy argument evaluation need extra policy parameters.
run/attempt-tool-search-executor.ts 0 Re-read complete nested execution, preparation/immediate outcomes, acceptance, owned transcript admission and durable activity. Inner abort race covers implementation/acceptance; outer race covers lifecycle settlement.
src/agents/embedded-agent-subscribe.handlers.tools.progress.ts 0 Shared item metadata projection already owns detailed versus channel-safe progress; bus carries sanitized partial result while callback deliberately omits it. Factoring their four common fields requires a six-line record and two spreads, zero net reduction while obscuring payload difference.
src/agents/compaction-planning-worker.ts 6 Shared the signal extension of each existing planner parameter contract instead of repeating planner fields in three wrappers. The existing runCompactionPlan still owns threshold selection, sanitization, cancellation reread, worker-kind checks and unavailable-only fallback.
run/attempt-tool-call-text-promotion.ts 0 Shared package owns promotion/scrubbing. Local stable IDs, checkpoint retirement and unopened iterator cleanup remain necessary.
run/attempt-session-identity.ts 0 Legacy marker lookup, keyed-entry lookup and current-target update preserve different read fences. Shared successor lookup already extracted; all assertions retained.
run/progress-controller.ts 0 A callback strategy table for three best-effort delivery paths changes the synchronous global-event boundary by adding await; preserving it leaves two callbacks plus strings and adds plumbing. Auto-off and reset flags are distinct one-shot observations.
run/attempt-stop-reason-recovery.ts 0 Synthetic event construction appears twice, but a typed builder plus parameter/call sites is longer than the existing literals. Creation, iterator and result error paths intentionally have different return contracts and settlement timing.
skill-runtime.ts 0 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.
post-compaction-loop-guard.ts 0 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.
plugin-runtime-refresh.ts 0 Continuation messages must reuse original array when no new messages exist. Generation, delivery, pending media and successful tools each reset differently.
run/attempt-timeout-prepare.ts 0 Measured shared grace-state intersection 141→143 (+2). Explicit bounded/paused variants are shorter and keep deadline, paused remaining budget and one-grace ownership visible.
compact-reasons.ts -8 Coordinated edit by attempt_prepare: shared buildCompactionFailureResult(reason, failure?) constructor (+8 owner LOC) consumed by compact/queued siblings. Optional failure presence and property order preserved.
compact.types.ts 0 These are SDK-reachable and intentionally narrower/required in attempt-vs-caller contexts; no type widening, config or protocol changes.
run/timeout-context-recovery.ts 0 Retained timeout marker custody and two-attempt pressure policy. Rechecked with compaction and run-control peers: neither exposes a narrower post-side-effect owner; prior measured shared timeout/overflow notification prototype +7 still applies.
src/agents/embedded-agent-messaging.ts 3 Implemented direct short-circuit core/plugin tool classification, retaining no plugin lookup for core tools. Send, target-evidence and delivery classifiers deliberately admit different action sets and normalize casing differently.
extensions.ts 0 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.
run/run-settlement.ts 0 Measured shared writer-field record 136→138 (+2); allocation and staging add code while the two target fields remain directly readable. Accounting-before-cleanup and original/successor authority are distinct.
run/model-harness.ts 0 Auth-attempt/model-provider core already unified. Presence of attempts including empty array chooses a different resolver; pinned error copy and transport/auth route facts remain distinct.
run/runtime-resolution.ts 0 Re-read attribution, thinking, transport override and preliminary model selection. Alias resolution only runs without explicit provider; catalog construction carries fallback distinctions.
server-endpoint-compaction.ts 0 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.
compact.foreground-work.ts 0 Retained after actual 130 -> 128 null-sentinel prototype. It conflates absence of an engine with transferred resource custody and stops expressing the separate lifecycle fact; three work scopes still close at distinct ownership boundaries.
context-engine-maintenance-execution.ts 0 Foreground keeps exact existing manager/lock; background must discard both and acquire its own target. Only acquisition differs and both already share rewrite/publish owner.
run/attempt-tool-run-context.ts 0 Re-read exact projection and its tests. The function deliberately excludes extra run/session/authority fields and preserves frozen trace and captured reply owner.
context-engine-maintenance-work.ts 0 Settling helper already shares failure collection. Work-only idle barriers and cleanup admission are distinct; combining them changes descendant/resource lifetime.
src/agents/embedded-agent-subscribe.types.ts 0 Public subscription parameter contract already composes attempt fields through Pick. Remaining declarations add subscriber-owned options and cannot remove runtime/SDK behavior.
plugin-runtime-refresh-delivery.ts 0 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.
run/permission-change.ts 9 Applied: derive closed state from the authoritative permission registry; remove duplicate closed boolean and its writes/check. Pending acknowledgement reuses Deferred instead of mirroring promise/resolve members.
run/attempt-sessions-yield.ts 4 Implemented shared trailing metadata preservation leaf with transcript cleanup. Live assistant suffix cap and persisted interrupt removal remain separate; stable message array and durable-before-live publication retained.
run/attempt-transcript-lifecycle-prepare.ts 0 Lifecycle wrapper adds cron generation release in finally; initial writer wrapper preserves inherited drain and close authority. Their different custody cannot collapse into the underlying lifecycle without widening that owner.
sandbox-info.ts 5 Applied: common unavailable-result projection uses explicit blockedByPolicy decision. Host policy still short-circuits elevation availability and custom blocked-reason reads.
src/agents/compaction-real-conversation.ts 7 Declared the five anchor roles once and reused that policy for direct and streaming classification, keeping assistant conversation eligibility separate. Content classification, lookback aging, silent/heartbeat filtering and hidden-message policy remain unchanged (576 differential classifications agree).
run/message-tool-terminal.ts 0 The source-message hook runs per tool; tool-authored completion runs only after the whole batch settles. Existing argument reader is used before and after a callback and must reread mutable arguments.
embedded-cyber-failover.ts 0 Selection context already shared. Eligibility, retry usefulness and committed-work evidence intentionally answer separate questions with distinct error/refusal/public-delivery policies.
usage-accumulator.ts 0 Recorded zero, provider-billed provenance, unavailable-price latch and per-call aggregate have distinct behavior; canonical priced-component traversal already shared.
src/agents/embedded-agent-subscribe.handlers.ts 2 Removed import-only tool handler barrel. Existing scheduleEvent remains one queue/failure owner; discriminated switch preserves ignored event kinds and agent_end-only returned settlement promise.
src/agents/embedded-agent-helpers/images.ts 7 Shared prepared label/limits through one sanitizer closure; inlined the only nonempty-content fallback and removed its overgeneral generic cast. User/tool results still filter after sanitization; assistant signatures/empty blocks still filter before sanitization. Conflict-only rebase retained main’s verifyDecodability: true and conditional tool-ID sanitizer alongside this shared sanitizeImages closure.
replay-session-state.ts 0 Legacy sync methods swallow non-incognito failures; V2 async method propagates, awaits, and asserts again. They share current-owner assertion already.
run/agent-end-context.ts 0 Ordered foreground public projection already shares its only long contiguous common section with dispatch. Other apparent overlaps are interrupted by different required property ordering; new short group helpers cost more than repeated fields.
thinking-replay-repair.ts 0 Durable rewrite effects are already shared. Thinking repair maps every affected message; checkpoint repair selects only the latest exact checkpoint.
tool-result-text-budget.ts 0 Head/tail share the same binary-search core with explicit direction. Separate public adapters preserve caller signatures.
run/attempt-orphan-repair.ts 0 Sequential metadata replay already one switch/one ID publication; label remapping intentionally consults prior writes before original target.
src/agents/compaction-planning.worker.ts 0 Input discriminants and return shapes are the worker protocol; validation handles two different finite numeric fields. Existing indexer is shared by all index-returning plans, while adaptive ratio returns no indexes.
run/attempt-tool-search-run-plan.ts 0 Visible/replay/live/capability name sets are separate authorities, not duplicate state; replay controls and deferred client matching differ. Building names via a table requires as many explicit entries and loses direct relationships.
run/failover-observation.ts 0 Explicit structured fields prevent rawError leakage and preserve own undefined fields. Spreading normalizedBase would change that contract; an omission/projection table adds type machinery and cannot shorten sanitization. Prior safeText helper prototype 111 to112 remains longer.
run/stream-wrapper.ts 0 Settlement return/throw/result already share finishAfter; next needs settle-versus-close distinction. Adjacent event-wrapper coalescing snapshots transform lists per opened iterator.
src/agents/embedded-agent-subscribe.run-state.ts 0 Initial state owns exact own-property presence and independent parser/delivery/recovery facts. Deriving pending trust/side-effect state from visible text would discard authority distinctions; no duplicate initializer owner.
packages/agent-core/src/harness/compaction/summarization-completion.ts 9 Applied: reused the shared envelope at the same pre-options construction boundary; completion invocation, usage callback, reason mapping and output/error handling unchanged.
run/abortable.ts 0 Re-read both promise lifecycles and tests. Abortable preserves value/rejection normalization; liveness join resolves abort/timeout and must release attempt captures through detached completion.
run/attempt-trajectory.ts 0 Retained one trajectory recorder owner with admission checks before and after awaited creation. Detached/disabled runs stay excluded; durable target identity, session-start facts and metadata projections have different fields and evaluation points.
compaction-safety-timeout.ts 0 Cancellation latch is independent of AbortSignal state because caller cancellation and timeout can race; watchdog and composed-signal owner distinct. Preserve required onCancel best effort and awaited cleanup.
src/agents/embedded-agent-subscribe.tool-lifecycle.ts 2 Removed tool barrel imports. Prototype moving terminal callback into finish helper reduced106 to104 but crossed an awaited helper-return boundary; rejected to preserve callback scheduling/authority timing.
run/attempt-trajectory-status.ts 0 Retained after prototype: shared original-text guard formatted 104 -> 105 (+1); restored. Error/interruption priority and explicit-delivery exceptions remain in single final classifier.
compaction-session-agent.ts 0 Key/stream resolution already takes prepared inputs; text transforms, thinking and runtime extra parameters apply in distinct order, with the summary-specific web-search denial kept explicit.
run/terminal-timeout.ts 0 Timeout retention/output and normal terminal projection differ. A second shared terminal envelope prototype measured with total +4 LOC; retain explicit variants.
cache-ttl.ts 7 Inlined the single-use context matcher into the backward marker scan, retaining ordered provider/model normalization, missing context permissiveness and caught malformed history.
direct-compaction.ts 0 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.
tool-schema-runtime.ts 7 Inlined single-use diagnostics summary owner. Six-tool and twelve-violation bounds, pluralization, untrimmed provider label and exact structured diagnostics retained.
src/agents/embedded-agent-subscribe.tool-text-diagnostics.ts 6 Inlined the single-use structured-invocation scan into diagnostic owner; keeps malformed-block checks, tool-call aliases and no private text in logs. Registry-name scan remains allocation-free and can stop at first match.
run/attempt-system-prompt.ts 0 Re-read raw-run behavior, stable/dynamic cache boundary and permission refresh. Named section identity and deferred refresh distinguish externally appended context from generated regions.
run/source-reply-payloads.ts 0 Transcript mirror omits transport fields and uses different presence guards from outgoing payload; exact source completion belongs to delivery-evidence owner, not array presence.
run/compaction-timeout.ts 0 Pre-compaction and current snapshots share trim already; current identity is intentionally retained outside timeout. Grace window tracks one independent use.
run/images.media-refs.ts 0 Path and media-URI handling share one resolver already. Full map-before-some conversion preserves errors from later media facts; normalized aliases and local-image-cache suppression remain distinct from hydration eligibility.
run/prepared-runtime-context.ts 0 Canonical/rooted/plugin-generation workspace selection handles separate ownership, and the binder already reuses the committed runtime record. A common workspace helper would hide preserveExecutionWorkspace rather than remove policy duplication.
run/internal-params.ts 0 Separate internal run versus attempt capabilities prevent public API growth and record authority/custody facts independently; no repeated runtime path exists.
transcript-byte-preflight-authority.ts 0 Re-read mint/release/consume flow. Claims are consumed even when the exact session/harness/trigger fails; one-shot authority differs from reusable admission.
run/attempt-subscription-cleanup.ts 0 MCP/LSP disposal already shared; guard removal and session disposal are synchronous, flush and bundle disposal awaited. One async cleanup loop would alter microtask/exception ordering.
model-resolution.ts 0 Already one provider iteration shared between dynamic and static tiers; final tier owns errors, preserving prepared-model authority and initial discovery miss fallback.
run-entry-cli.ts 0 Read-only versus writable read admission differs in consistency options; one conditional reader cannot share argument tuples without extra wrappers. Settlement must retain native binding before placement release and classify after current result.
run/backend.ts 0 Attachment hydration and captured authority, native provenance replacement and continuation-field stripping remain separate owning boundaries; no broad result spread change.
cli-backend-dispatch-eligibility.ts 0 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.
run/attempt-decision-diagnostics.ts 4 Implemented deriving surfaceEffect directly from the already-computed optional delta. Undefined still means unknown, positive reduced, all other values unchanged-or-expanded.
run/attempt-execution-types.ts 0 Prepared owners already derive their output types. Picks document the exact authority and resources visible to execution; further merging would expose unrelated owner operations.
run/prompt-image-preparation.ts 0 Retained separate native hydration/strip and ordinary image-result policies. A shared prompt/history image-policy prototype across two consumers grew 558 to 569 lines (+11), including helper/import costs.
compaction-duplicate-user-messages.ts 0 Re-read normalization and retry batch detection. Timestamp monotonicity, NFC sender/text tuple, persisted-media exemption and assistant reset each own distinct behavior.
run/attempt-nested-tool-activity.ts 0 Measured two-index strategy loop 81→82 (+1), adding an array and weakening tuple index inference. Existing findIndex calls preserve first-occurrence semantics and clear bounds.
run/attempt-thread-helpers.ts 0 Prompt joining, sandbox mount selection and cache-TTL persistence have separate callers and contracts. Eligibility callback and projection timestamp execute at their original points; no forwarding-only helper found.
src/agents/embedded-agent-helpers/messaging-dedupe.ts 2 Derived hold from normalized-text presence and prefix matching, then assigned held state and returned through one path. Empty normalized text still short-circuits the sent-text scan and clears the exact same property.
run/attempt-before-agent-run.ts 0 One gate owner and one redacted persisted outcome. Hook runner/session structural views keep narrow authority, and guarded append/flush/replay order cannot collapse with ordinary session prep.
run/recovery-message-action-capability.ts 0 Re-read trusted ingress guard and recovery capability projection. Captured source correlation and authority lifetime are not interchangeable with caller run params; preserve explicit narrow tool context and sender-null normalization.
run/run-attempt-result.ts 0 Normalized absent arrays, concrete tool outcome order, sorted nested tool names and source-result provenance are distinct fields. Generic map-based defaults would weaken the contract.
run/attempt-steering-admission.ts 0 Admission already uses exactly the three valid states. Stop and unsubscribe intentionally have different ordering and idempotence, so a generic cleanup loop would change error handling.
prompt-cache-request-observer.ts 0 Started-request count, unconsumed current request, and last completed observation cannot be derived from one another; all three have distinct lifetimes.
run/terminal-outcome.ts 0 Shared classification wrappers have multiple production consumers; combining them requires repeated classifications or a larger projection API at callers. Terminal refusal copy and frozen signal-owned interruption remain separate facts.
prompt-cache-retention.ts 0 Provider eligibility and native marker TTL aliases are independent; conflating them broadens support. Current alias guards remain two explicit exact variants.
run/attempt-gateway-tools.ts 0 Single gateway preparation owner already carries the admission capability and revalidates after await. Callback wrapping establishes caller context and cannot be flattened.
run/attempt-memory-audience.ts 0 One owner resolves delegated versus stored audience; existing denial log dispatch is already shared. Supplied audience lease remains caller-owned while row-derived lease belongs to attempt.
run/execution-context.ts 0 Run and dispatch contracts carry distinct lifecycle owners and current-attempt state; aliases already derive from actual owner operations.
compaction-diagnostics.ts 0 Re-read contributor sizing, tool label fallback and token estimator stop-on-first-failure. Different message views are intentional loose diagnostics.
run/attempt-stage-timing.ts 0 Summary formatting and dispatch are already shared with the setup owner. Warn/trace gates precede prefix evaluation, and caller-specific thresholds stay explicit.
runs.probes.ts 0 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).
model.static-id.ts 0 Exact and normalized lookup indexes own different precedence with first-row retention and pinned metadata generation; no duplicate cache owner.
run/attempt-context-summary.ts 0 Single-use payload helper separates per-message counting from aggregate maxima and role sorting. Inlining requires nested loop/branch flags and grows the already concise aggregation.
run/codex-app-server-recovery.ts 0 Ordered refusal reasons are observable and early-exit callback table would cost closures/type declarations. No recovery predicate or Codex behavior changed; no direct API proof required.
run-permissions.ts 0 Generation and owner checks intentionally run before revoke and after asynchronous apply. Logical ownership can survive a handle handoff; deriving solely from current handle would remove that contract.
skills-prompt.ts 0 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.
effective-tool-policy.ts 0 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.
run/compaction-retry-aggregate-timeout.ts 0 The reflected promise must retain late failures while the per-window timer re-arms on current activity. Its boolean activity helper has a caller in attempt-stream-settle; any removal requires a coordinated boundary test migration.
run/tool-loop-recovery.ts 0 Normalization and admission already one core. Lifecycle attachment exists only when both callbacks are present; fail-closed first-call intervention has a separate shape.
src/agents/compaction-planning-worker-runtime.ts 0 The shared pool and caller-selected worker pool have different ownership; only the latter is closed. Error conversion preserves exact caller abort identity and classifies timeout separately.
src/agents/embedded-agent-helpers/context-overflow-observation.ts 11 Merged the ordered sum/single regex inventory and capture-number parser. Pattern capture count expresses the real difference; first positive input plus optional nonnegative output are validated identically, including comma-only rejection and summed overflow.
terminal-tool-failure.ts 0 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.
tool-call-argument-decoding.ts 0 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-helpers/assistant-message-failures.ts 0 Public failure predicates have different classifiers and are already one expression each; a generic factory costs more than the three four-line adapters. Signal construction owns distinct status, retry evidence and detail normalization.
active-run-projections.ts 0 Rejected set-union counting after source audit: current counting preserves multiplicity of reply session IDs absent from embedded map; Set changes two identical reply-only IDs from 2 to 1. A semantics-preserving direct reduce is shorter only by hiding state in an accumulator expression; explicit loop retained.
run/attempt-delivery-state.ts 0 Existing generic append owns bounded array joining; optional source payloads, unbounded spawns, boolean OR and literal true are explicit policies. Key-driven alternative requires conditional generic return typing/casts and obscures absence/identity.
run/lane-runtime.ts 0 Priority table and restart/inter-session override already consolidated; finite timer sentinel handling and grace addition are distinct numeric contracts.
src/agents/compaction-usage.ts 0 Both mutation modes are called in production: replay preserves array identity when unchanged, and subscriber compaction mutates active messages while optionally zeroing usage without a summary. Timestamp-based and order-based staleness fallback remain necessary distinct facts.
run/message-transform-stream-wrapper.ts 0 Optional materialization consumes context once with private handoff, preserving reference identity on no-op transform. Removed state would lose consume-once enforcement.
wait-for-idle-before-flush.ts 0 Immediate timeout bypasses optional idle work, while cancellation never bypasses required transcript persistence. Reordering local async wait would change the promise boundary.
run/context-engine-admission.ts 0 Owned and borrowed leases have different disposal obligations. The existing synchronous selection plus owned-only awaited catch preserves error timing; a shared awaited disposer would add work on borrowed failures.
run/model-admission.ts 0 Initial model selection already consumes shared owner input. Configless defaults and pinned native exclusion protect separate policy admission; removing either changes requests.
run/tool-activity-heartbeat.ts 0 Preparation and prepared execution have independent liveness intervals and metadata identity propagation. A callback wrapper factory moves but does not remove the owner and complicates generic execute typing.
run/prompt-image-metadata.ts 0 Fact indexes preserve null slots, while layouts filter invalid slots and may be absent. Sharing the single metadata lookup would add plumbing and the filters have different data contracts.
tool-send-receipts.ts 0 Re-read shallow receipt snapshots, consume-once registry deletion and optional field presence. One existing weak session registry owns lifetime.
replay-state.ts 0 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.
run/auth-store.ts 0 Scoped profile object, external/persisted list filtering and authoritative empty-list semantics already shared. Early return for empty selection adds three lines while retaining two shape variants.
run/midturn-precheck.ts 0 Exception request and synthetic assistant message recognition serve separate error/replay contracts; keep canonical message text and class.
src/agents/sessions/compaction/compaction.ts 0 Retained: public throwing SDK summary API over result-returning agent core; its positional API and per-call usage sink are required contracts.
src/agents/embedded-agent-helpers/thinking.ts 0 Ordered supported-value parsing plus the mandatory-minimal/unsupported-off fallbacks each run once. Replacing the scan with map/find would normalize entries beyond the first accepted value and allocate additional state.
run/context-recovery-state.ts 0 Accounting snapshots, overflow budgets and timeout marker custody reset at different events. Count/state derivation would lose the last authoritative producer snapshot or one-shot timeout restoration.
run/retry-limit.ts 0 One typed fallback throw and one terminal payload are distinct externally visible outcomes; generic result construction would need more flags and custom message fields than it removes.
lanes.ts 0 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-helpers/image-errors.ts 0 Dimension and size parsers have distinct broad admission patterns and different output fields. Shared record construction would still require per-variant parsing callbacks plus the same exact optional keys, longer than the 45-line pair.
run/attempt-compaction-thinking.ts 0 Catalog/runtime route core is already shared between configuration and provider mapping. Remaining fields express different policy ownership and are not duplicate decisions.
src/agents/session-tool-result-guard.transcript-seq.ts 0 Lazy branch cache owns bounded transcript-sequence derivation and exact missing-parent semantics; no repeated owner.
run/attempt-preparation.ts 0 One process-wide start queue with overlap after admission. Counter/sync-time reset happens only after yielding; no redundant state can derive the two independent budgets.
run/agent-hook-context.ts 0 Memory session assertion is immediate; current-audience assertion reads the current run field when invoked. Capturing it or unifying both checks loses live authority; channel/identity fields already shared.
src/agents/embedded-agent-subscribe.raw-stream.ts 0 Minimal lazy best-effort diagnostics with incognito gate. Ready flag owns mkdir-at-most-once; serializing only after enabled gate and before append is required.
context-engine-capabilities.ts 0 Lazy import and per-complete runtime construction preserve current config and captured normalized identity. Remaining 42 lines are contract/type projection, not duplicated implementations.
run/attempt-exec-approval-continuation.ts 0 Prompt and transcript resizing already share closure and bounds. Optional transcript-range fallback and recorder replacement semantics cannot derive from model prompt alone.
runs.session-index.ts 0 Re-read exact-key vs full-index clear and stable parent-realpath normalization. Existing shared deletion loop preserves aliases.
run/compaction-accounting-bridge.ts 0 Minimal identity-bound WeakMap owner with attach/read accessors. Receipt and memory transcript authority are owner facts, not derivable from portable public context.
src/agents/embedded-agent-messaging.types.ts 0 Shared exported metadata declarations are public SDK shapes, with optional capability fields carrying distinct meanings. No redundant local-only generality.
model.compat.ts 0 Re-read nested image merge identity and reasoning override precedence. Missing base/override deliberately returns the existing object; unconditional spreads change identity.
run/execution-phase-diagnostics.ts 0 Callback-in-result prior measured 39 to 41; explicit callback snapshots and live rotated session ID are the actual required state. Current file remains 39.
run/retry-budget.ts 0 Dispatched count and charged count intentionally diverge for progress continuation; neither derives from the other without replacement state.
failure-signal.ts 0 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.
run/auth-profile-failure-policy.ts 0 Current common-null gate already includes provider-started timeout policy. A table would lose literal-union narrowing or require casts, while state-local exclusions are intentionally explicit.
src/agents/embedded-agent-subscribe.trajectory.ts 0 One recorder boundary with call/result variants; argument sanitization and result redaction differ, and ingress-before-delivery ordering remains explicit.
utils.ts 0 Positive finite budget flooring permits positive fractions to become zero; generic positive-integer normalization changes behavior. Thinking adapters encode distinct product/runtime mode contracts.
run-entry-runtime.ts 0 Explicit native override and ordinary provider-derived CLI path differ in pinned harness exclusion and lookup. They share only the two-field returned record; constructor abstraction exceeds existing six aggregate return lines.
empty-assistant-turn.ts 0 Existing normalized zero-presence plus all-zero test is minimal and preserves nullish total fallback and nonnumeric usage handling.
model.provider-transport.ts 0 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.
src/agents/session-raw-append-message.ts 0 Sync and async raw appenders are separate public types and WeakMaps; a generic key-parametrized helper adds casts or overload boilerplate for 1-line get/set operations.
context-engine-maintenance.types.ts 0 complete type contract re-read; no extra internal variant remains without a caller.
src/agents/embedded-agent-subscribe.callback.ts 0 One callback error/completion/pending-set owner; synchronous callback exceptions and Promise rejection tracking preserve distinct settlement/fatal error behavior.
src/agents/embedded-agent-subscribe.handlers.compaction.runtime.ts 0 One durable max-count reconciliation owner; no-change null and monotonic timestamp update preserve exact rows. Clock injection/optional session are used by existing tests/callers.
run/attempt-system-prompt-additions.ts 0 One progress/incognito preparation followed by one exact five-field coauthor projection. Passing full params changes a bounded collaborator shape; a one-use field picker adds code.
run/attempt-user-transcript-context-registry.ts 0 The list view is the same live array across steering upserts. A map owner needs a new array on reads or a second synchronized collection. Splice ternary prototype is a compact rewrite of the same operation, not clearer ownership.
run/compaction-live-model-selection.ts 0 Shared requested selection already exists. No-request retains identity; pinned auth, same-provider inheritance and cross-provider omission remain explicit variants.
run/provider-refusal.ts 0 First refusal extraction and optional fields preserve absent-versus-undefined output contract. A general optional-field collector requires a typed table and is no shorter than three spreads.
run/blocked-run-result.ts 0 Re-read complete result constructor. Already the shared blocked result owner; timeout paths require different metadata and diagnostics.
model.static-catalog-row.ts 0 Sole explicit projection intentionally excludes unknown fields and selectively clones window/thinking data. Table/spread would change own keys or require unsafe assertions.
tool-name-allowlist.ts 0 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-subscribe.shared-types.ts 0 Public emitted event shape contains private callback transcript facts and derived command-output fields. Existing composition is minimal; no duplicate runtime owner.
run/idle-timeout-breaker.ts 0 Increment and reset are two distinct transitions; arithmetic compression obscures progress precedence. No duplicate owner/state found.
run/terminal-retry-state.ts 0 Explicit counters and optional completion check carry distinct reset behavior. Return-type inference would lose optionality; generated keys need an assertion and add a type/field table.
execution-phase.ts 0 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.
model.provider-hooks.types.ts 0 Hooks deliberately use unknown at plugin implementation boundaries while preserving shared parameter types. No unused caller generality or alternate runtime implementation remains.
run/attempt-stream-runtime.types.ts 0 Re-read narrow type composition and callers. All fields describe consumed prepared lifecycle owners; no runtime owner or redundant state to remove.
run/attempt-trajectory-flush.ts 0 Existing owner receives the record directly; wrapper supplies the exact trajectory cleanup name and delayed diagnostic/flush access.
legacy-compaction-session-key.ts 0 This is the PR1 shared successor selection; raw retained and normalized lookup keys remain distinct.
run/preparation-timing.ts 0 Retained the shared async preparation-span adapter; inlining would duplicate the canonical phase/stage fields and config/environment forwarding at callers.
run/session-boundary-prompt-cache-key.ts 0 Explicit override, API eligibility and Unicode suffix reserve each run once. Flattening these decisions does not remove a repeated core.
provider-prompt-serialization.ts 0 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.
run/shared-run-context.ts 0 Exact ordered explicit message-context projection intentionally excludes other fields and remains shared by dispatch/end contexts.
src/agents/embedded-agent-helpers/user-facing-text.ts 0 These wrappers are the canonical composition seam, joining sanitization with public copy and preflight ownership. Both have production callers; no duplicate policy or internal-only adapter to remove.
run/attempt-terminal-anchor.ts 0 Seven-line loop already shares missing/non-cache exit and traverses only cache TTL markers. No further structural duplicate.
src/agents/agent-compaction-constants.ts 0 Sixteen lines define the one reserve-budget clamp and the externally observed retry count; normalization and the 25-percent cap remain explicit.
abort.ts 0 Exact error-name matching and normalized string-message matching have different coercion rules, so merging them would broaden accepted errors.
run/attempt-http-runtime.ts 0 Re-read ordered proxy installation and stream timeout tuning. Two existing global owners have a required order; folding into one would cross scope and remove no behavior.
run/attempt-tool-call-block-type.ts 0 Shared normalization and three literal-kind narrowing is already the minimum clear runtime/type contract; a Set loses predicate narrowing.
run/turn-taint-state.ts 0 Retained run-local sticky taint state: later clean tool results cannot clear taint acquired earlier in the turn.
src/agents/embedded-agent-helpers/google.ts 0 Public provider detector plus compatibility barrel export; actual ordering implementation already belongs to shared/google-turn-ordering. No feature logic duplicated.
compact.runtime.ts 0 Cached lazy import keeps compaction graph behind execution admission. Deleting its facade would eagerly move the graph or duplicate loader mechanics in callers.
src/agents/embedded-agent-subscribe.handlers.tools.ts 12 Deleted12-line forwarding barrel. Four production callers and all existing test/type/mock imports now target start/progress/completion owners directly; no remaining references in src/packages/test/scripts.
src/agents/sessions/compaction/runtime.ts 0 Retained: shared optional usage sink owner has three runtime callers. Folding it into the summary adapter would duplicate tree/session compaction behavior.
packages/agent-core/src/harness/compaction/summarization-prompts.ts -13 Applied: owns the shared summary request envelope for ordinary and branch summary paths. Constructor preserves systemPrompt/messages and message role/content/timestamp key order; the existing prompt strings are byte-identical.
src/agents/compaction-replay.ts 0 Ten-line shared replay composition is used by transcript rebuild callers and preserves the required usage-before-signature sanitation order.
model.static-catalog.types.ts 0 Eight-line shared catalog state shape; every member has different owner semantics. Merging with implementation changes import dependency direction without reducing fields.
run/preemptive-compaction.types.ts 0 Four named route values are independently observed by callers; the file is the complete eight-line shared contract.
src/agents/embedded-agent-helpers/context-file.ts 0 Seven-line canonical value type carries the authenticated personal-user marker; no duplicate code.
provider-prompt-state.worker.ts 0 Re-read sole typed worker adapter and transfer-list ownership. Seven-line boundary is already minimal; no interface or transfer behavior change.
run/session-context-limits.ts 0 Single seven-line bounded hydration policy already shared by attempt and compaction.
src/agents/sessions/compaction/index.ts 0 Retained: five-line public barrel; deleting its import surface is outside behavior-preserving simplification.
context-truncation-notice.ts 0 Four-line shared formatter with multiple callers and exact visible bytes; already one owner.
run.ts 0 Four-line public export boundary contains no implementation duplication; removing it moves consumers with no feature-internal reduction.
run/auth-profile-failure-policy.types.ts 0 Four-line type-only shared union; shared/local/local_transient all have consumers; moving into behavior file gains no LOC.
src/agents/embedded-agent-helpers/anthropic-api.ts 0 Three-line shared two-API predicate used across replay owners; no further shared core.
logger.ts 0 Three-line concrete subsystem logger is already the sole owner.
src/agents/embedded-agent-messaging-history.ts 0 Two-line shared history bound; no duplicate implementation.
run/transcript-tail-metadata.ts -10 New 10-line pure shared owner of the existing metadata-preservation predicate. Runtime imports only the same assistant-marker leaf previously imported by both consumers; SessionManager is type-only. Combined net reduction including new file is one line.

@steipete
steipete marked this pull request as ready for review October 8, 2026 11:10
@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: d12224379b2729e2bff6500f63b2b962f457db46
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

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

Carefully review these changes before merging.

@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, 7:18 AM ET / 11:18 UTC.

ClawSweeper review

What this changes

The branch consolidates repeated agent preparation, recovery, streaming, compaction, and transcript operations while migrating callers away from an internal forwarding module.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful consolidation with no concrete finding, supported by extensive test receipts but limited runtime proof.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The verified maintainer PR is exempt from the external-contributor proof gate. Its receipts exercise runtime owners through tests and differential checks, without a shipped-entry-point run; the diff introduces no stored-data format change or material expansion of authority.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: This owner-directed maintenance reduces repeated implementations without adding product surface. Its value is simpler ownership and less code to maintain.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: this maintainer-authored PR contains distinct consolidation work that current main does not already cover. No concrete introduced regression was found; confidence is limited by test-based runtime evidence and partially unavailable history.

Priority: P3
Reviewed head: d12224379b2729e2bff6500f63b2b962f457db46

Before merge

  • Resolve review confidence - ClawSweeper must reach high confidence before merge readiness is known.
  • 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.

Tests

  • Missing end-to-end proof: No shipped CLI or Gateway run is recorded for this consolidation; the supplied validation consists of subsystem tests, differential checks, builds, and static gates.
Agent review details

How this fits together

The embedded agent runtime turns conversation history, selected models, credentials, and tools into model requests, streamed replies, and transcript updates. This consolidation shares existing operations within that runtime.

flowchart TD
  A[Conversation and settings] --> B[Prepare agent run]
  B --> C[Select model and credentials]
  C --> D[Execute model and tools]
  D --> E[Stream replies]
  D --> F[Recovery and compaction]
  F --> D
  E --> G[Settle and update transcript]
Loading

Technical review

Best possible solution:

Keep the existing runtime owners and consolidate only equivalent operations, preserving explicit variant ordering and public contracts.

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

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

Is this the best way to solve the issue?

Yes: sharing operations inside their existing owners and removing the migrated forwarding path is a maintainable approach; the reviewed hunks retain the relevant ordering and policy distinctions.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

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

Security

None.

Evidence

What I checked:

  • Applicable repository policy: Read the complete root policy and applicable agents, embedded-attempt, and plugins policies. Applied ownership, authority, caller-cutover, test-value, and read-only review guidance; no maintainer-notes directory was present. (AGENTS.md:1, d12224379b27)
  • Pinned introduction and remaining work: Inspected the merge-base-to-head hunks in bounded path groups and checked current-main context. The shared summary-envelope constructor and permission-state consolidation remain distinct from fetched main; the merged bookkeeping PR does not supersede the branch. (packages/agent-core/src/harness/compaction/summarization-prompts.ts:12, d12224379b27)
  • Verified test-merge identity: Raw commit records confirm the test merge has the recorded base followed by the exact PR head as parents. Subsequent fetched-main changes in the touched prompt-failure test concern separate history-failure scenarios rather than the migrated profile-dispatch hunks. (d284ef202eb3)
  • Permission lifetime remains owner-bound: The permission owner is freshly allocated and registered once; close deletes its registry entry. Replacing the duplicate closed flag with registry membership preserves rejection after close, while recordApplied retains the exact authority and authorized-mode check. No material transfer or expansion of authority was identified. (src/agents/embedded-agent-runner/run/permission-change.ts:93, d12224379b27)
  • Recovery and sandbox safeguards preserved: The unified auth-profile operation retains the rate-limit rotation counter, fallback cap, and error context. Sandbox full-access availability still short-circuits on explicit execution or host policy restrictions. (src/agents/embedded-agent-runner/run/failover-retry-controller.ts:173, d12224379b27)
  • Internal caller cutover: Production and test callers now import the start, progress, and completion owners directly. A source search found no remaining references to the removed .js forwarding path; the patch-event type remains consumed inside its owning module. The body additionally reports no public SDK entrypoint or export-kind changes. (src/agents/embedded-agent-subscribe.handlers.ts:16, d12224379b27)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • computment: 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: serialized state: src/agents/embedded-agent-runner/compact.queued.ts, unknown-data-model-change: src/agents/embedded-agent-runner/compact.queued.ts, 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 behavior change or demonstrated urgent regression.
  • 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 behavior change or demonstrated urgent regression.
  • 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

Review checklist disposition for d12224379b2729e2bff6500f63b2b962f457db46:

  • Config compatibility: the complete 127-path Git diff changes no config key, default, CLI flag, schema, migration, or public protocol. The two files under config/ are shrink-only lint inventories. No upgrade action is needed.
  • Data model: the cited compact.queued.ts hunks replace four failure-result literals with buildCompactionFailureResult. It returns the same ok: false, compacted: false, exact reason strings, and conditionally present failure object. The compaction result types, storage operations, admission checks, and scheduling branches are unchanged. This is result-construction reuse, not a persisted-data migration. The full native SDK comparison also found no public compatibility change after all five internal declaration deltas were assessed.
  • Proof and confidence: there are zero added test files; existing tests changed only at removed internal seams. The recorded full suite includes four repository E2E files (57 passing cases), plus all 345 runner-directory files. Correction and conflict-integration checks are separately attributed in the coverage comments. Fresh whole-branch independent P3 review found no actionable issue, and all exact-head hosted checks are now successful, skipped, or neutral, with no failed or cancelled check remaining.

The review reports no concrete finding. Its config/data-model checklist was triggered by incomplete file metadata and the compaction filename, rather than a demonstrated contract change. The complete diff, source inspection, compatibility assessment, and test evidence resolve those items. The inherited local lint-suppression failure remains explicitly documented and reproduced on current main; this PR does not change either implicated file.

@steipete
steipete enabled auto-merge (squash) October 8, 2026 11:33
@steipete
steipete merged commit a889961 into main Oct 8, 2026
224 of 225 checks passed
@steipete
steipete deleted the deslop/d03-p2-20261007 branch October 8, 2026 11:34
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
)

* refactor(agents): consolidate embedded runtime variants

* chore: shrink agent assertion safety baseline

* test(agents): preserve tool-start mock exports

* test(agents): remove stale settlement fixture inputs

* refactor(agents): keep patch activity type local

* test(agents): observe recovery profile dispatch

* refactor(agents): preserve lint-safe runtime forms
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