Skip to content

refactor: consolidate outbound delivery and auth profile internals - #167002

Merged
steipete merged 2 commits into
mainfrom
deslop/d12-p2-20261007
Oct 8, 2026
Merged

steipete merged 2 commits into
mainfrom
deslop/d12-p2-20261007

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Outbound delivery and auth-profile handling duplicate selection, preparation, projection, and publication work across related paths.

User Impact

No user-visible change. Credential scope, live authority, recovery/replay, configuration, CLI flags, protocol and persisted shapes, and user-visible text are preserved.

Why This Change Was Made

Shared cores now handle auth selection/publication, CLI credential caches, queue projections, and message/receipt construction. Scope, lease, recovery-state, and reply-metadata differences remain explicit.

542 net production lines removed (857 added, 1,399 deleted; 68 files). This uses the campaign's 500–999 line exception with coverage log, after more than two hours of implementation. The log covers all 234 original production files and 28 adjacent owners/callers, including measured rejected prototypes. Tests only migrate removed internal seams; assertions remain equivalent. The assertion baseline shrinks for removed casts.

Evidence

Prior-head f01148fd46e7 AWS proof: full changed checks (types/lint/guards), build, 3,459 tests / 255 files, lint-suppressions (3/3), and 0 runtime / 0 Madge cycles.

pnpm test src/infra/outbound/message-action-execution.{accepted-results,source-reply}.test.ts --maxWorkers=1: 36.745 s on AWS; no test cases added.

SDK JSON review: 0 entrypoint/direct-signature changes. The 139 reachable exports differ only through 13 equivalent/private declaration sections (digest bbd388f0).

Managed review: no accepted actionable findings. Prior inherited lint failures were resolved upstream (#166841, #166943). Conflict resolution adopts #167012 unchanged and preserves #166985; the remaining patch is identical. Rebased-head proof: 140 affected tests across 7 files, including lint suppressions; runtime/Madge cycles both 0. Full changed checks passed on AWS (851 s); SDK comparison reviewed compatible (271 s).

Per-file coverage: 234 original production files and 28 adjacent/caller files

Positive Δ means production lines removed. All rows were read and evaluated; rejected alternatives were measured where a shared implementation was prototyped. Test/support/generated files are excluded.

src/agents/auth-profiles/

File Δ Applied simplification or retention reason
ambient-auth.ts 0 Retained30 to30: one short-circuit predicate already implements all ambient pin outcomes and provider alias fallback.
candidate-stores.ts 0 Retained181 to181: configured, filesystem and registered sources merge into the existing canonical-path owner. Each source needs different discovery and configured-custody policy.
clone-value.ts 7 Object.fromEntries replaces per-property descriptor construction. It preserves own enumerable writable configurable string keys, including proto, ordering, undefined omission and existing recursive normalization;62 to55.
clone.ts 0 Retained15 to15: cloning must preserve canonical credential observations after detaching data. The two owners cannot be collapsed to a native clone.
constants.ts 0 Retained38 to38: static lock/timeout/freshness constants and postcommit logging isolation are required policies. Budgets are not reduced for LOC.
credential-normalize.ts 0 Retained47 to47: shared static normalization retains key/token-specific deletion and same-object returns. Further projection would need casts or duplicate field descriptors.
credential-observation.ts 0 Retained141 to141: canonical matching is key-order-sensitive after JSON-compatible cloning. DeepStrictEqual or JSON serialization would change its evidence contract or re-encode secrets.
credential-schema.ts 0 Retained67 to67: canonical strict discriminated schema and exported inferred fields are the contract. No schema change is authorized.
credential-state.ts 0 Retained121 to121: static forms already share literal/reference presence. Malformed API-key and invalid token expiry have deliberate diagnostic precedence; OAuth fences stay expired.
display.ts 0 Retained13 to13: one canonical metadata read and display interpolation; no alternate path remains.
doctor.ts 0 Retained50 to50: Qwen migration guidance precedes plugin hints; successful hints retain original whitespace. Single fallback already flattened in PR1.
effective-oauth.ts 0 Retained75 to75: local-versus-bootstrap returns preserve object identity and exact provider-specific diagnostics; an output strategy still needs all these branch facts.
explicit-order.ts 0 Retained25 to25: four lazy owner/alias lookups implement stored-over-config precedence. Eager table construction changes demanded reads.
external-auth-runtime.ts 0 Retained4 to4: direct native binding projection with no additional decisions.
external-auth.ts 0 Retained260 to260: plugin winners and retired CLI overlay owners require separate provenance sets; plugin persistence can be runtime-only or persisted. Deriving source ownership from persistence would change precedence.
external-cli-auth-selection.ts 0 Retained173 to173: the first compatible profile can intentionally have no CLI provider; explicit order and unambiguous automatic selection therefore require separate selected/count state.
external-cli-discovery.ts 0 Retained91 to91: none/existing/scoped constructors preserve omission versus explicit false/empty IDs. Their public option shapes remain unchanged.
external-cli-scope.ts 0 Retained133 to133: model/default and runtime-source traversal preserves order and raw plus normalized IDs. A descriptor registry repeats seven actual source expressions and adds its own iteration.
external-cli-sync.ts 0 Retained300 to300: current MiniMax producer is already narrowed to persisted results. Unscoped existing-profile discovery, explicit IDs (including duplicates), fence refusal and token-proven backfill remain independent decisions.
identity.ts 0 Retained29 to29: profile ID construction and display metadata use different precedence rules; both already use canonical string normalization.
inherited-store.ts 0 Retained98 to98: the generator is already the single sync/async snapshot policy; its persisted fallback is demanded only for the missing owner. Refusal classification must preserve native-path identity.
inline-usage-kernel.ts 0 Retained125 to125: inline health can create an empty credential anchor; selected-profile usage must not create a missing profile. Their error/anchor contracts prevent one unqualified writer path.
inline-usage-publication.ts 0 Retained206 to206: each reader carries its native/mutation authority until publication; per-owner failures are logged and cleaned independently. Sharing the outer publication loop would conflate failure and propagation policies.
inline-usage.ts 0 Retained236 to236: PR1 already shares operation cleanup; release aggregation must retain the original failure as cause, separate from the caught release error. No extra cleanup helper reduced this caller.
inline-usage.worker.ts 0 Measured/reverted after production typecheck: union receipt prototype formatted102 to98, but an object containing a union receipt is not assignable to the two complete tagged result shapes. Complete-result typing costs more than the four-line saving; restored the separate original receipt slots and returns byte-for-byte, without casts or protocol changes.
legacy-flat-credential.ts 0 Retained177 to177: Doctor alias promotion and runtime credential parsing stay distinct; normalization already shares static literal/ref fields. Moving these aliases into runtime would violate migration semantics.
legacy-oauth-ref.ts 0 Retained30 to30: exact source/provider/hex identity is a shipped data recognizer; no fields or validation can be removed.
legacy-source-diagnostic.ts 0 Retained386 to386: merged refusal metadata already shares one source projection. Refusal registration, lifecycle-only clearing and endpoint alias checks cannot be replaced by a filtered credential view.
legacy-source-files.ts 0 Retained90 to90: fixed source candidates include legacy OAuth only for the shared owner; archive discovery always includes it and preserves source-order deduplication. One generic inventory needs both policies.
mutation-lineage.ts 0 Retained227 to227: row, credential, per-profile and set revisions have different eviction/known semantics. Combining floors or lookup tokens would change stale-read and rollback authority.
oauth-identity.ts 0 Retained156 to156: OIDC registration, routing scope and legacy account/email fallback have distinct asymmetric contracts. Preserve missing-field checks and plugin-owned Copilot policy.
oauth-manager.ts 10 one terminal-peer operation with caller-owned failure strategy; formatted1203 to1193. Sync error capture, aggregate ordering and warn-versus-collect policies stay at call sites.
oauth-profile-lock.ts 0 Retained42 to42: stable ordered recursive acquisition prevents deadlock; replacing it with parallel or table dispatch changes custody and lock ordering.
oauth-refresh-error-format.ts 0 Retained49 to49: raw cause traversal and exact-secret redaction precede generic masking; a general formatter would alter unsupported values or cause order.
oauth-refresh-failure.ts 0 Retained512 to512: provider presentations permit absent reason while owner errors permit explicit null; public-cause redaction and private refreshed-store custody remain separate. No normalization or cause traversal semantics changed.
oauth-refresh-fence.ts 0 Retained398 to398: initial selection and post-await CAS have separate authority edges. Serialized refresh retains its native section through settlement; shared classification already serves changed candidates. No marker, deadline or cleanup behavior changed.
oauth-refresh-lock-errors.ts 0 Retained28 to28: one exact timeout/path recognizer and one stable public error factory; removing fields changes recovery behavior.
oauth-refresh-marker.ts 3 one access/refresh marker constructor shares claim ID, version prefix and digest inputs;182 to179. Exact marker bytes, property order and excluded fields stay identical.
oauth-refresh-observation.ts 0 Retained134 to134: target retirement cannot finish an active owner with remaining peer cleanup. Current/replaced targets and settled work remain distinct facts.
oauth-refresh-peers.ts 18 claim validation returns historical-peer eligibility for both initial and CAS-loser paths;453 to435. Exact-fence adoption, external-source refusal and generation checks remain in order.
oauth-shared.ts 0 Retained147 to147: exact credential comparison, safe identity adoption and external overlay persistence are different questions. Data-driven field equality retains the same field inventory without reducing it.
oauth-store.ts 0 Retained179 to179: claim settlement adopts a safe newer owner; rollback can restore only an exact fence and otherwise terminally fences it. Those transitions already share updateOAuthStore and CAS.
oauth.ts 2 static credential resolution reuses the existing SecretRef-key owner;537 to535. Reference-first precedence and published-materialization failures remain identical.
operation-cleanup.ts 0 Retained19 to19: shared outcome capture and cleanup now serve an additional reader; cleanup policies remain with callers.
order.ts 41 prepare requested-provider identity and stored-provider matcher once per selection;352 to311. Every public caller retains its config/metadata lookup context, storedCredential override and existing provider/mode decisions.
ownership.ts 0 Retained68 to68: same refresh generation wins before identity/expiry comparison; inherited-save omission additionally requires local absence. Unifying these predicates would erase their different questions.
path-resolve.ts 0 Retained198 to198: async cache fill rechecks a newer committed owner; reload bypasses initial-root admission limits intentionally. Lock digest bytes are a shipped coordination contract.
paths.ts 0 Measured/reverted: display reader cleanup extraction formatted138 to138 (38 added/38 removed). The pre/post-consume and post-disposal authority checks remain; the adapter added no reduction.
persisted-credential.ts 0 Retained130 to130: filterStringRecord was rejected after inspecting its source: Object.fromEntries retains a proto key that the current ordinary-object assignment drops. API-key versus token ref precedence also differs.
persisted.ts 0 Retained676 to676: store merging preserves separate explicit-undefined state fields, legacy OAuth replacement ordering and per-owner credential provenance. Combining generic map transforms would need different empty-record and reference policies; no semantic-neutral smaller implementation survived examination.
personal-profiles.ts 0 Retained35 to35: prepared and synchronous personal reads already share one materialization owner; these exports retain separate I/O contracts.
personal-store.ts 0 Retained185 to185: caller result can settle before detached OAuth work drains; acceptance and replacement use different live-authority facts. A shared request wrapper would hide the digest/row distinction.
personal-usage.ts 0 Retained50 to50: one actor-bound preparation already serves every personal health reduction with exact-credential reconciliation. It cannot share global snapshot publication.
policy.ts 0 Retained54 to54: OAuth material and static credentials under OAuth config have distinct field inventories and exact errors. The canonical ref parser is already shared.
portability.ts 0 Retained70 to70: one filter already produces copied/skipped IDs and portable profiles; the remaining reason branches are public copy policy.
profile-ids.ts 0 Retained8 to8: shipped deprecated identities remain compatibility constants; removing them is feature/API removal.
profile-list.ts 0 Retained26 to26: deduplication is already a direct canonical alias; provider listing and subscription-mode selection have distinct results.
profile-usage-stats.ts 0 Retained84 to84: typed setStat preserves ordered field projection and classification/reason consistency. Numeric counts, enum fields and optional strings use distinct coercion contracts.
profiles.ts 13 compute optional explicit order once, eliminating duplicate set/clear assignments; all four removal reads now use one physical-owner read operation. Formatted676 to663.
read-only-availability.ts 0 Retained124 to124: false, true and unknown distinguish malformed, resolved and unresolved refs. Token expiry must precede reference availability; OAuth refresh capability has a separate owner.
repair.ts 0 Retained176 to176: legacy ID suggestion chooses configured email, last-good and unambiguous fallback in order; repair separately preserves destination config. A common selector cannot remove those policies.
runtime-external-profile-references.ts 0 Retained198 to198: remove and prune deliberately differ on empty orders, local-ID deduplication, sorting and authoritative empty external IDs. A generic filter cannot replace both without reproducing these policies.
runtime-materializations.ts 0 Retained115 to115: field normalization preserves case-sensitive model IDs, lowercased runtime/API labels and optional profile identity. Generic projection would retain all field-specific transforms.
runtime-persisted-rows.ts 0 Retained117 to117: warm hits avoid filesystem probes; interval hits update checkedAt, cold reads require identity before/after and committed-cacheability proof. A merged hit branch added state or extra probes.
runtime-read.ts 0 Measured/reverted after parent review: shared cleanup formatted656 to651, but awaiting its async cleanup callback introduces a continuation after the final authority check. Retained the original same-continuation assertCurrent, return and active=false boundary; no weaker authority window is accepted.
runtime-scope.ts 0 Retained62 to62: bounded auth and worker-write scopes own distinct authority. Native write allowance cannot be inferred from ordinary read scope.
runtime-snapshot-owner.ts 0 Retained492 to492: local-only metadata differs from shared snapshots; generic composition cannot replace both without carrying this policy. Static-key and token materialization retain distinct typed fields and equality checks.
runtime-snapshot-publication.ts 0 Retained47 to47: current materializations, optional predecessor and external overlays apply in a specific order within the existing shared publication owner.
runtime-snapshot-selection.ts 2 removed unused target revision field/callback; formatted255 to253. Both private target consumers discarded it; real snapshot revisions remain owner-captured.
runtime-snapshots.ts 1 stopped supplying removed revision callback; formatted768 to767. Remaining mutation/publication phases retain their observer order.
selection-error.ts 0 Retained16 to16: fixed public error class payload and exact user recovery text; no duplicate implementation remains.
session-override.ts 0 Retained671 to671: user/person-linked pins, automatic rotation and stale-snapshot CAS are distinct return contracts. Existing key/value assignment primitive already shares mutation without weakening field types.
setup-access.ts 0 Retained100 to100: missing access returns undefined; revoked matching materialization returns null to prevent global fallback. Optional-agent selection and exact-agent materialization intentionally differ.
shared-main-dir.ts 0 Retained12 to12: supported explicit relocation and shipped implicit main path both remain necessary.
shared-store-bootstrap.ts 0 Retained245 to245: empty-store relocation requires source inspection and pending-cleanup proof, while failures remain Doctor-owned. Typed legacy store/state queries retain their distinct result columns.
shared-store-scope.ts 0 Retained50 to50: portability filtering excludes OAuth even when opted in; shared-owner authority remains checked at scope entry. This is not equivalent to ordinary portable copying.
source-check.ts 28 one local/shared provider-source probe keeps runtime, retired-source and canonical-row precedence;258 to230. Collapsed same-result source guards without changing read order.
sqlite-json.ts 37 shared execution for three typed INSERT variants and two DELETE variants, one shared-key inventory, and direct typed Kysely access;262 to225. Queries, keys, JSON serialization, commit recording and timestamps remain unchanged.
sqlite-read-pool.ts 0 Retained185 to185: unadmitted failed-close handles retain custody separately from ready LRU entries; idle retry and root cleanup cannot derive readiness from db.isOpen alone.
sqlite-read.ts 0 Retained277 to277: closed and revoked are independent: disposed readers still validate captured authority, revoked readers always fail. A single phase would remove a tested lifetime; current transport validation stays explicit.
sqlite.ts 0 Retained430 to430: transaction, connection and readonly adapters have different missing/unreadable and caller-owned transaction contracts. Mutations already share one write/delete dispatcher; no raw SQL or schema change attempted.
state-observation.ts 0 Retained56 to56: public console text and structured fields deliberately use different identifier treatments; every emitted key and diagnostic string remains unchanged.
state.ts 0 Retained99 to99: one typed normalization core already owns order, last-good and usage maps with field-specific strategies and ordinary-object assignment semantics.
store-mutation.ts 0 Retained131 to131: legacy refs survive only unchanged inline token material; selection metadata uses different before/after state. Existing diff classification remains owned here, with rollback separately comparing raw snapshots.
store-read.ts 16 one synchronous selected-personal-profile adapter replaces three recursive branches; external-overlay merge computed once. Formatted554 to538; isolated scopes still cannot materialize personal accounts.
store-runtime.ts 0 Retained17 to17: direct native-binding projection; a forwarding wrapper would grow the code and create competing ownership.
store-save.ts 0 Retained138 to138: preserving state/order IDs and suppressing inherited/runtime credentials are independent policies; the existing owner already handles both maps together where semantics agree.
store-unreadable-error.ts 0 Retained15 to15: stable class name/code/action/path and recovery message; reducing fields changes the public error contract.
store-update-commit.ts 0 Retained52 to52: transaction staging must publish only on commit and retain watcher identity until disposal. Unconditional notification would falsely advance rolled-back writes.
store-update-kernel.ts 0 Retained169 to169: env-only callbacks defer canonical reads until they actually save. Credential/state parsing intentionally differs on malformed JSON and must stay inside this worker transaction.
store-update-publication.ts 6 three reader creation sites share captured owner env with explicit database path and optional projected agent dir;224 to218. Per-owner admission, publication and cleanup remain separate.
store-update-transfer.ts 0 Retained23 to23: batching/assembly already delegate to the canonical field transport; array validation and final completion cannot be removed.
store-update.ts 0 Measured/reverted: repeated outcome cleanup extraction using withAuthProfileCleanup formatted565 to565 (47 added/47 removed). Invalidation-before-release and acknowledged-commit cleanup policy consume the apparent saving.
store.ts 18 shared typed snapshot indexing, revision capture and edge projection; formatted 1584 to1566. Raw rollback receipts and per-edge authority comparisons remain unchanged.
store.worker-contract.ts 0 Retained93 to93: operation names, payloads, outputs and receipt fields are protocol contracts, not duplicated implementation. No protocol/type weakening attempted.
store.worker.ts 0 Retained196 to196: personal acceptance, replacement, usage and row read have distinct transaction/commit facts. Combining dispatch would keep every protocol payload and owner callback.
types.ts 0 Retained204 to204: exported credential, persisted state, runtime provenance and error/result types retain every field and discriminant. Schema/type weakening is outside this pass.
upsert-with-lock.ts 3 one authority-map reader runs at both observation and lock-admission edges;406 to403. Neither read is eliminated or moved across lock acquisition.
usage-failure-state.ts 11 billing, permanent auth and rate-limit policies share capped-backoff/deadline assignment; formatted180 to169. Per-reason counters and disabled/cooldown model metadata remain distinct.
usage-kernel.ts 0 Retained101 to101: one worker transaction already reads, validates, reduces and publishes. Success ordering and failure reduction share the transaction while preserving their distinct output rules.
usage-lifecycle.ts 0 Retained131 to131: released unused reservations can execute later work directly, while selected reservations retain FIFO custody. Neither released nor selected is derivable solely from promise settlement.
usage-reduction.ts 0 Retained200 to200: WHAM claims, retry backoff and model-scoped block reconciliation already feed the common reducer. Output undefined keys and old-window preservation are part of the persisted projection.
usage-state.ts 0 Retained379 to379: window clearing already uses one ordered field inventory; matching-model minimum/maximum expiry rules and diagnostic reason priorities are intentionally different reductions.
usage-write.ts 11 capture one agent target per owner and derive reused source path list once; removed unused inherited field from private consumer view (the writer still owns it). Corresponding fixture field only removed; no assertions changed.
usage.ts 0 Retained759 to759: WHAM claim and reconciliation compare different captured generations; current per-owner writes and deferred refresh-error handling are required. Probe result classification already shares output construction.

src/infra/outbound/

File Δ Applied simplification or retention reason
abort.ts 0 Complete source re-read; baseline bytes equal landed PR1. Native throwIfAborted would throw arbitrary signal.reason instead of the fixed Operation aborted AbortError. Keep public error contract.
account-scoped-conversation-bindings.ts 7 Implemented one account-bound binding-id decoder for sync touch, async touch and unbind: 424 to 417 formatted. Released synchronous manager, exact target-kind callbacks, opaque metadata, expiry policy and async owner checks unchanged. Shared projection prototype grew the worker by three lines and was rejected.
agent-delivery.ts 0 Exact recipient, shared-main direct alias, and isolated delivery identity intentionally retain separate authority predicates. Reusing heartbeat policy would merge distinct best-effort and fail-closed contracts; no equivalent common pipeline retained.
base-session-key.ts 0 Complete source re-read; baseline bytes equal landed PR1. Already forwards route fields once to the canonical routing owner with unchanged defaults; no second policy owner remains.
best-effort-delivery.ts 0 Prior branch prototype grew 57 to 66; returning only deliver:false would remove explicit undefined fields. Deliverable normalization and internal-channel downgrade remain separate responsibilities.
bound-delivery-router.ts 6 Implemented requester-match derivation from normalized records (44 to 38), replacing three mutable counters/selections. First exact match and single-scope fallback preserved. Cold missing-requester lookup still admits/creates the store before returning null.
channel-bootstrap.runtime.ts 0 Current source and tests are byte-identical to PR1; full source reread. Shared bootstrap plan/load core already serves sync and async. The async adapter must retain capture, two awaited preparation checks and finally release; a common runner cannot remove these boundaries without making the released sync API asynchronous.
channel-resolution.ts 0 Rejected the formatted shared runtime/activated-surface predicate prototype: 218 -> 223 (+5). The existing generator already shares policy; sync/async drivers preserve authority timing. didBootstrap cannot derive from a possibly undefined result without adding a nullable outcome state.
channel-selection.runtime.ts 0 Complete facade re-read; baseline bytes equal landed PR1. One lazy channel-selection export; deletion moves heavy discovery across its import boundary.
channel-selection.ts 12 Inlined sole-use availability adapter into the existing explicit/fallback loop. Preserve cfg/channel/agent input read order, exact scoped bootstrap options, returned plugin identity and fallback order. No read-only inspection/runtime account policy changed.
channel-target-prefix.ts 0 Single provider strip, repeated normalizer strip, generic kind strip, topic suffix strip and registry-owned provider validation have different grammars and cannot share one parser without semantic changes.
channel-target.ts 0 Complete source re-read; baseline bytes equal landed PR1. Two public human-readable strings and their separate docs are the deliverable. No executable behavior to consolidate.
clawhub-recommendations.ts 0 Plugin and skill card paths have different discovery, failure, installation and icon registry contracts. A fresh common summary formatter prototype measured 126 to 127, so it was rejected. Unique text and card fields retained.
conversation-delivery.ts 0 PR1 already shares existing-operation projection. Live-send confirmation and persisted recovery status use different message-ID precedence and rejection behavior; merging them changes outputs.
conversation-id.ts 0 Ordered targets, explicit prefix extraction including multiline suffixes, provider-native colon refusal, mention and numeric fallback are distinct grammar cases. Existing anchored regex already owns extraction.
current-conversation-bindings.kernel.ts 8 Implemented a typed Kysely conjunction object for the three scoped equality predicates (582 to 574), retaining required scope types and bound-value order. Installed Kysely parseFilterObject uses Object.entries and = for these expression values. Prior common query factory also measured 574 but weakened scope into optional; rejected.
current-conversation-bindings.ts 16 Implemented shared write-admission options across five worker operations: 705 to 689 formatted. Read publication fences remain explicit; mutations settle directly. Existing transaction/commit retirement and worker bind/touch/list tests own proof.
current-conversation-bindings.worker-contract.ts 0 Complete new 31-line IPC owner read. Touch account policy, bind metadata-own-key capture and expected-row comparison, and conversation/session remove union are distinct persisted operation inputs. No runtime code and no duplicate owner.
current-conversation-bindings.worker.ts 0 Full source and worker/retirement/persisted-byte parity tests read. Projection through projectThreadBindingRecord measured 157 to 160 formatted; rejected. Scope, expiry Math.min semantics and write settlement remain explicit.
deferred-delivery-admission.ts 0 Complete source re-read; baseline bytes equal landed PR1. Async adapter preparation and returned authority-checked policy call intentionally straddle recovery continuation fencing. Folding them changes admission timing.
deliver-channel.ts 4 One capability-mismatch return preserves first-failure ordering; media fallback chooses between the already-captured legacy methods before the unchanged authority-fenced dispatch.
deliver-contracts.ts 0 Read complete. Preserve the exact common channel context, different platform-start callback arities, public delivery parameters and private captured-state extension. No sound further reduction.
deliver-core.ts 8 Suppression construction belongs beside the per-payload recorder; error wrapping is inline at its sole call site, retaining preexisting error identity and partial evidence. All diagnostic/observer ordering stays in place.
deliver-handoff.ts 0 Prior recursive prototype 39 to 38 changes public arguments and loses cycle/stack safety. Rejected; exact undispatched retry custody remains.
deliver-hooks.ts 34 Removed two obsolete internal exports after moving suppression recording beside the payload owner and single-caller error construction directly into core. Legacy/projected hook context and capture timing remain distinct.
deliver-log.ts 0 Complete constant re-read; baseline bytes equal landed PR1. One exact diagnostic-scope string; literal rewrite remains two lines and would not remove production LOC.
deliver-payload.ts 3 Combine pin's invalid/disabled guards in the same short-circuit order. Recursive stripping retains sparse arrays, plain/null prototypes, identity reuse and own __proto__ data.
deliver-prepare.ts 3 The existing final undefined filter now owns omission; removed redundant conditional spreads. Keep destructuring exclusions and surviving property order, null reply IDs, literal-true flags, and metadata.
deliver-queue-admission.ts 10 Use existing 15-field send-option projection, retaining captured channel/to and pre-staging rendered plan overrides. Completion/custody/reply fields remain explicit. Queue owner confirmed helper contract is stable.
deliver-queue-execute.ts 12 One acknowledged-delivery finish operation caches the ACK fact, joins existing commit hooks, and emits the lazy terminal; shared audit batch projection. Cancellation, claim loss, pre/post-send evidence and retry ownership remain distinct.
deliver-queue-state.ts 0 Phase-union marker prototype grew five lines; rejected. Public recorder remains exactly four arguments; only canonical recorders receive private captured context.
deliver-queue.ts 1 Reuse the exact live authority assertion at deferred admission and stable-owner lookup, preserving abort/producer-signal/worker-admission order.
deliver-results.ts 0 Map-to-array search saved two lines but copied the full map per match; rejected. Preserve aggregate receipt multiplicity and adapter-invocation match boundaries.
deliver-runtime.ts 0 Complete facade re-read; baseline bytes equal landed PR1. Two retained public runtime exports plus their deprecation doc; no executable implementation.
deliver-transcript.ts 0 Existing warning owner already unifies refusal and exception text. Destination transcript writer fence, lazy runtime loading and accepted-send nonfatal failure remain distinct required stages.
deliver-types.ts 4 Receipt count uses parts, then IDs, then the existing minimum of one; explicit not_sent stays excluded. No types or error contracts change.
deliver.ts 0 Complete facade re-read; baseline bytes equal landed PR1. Compatibility names and deprecation annotations are public SDK; combining exports does not reduce formatted lines without attaching docs to different symbols.
delivery-commit-hooks.ts 0 WeakMap-held callbacks run in registration order and isolate post-send failures. Replacing hooks by one Promise would change lazy invocation and per-hook error settlement.
delivery-completion.ts 0 Unified transition prototype saved five lines but hid distinct owner contracts behind a larger descriptor; rejected. Keep the real completeDurableDelivery success operation and protected caller contract.
delivery-format-prompt.ts 0 One existing renderer already serves reply/message-tool and all account variants. Passing a prepared plugin could reduce repeated lookup work but adds an adapter/parameter rather than removing a duplicate implementation; lazy discovery, account unanimity and exact prompt bytes remain explicit.
delivery-generation.ts 0 Existing error translator already serves preparation and retained assertion. Returning canonical callbacks directly would remove required outbound retry/terminal translation.
delivery-queue-ack.kernel.ts 0 Retained PR1 exact-claim-presence fact and prepared payload projection. ACK, fail-pending, and unsent retirement have different terminal/retention mutations; one mode table would still require every guard and cleanup result.
delivery-queue-ack.ts 0 Fresh formatted optional-cleanup/result prototype 103 -> 113 rejected: generic cleanup sentinel and result plumbing are longer than the two existing conditions. Pre-await options/JSON capture remains explicit.
delivery-queue-enqueue.worker.ts 0 Retained the shared transaction and rollback evidence for random, stable and prepared enqueues. Stable-ID namespace conflicts, preparation CAS and atomic media-stage consumption require distinct branches; merging them would change custody or error classification.
delivery-queue-lease.ts 0 Retained memoized stop promise as the only stopped-state fact. Expiry timer and heartbeat are independent: transient renewal failures retain the last confirmed expiry; collapsing timers would change that contract.
delivery-queue-media-paths.ts 0 Already one source collector and one ordered flatMap/filter/map. Absolute-path collection and release-path validation have different admission contracts and cannot drop either check.
delivery-queue-media-spool.ts 2 One ENOENT rejection handler serves directory and artifact-stat reads. Uses existing fs-safe code classifier; ENOTDIR and all other native errors still propagate. Permissions, staging order, source dedupe, cleanup and retention stay unchanged.
delivery-queue-media-staging.kernel.ts 0 Already shares native stage insertion and atomic retention inventory. Legacy payload extraction and prepared payload extraction accept different shipped row shapes; current conditional is the smallest complete adapter.
delivery-queue-media-staging.ts 0 Thin distinct worker operations; UUID/time capture precedes artifact copying. Cancel intentionally skips absent IDs; folding all calls into a forwarding layer adds another level over executeDeliveryQueueOperation.
delivery-queue-migration.ts 0 Retained PR1 common exact-row CAS, authoritative modifier state and phase-explicit claim path. Phase scans occur after earlier awaited settlement; eager combined inventories change which rows are observed. Lease renewal, raw/prepared checkpoint and media transfer remain separate checkpoints.
delivery-queue-namespaces.ts 0 Already one ordered namespace projection, command authority before session generation. Constants are stored compatibility identifiers and remain identical.
delivery-queue-ownership.kernel.ts 0 Already one namespace descriptor table and batched owner snapshot. Executable ambiguity is checked independently from retired-namespace precedence; neither check duplicates the other.
delivery-queue-pending-failure.worker.ts 0 Exact-claim path has an admitted write transaction; claimless path keeps existing native terminal behavior. Prepared snapshot and cleanup preference are captured before worker execution; shared payload projection already landed.
delivery-queue-platform-lease.ts 0 PR1 shared-claim prototype remained longer (54 -> 59); its public positional signatures differ and the extra command helper/type cannot remove those argument projections. No new sound internal duplication beyond executeDeliveryQueueOperation.
delivery-queue-preparation.ts 0 Retained shared checkpoint queue and single unpublished branch. Renewal joins before publication/cleanup are required; moving those waits to one finalizer changes publication ordering. No remaining duplicate state flag.
delivery-queue-projection.ts 0 Held the existing fifteen-field send-option contract stable while the execution worker reused it. Decoder required-field reconstruction preserves validation without casts; authority namespace checks remain one owner.
delivery-queue-reconciliation.ts 0 Already one capability-to-handler selection. Optional field presence in plugin reconciliation context is deliberately projected; the broader common send-options helper would add fields that are absent today.
delivery-queue-recovery-params.ts 0 Already consumes shared payload/send-option projections. Pending-final command/writer checks are required at separate awaited/synchronous transport boundaries; callback merging cannot remove their checks.
delivery-queue-recovery-policy.ts 7 Removed the second attempt-count implementation; reservation and recovery now use the entry-state owner. Max-retry policy keeps its positive-integer/default-five contract directly.
delivery-queue-recovery.ts 9 Shared terminal success/failure event projection keeps source-index gaps and empty-batch behavior. Success events are fresh typed projections with messageId added last when present, preserving field order without map spreads or plugin mutation. Required reconciliation receipts stay required in inferred result type, removing unreachable synthetic fallback. Uses canonical queue attempt count. Shared scan prototype 1223 -> 1234 (+11) was reverted.
delivery-queue-settlement.types.ts 0 Fresh formatted status-property union 10 -> 10 rejected: loses whole-object discriminant narrowing with no LOC reduction. ACK options remain three independent custody/cleanup contracts.
delivery-queue-storage.kernel.ts 0 Retained separate exact-claim rollback and read-only inventory paths. Rollback verifies the reserved attempt before restoring captured claim fields; inventory orders executable namespaces in one snapshot and rejects duplicate custody. Combining these paths would obscure their different authority and mutation contracts.
delivery-queue-storage.ts 0 Retained PR1 common send-option projection, missing-stage classification, claim-preserving marker factory and read-mode factory. Further universal mutation wrapper repeats command typing/argument adapters instead of removing an owner.
delivery-queue-storage.types.ts 0 Fresh formatted queueName-only alias prototype 17 -> 11 rejected for clarity: hides both complete two-field storage shapes behind a third type and removes spacing solely to share one scalar property.
delivery-queue-types.ts 0 Runtime owner predicate already branches on producer mode after one lease check; the remainder defines retained queue/payload shapes. No duplicate field owner to remove without changing contracts.
directory-cache.ts 0 Complete source/tests and existing LruCache/retained owners re-read. Fresh LruCache.peek prototype 86 to 84 adds byte/recency infrastructure and a new non-null assertion for two lines; rejected. Prior common access prototype 86 to 90 also retained. TTL and config identity remain locally owned.
format.ts 0 Reimplemented shared summary renderer and rejected after formatting: 39 -> 43. Direct and Gateway labels/defaults remain inputs but the helper adds more code than two templates remove.
formatting.ts 0 One exported five-field formatting contract, no runtime or duplicate handler. All fields are independently consumed.
heartbeat-route-context.ts 3 Newly assigned adjacent scope. Implemented one conversation-to-delivery projection for scoped and parent routes. Exact plugin callback order and receivers, thread disagreement refusal, normalization and target revalidation remain. Real Telegram exec-authority suite owns proof.
identity-types.ts 0 Complete type re-read; baseline bytes equal landed PR1. Two-line closed optional record is already minimal and preserves all four public fields.
identity.ts 0 Complete source re-read; baseline bytes equal landed PR1. Four normalized fields and exact four-key object are returned only if any value exists. One identity decision already owns output.
internal-source-reply.ts 7 Implemented sole-caller external-session-route check at the current-source branch: 95 to 88. Preserve provider normalization, private source fallback, no-context denial, config/bootstrap order and all output text. Existing WebChat integration and broadcast validation cases retained.
markdown-details.ts 3 Removed the impossible third tag-kind branch: the fixed private capture grammar is exactly details or summary. Retained bounded traversal and container prefix strategies; their prior shared mapping prototype remains longer (210 -> 211).
message-account-selection.ts 0 Retained two ordered broadcast phases: all availability probes precede account/secret eligibility probes. Async filtering cannot parallelize these callbacks; a serial callback adapter adds a second iteration owner while retaining every branch. Shared account-enabled assertion already owns repeated policy.
message-action-contracts.ts 0 Retained exact discriminated result variants and per-field context projection. Common variant envelope would retain all discriminators/fields while adding an intersection boundary; no runtime duplication remains. Exhaustive send-outcome guard remains a compile-time contract.
message-action-denial.ts 0 Single public error class preserves name and readonly reason/policy fields. No duplicate implementation to consolidate.
message-action-execution.ts 7 Shared local-plugin partial/accepted result construction and annotation (-5), and removed annotation forwarding export (-2). Measured common Gateway error classifier 684 -> 688 (+4); rejected. Gateway reconciliation and exact unknown-send cancellation boundaries remain unchanged.
message-action-gateway-media.ts 0 One staging map owns bounded workspace media loading; return identity is preserved when no URL changes. Attachment projection removes three aliases explicitly; no same-shape second staging implementation exists.
message-action-normalization.ts 0 One existing pipeline owns target aliases, source fallback and final validation. Target-field deletion stages intentionally occur before different checks; merging them would reorder aliases versus validation. No redundant state remains after PR1.
message-action-param-keys.ts 0 One canonical standard-key set and one value-presence predicate. Deriving this from a schema would bootstrap plugin/runtime code and change the ownership boundary; no duplicate dispatch path exists.
message-action-params.ts 12 One content-type alias reader, ordered media-list concatenation, direct private media-cap context, and removed interactive-only JSON forwarding seam.
message-action-result-acceptance.ts 1 Narrowed private annotation return to MessageActionResult used by every production caller, removing the generic assertion. The test now asserts the same toolResult.details content by property path. Paired authority checkpoint wrapper was previously 123 -> 125; current common function would still add two lines and hide explicit before/after checks.
message-action-routing.ts 10 One candidate owner adds raw, unprefixed and optional provider-normalized aliases at the same call sites/order, eliminating three duplicate preparation blocks.
message-action-runner.ts 1 Uses the surviving JSON parser for interactive input at the identical call site.
message-action-send-payload.ts 0 Retained one canonical payload-to-action projection. A shared text setter across this owner and buildMessagePayload requires another parameterized helper while retaining presentation-presence differences; current text/metadata updates remain explicit.
message-action-send.ts 12 One ordered primary/list/attachment entry list replaces a push helper and three assembly paths. Mapped metadata is assigned into fresh objects. Sandbox normalization still completes for all entries before first-wins dedupe. Direct annotation import migrated with parent owner cutover.
message-action-spec.ts 0 Retained exhaustive action-to-target table: default-based sets lose required key exhaustiveness and inherited lookup behavior for raw action strings. Alias callbacks remain selected per call; combining resource and delivery lookup would change callback invocation timing.
message-action-threading.ts 0 Reimplemented shared markReplied mutation prototype and rejected after formatting: 144 -> 145. Existing explicit and implicit consumption use different validation boundaries; retaining captured ref reads avoids changed accessor timing.
message-action-tts.ts 0 One lazy TTS path; dry-run bypass, session-read failure isolation, preference preparation and explicit-TTS override have distinct contracts. Removing any stage changes work or failure ordering.
message-action-write-authority.ts 0 Admission and invocation closure retain different live-authority lifetimes. Prior shared handoff prototype 71 -> 75 remains longer; no scope check or settlement callback removed.
message-gateway-options.ts 0 One normalization/projection owner carries exact explicit undefined fields and managed endpoint policy. Generic picking would need a key list plus timeout/client overrides and would obscure omission/security semantics.
message-plan.ts 5 One owned units collection converges chunked and unchunked text before topology finalization, removing the two-return callback adapter; preserves chunker calls, reply-slot consumption and formatting branches.
message-sent-hook.ts 0 Plugin and internal hooks already share canonical context. Remaining variant branches invoke different event mappers and transports; a shared fire-and-forget adapter keeps all mappings and adds callback plumbing. Captured hook-availability flags are preparation facts, not derivable live state.
message.config.runtime.ts 0 Two-line lazy config facade retains import boundary. Inlining into eager message helpers would load config/runtime early.
message.gateway.runtime.ts 0 Seven-line lazy Gateway facade retains selected imports behind one runtime owner; callers need all four exports.
message.ts 2 Shared direct send/poll target resolution and error propagation, preserving the returned target object's identity and late to reads across awaited preflight; removed one-use preparation bindings. This replaces the previous wider channel-preparation prototype (+5 lines) with the smaller shared target core.
mirror.ts 0 Complete types re-read; baseline bytes equal landed PR1. Seven public mirror fields and two group-correlation fields have distinct required/optional contracts. No executable statements.
outbound-audit.ts 0 PR1 already shares payload-history projection and run-ID resolution. Terminal variants keep correlated status/outcome and forbidden-field types; flattening into independent optional fields breaks the typed audit contract.
outbound-policy.ts 1 One canonical nested policy merge and two distinct cross-context consumers remain. Decoration and rejection deliberately use different current-target precedence/normalization. Applied the formatted direct decoration return (307 -> 306), eliminating a single-use intermediate without changing interpolation.
outbound-send-service.ts 4 Consolidate presentation fallback guards, keeping normalization and rendering lazy in the original order. Plugin partial acceptance and mirror sequencing remain distinct.
outbound-session.ts 0 Retain separate logical capture, physical preparation, best-effort ensure and required bind contracts. Shared source/destination store-path closure measured 394 to 392 but adds a naming-only forwarding layer for two lines; rejected. No protected session owner changes.
payloads.ts 8 Mirror-block variants use one mutually exclusive chain with unchanged block/label order. Raw/structured normalization and JSON/transport/mirror field-presence policies remain distinct.
prepared-batch.ts 0 Kept accepted-only payload projection stable for execution caller cutover. Metadata-aware entries and payload-only consumers remain distinct; map validation preserves accepted-slot cardinality and suppression metadata.
protocol-scaffolding.ts 0 Pattern variants already use ordered tables. Wrapper matching, inline delimiters and standalone canonical stripping have different text grammars and protected-code boundaries; no second equivalent owner remains.
reply-media-entries.ts 0 Existing first-key owner dedupes recovered references, preserving modifier decisions and positional attachment association. Raw legacy media selection differs from sendable media fallback, so no interchangeable helper exists.
reply-payload-normalize.ts 6 Implemented one typed result assembled in original source-field read order: 55 to 49. Kept explicit undefined fields and conditional omission of presentationTextMode/location/videoAsNote, output property order, and public type. Existing Plugin SDK rich payload/location/video tests own proof.
reply-payload-parts.ts 0 Prior common projection prototype grew 61 to 66. Raw legacy count/presence and trimmed sendable media are intentionally different public helpers; output facts preserve all explicit keys.
reply-policy.ts 0 PR1 already derived single-use consumption from the owning reply. Explicit and implicit calls have different identity/omission semantics, so a shared supplier cannot replace both state machines without adapters.
runtime-visible-channels.ts 3 Implemented first-match registry selection through find: 70 to 67. Scoped/root/bootstrap precedence, plugin alias matching and first scoped id order unchanged; runtime-visible channel suite retained. Registered plugin values remain subject to the SDK no-mutation-after-handoff contract.
sanitize-text.ts 0 Fixed-point stripping already shares one loop across empty-tree and tag removal. Table conversion would still retain each regex/replacement grammar and add dispatch. Preserve code marker identity and exact plain/Markdown variants.
send-deps.ts 0 Full source and actual bundled callers re-read; baseline bytes equal landed PR1. Modern direct keys, Ms/MS alternate spellings and explicit legacy keys are all used/released contracts. Existing implementation already owns lookup order in one loop.
session-binding-adapter.ts 0 Full source and external SDK callers re-read; baseline bytes equal landed PR1. Prior same-byte sync/async touch prototype remains 106 to 110 formatted. Awaited mutation settlement and released synchronous callback contracts remain separate.
session-binding-errors.ts 0 Complete source re-read; baseline bytes equal landed PR1. Constructor/class identity, stable error name and typed details are public SDK behavior. Prior move into type owner saved one line but mixed runtime/type boundaries; retained.
session-binding-native-selection.ts 0 Complete current type/symbol owner read. Three unique core-only read symbols plus expected-current mutation symbol preserve private authority identity; no runtime branch or duplicated policy to collapse.
session-binding-normalization.ts 0 Generic normalization preserves caller fields; IPC capture intentionally projects only identities; symbol-bound inspection scope remains frozen. Those three contracts are not interchangeable.
session-binding-service.ts 3 Implemented in-place updates of the private global registration stack (650 to 647). No consumer retains stack arrays; public readers expose adapters or records. Duplicate-graph teardown and stale-adapter async tests retained. Sync and async readers stay distinct because unconditional await changes legacy authority timing.
session-binding.types.ts 0 Current complete type owner read. All fields are public binding/inspection/mutation/capability contracts; the newer inspection union preserves available-with-null versus unavailable. Zero executable statements and no removable internal state.
session-context.ts 0 Declared audit kind and derived policy conversation type intentionally differ; five requester fields already share the typed normalization loop. Public comments document distinct ownership, not duplicated executable logic.
source-delivery-plan.ts 0 PR1 already removed the implicit-target wrapper. Provider identity comparison, account checks and explicit/implicit topic proof are independent guards; visible metadata remains distinct from committed delivery evidence.
source-reply-mirror.ts 0 PR1 already shares send/reply target comparison with explicit mode. Completion, transcript and restart receipt ownership intentionally differ for action variants and partial receipts; merging those entry points would widen ownership.
target-errors.ts 0 Prior table prototype grew the same missing/ambiguous/unknown/reserved error construction; existing shared required-target constructor already removes repetition. Preserve exact messages and denial codes.
target-normalization.ts 0 Prepared-plugin identity, registry-version normalizer cache, reserved literals and signature bytes remain distinct responsibilities. No existing identical 5381/XOR hash owner found in shared/utils/infra/normalization-core. Factoring its sole loop adds indirection.
target-resolver.ts 6 Implemented direct scoped cache-clear predicate and one return for plugin-inferred group/channel kinds (390 to 384). Directory/cache, reserved-literal, plugin precedence, and external scoped-registry tests unchanged.
targets-loaded.ts 0 Complete source/caller re-read; baseline bytes equal landed PR1. Existing shared resolver already owns behavior. Prior loaded-reader factory 18 to 24 still adds an abstraction and risks bootstrap boundary.
targets-resolve-shared.ts 0 Credential/allowFrom/default-target reads retain order; heartbeat alone defers reserved literals to directory resolution. This is already the common loaded/direct/heartbeat target owner.
targets-session.ts 0 Requested channel, explicit target, source channel presence, account ownership and heartbeat thread selection have intentionally different precedence. No state mirror remained beyond fields required in the returned public shape.
targets.runtime.ts 0 Complete facade re-read; baseline bytes equal landed PR1. Retained lazy facade is used by protected cron callers; removing it needs out-of-scope caller/import-graph changes.
targets.ts 8 Implemented shared inputs for heartbeat versus explicit policy resolution and reuse of the resolved route for exec identity checking (672 to 664). Full heartbeat target, owner, and real-plugin exec-authority suites retain exact precedence and messages. A unified four-branch route projection measured 672 to 666 but obscured precedence; rejected.
thread-id.ts 0 Complete source re-read; baseline bytes equal landed PR1. Prior typed alias prototype 8 to 7 changes public function identity/name for one line. Retained named boundary.

src/channels/message/

File Δ Applied simplification or retention reason
capabilities.ts 10 Ordered requirement table replaces individual setter calls; strict true-only accumulation means false extras cannot disable derived requirements.
outbound-bridge.ts 0 Read complete. Preserve dynamically resolved method receivers, optional send-method presence, progress normalization, and owner-fact allowlist.
outbound-echo-state.ts 0 Keep the lightweight shared state module and plugin cold-load boundary.
outbound-echo.ts 0 Read complete. Preserve symbol-backed state, expiry overflow handling, insertion-order pruning, and account/conversation isolation.
receipt.ts 10 Share synthetic part construction for direct results and nested receipts without physical parts, assigning optional fields into a fresh object. Keep authoritative empty receipts, raw result identity, distinct result/part indexes, per-part reply metadata, thread conflict handling, and nested priority.
rendered-batch.ts 0 Read complete. Existing one-pass counters retain ordered media multiplicity and title-only presentations.
reply-pipeline.ts 0 Read complete. Lazy plugin resolution intentionally caches both missing and throwing lookups while reading the cached plugin's messaging property dynamically.
reply-transform.ts 0 Read complete. No existing synchronous map-owner helper; preserve adapter/account identity and method receiver.
send.ts 7 Recipient-reach predicate becomes one left-to-right boolean expression, preserving all failure and suppression evidence. Full send test read complete.

src/agents/

File Δ Applied simplification or retention reason
cli-credentials.ts 10 shared file-reader setup and cache owner now keep each provider cache private without setter callbacks; narrowed freshness strategy to the mtime source every actual caller uses. Original named public functions, TTL bypass, cache key/intent separation, before/after fingerprints and credential payloads remain unchanged. Formatted485 to475.
embedded-agent-subscribe.handlers.tools.results.ts 3 Required caller migration from interactive-only wrapper to canonical JSON parse in the existing catch boundary.
model-auth-availability.ts 3 removed final apiKey-present evidence branch proven unreachable by the earlier identical terminal presence guard; formatted1373 to1370. Source-plan, native readiness, unknown availability, cooldown and route policies remain unchanged. Larger unifications retained because unknown availability cannot use the helper default boolean without changing outputs.
model-auth-model.ts 9 one provider-scoped sentinel operation replaces repeated label construction; formatted440 to431. Every mint still occurs at its original branch and reads the provider then; attached request auth/header and model header policies stay separate.
model-auth-provider-config.ts 0 Retained720 to720: current/source/runtime config provenance and literal/profile/ref/marker precedence are distinct public outcomes. Shared comparison already owns snapshot reuse; replacing record filtering with Object.fromEntries or eager config reads would change bytes or observation behavior.
model-auth-provider.ts 1 the selected-profile and ordered-profile paths share resolved credential projection after their original checks. Formatted673 to672; sentinel minting remains after locked-profile and endpoint validation, with no moved await or public type change.
model-auth-runtime.ts 0 Retained393 to393: synchronous and prepared plugin auth already use one decision owner. Preparation must consume exact completed hook results, including absence, without another lookup; collapsing it with synchronous resolution would add calls or move await/authority boundaries.
tools/message-tool-visible-content.ts 3 Required caller migration from interactive-only wrapper to identical canonical JSON parse operation; no other behavior changed.

src/infra/

File Δ Applied simplification or retention reason
delivery-queue-sqlite-bound.ts -4 Canonical batch inflation helper returns fresh ordered arrays and excludes corrupt rows using the existing single-row decoder. No SQL, row binding, or retention query changes.
delivery-queue-sqlite-claim.kernel.ts 0 Upstream #167012 independently consolidated promote/dispatch. Adopted main unchanged; verified equivalent authority, lease, attempt, reply and recovery behavior.
delivery-queue-sqlite-namespace.kernel.ts 4 Shared pending CAS strategy with explicit mutation and optional synchronous pre-transaction validation. Replacement ID rejection is one exported validator reused by the native and facade owners. Matched-row comparison, bool results, transaction labels and before-open ordering are preserved.
delivery-queue-sqlite-namespace.ts 7 Reuses native replacement input type and the same ID validator before opening write state; the kernel still validates direct callers. No context/env or transaction behavior changes.
delivery-queue-sqlite.kernel.ts 11 Uses batch inflation after staging transaction settlement, exactly where prior map/filter ran. Reservation consumes the same canonical attempt-count policy as recovery; invalid-count fallback and retryCount dominance remain.
delivery-queue-sqlite.ts 0 Read all facade operations. Maintenance native reads, artifact-preserving read-only reads, and live worker reads have different admitted owners. Existing openStateDatabase and executeDeliveryQueueOperation already share the valid mechanics.
delivery-queue-sqlite.types.ts -8 Owns shared attempt-count derivation for native reservation and outbound recovery: nonnegative integer attemptCount or zero, max with retryCount. Existing persisted shape and terminal retention policy unchanged.
delivery-queue-state-context.ts 0 One captured context/env projection. Captured absence of supervisor mode must stay explicit; conditional object spreading preserves that boundary and cannot be replaced by ambient defaults.
delivery-queue-worker-store.ts 0 Already one typed command executor; one captured worker admission is carried into the operation. No per-command wrappers remain in this owner to consolidate.
delivery-queue.worker-contract.ts 0 Four-line mapped operation contract derived from the registry; no copied protocol declarations or runtime branch to remove.
delivery-queue.worker.ts 1 Measured matching-reader factory 501 -> 500 applied. Only findIntentOwners, inspectReceipt and mediaRetentionSnapshot share it; undefined-input/count and write handlers keep their exact signatures and policy.

@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 the agents Agent runtime and tooling label Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

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

  • Current SHA: 29e3fe383e827dbe69ac671c7551398d7e381423
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/clone-value.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-manager.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-refresh-marker.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-refresh-peers.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/order.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/profiles.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/runtime-snapshot-selection.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/runtime-snapshots.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/source-check.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/sqlite-json.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/store-read.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/store-update-publication.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/store.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/upsert-with-lock.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/usage-failure-state.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/usage-write.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/cli-credentials.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/model-auth-availability.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/model-auth-model.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/model-auth-provider.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 5:30 AM ET / 09:30 UTC (Revision 2).

ClawSweeper review

What this changes

The branch consolidates credential selection, publication, caching, outbound preparation, queue operations, and receipt construction into shared internal implementations.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful consolidation with no actionable defect found, supported by substantial reported owner-level validation rather than shipped-entry-point proof.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: This maintainer-authored internal refactor is outside the ordinary external-contributor proof gate. Reported tests exercise auth and delivery owners, while the inspected Telegram images belong to related progress work. No materially changed authority boundary was established. Source comparison verifies unchanged storage contracts and a no-migration upgrade case.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: The established area owner continues an existing consolidation campaign, reducing repeated implementation without adding product surface. The inspected patch retains the contracts that motivated earlier ownership and lifecycle work.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-owned PR remains useful, and no actionable defect or merged replacement was established. The inspected changes preserve existing behavior.

Priority: P3
Reviewed head: 29e3fe383e827dbe69ac671c7551398d7e381423

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No shipped-entry-point run of this refactor is established; supplied validation exercises production owners through tests and synthetic channel fixtures. This is preservation work, so a failing-base regression is not claimed.
Agent review details

How this fits together

Authentication profiles supply the credentials used for model requests. Outbound delivery prepares messages, retains durable queue custody, invokes channel transports, and records delivery results.

flowchart TD
  A[Model request] --> B[Credential selection and publication]
  B --> C[Authenticated model execution]
  C --> D[Outgoing message]
  D --> E[Preparation and durable queue]
  E --> F[Channel transport]
  F --> G[Receipts and settlement]
Loading

Technical review

Best possible solution:

Retain the shared implementations while preserving the existing credential, delivery, and public SDK contracts.

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

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

Is this the best way to solve the issue?

Yes: the inspected consolidations reuse existing owners, migrate internal callers, and retain distinct scope, recovery, and settlement policies.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness. Added test files: 2.

Security

None.

Evidence

What I checked:

  • Pinned introduction and merge composition: Reviewed the introduced merge-base-to-head hunks. The raw test-merge commit records the supplied main SHA followed by the exact PR head as its two parents; its auth-store delta retains the same proposed refactor. (2c237758a7d5)
  • Complete PR-body context: Retrieved the complete body rather than relying on its supplied prefix. Captured body identity: SHA-256 291878a2919b191579330e227bd71a38caef5c4fa692a8632f0b6eedff7da748. It reports prior-head build and 3,459 tests, rebased-head affected tests and changed checks, and an SDK comparison with no entrypoint or direct-signature changes. These are contributor-reported validation results, not reviewer-executed proof. (29e3fe383e82)
  • Credential isolation preserved: The shared synchronous adapter materializes a selected personal credential only outside isolated scopes. The production scope owner marks every bounded runtime mode, including environment-only mode, isolated; the suspected environment-only bypass regression is therefore disproved. (src/agents/auth-profiles/store-read.ts:151, 29e3fe383e82)
  • Scope owner: captureScope derives isolation from the existing runtime mode, preserving the personal-account exclusion used by the consolidated reader. (src/agents/auth-profiles/store.ts:1028, 29e3fe383e82)
  • Verified no-migration case: Auth-cell writes retain JSON serialization, table and key selection, timestamp columns, conflict updates, and commit recording. Queue entry fields, namespaces, replacement-ID checks, pending-row comparison, and attempt-count policy remain equivalent; no schema or persisted-format migration is introduced. (src/agents/auth-profiles/sqlite-json.ts:178, 29e3fe383e82)
  • Live admission checks retained: The extracted binding-write options retain database admission, caller currentness, and transaction-stage agent-resolution checks at the original worker boundaries. The inspected refactor does not materially widen authority or extend its lifetime. (src/infra/outbound/current-conversation-bindings.ts:67, 29e3fe383e82)

Likely related people:

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

PR surface

Source -542, Tests +3, Other -1. Total -540 across 72 files.

View PR surface stats
Area Files Added Removed Net
Source 68 856 1398 -542
Tests 3 7 4 +3
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 72 863 1403 -540

Stored data model

Persistent data-model change detected: serialized state: src/agents/auth-profiles/oauth-manager.ts, serialized state: src/infra/delivery-queue-sqlite.types.ts, unknown-data-model-change: src/agents/auth-profiles/oauth-manager.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Labels

Label changes:

No label changes.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-08T06:33:58.809Z sha f01148f :: needs maintainer review before merge. :: none

@steipete

steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Exact-head CI attribution

Reviewed head: 29e3fe383e827dbe69ac671c7551398d7e381423. All check runs were enumerated through the paginated commit check-runs API. The only failures are:

Check Attribution and proof
checks-node-changed-2 Two unchanged Discord quiet-progress E2E assertions reject the bounded work-status text introduced on main by #166861. Independently reproduced both failures on a fresh, main-only checkout at 2f1f73ccb2224bbe7d961b4c0d3b29cfdd51e7f8, without any PR2 commits or test edits.
openclaw/ci-gate Aggregates the failed Node shard above; there is no separate failing test, lint, type, baseline, or other guard job.

The cancelled PR context/evidence run was rerun as required. Run 37756174838, attempt 2, completed successfully on this exact head. The complete census has 98 successes, 50 workflow-selected skips, one informational CodeQL neutral result, and the two attributed failures; no cancelled or pending checks remain.

Independent main reproduction

The fresh checkout was clean and frozen-installed once. Its head was 2f1f73ccb2224bbe7d961b4c0d3b29cfdd51e7f8, tree 4233ce4507cefe3918a50e5e3cd640390cd5bd07:

node scripts/run-vitest.mjs test/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts -t 'renders discord progress .*toolProgress=false'

Both selected cases (failTool=undefined and failTool=true) fail at line 1782 with the same assertion as CI: progress must not match /\b(?:Exec|Bash)\b/u, but it contains Exec: running. Main additionally records Last activity: Exec. The other 14 cases were outside the filter. The tests and assertions were not edited, and no timeout, retry, baseline, or suppression was changed. Exit was 1, with two assertion failures; the tracked checkout remained clean after execution.

CI actually executed merge 2c237758a7d594148a987dba42f88a94a40f35d0 (this head into main parent 5a060dd1e18e3181a4addd3b7b761f0d1c82f2a9). That parent includes #166861. Fresh main 0acc55cfa8a973f9d1764f7641f41e5a38e88abe retains the same producer, compositor, work-status projector, Discord draft transport, and failing-fixture blobs as the reproduced main.

No overlap with the failure's production path

The text follows the unchanged exec-start item producer → Discord progress handler → showWorkStatus: true compositor → quiet work-status projector → direct Discord REST draft post/edit. Those files and the E2E fixture are absent from this PR's changed-file set. The new main compositor test explicitly requires Exec: running with detailed tool logging disabled. The old E2E assertion conflates those bounded status labels with detailed tool rows.

The PR's interactive-parser cutover runs only for messaging-send completion. This fixture fails during its earlier exec operation, before its later message-tool invocation. The changed outbound queue, receipt, and durable-send paths do not construct or send the offending progress row.

The follow-up belongs to the upstream progress test owner: reconcile this E2E oracle with the approved bounded-status behavior while retaining privacy and explicit-off assertions. It is not changed in this refactor.

Review and compatibility disposition

The exact-head ClawSweeper review reports no findings and no before-merge items. Its automated stored-data flag was checked against source: oauth-manager.ts only shares identical peer-fencing calls/error handling; DeliveryQueueEntryState is unchanged, with an internal counter helper added beside it; SQLite table names, keys, JSON serialization, timestamps, conflict updates, and stored fields are retained. No schema or migration change is introduced. The full SDK JSON likewise has no public entrypoint or direct-signature changes; its complete reachable differences are equivalent types or private implementation declarations.

Prior head f01148fd46e7 passed the full build, changed checks and 3,459 behavioral tests. The conflict-only rebase adopted upstream #167012 unchanged and preserved #166985; the remaining patch is identical. This exact head passed all changed checks, 140 affected tests across 7 files (including lint suppressions), zero runtime/Madge cycles, and the reviewed full SDK comparison (digest bbd388f0). This attribution supports the standing main-red merge exception pinned to the reviewed head, without treating the failed CI attempt as green.

@steipete
steipete force-pushed the deslop/d12-p2-20261007 branch from f01148f to 29e3fe3 Compare October 8, 2026 09:22
@steipete
steipete merged commit d3309e5 into main Oct 8, 2026
151 of 155 checks passed
@steipete
steipete deleted the deslop/d12-p2-20261007 branch October 8, 2026 09:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…penclaw#167002)

* refactor: share outbound dispatch and auth selection primitives

* chore(outbound): shrink removed assertion baseline
steipete added a commit that referenced this pull request Oct 11, 2026
## What Problem This Solves

Agent runtime bookkeeping repeatedly restarted otherwise valid work when configuration, plugin, or catalog metadata changed during an asynchronous operation. This maintainer-requested simplification removes that speculative retry machinery.

## User Impact

Normal model selection, tool execution, credential checks, FIFO scheduling, and shutdown settlement remain. A request racing a reload may fail visibly and be retried by the caller; passive metadata may remain at its captured version until the next refresh. No configuration, protocol, SDK, schema, durability, retention, or permission contract changes.

## Why This Change Was Made

Prepared runtime acquisition and remote catalog adoption now take one preparation path rather than repeatedly rebinding and rebuilding. Admission still handles the concrete drain, retirement, and failed-activation recovery stages. Cache publication keeps its final currentness check; tool and credential effects keep their authority checks. Steering and Tool Search retain their actual owner, FIFO, and settlement contracts without comparing unrelated metadata.

Production: **519 net lines removed**. Tests that exclusively required the removed synthetic interleavings were removed with them. Open-parent borrowing, pending-auth cancellation, explicit MCP acquisition config, and queued-tool implementation checks remain. No new lint suppressions, timeouts, retries, or skips were added.

Scope proof also caught two nearby correctness issues: an earlier MCP reload could overwrite a new caller's explicit configuration, and snapshot reconciliation could prepend a separator to a later text block. Both are fixed with their existing boundary tests. Bootstrap fixtures now test the no-clobber fallback already shipped by the pinned fs-safe version; no dependency or storage policy changed.

## Best-effort tradeoffs accepted

| Removed guard | Provenance and accepted result |
| --- | --- |
| Per-batch context projection cancellation | #119607 measured the value of cooperative yielding; its mid-batch cancellation callbacks were synthetic coverage. Yielding and the final publication check stay; obsolete pure computation may finish unused. |
| Mixed-version module/cache repair | #119607 seeded an old global singleton inside a synthetic process. Normal upgrades restart the process; unsupported mixed-version module replacement no longer repairs that marker. |
| Runtime acquisition retry/rebind loop | #128138/#127217 exercised forced reload timing. A racing request now returns a visible supersession error; the next request uses the current owner. The actual no-spin incident in #153313 remains addressed. |
| Configured-generation re-admission | 171df4e / #168410 adds re-admission for a gated Docker reproduction with a catalog publication 0.3s after admission, not a human-user incident. A superseded request now fails visibly. Parent confinement remains fail-closed, with its security test retained. The retry-only WeakSet and two retry-specific tests are removed. |
| Repeated passive owner selection | a718c1c / #162484 added recursion alongside the real self-drain fix; that incident did not require recursive reselection. The self-drain refusal stays. Reads use one captured owner or fail visibly, rather than recursively trying later publications. |
| Remote catalog config reread/per-attempt cancellation | #158000 used synthetic config/auth churn. Adoption reads once and prepares once; an overlapping change can defer adoption until the next normal catalog check. |
| Parent-generation cancellation subscriptions during adoption | 504d290 / #158000 used the same synthetic churn. Parent replacement may leave bounded preparation running until its final owner/config check rejects it. Shutdown cancellation, candidate-retirement aborts, cleanup, and the final serialized effect check remain. |
| Three-attempt catalog adoption settlement recovery | The same synthetic churn caused a second retry protocol around owner publication. One attempt remains, with one final checked atomic rows/pricing commit. |
| Duplicate early publication checks/error relabeling | Same-tick checks and concurrent-change relabeling did not guard an effect. The final effect check stays; failures retain their actual reason. |
| Auth-batch sibling retry after supersession | f3c52bd / #152467 used synthetic tests that superseded one owner during a sibling build. The operation now settles with its original error instead of selectively rebuilding siblings. Credential authority checks remain. |
| Post-await cache-stale generation check | No human incident supports fencing this metadata flag. A config/auth change during discovery can let the older load clear a reused owner's stale marker; discovery may remain stale until another explicit refresh/reload. This does not grant credentials or execution authority. |
| Passive harness catalog cancellation | #134524 fixed the actual availability report #134460; replacement/closure guards were additional synthetic hardening. Completed discovery rows are retained, and later discovery observes replacement. |
| Native binding clock-only rechecks after worker waits | #158396 used clock-jump fixtures. An expired but unreplaced exact row can finish its prepared bookkeeping mutation; CAS takeover detection and current mutation authority still gate commit. One exact, unexpired lease check gates protected callback entry, and live effect assertions remain. |
| Tool Search ancestor reentrancy tracking | #140767 covered synthetic nested control calls, not a reachable production control target. FIFO/exclusion and real implementation settlement remain. |
| Complete steering metadata fingerprint | #163195 recorded a real production ordering/ownership incident. Its owner, pending-row, result-authority, and lease checks stay; metadata-only edits no longer invalidate already-captured prompt bytes. |
| Repeated MCP acquisition/reload replay | #138694 used synthetic crossed-publication choreography. A new runtime catches up once; later reloads target the published owner. A racing creation can fail and reconnect on the next acquisition. |
| MCP tools/list invalidation generations and replay | #125541/#125564 describe isolated protocol stress fixtures. A notification inside tools/list no longer triggers immediate replay; the next notification or explicit refresh replaces the inventory. Normal exit/reconnect, bounds, validation, and cleanup remain. |
| Failed-start replay crossed by config publication | #158088's test forces a config publication into an in-flight failed initialization. That request may now report its first failure; ordinary backoff and explicit-refresh retry remain. |

## Evidence

Candidate head: `d72afea0c17a45c677977e23937049d7c7fc43ec` (tree `51daca08d7288e906188bc25ec3d1896bf841349`).

Final exact-head CI: [run 38132644989](https://github.com/openclaw/openclaw/actions/runs/38132644989) completed successfully; all 82 jobs terminal with no failed or cancelled jobs. Full head-bound check census also confirms the CI gate and applicable security checks passed. Earlier failed/cancelled attempts are described below, not represented as passing proof.

- Independent P2 reviews completed. The catalog-staleness, duplicate steering metadata fingerprint, and auth-sibling retry findings are explicitly accepted tradeoffs listed above; steering result facts and destination eligibility remain checked at their owners. The latest native-lease callback-entry finding was accepted and fixed with one live lease check instead of restoring per-write expiry callbacks. Its new fake-clock regression failed before the fix by entering the protected callback after expiry.
- Conflict-only integration kept main's three repaired test fixtures byte-for-byte. All **22 conflict tests** passed (cursor, sandbox, bootstrap publication, lint suppressions); affected root/tools test graphs, core types, typed lint and both cycle checks passed. Runtime and Madge cycles remain **0**.
- The native callback-entry fix passed fresh P2 review and **24 focused tests** (21 native binding tests plus 3 lint-suppression tests), wrapper 212.01s; native test project 164.77s including 113.11s compiled-worker preparation. The added fake-clock case performs no real wait; the existing native suite exercises authority and worker settlement. Final affected types and typed lint are checked before push.
- CI run `38125430266` found one owned stale expectation: the remote-catalog integration still forced config/auth replacement while pricing was paused and demanded the removed immediate retry. Only that scenario was removed; both schema variants retain normal publication, pinned pricing, input validation, worker recovery and disable coverage and pass locally (141.35s project), with gateway test types, typed lint, lint suppressions (3/3), and fresh P2 review passing.
- The other root failure, `checks-node-changed-compact-small-11`, independently reproduced on clean main `fd1fd2ce0ef8cb7e9c4074c8f855eff8992a54c2`: `embedded-agent-runner.prompt-cache.test.ts` responses and in-history both raised `SqliteTranscriptMutationConflictError` in the session actor append path (2 failed / 2 passed). Investigation found a cold actor snapshot prevented the existing implicit-watermark retry. Fixed directly on main as `e65bd3be4134f1453bb4ab26e68704c678086b58` and integrated here: all 4 prompt-cache cases and 35 session-manager siblings plus lint-suppressions pass, including explicit stale rewrite refusal. The repair passed types, typed lint and fresh P2 review.
- Follow-up CI `38127338915` reached one more synthetic-only case: compaction's `mutate=input` row changes an internal selection object after starting acquisition. Removed only that row/branch under the campaign rule; five remaining compaction cases pass, along with lint-suppressions, affected types, typed lint and fresh P2 review. Its provenance is `c131ec041e1` / #139429, not a human report of post-call input mutation. The final conflict repair keeps main's equivalent streaming/steering refactors, removes the obsolete retry predicate, and passes 49 owner tests plus lint-suppressions. Cancelled jobs are not counted as passing; final-head hosted CI remains the gate. No CI job was rerun.
- CI `38130432441` had one inherited fixture failure: three `sessions-mutations.catalog-queue` cases selected their configured default while expecting override fields, after #169030 intentionally made that selection a default reset. Integrated main's existing fixture-only correction `194a08e59632`, retaining all assertions. The corrected file passes all 14 cases on clean main under Node and Bun; the three affected cases also pass under Bun on this branch (249.87s project, mostly transformation). Exact-head hosted CI remains the final gate.
- Focused effects suites: **43 passed** across inbound-registry, remote-publication, hot-reload-dispatch and tool-search-scheduling. This includes cancellation, parent confinement, ordinary rollback/failed-activation recovery, and queued implementation replacement. Single-worker wrapper 752.15s including 142.017s compiled-worker preparation; infra 432.15s and agents-core 115.09s. Final restored remote-publication file: **7 passed**, including first reply crossing catalog adoption and exact derived-parent confinement; wrapper 372.77s (184.30s worker preparation; 131.87s Vitest). These loaded-host timings are not a performance claim.
- Integrated native-binding suites: **20 passed**, including exact token cleanup, successor protection, and revocation. The same command passed all **3 lint-suppression tests**. Single-worker wrapper 354.47s including 145.31s worker preparation.
- Current core types and native-binding test graph passed; runtime cycles **0**, Madge cycles **0**; changed-file typed lint passed. The full changed-check run reached an old-base UI duplicate-import error already fixed on main by `48588a65222`; that fix was integrated and the affected UI graph passed. Remaining type graphs and static guards were completed separately without changing baselines.
- Isolated Linux scope run and canonical remaining projects exercised **19,900 passing tests**. Eight failures were investigated: three pinned removed synthetic retry paths and were deleted; five exposed the correctness/fixture issues described above and were repaired with focused proof. Existing platform skips were unchanged. This is combined incremental proof, not a claim that one final-head all-scope invocation was green.
- Final repair suites: **71 passed** across passive runtime, SSE recovery, startup backoff, bootstrap, stream reconciliation/markup/phase coverage; **12 passed** across sandbox/cursor coverage, followed by **2 passed** for the real-append cursor fixture. Final MCP regression retained stdio-exit recovery and HTTP failure semantics; it passed 64 cases but hit two unchanged local child-start deadlines (1s/2s). Those initial-start paths passed on the isolated Linux run; no timeout, retry, or skip was changed to mask the local failures.
- Full-core Linux lint passed with 13 existing max-lines warnings, none in changed files. Deadcode identified and drove removal of the unused owner-publication helper. Remaining findings were in unmodified config/state/Gateway/UI files. A separate fresh current-main checkout (`f4d601a006`) passed production deadcode and failed full-tree deadcode only on the unrelated `readActiveGatewayLockPortMock` export. The PR does not change any deadcode baseline.
- Blacksmith Testbox did not admit a runner within 15 minutes; AWS quota pressure supplied an undersized instance, which was released. The authorized Hetzner fallback supplied the Linux proof above. All owned remote leases are stopped. Hosted CI on the exact final head remains the landing gate; no CI jobs were rerun.

<details>
<summary>Audit coverage ledger and retained boundaries</summary>

| Mechanism (base lines) | Scenario and provenance | Decision |
| --- | --- | --- |
| context-cache-projection.ts:145-213, context.ts:87-109,146-169 | Cancellation/replacement during pure batched metadata computation. bf7840f / #119607 fixed a measured multi-second RPC stall by yielding and atomic publication. Mid-batch authority callbacks were extra cancellation machinery; no effect occurs in projection. | REMOVE repeated projection/early checks; KEEP cooperative yields and the caller's check immediately before publication. |
| context-runtime-state.ts:33-38 | bf7840f / #119607 seeds an old global singleton and new cache module in a synthetic child process; no human report of mixed code versions within one live process. | REMOVE old-module/cache-pair normalization, its only reuse flag, and the synthetic migration test. Ordinary process startup and same-version bundled singleton sharing remain. |
| prepared-model-runtime-lease.ts:149-164 | 8720fbf / #153386. Human report #153313 by stackingrockss includes the deployed Docker version, profiler samples, and repeated boot-loop observations. Its infinite retry was caused by non-idempotent runtime selection normalization. | KEEP normalized owner selection and a visible error when a settled replacement never published; REMOVE the acquisition retry loop entirely, so it cannot spin. |
| prepared-model-catalog-worker.ts:71-220 | 349aef7 / #150354. Human report #149538 by 609NFT describes copied production fleet state, 632 agents, 504 failed health probes and growing RSS. #161738 by matthematics1137 reports 92 worker lifetimes, OOMs and 1.285 TB written. | KEEP one bounded shared worker, borrower cleanup, failure logging, and ordinary crash recovery. These are measured resource and real concurrency contracts, not permission to retain unrelated reload fences. |
| prepared-model-runtime.refresh-scope.ts:240 | d56279c / #151597 by obviyus describes a controlled worker crash and synthetic Gateway regression, not a human production report. Later #161738 independently establishes actual recurring worker failures. | KEEP source-bound failure reporting and bounded recovery to avoid reintroducing the observed restart/discovery amplification. The #151597 PR alone is not accepted incident evidence. |
| prepared-model-runtime.resources.ts:30-127 | 73b4086 / #143109 contains native regressions and synthetic compiled CLI/Gateway proof, no linked human incident. | KEEP physical resource claims until ordinary concurrent borrowers settle and shutdown joins their cleanup; these are required cleanup mechanics, not a blanket historical-incident exemption. Inspected the complete resource owner; no extra reload retry protocol lives here. |
| prepared-model-runtime.plugin-lifetime.ts:230-319 | 382c987 / #159448 links #157842 by highfly-hi: five-agent Linux deployment with catalog-worker heap increasing 70-80 MB per scheduled turn, watchdog restarts and before/after version evidence. | KEEP final registry-reference release, current execution authority, and ordinary borrowed-resource settlement. Retained memory claims are scoped to physical lifecycle, not all historical publication machinery. |
| prepared-model-runtime.lifecycle.ts:101-164 | a718c1c / #162484 by jalehman records actual lossless-claw maintenance calls stuck about 45 minutes during reload until restart. a3e4005 / #162301 explicitly says synthetic Gateway, no production deployment. | KEEP refusal of plugin work waiting on its own drain and process-close settlement. #162301 is synthetic evidence, not an independent incident exemption. |
| prepared-model-runtime-lease.ts acquisition loop and borrowed-generation branch | 79e6755 / #128138 and related #127217 describe synthetic QA-channel/config replacement tests; #127217 explicitly reports that its pre-fix real-Gateway run still delivered replies. Retained inbound-registry tests exposed ordinary nested selected-parent borrowing as a distinct contract. | REMOVE retry/rebind loop. KEEP exact open-parent borrowing and selection confinement; a reload during new acquisition may fail that request visibly. |
| prepared-model-runtime.published-owner.ts:91-203 | a718c1c / #162484 added retry/recursive rereads alongside the real plugin-drain repair. That incident justifies self-drain refusal and ordinary settlement, not recursive passive owner reselection. | REMOVE repeated rereads/retries; wait once, then project or activate once. Pure catalog-stale bookkeeping no longer revalidates generation after its await. |
| prepared-model-runtime.configured-refresh.ts remote catalog adoption | 504d290 / #158000 has explicitly synthetic config/auth churn and fixture-provider proof; no human incident cited for the reread loop, per-attempt controllers or three-attempt owner settlement recovery. | REMOVE those race-specific retries, plus early duplicate currentness checks/error relabeling. KEEP the final owner/authority check, atomic rows/pricing commit, current catalog ordering, and ordinary cancellation/disposal. |
| prepared-model-runtime.configured-refresh.ts:396-430 parent subscriptions | 504d290 / #158000; same synthetic churn proof. Parent-generation subscriptions duplicate the final owner/generation/config check. | REMOVE parent-generation early cancellation listeners. KEEP shutdown and candidate-retirement cancellation, bounded work, cleanup, and the final serialized effect check. |
| prepared-model-runtime.owner.ts:612-631 batch supersession retry | f3c52bd / #152467. Tests force one auth owner to supersede while a sibling is building. No independent human incident identified for sibling retry. | REMOVE retry of the surviving batch; retain source-bound credential/current-owner checks and report the original publication failure. |
| prepared-model-runtime.owner.ts:124-134 unused publication probe | dd2d66c / #130856 introduced a helper returning matching/pending publication facts for acquisition retries. Its callers are gone; full-repository search finds only the definition. | REMOVE the dead helper/export. Credential-refresh cancellation remains supported by the direct, abortable configured-owner wait and its unchanged regression tests. |
| sandbox/registry.kernel.ts:396,420; sandbox/registry.ts:295 | 2889a99 / #151172 is not treated as an incident report. Read-only admission accepts older schemas; tableExists consumes admitted schema.tables facts, not repeated SQL/format validation. | KEEP the existing absent-table empty/null contract. No runtime foreign-commit or repeated validation probe exists in these calls. |
| harness/native-session/binding-leases.ts | cfef174 / #158396 moved writes to workers; elapsed-time rechecks were covered by synthetic clock-jump tests. 283d5e6 / #164197 supplies native successor authority behavior, not a blanket exemption. | REMOVE prepared callback plumbing and post-worker wall-clock-only rechecks. KEEP exact-row CAS, token/phase/failure checks, current mutation authority, bounded acquisition, renewal, and write settlement. |
| harness/context-engine-logical-turn.ts | #143491/#140023 supply synthetic lifecycle tests, not qualifying human incident evidence. The owner actually holds resources used by outstanding context-engine work. | KEEP ordinary work completion and deferred disposal until implementation settlement; no extra synthetic reload retry was retained here. |
| harness/model-catalog.ts:168-177,242-284,353 | 6c44634 / #134524 repairs human availability report #134460. Passive replacement/closure branches were additional maintainer hardening and synthetic variants, not that report's failure. | REMOVE passive isCurrent callbacks and ambient registry replacement checks. KEEP exact owned registry/config, provider outcomes, discovery, selection and the actual availability repair. |
| auth-profiles/oauth-refresh-peers.ts | #166183/#167002/#166659 are not claimed as human incident evidence. Refresh credentials rotate/revoke and carry account identity; copied historical peers must not replay spent tokens or inherit another account. | KEEP these credential/identity effect boundaries and ordinary uncertain-write settlement. No auth-profile schema, secrets, permissions or durability changes. |
| worktrees lifecycle/removal | Audited run-lease-owner.ts, service-preparation.ts, eviction.runtime.ts and gc-removal.ts. They coordinate destructive removal of user artifacts with live checkout/source handles, exact refs and ordinary parallel sessions. No PR title is treated as incident evidence. | KEEP current-row removal/exclusive source checks and rollback/cleanup custody for writes and deletion. Removing them would risk user artifacts, independently prohibited by the data-loss boundary. |
| tool-search-scheduling.ts | 9b93fc8 / #140767 adds ancestry reentrancy and queued object/mode identity checks with automated interactive/headless regressions. Production catalogs exclude control tools; recursive calls using the same runtime were synthetic only. | REMOVE unreachable nested-call ancestry. KEEP one exact queued implementation/mode check at the effect, catalog-ID authorization, FIFO/exclusion, abort and implementation settlement. |
| agent-steering-queue.ts:194-263 | 3f761a8 / #163195 records Peter's actual three-day production errors. The incident justifies owner/FIFO repair, not a fingerprint of every result label/task/time/outcome/origin/transcript field. | REMOVE full payload fingerprints and deep-equality invalidation. KEEP run-owner identity, prepared result authority, current requester store, pending-row effect checks, FIFO, exact lease/status acknowledgment and release. |
| agent-bundle-mcp-manager.ts and manager-install.ts | 89c1a09 / #138694 reports synthetic fail-before/real-transport proof but no cited actual-use incident for repeated crossed-publication acquisition/reload. | REMOVE the acquisition retry/rebind loop and repeated reload replay. KEEP the runtime-key queue, ordinary cleanup, one postcreation config catchup, requester credentials/authorization and live tool effect checks. |
| agent-bundle-mcp-runtime.ts catalog generations | 1cf8ea4 / #125564 and follow-up 1d03e5d / #167642 have synthetic notifications/listing interleavings, not human reports for replaying tools/list during its own response. | REMOVE catalog invalidation generations, replay of a notification arriving inside tools/list, and the impossible repeated replacement-retirement loop. KEEP listing single-flight, caching, bounds, diagnostics, normal reconnect, one retry for an actually exited previously healthy server, and execution authority. |
| prepared-model-runtime-lease.ts / plugin-lifetime.ts configured-generation re-admission | 171df4e / #168410, landed during this lane, describes a gated Docker reproduction with catalog publication 0.3s after admission, not an actual human-user incident. | REMOVE configured-generation retry and its now-unused WeakSet plus the two retry-only tests. KEEP fail-closed superseded-generation rejection and the new derived-parent confinement security test. |

</details>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…168981)

## What Problem This Solves

Agent runtime bookkeeping repeatedly restarted otherwise valid work when configuration, plugin, or catalog metadata changed during an asynchronous operation. This maintainer-requested simplification removes that speculative retry machinery.

## User Impact

Normal model selection, tool execution, credential checks, FIFO scheduling, and shutdown settlement remain. A request racing a reload may fail visibly and be retried by the caller; passive metadata may remain at its captured version until the next refresh. No configuration, protocol, SDK, schema, durability, retention, or permission contract changes.

## Why This Change Was Made

Prepared runtime acquisition and remote catalog adoption now take one preparation path rather than repeatedly rebinding and rebuilding. Admission still handles the concrete drain, retirement, and failed-activation recovery stages. Cache publication keeps its final currentness check; tool and credential effects keep their authority checks. Steering and Tool Search retain their actual owner, FIFO, and settlement contracts without comparing unrelated metadata.

Production: **519 net lines removed**. Tests that exclusively required the removed synthetic interleavings were removed with them. Open-parent borrowing, pending-auth cancellation, explicit MCP acquisition config, and queued-tool implementation checks remain. No new lint suppressions, timeouts, retries, or skips were added.

Scope proof also caught two nearby correctness issues: an earlier MCP reload could overwrite a new caller's explicit configuration, and snapshot reconciliation could prepend a separator to a later text block. Both are fixed with their existing boundary tests. Bootstrap fixtures now test the no-clobber fallback already shipped by the pinned fs-safe version; no dependency or storage policy changed.

## Best-effort tradeoffs accepted

| Removed guard | Provenance and accepted result |
| --- | --- |
| Per-batch context projection cancellation | openclaw#119607 measured the value of cooperative yielding; its mid-batch cancellation callbacks were synthetic coverage. Yielding and the final publication check stay; obsolete pure computation may finish unused. |
| Mixed-version module/cache repair | openclaw#119607 seeded an old global singleton inside a synthetic process. Normal upgrades restart the process; unsupported mixed-version module replacement no longer repairs that marker. |
| Runtime acquisition retry/rebind loop | openclaw#128138/openclaw#127217 exercised forced reload timing. A racing request now returns a visible supersession error; the next request uses the current owner. The actual no-spin incident in openclaw#153313 remains addressed. |
| Configured-generation re-admission | 8b13535 / openclaw#168410 adds re-admission for a gated Docker reproduction with a catalog publication 0.3s after admission, not a human-user incident. A superseded request now fails visibly. Parent confinement remains fail-closed, with its security test retained. The retry-only WeakSet and two retry-specific tests are removed. |
| Repeated passive owner selection | d92dc37 / openclaw#162484 added recursion alongside the real self-drain fix; that incident did not require recursive reselection. The self-drain refusal stays. Reads use one captured owner or fail visibly, rather than recursively trying later publications. |
| Remote catalog config reread/per-attempt cancellation | openclaw#158000 used synthetic config/auth churn. Adoption reads once and prepares once; an overlapping change can defer adoption until the next normal catalog check. |
| Parent-generation cancellation subscriptions during adoption | 27a0f6d / openclaw#158000 used the same synthetic churn. Parent replacement may leave bounded preparation running until its final owner/config check rejects it. Shutdown cancellation, candidate-retirement aborts, cleanup, and the final serialized effect check remain. |
| Three-attempt catalog adoption settlement recovery | The same synthetic churn caused a second retry protocol around owner publication. One attempt remains, with one final checked atomic rows/pricing commit. |
| Duplicate early publication checks/error relabeling | Same-tick checks and concurrent-change relabeling did not guard an effect. The final effect check stays; failures retain their actual reason. |
| Auth-batch sibling retry after supersession | 4616d20 / openclaw#152467 used synthetic tests that superseded one owner during a sibling build. The operation now settles with its original error instead of selectively rebuilding siblings. Credential authority checks remain. |
| Post-await cache-stale generation check | No human incident supports fencing this metadata flag. A config/auth change during discovery can let the older load clear a reused owner's stale marker; discovery may remain stale until another explicit refresh/reload. This does not grant credentials or execution authority. |
| Passive harness catalog cancellation | openclaw#134524 fixed the actual availability report openclaw#134460; replacement/closure guards were additional synthetic hardening. Completed discovery rows are retained, and later discovery observes replacement. |
| Native binding clock-only rechecks after worker waits | openclaw#158396 used clock-jump fixtures. An expired but unreplaced exact row can finish its prepared bookkeeping mutation; CAS takeover detection and current mutation authority still gate commit. One exact, unexpired lease check gates protected callback entry, and live effect assertions remain. |
| Tool Search ancestor reentrancy tracking | openclaw#140767 covered synthetic nested control calls, not a reachable production control target. FIFO/exclusion and real implementation settlement remain. |
| Complete steering metadata fingerprint | openclaw#163195 recorded a real production ordering/ownership incident. Its owner, pending-row, result-authority, and lease checks stay; metadata-only edits no longer invalidate already-captured prompt bytes. |
| Repeated MCP acquisition/reload replay | openclaw#138694 used synthetic crossed-publication choreography. A new runtime catches up once; later reloads target the published owner. A racing creation can fail and reconnect on the next acquisition. |
| MCP tools/list invalidation generations and replay | openclaw#125541/openclaw#125564 describe isolated protocol stress fixtures. A notification inside tools/list no longer triggers immediate replay; the next notification or explicit refresh replaces the inventory. Normal exit/reconnect, bounds, validation, and cleanup remain. |
| Failed-start replay crossed by config publication | openclaw#158088's test forces a config publication into an in-flight failed initialization. That request may now report its first failure; ordinary backoff and explicit-refresh retry remain. |

## Evidence

Candidate head: `d72afea0c17a45c677977e23937049d7c7fc43ec` (tree `51daca08d7288e906188bc25ec3d1896bf841349`).

Final exact-head CI: [run 38132644989](https://github.com/openclaw/openclaw/actions/runs/38132644989) completed successfully; all 82 jobs terminal with no failed or cancelled jobs. Full head-bound check census also confirms the CI gate and applicable security checks passed. Earlier failed/cancelled attempts are described below, not represented as passing proof.

- Independent P2 reviews completed. The catalog-staleness, duplicate steering metadata fingerprint, and auth-sibling retry findings are explicitly accepted tradeoffs listed above; steering result facts and destination eligibility remain checked at their owners. The latest native-lease callback-entry finding was accepted and fixed with one live lease check instead of restoring per-write expiry callbacks. Its new fake-clock regression failed before the fix by entering the protected callback after expiry.
- Conflict-only integration kept main's three repaired test fixtures byte-for-byte. All **22 conflict tests** passed (cursor, sandbox, bootstrap publication, lint suppressions); affected root/tools test graphs, core types, typed lint and both cycle checks passed. Runtime and Madge cycles remain **0**.
- The native callback-entry fix passed fresh P2 review and **24 focused tests** (21 native binding tests plus 3 lint-suppression tests), wrapper 212.01s; native test project 164.77s including 113.11s compiled-worker preparation. The added fake-clock case performs no real wait; the existing native suite exercises authority and worker settlement. Final affected types and typed lint are checked before push.
- CI run `38125430266` found one owned stale expectation: the remote-catalog integration still forced config/auth replacement while pricing was paused and demanded the removed immediate retry. Only that scenario was removed; both schema variants retain normal publication, pinned pricing, input validation, worker recovery and disable coverage and pass locally (141.35s project), with gateway test types, typed lint, lint suppressions (3/3), and fresh P2 review passing.
- The other root failure, `checks-node-changed-compact-small-11`, independently reproduced on clean main `8d45488ae2075bd14a50c881aff6e18c32182538`: `embedded-agent-runner.prompt-cache.test.ts` responses and in-history both raised `SqliteTranscriptMutationConflictError` in the session actor append path (2 failed / 2 passed). Investigation found a cold actor snapshot prevented the existing implicit-watermark retry. Fixed directly on main as `0fa340c21f484740ec7b4ed1169b7b02439aa970` and integrated here: all 4 prompt-cache cases and 35 session-manager siblings plus lint-suppressions pass, including explicit stale rewrite refusal. The repair passed types, typed lint and fresh P2 review.
- Follow-up CI `38127338915` reached one more synthetic-only case: compaction's `mutate=input` row changes an internal selection object after starting acquisition. Removed only that row/branch under the campaign rule; five remaining compaction cases pass, along with lint-suppressions, affected types, typed lint and fresh P2 review. Its provenance is `44d905388f9` / openclaw#139429, not a human report of post-call input mutation. The final conflict repair keeps main's equivalent streaming/steering refactors, removes the obsolete retry predicate, and passes 49 owner tests plus lint-suppressions. Cancelled jobs are not counted as passing; final-head hosted CI remains the gate. No CI job was rerun.
- CI `38130432441` had one inherited fixture failure: three `sessions-mutations.catalog-queue` cases selected their configured default while expecting override fields, after openclaw#169030 intentionally made that selection a default reset. Integrated main's existing fixture-only correction `a8ef16f77650`, retaining all assertions. The corrected file passes all 14 cases on clean main under Node and Bun; the three affected cases also pass under Bun on this branch (249.87s project, mostly transformation). Exact-head hosted CI remains the final gate.
- Focused effects suites: **43 passed** across inbound-registry, remote-publication, hot-reload-dispatch and tool-search-scheduling. This includes cancellation, parent confinement, ordinary rollback/failed-activation recovery, and queued implementation replacement. Single-worker wrapper 752.15s including 142.017s compiled-worker preparation; infra 432.15s and agents-core 115.09s. Final restored remote-publication file: **7 passed**, including first reply crossing catalog adoption and exact derived-parent confinement; wrapper 372.77s (184.30s worker preparation; 131.87s Vitest). These loaded-host timings are not a performance claim.
- Integrated native-binding suites: **20 passed**, including exact token cleanup, successor protection, and revocation. The same command passed all **3 lint-suppression tests**. Single-worker wrapper 354.47s including 145.31s worker preparation.
- Current core types and native-binding test graph passed; runtime cycles **0**, Madge cycles **0**; changed-file typed lint passed. The full changed-check run reached an old-base UI duplicate-import error already fixed on main by `ef175b247c9`; that fix was integrated and the affected UI graph passed. Remaining type graphs and static guards were completed separately without changing baselines.
- Isolated Linux scope run and canonical remaining projects exercised **19,900 passing tests**. Eight failures were investigated: three pinned removed synthetic retry paths and were deleted; five exposed the correctness/fixture issues described above and were repaired with focused proof. Existing platform skips were unchanged. This is combined incremental proof, not a claim that one final-head all-scope invocation was green.
- Final repair suites: **71 passed** across passive runtime, SSE recovery, startup backoff, bootstrap, stream reconciliation/markup/phase coverage; **12 passed** across sandbox/cursor coverage, followed by **2 passed** for the real-append cursor fixture. Final MCP regression retained stdio-exit recovery and HTTP failure semantics; it passed 64 cases but hit two unchanged local child-start deadlines (1s/2s). Those initial-start paths passed on the isolated Linux run; no timeout, retry, or skip was changed to mask the local failures.
- Full-core Linux lint passed with 13 existing max-lines warnings, none in changed files. Deadcode identified and drove removal of the unused owner-publication helper. Remaining findings were in unmodified config/state/Gateway/UI files. A separate fresh current-main checkout (`401216ac50`) passed production deadcode and failed full-tree deadcode only on the unrelated `readActiveGatewayLockPortMock` export. The PR does not change any deadcode baseline.
- Blacksmith Testbox did not admit a runner within 15 minutes; AWS quota pressure supplied an undersized instance, which was released. The authorized Hetzner fallback supplied the Linux proof above. All owned remote leases are stopped. Hosted CI on the exact final head remains the landing gate; no CI jobs were rerun.

<details>
<summary>Audit coverage ledger and retained boundaries</summary>

| Mechanism (base lines) | Scenario and provenance | Decision |
| --- | --- | --- |
| context-cache-projection.ts:145-213, context.ts:87-109,146-169 | Cancellation/replacement during pure batched metadata computation. 0dd154f / openclaw#119607 fixed a measured multi-second RPC stall by yielding and atomic publication. Mid-batch authority callbacks were extra cancellation machinery; no effect occurs in projection. | REMOVE repeated projection/early checks; KEEP cooperative yields and the caller's check immediately before publication. |
| context-runtime-state.ts:33-38 | 0dd154f / openclaw#119607 seeds an old global singleton and new cache module in a synthetic child process; no human report of mixed code versions within one live process. | REMOVE old-module/cache-pair normalization, its only reuse flag, and the synthetic migration test. Ordinary process startup and same-version bundled singleton sharing remain. |
| prepared-model-runtime-lease.ts:149-164 | 9505286 / openclaw#153386. Human report openclaw#153313 by stackingrockss includes the deployed Docker version, profiler samples, and repeated boot-loop observations. Its infinite retry was caused by non-idempotent runtime selection normalization. | KEEP normalized owner selection and a visible error when a settled replacement never published; REMOVE the acquisition retry loop entirely, so it cannot spin. |
| prepared-model-catalog-worker.ts:71-220 | 9d58cf2 / openclaw#150354. Human report openclaw#149538 by 609NFT describes copied production fleet state, 632 agents, 504 failed health probes and growing RSS. openclaw#161738 by matthematics1137 reports 92 worker lifetimes, OOMs and 1.285 TB written. | KEEP one bounded shared worker, borrower cleanup, failure logging, and ordinary crash recovery. These are measured resource and real concurrency contracts, not permission to retain unrelated reload fences. |
| prepared-model-runtime.refresh-scope.ts:240 | 3e7ca30 / openclaw#151597 by obviyus describes a controlled worker crash and synthetic Gateway regression, not a human production report. Later openclaw#161738 independently establishes actual recurring worker failures. | KEEP source-bound failure reporting and bounded recovery to avoid reintroducing the observed restart/discovery amplification. The openclaw#151597 PR alone is not accepted incident evidence. |
| prepared-model-runtime.resources.ts:30-127 | d70d026 / openclaw#143109 contains native regressions and synthetic compiled CLI/Gateway proof, no linked human incident. | KEEP physical resource claims until ordinary concurrent borrowers settle and shutdown joins their cleanup; these are required cleanup mechanics, not a blanket historical-incident exemption. Inspected the complete resource owner; no extra reload retry protocol lives here. |
| prepared-model-runtime.plugin-lifetime.ts:230-319 | 1233536 / openclaw#159448 links openclaw#157842 by highfly-hi: five-agent Linux deployment with catalog-worker heap increasing 70-80 MB per scheduled turn, watchdog restarts and before/after version evidence. | KEEP final registry-reference release, current execution authority, and ordinary borrowed-resource settlement. Retained memory claims are scoped to physical lifecycle, not all historical publication machinery. |
| prepared-model-runtime.lifecycle.ts:101-164 | d92dc37 / openclaw#162484 by jalehman records actual lossless-claw maintenance calls stuck about 45 minutes during reload until restart. 1f3038b / openclaw#162301 explicitly says synthetic Gateway, no production deployment. | KEEP refusal of plugin work waiting on its own drain and process-close settlement. openclaw#162301 is synthetic evidence, not an independent incident exemption. |
| prepared-model-runtime-lease.ts acquisition loop and borrowed-generation branch | 1977a39 / openclaw#128138 and related openclaw#127217 describe synthetic QA-channel/config replacement tests; openclaw#127217 explicitly reports that its pre-fix real-Gateway run still delivered replies. Retained inbound-registry tests exposed ordinary nested selected-parent borrowing as a distinct contract. | REMOVE retry/rebind loop. KEEP exact open-parent borrowing and selection confinement; a reload during new acquisition may fail that request visibly. |
| prepared-model-runtime.published-owner.ts:91-203 | d92dc37 / openclaw#162484 added retry/recursive rereads alongside the real plugin-drain repair. That incident justifies self-drain refusal and ordinary settlement, not recursive passive owner reselection. | REMOVE repeated rereads/retries; wait once, then project or activate once. Pure catalog-stale bookkeeping no longer revalidates generation after its await. |
| prepared-model-runtime.configured-refresh.ts remote catalog adoption | 27a0f6d / openclaw#158000 has explicitly synthetic config/auth churn and fixture-provider proof; no human incident cited for the reread loop, per-attempt controllers or three-attempt owner settlement recovery. | REMOVE those race-specific retries, plus early duplicate currentness checks/error relabeling. KEEP the final owner/authority check, atomic rows/pricing commit, current catalog ordering, and ordinary cancellation/disposal. |
| prepared-model-runtime.configured-refresh.ts:396-430 parent subscriptions | 27a0f6d / openclaw#158000; same synthetic churn proof. Parent-generation subscriptions duplicate the final owner/generation/config check. | REMOVE parent-generation early cancellation listeners. KEEP shutdown and candidate-retirement cancellation, bounded work, cleanup, and the final serialized effect check. |
| prepared-model-runtime.owner.ts:612-631 batch supersession retry | 4616d20 / openclaw#152467. Tests force one auth owner to supersede while a sibling is building. No independent human incident identified for sibling retry. | REMOVE retry of the surviving batch; retain source-bound credential/current-owner checks and report the original publication failure. |
| prepared-model-runtime.owner.ts:124-134 unused publication probe | e56f825 / openclaw#130856 introduced a helper returning matching/pending publication facts for acquisition retries. Its callers are gone; full-repository search finds only the definition. | REMOVE the dead helper/export. Credential-refresh cancellation remains supported by the direct, abortable configured-owner wait and its unchanged regression tests. |
| sandbox/registry.kernel.ts:396,420; sandbox/registry.ts:295 | 5c7e44c / openclaw#151172 is not treated as an incident report. Read-only admission accepts older schemas; tableExists consumes admitted schema.tables facts, not repeated SQL/format validation. | KEEP the existing absent-table empty/null contract. No runtime foreign-commit or repeated validation probe exists in these calls. |
| harness/native-session/binding-leases.ts | b272376 / openclaw#158396 moved writes to workers; elapsed-time rechecks were covered by synthetic clock-jump tests. ffd0759 / openclaw#164197 supplies native successor authority behavior, not a blanket exemption. | REMOVE prepared callback plumbing and post-worker wall-clock-only rechecks. KEEP exact-row CAS, token/phase/failure checks, current mutation authority, bounded acquisition, renewal, and write settlement. |
| harness/context-engine-logical-turn.ts | openclaw#143491/openclaw#140023 supply synthetic lifecycle tests, not qualifying human incident evidence. The owner actually holds resources used by outstanding context-engine work. | KEEP ordinary work completion and deferred disposal until implementation settlement; no extra synthetic reload retry was retained here. |
| harness/model-catalog.ts:168-177,242-284,353 | 01fd244 / openclaw#134524 repairs human availability report openclaw#134460. Passive replacement/closure branches were additional maintainer hardening and synthetic variants, not that report's failure. | REMOVE passive isCurrent callbacks and ambient registry replacement checks. KEEP exact owned registry/config, provider outcomes, discovery, selection and the actual availability repair. |
| auth-profiles/oauth-refresh-peers.ts | openclaw#166183/openclaw#167002/openclaw#166659 are not claimed as human incident evidence. Refresh credentials rotate/revoke and carry account identity; copied historical peers must not replay spent tokens or inherit another account. | KEEP these credential/identity effect boundaries and ordinary uncertain-write settlement. No auth-profile schema, secrets, permissions or durability changes. |
| worktrees lifecycle/removal | Audited run-lease-owner.ts, service-preparation.ts, eviction.runtime.ts and gc-removal.ts. They coordinate destructive removal of user artifacts with live checkout/source handles, exact refs and ordinary parallel sessions. No PR title is treated as incident evidence. | KEEP current-row removal/exclusive source checks and rollback/cleanup custody for writes and deletion. Removing them would risk user artifacts, independently prohibited by the data-loss boundary. |
| tool-search-scheduling.ts | 49f8d29 / openclaw#140767 adds ancestry reentrancy and queued object/mode identity checks with automated interactive/headless regressions. Production catalogs exclude control tools; recursive calls using the same runtime were synthetic only. | REMOVE unreachable nested-call ancestry. KEEP one exact queued implementation/mode check at the effect, catalog-ID authorization, FIFO/exclusion, abort and implementation settlement. |
| agent-steering-queue.ts:194-263 | 94acbe6 / openclaw#163195 records Peter's actual three-day production errors. The incident justifies owner/FIFO repair, not a fingerprint of every result label/task/time/outcome/origin/transcript field. | REMOVE full payload fingerprints and deep-equality invalidation. KEEP run-owner identity, prepared result authority, current requester store, pending-row effect checks, FIFO, exact lease/status acknowledgment and release. |
| agent-bundle-mcp-manager.ts and manager-install.ts | 1d60d3d / openclaw#138694 reports synthetic fail-before/real-transport proof but no cited actual-use incident for repeated crossed-publication acquisition/reload. | REMOVE the acquisition retry/rebind loop and repeated reload replay. KEEP the runtime-key queue, ordinary cleanup, one postcreation config catchup, requester credentials/authorization and live tool effect checks. |
| agent-bundle-mcp-runtime.ts catalog generations | 140dbbd / openclaw#125564 and follow-up 0818bcb / openclaw#167642 have synthetic notifications/listing interleavings, not human reports for replaying tools/list during its own response. | REMOVE catalog invalidation generations, replay of a notification arriving inside tools/list, and the impossible repeated replacement-retirement loop. KEEP listing single-flight, caching, bounds, diagnostics, normal reconnect, one retry for an actually exited previously healthy server, and execution authority. |
| prepared-model-runtime-lease.ts / plugin-lifetime.ts configured-generation re-admission | 8b13535 / openclaw#168410, landed during this lane, describes a gated Docker reproduction with catalog publication 0.3s after admission, not an actual human-user incident. | REMOVE configured-generation retry and its now-unused WeakSet plus the two retry-only tests. KEEP fail-closed superseded-generation rejection and the new derived-parent confinement security test. |

</details>
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