Skip to content

refactor(gateway): share handler preparation and lifecycle projections - #167335

Merged
steipete merged 4 commits into
mainfrom
deslop/d01-gateway-server-methods-p3-20261007
Oct 8, 2026
Merged

steipete merged 4 commits into
mainfrom
deslop/d01-gateway-server-methods-p3-20261007

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway session and request handling repeats preparation, error projection, and lifecycle bookkeeping across variants.

User Impact

No user-visible change. Authorization, recovery and replay, configuration, RPC and persisted shapes, SDK declarations, and response text stay the same. Tests are unchanged.

Why This Change Was Made

Share membership access and mutation handling, session creation/reset refusals, chat preparation and delivery projections, and terminal/runtime cleanup cores. Keep variant-specific authority checks, actor/timestamp capture, partial-delivery precedence, and late cleanup explicit. Derive settled state from the owning registries and remove single-use internal seams and unreachable stored-state handling.

The authored diff removes 693 net production lines across 92 files, measured against b3196dfda33555857eae9cd52ea29367a91bd9ea. The per-file census covers 608 production modules, including all 427 current server-methods modules and reserved exclusions. Measured alternatives that grew the code, obscured ownership, changed reachable SDK declarations, or lost accepted raw parameter properties were discarded.

Per-file coverage: part 1, part 2, part 3, part 4, part 5.

Evidence

  • Independent review through P2 is clean for the complete refactor and each correction.

  • Production types, all selected test type graphs, structural guards, formatting, and focused lint pass. check-changed reports only two untouched unused exports reproduced on the clean base: SessionPendingInputState in config/session storage and discardStreamSegmentIndexes in the UI. The former is already removed upstream by 19f37f076862830f9b8953287f94a4725e3b8908.

  • SDK API comparison reports no direct, reachable, or entrypoint changes at implementation commit 6e3961495e544f65e350e6b2e18c5e5265b260a7. The later delta only restores the baseline system-event body under its unchanged GatewayRequestHandlers annotation.

  • Terminal tests: 128 passed; suppression tests: 3 passed. Presence routing after restoration: 9 passed, plus the suppression suite. Packaged-script and PR-wrapper eager-import closure tests passed. Direct tooling-import audit found no imports from changed modules in the protected landing helpers.

  • The focused send file passes all 78 tests. Same-host wall times were 90.98 seconds before and 364.00 seconds after, with the latter rebuilding the worker cache on a host reporting load 61.50 on 16 CPUs. These are validation timings, not a performance comparison; no tests or their CI cost were added.

  • Dedicated AWS validation passed all four selected Vitest projects: 9,787 tests passed across 749 files, with 21 existing skipped tests in four files. This includes the full server-methods directory, agent-turn, desktop, methods, Talk, terminal, and affected adjacent-owner suites. The test wrapper exited 0 in 3,424.77 seconds; runtime and Madge cycle checks both passed. The clean baseline also has zero cycles.

  • Remote run run_373168b5e65d4264e817cf03b496c537 on AWS lease cbx_7802687261d5 tested implementation commit 6e3961495e544f65e350e6b2e18c5e5265b260a7. Every final changed production file is byte-identical to that snapshot; final head 900b74a38d291476a712cfa5c601cf2c269e8eb1 only restores the untouched baseline system.ts, covered by the focused routing check above. The aggregate remote command exited 1 solely for the two inherited Knip findings. Hosted CI run 37812357878 passed on exact head 900b74a38d291476a712cfa5c601cf2c269e8eb1; the combined CI, dependency-review, and security-sensitive-review statuses are successful. Three publication-time cancelled automation jobs (Auto response, PR context and evidence, and ClawSweeper Dispatch) were rerun successfully; no cancelled job is being treated as passing proof.

  • ClawSweeper reported no correctness or security findings and requested compatibility review because its file inventory was incomplete and doctor.ts was classified as an unknown data-model change. The paginated GitHub inventory matches all 92 local changed files. The only doctor.ts edit derives diagnostic arrays/sets from the same prepared records in mergeDreamingStoreStats, preserving filtering, ordering, totals, sort limits, and timestamp selection. It performs no writes and changes no config key, default, schema, migration, or stored shape. The complete diff and zero-change SDK declaration comparison confirm that no upgrade action is required. This completes the compatibility follow-up.

Investigated local failures

A partial local broad run hit the 90-second first-case timeout in chat.reset-visible-yield.test.ts before any provider or lifecycle event. The clean base reproduced that exact timeout. The following candidate case reported revoked reader custody; the baseline instead reported changed session authority. That secondary custody error is not an exact baseline reproduction. The startup/cleanup-overlap explanation remains a hypothesis, and no passing replay is claimed as a fix.

The focused Talk selection passed 295 cases and failed only client-native-control.test.ts's registration-readiness case. A clean-base full-file run reproduced the exact error and assertion: registration readiness not observed within 1000 ms; last phase: preparing tool authority at line 94. The deliberate workspace delay precedes that timer; the failure occurs during later real authority preparation. No timeout, retry, skip, assertion, baseline, or suppression was changed.

The local broad run was stopped under measured host contention and replaced by dedicated Linux validation. Both visible-yield cases passed there (26.930 seconds and 10.574 seconds), as did the Talk readiness case (4.413 seconds). These passes establish dedicated-run coverage, not a fix for the local failures; those failures remain recorded separately.

@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

d01 PR 3 per-file coverage — part 1/5

Reviewed implementation head: 900b74a38d291476a712cfa5c601cf2c269e8eb1.

Gateway server-methods lane d01, PR 3 coverage

Baseline b3196dfda33555857eae9cd52ea29367a91bd9ea. This final lane pass re-evaluated prior rejected and partially simplified files, completed the current server-methods directory, and revisited its adjacent runtime owners.

608 production modules have per-file decisions, including all 427 current server-methods modules and the original exclusions. The implemented production diff removes 693 net lines; no test, protected storage, global-identity, config-retirement, tooling, or changelog paths changed. Existing assertions remain intact.

Counts describe the actual applied source against the original fresh-main base. Measured rejected prototypes are recorded in each relevant row. The PR body records executed validation separately; a named test below is a target unless that validation says it passed.

File Before After Net removed Decision and evidence
src/gateway/server-chat.ts 1702 1693 9 Applied shared prepared-row publication after successful/failed terminal persistence, one current-text projection core for immediate/paced output with explicit delivery options, common session/heartbeat envelope, The open-ended stream type retains its original literal narrowing after declaration validation. Read complete module and its live-text/state callees. Persistence logs/fallbacks, live claim checks, heartbeat suppression, callback ordering and synchronous row consumption remain at their original boundaries.
src/gateway/server-channels.ts 1670 1669 1 Applied: root-prototypes/server-channels.ts shares the adjacent recoveryStopTimedOut/recoveryStartRequested deletes at five sites in a local clearRecoveryState helper. Same maps, deletion order, call sites and synchronous timing; the distinct sixth path that consumes delete’s boolean remains explicit. Net 1 line. The applied helper keeps the paired recovery reset together at all five sites. Existing full channel suites cover this change.
src/gateway/managed-image-attachments.ts 1592 1592 0 REJECTED +1: root-prototypes/managed-image-attachments.ts combines the two unlink outcomes in preparation cleanup using explicit current read-scope and uncertain-insert conditions. Same cleanup precedence and short-circuit order, but the compound predicate formats longer than the direct outcome branches. Keep exact inserted-record custody, uncertain write retention, and current-scope file cleanup visibly separate. The larger image/AV/document paths already share saving, recording, publication and failure ownership.
src/gateway/session-reset-service.ts 1446 1417 29 Applied: one loadResetSession closure repeats the same selected-agent read at all four original points; one selection-first access check is shared by preparation and execution while initial ownership-first precedence remains explicit. Reuse unavailableSessionRequest only for identical plain unavailable result envelopes. Prepared plugin cleanup extraction was implemented as a local prototype and rejected: applied file at prototype capture 1432 -> 1437 (+5), adds an async frame without reducing the source. Full runtime drain remains on the existing shared ensureSessionRuntimeCleanup owner.
src/gateway/node-registry.ts 1359 1359 0 REJECTED +5: root-prototypes/node-registry.ts implements one typed raw/value event-send core with an explicit trusted discriminator. It shares pairing/currentness, transport selection and WebSocket delivery, preserving raw payload validation before transport and lazy serialization. The input union and call-site object construction cost more than the duplicated guard; original direct methods remain clearer. This prototype does not infer an operation from payload property presence.
src/gateway/session-create-service.ts 1356 1324 32 Applied: share initialization-pending refusal and missing-initializer branch, combine equivalent initialization flags, and reuse the narrow unavailableSessionRequest constructor. Creation/atomic rollback/ordinary post-commit contracts, property omission and callback ordering are preserved. Import the actual AdmittedRunOperatorAuthority type after removing its single-use construction seam.
src/gateway/server-methods/config.ts 1115 1115 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/agents.ts 1103 1103 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/talk/handlers/index.ts 927 925 2 Applied: resolveConfig(rawInput) shares default and selected realtime provider resolution, retaining available-first short circuit, exact raw fallback objects, default-before-selected call order, active model precedence and output shape. No config/schema changes. Tests: handlers/index.test.ts, handlers/provider-discovery.test.ts.
src/gateway/server-methods/send.ts 926 915 11 Applied existing failure-result core to all three catches with explicit authority predicates. Partial-delivery-first short circuit and direct versus action authority checks preserved; no new async boundary.
src/gateway/server-methods/cron.ts 835 835 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/terminal/session-manager.ts 790 771 19 Applied shared limit-refusal construction as a local closure inside open, preserving the class declaration and call-time maxSessions reads. Reuse existing eviction-claim release, simplify write/resize/snapshot guards and pending connection branches. Capacity reservation, late-spawn kill, revalidation, exit draining and ownership adoption stay ordered. Earlier private-method prototype was 790 to 774; final declaration-preserving form is 790 to 771. Measured backend-operation strategy added 6 lines; list strategy added 3, both rejected.
src/gateway/exec-approval-lifecycle.ts 763 754 9 APPLIED: Derive observer settlement from membership in the lifecycle-owned observer Set instead of a separately maintained boolean. Both completion and close already delete the exact observer before settling; callback registration precedes every possible synchronous close and promise continuations remain deferred. Share raw/trimmed exact-id filtering after selecting the exact candidate, preserving raw-first lookup, skipping trim on a raw match, repeating the trimmed lookup when raw misses, and returning none for a filtered exact record before prefix matching. | exec-approval-manager.test.ts; exec-approval-manager.lifetime.test.ts; exec-approval-manager.expiry.test.ts; server-methods/approval-shared.test.ts; server-methods/approval.legacy-authority.test.ts
src/gateway/agent-turn/agent-job.ts 753 743 10 Applied: remove terminalOutcomeFromSnapshot and its unreachable pendingError path. Only createPendingErrorTimeoutSnapshot creates that waiter-only flag, and its result goes directly to finish rather than any stored snapshot. StoredAgentJobSnapshot now excludes pendingError. Lifecycle and dedupe factories always produce canonical terminal outcomes, so the redundant undefined-outcome branch also disappears. Kept source-specific replay barriers, sticky precedence, retry deadlines and all outward pendingError fields.
src/gateway/exec-approval-manager.ts 740 740 0 RETAINED: Built a readExistingRegistration closure shared before and after persistence; formatted 740 to 741 (+1). Saved prototype .local/d01-p3/admin-prototypes/exec-approval-manager.ts, then discarded the longer abstraction. The larger verdict paths already share createExecApprovalMutationGuard, recovery readback, settlement and standing-grant owners. Resolution retains initial-time expiry crossing checks, auto-review committed provenance and placement grant publication; cancellation closes executable authority synchronously before durable I/O. No additional duplicate effect owner was found. | exec-approval-manager.test.ts; exec-approval-manager.lifetime.test.ts; exec-approval-manager.expiry.test.ts
src/gateway/server-broadcast.ts 733 725 8 Applied shared plain-event classification from the existing scope owner, replacing the second inline prototype/proxy/toJSON inspection. Classification stays after header serialization and before source serialization/projection. Measured consolidated last-frame state prototype against the edited file 725→726 (+1), rejected. Distinct per-recipient authority, projection, sequence, slow-consumer and replay paths remain explicit.
src/gateway/server-methods/update.ts 726 726 0 Retained after full read: one native handoff spine already owns foreground and managed-service operation, with explicit beforePark strategy. Refusals share refusedUpdate; different version reads and authority checks remain at their original positions.
src/gateway/methods/core-descriptors.ts 725 725 0 REJECTED PROTOTYPE (rejected/ mirror): adminWrite across 43 tuples measures 725 -> 715 (-10). Three literal-preserving generics plus a second table notation conceal the current explicit scope/write-policy fields; the canonical table is already the strategy data. All 725 source lines retained and append-only order unchanged.
src/gateway/server-methods/chat-send-agent-dispatch.ts 723 723 0 Retained: one detached dispatch owner. Dispatched replies, native/source replies and accepted steering already share delivery facts; their predicates retain native transcript ownership, returned-error classification and terminal replay timing. A proposed post-dispatch strategy did not remove a second implementation because the two finalizers already own different persisted paths.
src/gateway/server-methods/chat-metadata-runtime.ts 721 721 0 Retained after implementation prototype: clearPreparation shared pending retirement measured 721 -> 722 lines (chat-prototypes/metadata-reset.ts), introducing another state-mutating helper for four common assignments. Ready-only startup reads still must neither start preparation nor await replacement; current reads and model projection already share readCurrent/projectAgent.
src/gateway/agent-turn/agent-run-execution-phase.ts 719 719 0 Retained: one dispatchAdmittedAgentRun already scopes generation/user input. Dispatch authority rejects cancellation, settlement authority deliberately survives it. Large ingress object maps different request, prepared owner, accepted provenance and restored-source policies; a generic field-copy table would add an indexed field list without reducing statements or preserving those explicit overrides more clearly.
src/gateway/session-row-projection-read.ts 719 718 1 APPLIED: remove unused cfg from the worker-read owner contract and its sole caller. All physical store capture, read-lane selection, incognito custody, assertion/release ordering and consuming frames remain identical. Missing/value private branches intentionally retain different acquisition lifetimes; merging their finally blocks would change when failed acquisition deactivates authority.
src/gateway/desktop/managed-linux.ts 718 716 2 Applied: share supervisor/tempDir/env argument construction in createPairAudio, taking the original live-authority callback explicitly. Startup and recovery retain their distinct checks and all await/assignment ordering. 718 -> 716 (-2).
src/gateway/server-methods/chat-send-admission.ts 718 715 3 Applied: remove independently threaded pending reservation key/run ID; reservation access captures those immutable values from the owning prepared session. Writer-barrier checks and all cleanup/ACK boundaries are unchanged.
src/gateway/server-methods/chat-send-handler.ts 718 710 8 Applied: carry the admitted setup record unchanged through attachments, recorder/user-turn preparation and detached dispatch, removing four reconstructions of request/session/admission. All awaits, guards and explicit overrides remain at their original boundaries.
src/gateway/talk/relay/operations.ts 718 718 0 Retained. Retested shared cancelled-consult provider-result construction across operations/session-create/forced-consults/provider-results: aggregate 1999 -> 1998, only one line saved while adding a new exported constructor/import wiring to four owners; rejected as less clear. Existing prepareTalkRealtimeRelayAgentControl currentness core retains pre-control caller assertion and post-control relay-only fence. Provider acceptance, epoch and pending-working barriers remain separate.
src/gateway/session-row-projection.ts 715 715 0 RETAINED: composition owns authoritative rows, revisions, topology and disposal; typed collaborators already parameterize refresh, archive, catalog and private presentation. Repeated closures defer access until later initialization or re-read current owner state. Prepared metadata/selection and exact display have distinct readiness contracts, with no parallel implementation to delete.
src/gateway/server-methods/chat-abort-handler.ts 711 711 0 Retained: active and queued withdrawal share captureAbortTargetIdentity and discardBeforeAbort. Active cancellation captures partials, cascades descendants and joins persistence; queued cancellation retains its separate queue predicate and withdrawal hold. Moving their post-await guards into an async strategy would add a yield after authority validation; no second identical cancellation owner remains.
src/gateway/session-row-projection-record.ts 704 696 8 Applied ordered dependent-set construction, first-match selection and optional parent enumeration. Restored the explicit prepared argument type after the five-line Omit reduction changed reachable SDK declarations; all physical ownership, private-source fences and row fields remain identical.
src/gateway/server-methods/approval-shared.ts 701 701 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Shared live custody acquisition between initial lookup and commit-time revalidation, and forwarded existing recipient context. Exclusive follow-up ownership handed to admin for approval method factories; all original exports retained. | src/gateway/server-methods/approval-shared.storage-failure.test.ts;src/gateway/server-methods/approval-shared.test.ts
src/gateway/server-methods/sessions-patch-engine.ts 697 697 0 Retained: preflight assigns indexed outcomes; queued projection resolves its writer snapshot and fills ordered group outcomes. The existing targetAccessError, catalogs/projectGroup, replacement writer and effects owner already share the repeated work. Collapsing into one loop would move authority and catalog waits across writer admission.
src/gateway/server-methods/sessions-abort.ts 696 696 0 Retained: exact embedded cancellation, queued collector cancellation, and general chat cancellation share session selection, source assertion, persistence settling and result projection. Their early-return custody and dedupe owners remain distinct; callback success cannot derive from final payload because respond may mutate that payload and callbacks can carry absent metadata.
src/gateway/server-methods/sessions-suggestions.ts 695 706 -11 Applied: the one private publication owner now projects StoredSessionSuggestion and returns the same object it broadcasts; add and resolve share that synchronous core after their unchanged readCurrent check. Measured identity-comparison helper prototype against the applied file: 706 -> 707 (+1), retains a separate null guard for type narrowing and is longer; rejected.
src/gateway/agent-turn/agent-run-admission-phase.ts 693 693 0 Retained: user-turn and subagent preparation already consume the shared input record. Revalidation remains synchronous on success at every await boundary, with phase-specific refusal/cleanup behavior. Different cleanup finally blocks settle runtime lease, adopted parent, completion and recovery owners even when a previous cleanup fails.
src/gateway/talk/client-agent-consult.ts 688 688 0 Rejected formatted private runArgs options-record prototype: 688 -> 689. Removing positional undefined arguments requires a local option shape and does not reduce the surface. Owned and reusable adapters already share runArgs; completion claims, requester-final registration and dynamic confirmation remain explicit differences.
src/gateway/talk/relay/session-create.ts 688 688 0 Retained. Common cancellation-result constructor participates in rejected 1999 -> 1998 four-module prototype. Harness already owns shared emit/error/current-relay operations. Playback identity, response owner and continuity reset retain different event timelines; terminal construction callbacks must keep the before-registration window.
src/gateway/server-methods/projects.ts 685 685 0 RETAINED: Re-read candidate admission, grouping, current profile/projection authority, register/clone/search/remove. Existing shared validated methods and checkout error projection remain. nameUsedAt and lastUsedAt are not identical for malformed numeric input (Math.max propagates NaN but name comparison does not), so deriving one from the other is not behavior preserving. | Existing focused/full test targets: projects.test.ts projects-incognito.test.ts projects-observed.test.ts
src/gateway/server-methods/question.ts 680 680 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Narrow selected-question preparation to original options responder; all three callers passed that same responder. Keep get preparation outside its error catch, as before. | src/gateway/server-methods/question.test.ts src/gateway/server-methods/question.own-run.test.ts src/gateway/server-methods/question.session-access.test.ts src/gateway/server-methods/question.hosted-caller.test.ts src/gateway/server-methods/question.recovery.test.ts
src/gateway/server-methods/sessions-create.ts 680 680 0 Retained: catalog, repository, empty workspace and ordinary creation already converge into one createGatewaySession request. Initial input custody and publication are separately captured callbacks; worktree preparation can intentionally preserve an unspecified key. Consolidating field projections would hide omission and fallback differences.
src/gateway/server-chat-state.ts 674 672 2 Applied: derive provisional subscription settlement from its private inflight map; preserve current state identity check, commit-before-removal ordering, and repeated rollback/commit no-op behavior. Existing concurrent replay and invalidation tests cover the owner.
src/gateway/server-methods/chat-abort-runtime.ts 673 673 0 Retained: active and pending run plans already share authorization aggregation; agent/chat pending aborts already use the explicit kind table. Queued-before-active order and committed partial settlement remain independent of errors from later owners.
src/gateway/server-methods/sessions-mutations.ts 672 667 5 Applied: reset uses one response envelope with explicit incognito-deletion versus reset-entry payloads; response arity, member order, fast-mode projection timing and subsequent event stay unchanged. Reset now consumes the existing canonical session-lifecycle-runtime loader instead of a second cache.
src/gateway/server-methods/chat-send-session.ts 671 664 7 Applied: one preparationFor closure captures the selected request/session arguments, comparing old and current config with identical evaluations and error text. Kept prepared config snapshots separate from later live comparisons so mutable config cannot erase freshness evidence.
src/gateway/server-methods/sessions-dispatch.ts 668 668 0 Retained: target resolution, workspace selection, grant retention and error translation are already shared. Dispatch retries retain attempt receipts and pending slot accounting; move publishes failure progress; reclaim compares committed placement generations. Their separate effect/cleanup owners do not duplicate one operation.
src/gateway/server-methods/sessions-files.ts 665 665 0 Retained: list/get/assets already share handleSessionFilesRead and its currentness/host-read publication owner. Ordered regex strategy prototype 665 -> 665 (0); two named passes make additions-before-moves ordering more direct than an extra nested loop. No production change.
src/gateway/server-methods/chat-history-handler.ts 664 664 0 Retained: full and delta paths share selection, startup, thinking and visibility owners. Their response envelopes and publication timing differ; delta must reread sharing after worker restoration. Factoring common response properties requires a new capture object for six lines, with two spreads, for no structural simplification.
src/gateway/server-methods/sessions-rewind.ts 662 662 0 Retained: fork/rewind/switch already share mutateSessionAtMessage. Upstream initialization versus repository fork have distinct rollback owners; local switches omit editor results. Authority, active-run refusal and lifecycle fences are already shared without moving awaits.
src/gateway/server-methods/chat-send-pre-admission.ts 652 652 0 Retained: resolveClaim already parameterizes warning policy. Stop, Goal receipt, orphan reconciliation and replay have separate authority/typed-error contracts; their shared current-reader and comparison owners are already central.
src/gateway/server-methods/models-list-result.ts 648 648 0 RETAINED: Re-read provider-config versus visible catalog projection and prepared public-entry cache. Shared decisionOwner is retained. Spreading it into resolveDefaultModelsPreview would also pass accountCatalog/observationConfig through utility completion into createModelCatalogDecisions, changing semantic inputs; retain exact parameter projection. | src/gateway/server-methods/models-list-result.arcee.test.ts;src/gateway/server-methods/models-list-result.cli-runtime-availability.test.ts;src/gateway/server-methods/models-list-result.configured-static.test.ts;src/gateway/server-methods/models-list-result.openai-routes.test.ts;src/gateway/server-methods/models-list-result.plugin-runtime.test.ts;src/gateway/server-methods/models-list-result.provider-outcomes.test.ts;src/gateway/server-methods/models-list-result.runtime-choices.test.ts;src/gateway/server-methods/models-list-result.service-tiers.test.ts
src/gateway/talk/client-gateway-control.ts 646 646 0 Rejected formatted synchronous assertConsultCurrent core: 646 -> 647. Four repeated active/signal pairs become four calls plus a typed helper, adding one line. It preserves timing but does not improve clarity. Readiness waits remain distinct (ordinary transcript flush versus confirmation readiness); accepted consults outlive transport disposal under separate controllers.
src/gateway/server-methods/board.ts 644 642 2 APPLIED: Replace the separately maintained origin-resolved boolean with null as the uninitialized origin state. Undefined still records an absent configured origin and prevents repeat reads across widgets. Full typed session-method extraction also prototyped 644 to 651 (+7), rejected because its handler and validator plumbing costs more than the duplicate setup. | board.test.ts; board.runtime-boundaries.test.ts; board.mcp-admission.test.ts; board.plugin-capabilities.test.ts; board.approval.test.ts; board.github-actions.test.ts
src/gateway/server-methods/chat-send-reply-dispatch.ts 643 640 3 Applied: derive run currentness directly as the conjunction of its existing ownership predicates, preserving short-circuit order and all awaited fences. Media finalization still distinguishes idempotency-key and indexed runtime ownership.
src/gateway/server-methods/system-agent.ts 641 641 0 Retained: setup startup already shares activation owner; greeting variants differ in persistence, acknowledgement, and rejoin controls. The new-session early response intentionally precedes lastUsedAt refresh.
src/gateway/server-methods/nodes.invoke.ts 640 638 2 APPLIED: Share the live runtime-authority error reader between final dispatch preparation and the transport callback; both call sites still re-read the current client, manager and forwarded approval with the same ordering and no new await. | nodes.invoke-abort.test.ts; nodes.invoke-wake.test.ts
src/gateway/server-methods/terminal.ts 631 629 2 Applied one local unavailable responder binding existing request hints at call time; ten refusal/timeout sites retain codes and messages. Open shell/catalog/node routes already share openTerminalSession. Deadlines retain late-success closure, pairing captured before awaited policy, and refreshed authority at dispatch. Input/resize/close share a parameterized handler with explicit close exception.
src/gateway/agent-turn/agent-turn-service.ts 628 583 45 Applied: capture immutable preflight scalars in runFacts at their original preparation time, then thread that record through admission/execution instead of separately destructuring and reconstructing every field. Prepared session facts feed buildAgentSessionPatch with fresh-entry/identity overrides explicit; content routing feeds delivery with current resolved identity explicit. Audited each consumer: it reads named fields and does not forward the extra private fields into persistence, replay or ingress payloads. No await, authority check or mutable accepted provenance moved.
src/gateway/server-methods/sessions-sharing.ts 613 569 44 Applied: one defineManagedSessionHandler owns validation, management-facts acquisition, disposal and explicit read/mutation mode. One membership mutation handler shares target/fence/response/publication while add retains known-identity preparation and pre-write actor/time, remove retains post-write actor/time. All storage calls and guards unchanged.
src/gateway/server-methods/channels.ts 608 608 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Shared start/stop account resolution, current runtime snapshot and response identity; explicit action preserves the start-only capability check, outcome requirement and deferred reload projection. No new await. | src/gateway/server-methods/channels.start.test.ts src/gateway/server-methods/channels.status.test.ts
src/gateway/desktop/session-registry.ts 605 605 0 REJECTED PROTOTYPE (rejected/ mirror): shared clearLinger for all four identical reset sites is 605 -> 605 (0). Stop/acquire/activate already share owning cores; observer released and stream stopped flags fence reentrant callbacks before container changes, so they cannot derive safely from those containers.
src/gateway/server-methods/exec-approval.ts 587 587 0 RETAINED: Re-read complete request, list, get, wait, grants and resolve paths. Requests already share delivery and lifecycle cores with plugin approval. Reusing list/wait boilerplate through approval-shared would add an eager authority import to request-only consumers; keep the current lazy graph and distinct terminal-reason projection. | src/gateway/server-methods/exec-approval.agent-runtime.test.ts; src/gateway/server-methods/exec-approval.request-schema.test.ts; src/gateway/server-methods/exec-approvals.test.ts
src/gateway/server-methods/control-ui.ts 585 585 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: createGitHubReadHandler already parameterizes both GitHub routes. Session preview, PR checks and subscriptions retain distinct read owner lifetimes; subscription responds at admission while preview must consume and respond synchronously in the authorized frame. | src/gateway/server-methods/control-ui.test.ts src/gateway/server-methods/control-ui.session-preview.test.ts
src/gateway/server-methods/doctor.ts 580 566 14 APPLIED: Derive path sets, error arrays and entry arrays directly from the collected immutable workspace stats instead of maintaining seven independent accumulators. Preserve per-workspace order, truthy omission, duplicate paths, error counts, timestamp comparison, sort and response limits. | doctor.test.ts; doctor.memory-provider.test.ts
src/gateway/server-methods/chat-transcript-persistence.ts 579 579 0 Retained: generation-qualified indexed rewrite versus idempotency rewrite share buildAssistantDisplayRewrite; implemented/formatted merged whole-operation prototype measured 579 -> 586 lines (chat-prototypes/transcript-rewrite.ts), requiring optional generation/after-sequence strategies and distinct result projections. The shared correction owner already contains persistence and authority; keeping lookup/result adapters direct is clearer.
src/gateway/server-methods/devices.ts 577 577 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One parameterized rotate/revoke handler owns validation, authority, mutation and refusal; post-commit token delivery and teardown remain explicit branches with unchanged awaits. | devices.test.ts;devices.lifecycle.test.ts (results recorded separately)
src/gateway/server-methods/system-changes.ts 577 574 3 Applied common summary formatting and direct cursor derivation from buffered/consumed scope facts. Journal order, independent scan bounds, pending collapse markers, unknown cursor fields and serialized shapes preserved.
src/gateway/server-methods/tools-effective.ts 577 577 0 Retained: base stale-while-revalidate cache and native/core MCP catalog are separate owners with one shared catalog projection. Native unavailable never falls back to core runtime. Earlier explicit inventory projection is required: forwarding toolOverrides/spawnedBy would change policy.
src/gateway/session-row-projection-materialize.ts 573 567 6 APPLIED: both private-row acquisitions pass the existing exact request bundle to the shared constructor while overriding physical path explicitly. Remove redundant candidates.length branch because empty mapping already yields an empty array without scope reads. Read/materialize refresh remains shared already; native/prepared private authority and archival retention are preserved.
src/gateway/server-methods/chat-abort-authorization.ts 569 569 0 Retained: createChatAbortRunSelection already centralizes deduplication and protected/unauthorized tallies. Exact preregistered matching permits legacy key omission while broad scans require session identity. Agent and chat cancellation mutate distinct dedupe/marker owners.
src/gateway/talk/handlers/session.ts 567 567 0 Retained. PR2 shared request error/success owners already serve handler variants. Realtime append/close awaits provider work; transcription append/close remains synchronous. Managed rooms resolve authorized sessions and handoffs but have no steering authority. A generic transport strategy would retain every branch-specific argument and rejection string while adding registration data.
src/gateway/server-methods/shared-types.ts 565 565 0 Retained: canonical context/client/authority leaf contract. Structural system-agent mirror prevents documented agents/config cycle; method and result variants are used and cannot be merged as runtime code.
src/gateway/agent-turn/agent-session-persist.ts 563 563 0 Retained after formatted prototype: shared superseded-session update measured 563 -> 564 (agent-turn-prototypes/agent-session-persist.ts). It adds a state-mutating helper while the two original assignments sit at distinct admission/publication boundaries. Persisted versus denied session and created-new state remain separate committed facts.
src/gateway/server-methods/workspace-files.ts 553 551 2 Applied forwarding prepared file-list parameters into private browser projection with explicit prepared-workspace and filtered-file overrides. Read authority, local/remote policy, traversal order and limits unchanged.
src/gateway/agent-turn/agent-run-dispatch.ts 541 541 0 Retained: common publishReplay/settleFollowup/settle/cleanupRunOwner already serve resolved and rejected results. Cleanup-started must remain latched before a possible synchronous cleanup throw, independently of its optional promise. Producer identity is captured after the capability bind callback, so it is not merged with the earlier registration snapshot.
src/gateway/server-methods/chat-send-work-admission.ts 535 535 0 Retained: reference count owns admission; active settlement additionally records whether one retained lease was released, so it cannot derive from the aggregate count. Retry comparison and root/caller release paths retain different failure and ordering contracts.
src/gateway/server-methods/push.ts 528 528 0 RETAINED: Prototyped reuse of the generic validated-handler owner while preserving narrow PushRequestOptions and async return behavior: push 528 to 516 (-12), validation 94 to 99 (+5), combined 622 to 615 (-7). Rejected the less clear API expansion and extra local factory for this marginal reduction. Native and worker authority acquisition must still receive the original options identity. | src/gateway/server-methods/push.test.ts src/gateway/server-methods/push-authority.test.ts src/gateway/server-methods/push-authority-in-process.test.ts src/gateway/server-methods/push-authority-router.test.ts src/gateway/server-methods/push-preferences.worker.test.ts
src/gateway/server-methods/session-catalog.ts 526 505 21 APPLIED: terminal availability chooses the same first failing message and shares one UNAVAILABLE response, preserving short-circuit gate order. Registry-response reuse prototype was 5 lines smaller but rejected because terminal intentionally consumes provider-only snapshot test seam; no test changes. Continue/import/archive retain distinct preflight and failure boundaries.
src/gateway/server-methods/environments.ts 522 522 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: REJECTED measured defineDesktopObserve factory: 522 to 526 (+4), misc-prototypes/environments.ts. Factory only wraps already-shared respondDesktopObserve and adds a request adapter. Applied the sound shared worker service/error core in environments.desktop.ts instead. | src/gateway/server-methods/environments.desktop.test.ts;src/gateway/server-methods/environments.node-command-authority.test.ts;src/gateway/server-methods/environments.pairing-snapshot.test.ts;src/gateway/server-methods/environments.pool.test.ts;src/gateway/server-methods/environments.session-exec-approval.test.ts;src/gateway/server-methods/environments.session-exec.test.ts;src/gateway/server-methods/environments.session.test.ts;src/gateway/server-methods/environments.test.ts
src/gateway/desktop/host-source.ts 521 519 2 Applied: one unavailable inspection constructor takes explicit detail, reason and optional security, preserving security omission and all first-failure messages. Acquisition and inspection retain distinct access/readiness semantics. 521 -> 519 (-2).
src/gateway/server-methods/chat-restart-recovery.ts 521 521 0 Retained: shared adopted-claim predicate and lifecycle snapshot projection already own repeat work. terminalized records a committed callback, not simply a returned persisted entry; removing it would classify a noncommitting result as settled.
src/gateway/server-methods/task-suggestions.ts 521 518 3 Applied a single SuggestedTaskContext to the three acceptance stages. Both request-capture prototypes were measured: method-table 521→519 saved 2 but obscured the explicit handler/req differences; callable variant 521→523 grew 2. Kept concrete requests, optional-handler fallback, all awaits and replay/rollback ordering.
src/gateway/server-methods/artifacts.ts 519 519 0 RETAINED: Reimplemented coalesced/fresh scan delivery tail: formatted 519 to 517 (-2). Rejected the less clear form: it allocates a collect closure for a joined request and adds a second !queued owner condition to save only the repeated three-line read/response tail. Retain the explicit coalesced early return, per-caller currentness and fresh-scan map publication. | src/gateway/server-methods/artifacts.test.ts
src/gateway/server-methods/usage.ts 517 517 0 Retained: shared detail resolver and date resolution already own common preparation. Timeseries missing data is INVALID_REQUEST; logs missing data is empty success. Cached report authority reread and release remain explicit.
src/gateway/server-methods/models-auth-status.ts 513 513 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Inline the one-use abort adapter at provider-wide logout. Preserve its exact six capabilities; do not pass the full context, whose optional getRuntimeConfig would change abort routing. | src/gateway/server-methods/models-auth-status.test.ts src/gateway/server-methods/models-auth-status-rollup.test.ts
src/gateway/server-methods/session-change-event.ts 512 512 0 REJECTED PROTOTYPE: shared capture with precomputed matching decision is 512 -> 512 (0), catalog-prototypes/session-change-event.ts. Removing the extra decision variable would reorder the key test across capture. Shared tombstone identity and clearing absent captured/captureFailed fields remain explicit.
src/gateway/talk/handlers/client-create.ts 502 502 0 Retained. Existing assertTargetCurrent shares identical authorization/replacement checks. Provider open, logical session creation, commit guard and owner activation are ordered barriers; logicalSessionCreated, delivered and providerReady represent independent facts. Browser versus relay launch cores differ in camera/control negotiation, provider cancellation and two-sided replacement readiness.
src/gateway/server-methods/sessions-read.ts 499 499 0 Excluded: coordinator-approved search-handler deferral; untouched.
src/gateway/server-aux-handlers.ts 498 498 0 REJECTED +3: root-prototypes/server-aux-handlers.ts implements a shared cancellation strategy for exact delegated-authority versus worker-turn closure. Both retain their source fields, log labels, immediate cancellation launch and subsequent question cancellation. The new typed target union and publication callback plumbing exceed the two explicit loops. Registration, shutdown and lazy handler families already share their existing owners.
src/gateway/server-methods/agents-files.ts 494 494 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One response projection for missing/local/remote document results; local fs-safe and remote bridge reads, decoder differences, write bounds and CAS remain unchanged. | agents-files.test.ts (results recorded separately)
src/gateway/server-methods/session-mutation-guards.ts 492 488 4 APPLIED: WebSocket source assertion reuses captureRequestMutationOptions with its explicit expected client. Signal/accepted-source read remains first, original field identity checks precede revocation, explicit undefined SDK guard check retained, and accepted source/policy/generation order unchanged.
src/gateway/server-methods/approval.ts 487 479 8 APPLIED: Forward the existing trusted handler dependencies into both visible-record lookups and resolution publication. Exact request id, authority, flags and context override the dependencies; readers consume only named fields. Export signatures and every await remain unchanged. | approval.test.ts; approval.request-authority.test.ts; approval.channel-custody.test.ts; full server-methods directory
src/gateway/session-lifecycle-preparation.ts 486 486 0 Retained after full read: one database/facts owner serves creation and patch consumers; child selection may be deferred into lifecycle custody, parent facts cannot. Commit action settlement preserves every failure and final error cause; workspace binding shares one commit/rollback owner. No safe shortening changes these custody boundaries.
src/gateway/agent-turn/agent-run-user-turn.ts 484 484 0 Retained: claimFollowup already shares canonical/alias claims. Private receipt admission, durable media custody, input completion and ordinary prompt persistence have distinct eligibility and errors. Single recorder owns input, and cleanup preserves both original and settlement failure.
src/gateway/server-methods/session-create-project.ts 480 473 7 APPLIED: prepare one shared cloneOptions bundle for materialize and refresh; owner functions only read it. Signal/token/startRun/current guard match both original objects. Identity checks, ref retry, persistence and rollback positions unchanged.
src/gateway/server-methods/sessions-delete.ts 476 476 0 Retained: deleteGatewaySession owns operator/expiry deletion with explicit incognito binding. Reader refreshes, drain handoff, worker retirement and generation checks have different custody boundaries. The outer drain release covers preparation failure while mutation finalize covers settled writes; neither is redundant.
src/gateway/server-methods/usage-session-selection.ts 469 469 0 Retained: canonical current identity and family owners are different maps; selecting historical families needs discovery while exact instance can skip it. Context reports retain physical target and revalidate session identity after worker reads.
src/gateway/server-methods/sessions-compact.ts 462 462 0 Rejected measured prototype: shared synchronous no-transcript response helper 462 -> 467 (+5). It preserves both authority checks without adding awaits, but requires result typing and repeated branch returns. Original direct checks are shorter; no production change.
src/gateway/server-methods/workspace-fs.ts 453 453 0 Retained: local fs-safe and remote bridge operations share root selection but deliberately differ in exception handling, canonical path, prefix support and CAS. A unified async root helper would add a yield for already prepared roots.
src/gateway/server-methods/chat-send-dispatch-errors.ts 451 451 0 Retained after implemented/formatted prototype: shared terminalizeFailure with explicit setup/dispatch phase measured 451 -> 450 lines (chat-prototypes/dispatch-terminalization.ts). The typed helper and call indirection save one line while hiding the direct callback invocation; retained the clearer direct paths. Prototype introduced no extra await, so async timing was not used as an estimate-only rejection.
src/gateway/server-methods/cron-caller-scope.ts 446 446 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/message-operation-route.ts 441 441 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One context-owned route state contains bindings and queue, eliminating duplicate WeakMap allocation/access owners. Binding expiry still runs only through binding reads, not queue acquisition; lock/replay sequencing unchanged. | src/gateway/server-methods/send.test.ts src/gateway/server-methods/send.scheduled-reads.integration.test.ts src/gateway/server-methods/send.discord-request-authority.integration.test.ts
src/gateway/session-row-projection-refresh.ts 440 439 1 APPLIED: remove the unused cfg argument from the sole withSessionRowDatabaseFacts call. REJECTED complete reserveBulkRead prototype is 439 -> 439 (0): preserving the metadata branch unconditional deletion and background branch identity-checked deletion requires a strategy argument, adding indirection for no reduction. Existing await/readiness loops remain in consuming frames.
src/gateway/desktop/computer-service.ts 437 433 4 Applied: one synchronous assertAvailable serves prepare and status with identical stopped-before-paused precedence and strings. Native runtime/provider checks remain at their original short-circuit positions. 437 -> 433 (-4).
src/gateway/server-methods/system-agent-approval.ts 437 437 0 Rejected actual shared transcript persistence prototype: 437 to 439 (+2) after formatting, due imported helper and five-line call versus existing four-line loop. Preserved original; prototype saved in lead-prototypes.
src/gateway/agent-turn/internal-facade.ts 429 429 0 Retained after formatted prototype: shared acceptance/final frame projection measured 429 -> 428 (agent-turn-prototypes/internal-facade.ts). A typed nine-line projector and two call sites hide two small direct response records for only one net line. Both distinct acceptance and final publication gates remain easier to read inline; lazy final Deferred avoids unobserved rejection when the caller only wants acceptance.
src/gateway/server-methods/chat-send-message-injection.ts 426 426 0 Retained: one captured starter serves pre-ACK and detached injection. Acceptance, outcome and finalization are independent barriers; failed/rejected/indeterminate outcomes remain separate. Main's uncertain-steering receipt behavior is unchanged.
src/gateway/server-methods/session-catalog-list.ts 426 426 0 REJECTED PROTOTYPE: extract final preparation with consuming-frame readiness recheck: 426 -> 425 (-1), catalog-prototypes/session-catalog-list.ts. Adds unconditional promise joins on already-ready reads and diagnostic nesting for one line; original branches keep response in the authorized consuming frame. Existing coalesced versus new-provider tails preserve distinct cleanup.

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 8, 2026
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

d01 PR 3 per-file coverage — part 2/5

Reviewed implementation head: 900b74a38d291476a712cfa5c601cf2c269e8eb1.

Gateway server-methods lane d01, PR 3 coverage

Baseline b3196dfda33555857eae9cd52ea29367a91bd9ea. This final lane pass re-evaluated prior rejected and partially simplified files, completed the current server-methods directory, and revisited its adjacent runtime owners.

608 production modules have per-file decisions, including all 427 current server-methods modules and the original exclusions. The implemented production diff removes 693 net lines; no test, protected storage, global-identity, config-retirement, tooling, or changelog paths changed. Existing assertions remain intact.

Counts describe the actual applied source against the original fresh-main base. Measured rejected prototypes are recorded in each relevant row. The PR body records executed validation separately; a named test below is a target unless that validation says it passed.

File Before After Net removed Decision and evidence
src/gateway/server-methods/plugins.ts 424 424 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One catalog failure mapper with explicit subject phrases for discovery/categories/details; preserve singular/plural text exactly and retain each handler own fallback. | Existing focused/full test targets: plugins.test.ts
src/gateway/server-methods/sessions-patch-model-selection.ts 420 416 4 Applied: the final selection/environment error chain uses one short-circuit policyError return, preserving selection precedence and no environment call after selection refusal. Prepared and raw model selection retain distinct exact-ref validation and result-shape projection.
src/gateway/talk/relay/state.ts 418 415 3 Applied: return the existing relay call ID or undefined directly from its agent-completed predicate. Same lookup, short-circuit, tombstone behavior and subsequent admission path. Kept output generation, cancelling/discarding and twin-terminal states independent. Tests: relay/index.test.ts, relay/cancellation-recovery.test.ts, relay/tool-call-ledger.test.ts.
src/gateway/talk/transcription-relay.ts 417 411 6 Applied: inline the single-use audio-format sample-rate reader into its one nullish fallback. Explicit sample rate still wins; regex executes only for a string after explicit parsing fails. Canonical parseFiniteNumber(undefined) returns undefined, preserving unmatched format behavior. TTL/draining/final transcript paths unchanged. Test: transcription-relay.test.ts.
src/gateway/server-methods/users.ts 414 414 0 Measured preference identity helper prototype 414→419 (+5); full preference factory was already +2 in PR2. The distinct set error conversion and get authority rethrow remain explicit. Profile edits retain differing write ownership, publication and post-merge receipt rules.
src/gateway/desktop/rfb-preauth.ts 412 412 0 REJECTED PROTOTYPE (rejected/ mirror): table-driven ARD username/password block writes with explicit byte offsets is 412 -> 414 (+2). Existing legacy/modern security headers already share zero/refusal behavior; encryption and exact-stream buffering retain separate wire contracts.
src/gateway/server-methods/chat-send-source-finalization.ts 412 412 0 Retained: late and ordinary source replies already share finalizeChatSendAgentReplyPayloads. Progress publication, terminal empty/canvas fallback and uncertain publication retain separate decisions; source mirror selection remains independent of dispatched transcript ownership.
src/gateway/server-methods/system.ts 411 411 0 Retained original explicit raw-parameter projection. Implemented 411-to-395-line spread prototype, then rejected it: the actual validator accepts nonenumerable host/deviceId fields that spreading drops, while in-process dispatch passes the payload by reference. Presence identity and fields must remain identical for those accepted inputs. Prepared-record spreads elsewhere were audited separately and their callers construct plain records.
src/gateway/talk/relay/forced-consults.ts 410 410 0 Retained. Common cancellation-result constructor participates in rejected 1999 -> 1998 aggregate prototype. Bounded allSettled snapshot retry and dynamic Promise.all recursion already share submitPending; their different failure and newly-arriving-ID contracts require both control flows.
src/gateway/server-methods/channel-pairing.ts 406 406 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Reuse publicAccount projection for request rows; raw code remains omitted and sender/metadata/expiry fields retain their original owners. | src/gateway/server-methods/channel-pairing.test.ts
src/gateway/talk/voice-selection.ts 403 403 0 Retained. Change/currentness/target/finish helpers already own repeat work. Claimed admission, client readiness, provider readiness and old-session retirement are independent handshake facts. Map membership cannot derive any of them without weakening replacement behavior.
src/gateway/server-methods/nodes.pairing.ts 401 401 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated approval/rejection/removal common handling. Pending ownership is already shared; approval additionally rotates pairing generation and updates only the retained connection while removal invalidates before replying and disconnects in finally. Shared event construction alone would need a separate return/broadcast adapter and does not replace those distinct owners. | src/gateway/server-methods/nodes.test.ts
src/gateway/server-methods/sessions-reactions.ts 401 401 0 Retained: reactionScope/withSessionReactionAccess already share preparation. Commit-time first/last-reactor decisions and FIFO channel-slot mirror settlement are different responsibilities; one write owner retains all no-op and delivery failure behavior.
src/gateway/server-methods/chat-send-reply-finalization.ts 398 398 0 Retained: one finalizer shares media custody with the source finalizer. Bound mirrors require a second target read and no source fallback; ordinary/native/BTW outputs preserve their own transcript and terminal semantics. A single output-message constructor would need empty-text/omitted-text flags for just two small literal projections.
src/gateway/server-methods/mcp-app.ts 398 398 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Existing requested-view resolver now accepts prepared config/requester facts for operationHandler. Original config reads, requester capture, restore:false and post-await authority checks stay at their existing boundaries. | src/gateway/server-methods/mcp-app.test.ts
src/gateway/server-methods/chat-reply-media.ts 397 392 5 Applied: express data/audio preservation as one short-circuit predicate; trusted local audio still requires audio filename classification and preserves the same reader limits. Mixed-media normalization retains whole-payload metadata and ordered per-item failures.
src/gateway/server-methods/session-catalog-list-lifetime.ts 396 396 0 REJECTED PROTOTYPE: shared publishNext with explicit captured/live publisher strategies: 396 -> 406 (+10), catalog-prototypes/session-catalog-list-lifetime.ts. Captured synchronous subscribers and live post-await subscribers remain explicit; native work custody cannot derive from delivery pending count.
src/gateway/server-methods/chat-send-attachments.ts 395 391 4 Applied: map each offloaded reference directly to the existing staged MediaFact, then derive fallback path/type at the final projection. Removed redundant intermediate path/MIME record construction; request order, managed-PDF fallback and cleanup remain unchanged.
src/gateway/server-methods/migrations.ts 394 394 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Pass the complete existing provider-plan parameter record directly to its owner; removes single-use four-field repack without changing plan input keys or call order. | migrations.test.ts;migrations.resources.test.ts (results recorded separately)
src/gateway/server-methods/secrets.ts 388 388 0 Read all store/resolve owners and lifecycle tests. mutateStore already shares set/delete redaction, commit evidence, refresh and failure projection. Its synchronous guard capture, nested attempt await, and committed flag are necessary to distinguish pre-write rejection from post-write refresh failure. Scope/config store unchanged.
src/gateway/server-methods/mcp-app-extensions.ts 387 387 0 RETAINED: Reimplemented launchOrCall shared variant: formatted 387 to 393 (+6). Rejected longer dispatch layer; call already owns approval/form custody, and launch calls that core before transferring a view lease. | src/gateway/server-methods/mcp-app-extensions.test.ts
src/gateway/server-methods/nodes.read.ts 386 386 0 REJECTED after boundary review: payload-field variant dispatch changed behavior for inherited properties accepted by TypeBox and in-process callers. Restored original method-owned handlers. Cast-free strategy prototype measures 386 to 390 (+4), so rejected. | node plugin-tools/skills update tests; pure actual-validator prototype probe
src/gateway/server-methods/themes.ts 383 381 2 Applied common profile-changed rejection with short-circuit OR; preserved check order and exact text. Read/write/canonical profile, catalog CAS and post-save reread owners are already shared; moving reread into writeThemes would change the existing awaited publication boundary.
src/gateway/desktop/observe-bridge.ts 371 371 0 RETAINED: preauth and transparent transport converge in startSplice and closeBoth already. Browser detach/credential release precedes listener installation on success and precedes failure closure on rejection; common finally would move these transitions. Flowing WebSocket buffering differs from native readable handoff in rfb-probe.
src/gateway/server-methods/sessions-lifecycle-drain.ts 371 371 0 Retained: drains are already joined as explicit work promises. Admissions, inference reservation, terminal ownership and reclaim release have distinct error/settlement rules; nested finalizers deliberately guarantee later release after earlier failure.
src/gateway/server-methods/sessions-patch-archive.ts 369 369 0 Retained: resolveCurrent already shares initial/commit-edge ownership checks. Initial placement validation deliberately uses false and projected preview uses true; their shared literals do not permit combining the pre/post-projection validation. Restore guard retains separate workspace admission.
src/gateway/server-methods/chat-assistant-content.ts 361 357 4 Applied: empty initial output uses the existing separator decision instead of a separate assignment/continue branch. Text, indentation and newline boundaries remain byte-identical; media display/persistence paths already share managed-block classification.
src/gateway/server-methods/chat-send-commentary-media.ts 361 361 0 Retained: observer serializes committed commentary rewrites with source authority; initial projection wait repairs a missing anchor, later wait follows media preparation. Uncertain rewrite retains media custody and blocks later writes; it cannot derive from ordinary committed state.
src/gateway/server-methods/request-authorization.ts 361 361 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One synchronous method/startup/profile/scope reauthorization core; explicit assertion callback distinguishes invocation from preparation and release callback preserves final-access cleanup. | Existing focused/full test targets: ../server-methods.dispatch-authorization.test.ts ../server-methods.canonical-validation.test.ts ../session-row-prepared-read.test.ts
src/gateway/server-methods/session-active-runs.ts 360 347 13 APPLIED: inline the single-use session-id matcher into its selecting owner. Key matching still runs first, and id fallback retains only resolved/default agent ownership; key fallback resolution remains distinct. Explicit undefined/empty-string checks retain truthiness while narrowing the owner type.
src/gateway/server-methods/update-admission.ts 356 356 0 Retained: host/immutable/OCM admission is ordered; error regex priority includes stage-dependent sentinel/transfer branches. Ledger refusal and error reporting reuse existing diagnostics owners.
src/gateway/server-methods/sessions-github.ts 355 355 0 Retained: defineSessionGitHubMethod already shares request owner validation/error mapping. Options owns deadline revocation and personal/shared revalidation; status owns captured request lookup. Consolidating these request bodies would obscure the distinct preparation and currentness timeline.
src/gateway/desktop/node-stream-broker.ts 350 350 0 RETAINED: desktop/portal already share mintStream, metadata parse and exact connection predicate before/after pairing awaits. Ticket pending versus redeemed tracks distinct handoff ownership, and terminal error listeners intentionally outlive first metadata parsing.
src/gateway/server-methods/chat-send-user-turn.ts 346 332 14 Applied: move single-use persistChatSendImages into the caller's async preparation closure, removing its argument/type mirror and two imports. Kept the original async/await structure, ACP bypass, no-media result, shared persistence promise and authority callbacks.
src/gateway/server-methods/chat-history-session-read.ts 343 343 0 Retained: projected, excluded and retained transcript reads share authorization but select different authoritative metadata owners. Final retained publication remains synchronous; a common asynchronous reader would reopen the visibility fence.
src/gateway/server-methods/chat-send-request.ts 341 333 8 Applied: one local rejection constructor projects the thirteen identical failure-result shapes. Every original validation condition, precedence, synchronous return and user-visible error text remains unchanged; successful normalization and forwarded owner errors are untouched.
src/gateway/server-methods/skills-library.ts 329 329 0 Retained: libraryHandler and selectedSession already share request admission. Read versus activate consume different authority and revision facts; get/save/import/upload use distinct owner APIs, and direct callback forwarding would pass the handler options as unintended database options.
src/gateway/session-row-projection-ancestors.ts 329 329 0 RETAINED: generic readSessionRowAncestors already shares ancestry expansion for metadata and materialized rows through explicit prepare strategy. Exact event preparation retains membership/placement handoffs, archived pins and recursive pending-facts recovery; moving these checks behind a promise would break synchronous consuming-frame readiness.
src/gateway/desktop/managed-linux-audio.ts 328 328 0 RETAINED: server and capture share supervisor ownership but not readiness or teardown: server marks optional capability unavailable; capture aborts first data, destroys its stream and joins per-capture descendants. Existing stop/fail helpers own each distinct lifecycle; private route bytes and daemon isolation remain explicit.
src/gateway/server-methods/chat-send-command-replies.ts 327 327 0 Retained: one fold owner preserves prepared plan ownership and raw-only dedupe. mergeDefinedReplySemantics reuses mergeMediaReplySemantics; optional field table prototype needs generic key assignment/type scaffolding and is longer than the six direct defined-field spreads.
src/gateway/server-methods/worktrees.ts 327 327 0 Measured required-owner shared factory 327→336 (+9), saved as misc-prototypes/worktrees-owned.ts. Optional-owner variants also have create identity and remove mutually-exclusive-flag validation before capture; retaining that order avoids scope errors hiding invalid-parameter refusals. Existing schema wrapper remains.
src/gateway/session-create-model-selection.ts 327 309 18 Applied: fold otherwise-single-use createSessionCreateCommitGuard into resolveSessionCreationCommitGuard. Keep captured selection array and order: caller, prepared target, current operator, model validation, selections. Removed exported helper had exactly one production caller plus a service type reference; no test, script or public SDK import found.
src/gateway/agent-turn/agent-dedupe-lifecycle.ts 321 321 0 Retained: reserve/bind/clear/reset/restart share recordCommittedReset and canonical dedupe writes. reserved and accepted capture independent custody state after another owner replaces map entries. Explicit reset notice strings and publication order remain unchanged.
src/gateway/talk/session-config.ts 321 321 0 Retained. Realtime/transcription share canonical voice-model default selection, provider lookup and configuredOrFalse. Their model precedence and provider fallback differ. Launch option sanitizer already table-drives string and finite-number families. Streaming provider assignment preserves inert/current key semantics; no config normalization rewrite attempted.
src/gateway/server-methods/usage-date-range.ts 320 320 0 Retained: shared date-part conversion, range table and atomic date validation already consolidate modes. Gateway/timezone skipped days retain different constructors and one-day lookahead contract.
src/gateway/talk/handlers/client.ts 318 318 0 Retained. Tool-call preparation, transcript write and close intentionally classify errors as INVALID_REQUEST; steer uses shared authority-aware request errors. Legacy binding is reread after await to consume concurrent replacement. Client and relay voice IDs retain exact target and origin restrictions.
src/gateway/server-methods/chat-history-response-page.ts 317 312 5 Applied: one grow(index) budget operation extends the anchored window on either side, retaining older-first alternating order and per-side stop flags. Removed unreachable private count-cost fallback because its sole caller always passes the byte-cost function.
src/gateway/server-methods/session-catalog-provider-access.ts 314 306 8 APPLIED: inline private providerCreateTargetCache into its sole resolver. Config/provider/agent cache hierarchy and exception non-caching remain identical; list step ownership and provider callback custody remain separate.
src/gateway/server-methods/claws-monitors.ts 313 313 0 RETAINED: Reviewed only. Monitor cleanup is adjacent cron/config retirement ownership and is retained untouched; inspect, quiesce and drain preserve different scheduler/journal authority and database preparation boundaries. | Full server-methods directory; results recorded separately
src/gateway/server-methods/agent-session-patch.ts 312 312 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Removed redundant inheritedGroup=undefined from the catch: the only assignment is the final expression in its try, so every throwing path leaves the fresh variable undefined. Canonical-key migration errors still rethrow. | agent-session-patch.test.ts;../agent-turn/agent-session-reuse.test.ts; results recorded separately
src/gateway/server-broadcast-narration.ts 304 304 0 Retained: one per-session pacing owner consumes chat snapshots and suppresses mirrored agent text. Flush re-enters broadcaster for live scope/sharing/socket checks. Pending text, last digest, timer and subscription keys encode different lifetime facts and cannot derive from each other.
src/gateway/server-methods/chat-send-turn-adoption.ts 303 303 0 Retained: enqueued, terminalKnown, steered and adoptionStarted describe independent handoff facts; map membership cannot derive them after controller retirement. Terminal projection is already shared by completion, abort and abandoned callbacks.
src/gateway/server-methods/plugin-approval.ts 303 303 0 RETAINED: Re-read complete plugin request/list/wait/resolve implementation and canonical decision source. Existing shared delivery/resolve/wait owners retain identity and allowed-decision differences. No second persistence or approval-effect owner remains. | plugin-approval.test.ts;plugin-approval.agent-runtime.test.ts (results recorded separately)
src/gateway/server-methods/tts.ts 303 303 0 Retained: status/providers already share prepared provider facts and enable/disable share one handler. Conversion returns a local path while speak returns bytes with secret-owner error details; collapsing responses would require equally large variant strategies. Preference routes validate at different boundaries before one canonical setter.
src/gateway/server-methods/sessions-suggestions-access.ts 301 286 15 Applied: moved the publication-only helper into its sole consumer alongside protocol projection, removing a cross-module seam; mutation access and settlement owner remain here unchanged.
src/gateway/desktop/rfb-probe.ts 296 296 0 RETAINED: probe owns readable-buffer preservation and same-connection version replay; preauth owns a flowing exact-byte queue. Replacing both with one reader would require separate read/abort/detach/EOF strategies and obscure native unread-byte custody. Version parser and security selection already serve all callers.
src/gateway/server-methods/config-write-flow.ts 294 294 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/chat-user-turn-recorder.ts 292 292 0 Retained: one recorder owns input merging, persistence and mention commit. Best-effort persistence intentionally suppresses only its owner error; stable original intent, committed mention projection and input promise merge are distinct operations.
src/gateway/server-methods/web-search-status.ts 291 291 0 Retained: config credential, environment and fallback precedence intentionally interleave; catalog route variants are a single selection tree, not parallel execution paths. Disabled/native/external/unready/managed routes have distinct public guidance and testability.
src/gateway/agent-turn/agent-request-preflight.ts 289 289 0 Retained: rejectInvalidRequest already consolidates failure construction. Collector admission, source provenance and recovery flags are ordered checks of separate authority facts; they do not perform duplicate effects.
src/gateway/server-methods/github-personal-authorization.ts 288 288 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Shared currentGitHubClient is the actual scope core. Read allows absent human profile and snapshots archive state; action requires personal owner and rejects archived rows. Another common target reader would add options for errors, profile requirements, archive and sharing policy. | github-personal-authorization.test.ts (results recorded separately)
src/gateway/server-methods/agent-session-prepare.ts 286 286 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Derived visibleRequest from the existing isSystemGatewayRun fact instead of repeating cron/heartbeat exclusion. Computation moves across no await or mutation; initial and admitted session reads and all retry errors unchanged. | ../agent-turn/agent-session-reuse.test.ts;artifacts.images.test.ts; results recorded separately
src/gateway/presence-summary.ts 285 285 0 Retained original after focused lint: conditional spreads inside map violate no-map-spread. The 10-line prototype was discarded; Object.assign or another helper would obscure the projection for no useful reduction.
src/gateway/server-methods/nodes.wake.ts 282 273 9 APPLIED: Flatten the shared stale-registration helper to one positive predicate and awaited conditional removal. The same registration and result reach the canonical cleanup owner; all wake/nudge generation guards and return states stay unchanged. | nodes.invoke-wake.test.ts; nodes.invoke-abort.test.ts; nodes.pending-work.test.ts
src/gateway/server-methods/users-personal-file.ts 282 282 0 Retained: read/write already share preparePersonalFile and runPersonalFile. Read guard, hash compare, no-alias write and postwrite authority check occupy distinct race boundaries. Durability, missing shape and actor authority unchanged.
src/gateway/server-methods/models-auth-status-usage-cache.ts 280 280 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read cache identity, SWR and timeout retention. cacheGeneration fences clear-and-replace; refresh object identity independently fences newer in-flight work. Identity fields are intentionally copied without retaining authStore/provider arrays in cached results. Scalar model-status and usage-status cold-read contracts differ. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/session-catalog-list-operations.ts 275 275 0 RETAINED: state-generation and per-client maps intentionally share only retirement, while per-client close releases provider operations and generation retirement clears all maps. Provider admission versus cached-page retention are different owners, already parameterized through listSessionCatalogWithinBudget.
src/gateway/server-methods/sessions-patch-expectations.ts 274 256 18 Applied: inlined private bindPreparedSessionPatchTarget into its only preparation-loop caller, removing the parameter threading object/type. Original guard is captured before creating the closure; assertion order, source mismatch and failure precedence stay unchanged.
src/gateway/agent-turn/agent-content-phase.ts 273 273 0 Retained: image capability preparation precedes voice routing while media parse follows it; collapsing them changes preparation and failure ordering. Agent- and session-selected voice routes share final output but preserve distinct validation and text.
src/gateway/session-reset-acp.ts 273 269 4 Applied: reuse one readMeta(sessionKey) closure for candidate selection and post-cleanup metadata reread. It returns the owner promise directly, preserving awaits, currentness checks, fallback key ordering and callback parameter shape.
src/gateway/server-methods/chat-metadata-session-projection.ts 271 271 0 Retained: prepared catalog projection already shares its decision owner with models.list; account selection and runtime lock are live overlays. Session catalog key fields and context predicate describe different data contracts, not duplicate preparation.
src/gateway/server-methods/update-status.ts 271 271 0 Retained: native and OCM status share common projection; native get has a no-reconciliation drain read distinct from rooted reconciliation. Both responses already one line; factoring adds parameters without removing substantive duplication.
src/gateway/desktop/computer-process.ts 268 262 6 Applied: failWhileOpen centralizes the same closing guard and error normalization for launch rejection, wait rejection and unexpected exit. Physical cleanup/finalization distinction and request cancellation stay unchanged. 268 -> 262 (-6).
src/gateway/server-methods/session-catalog-entry-snapshot.ts 268 268 0 RETAINED: planning caches are revision/config/agent scoped, delivery profile caches are request scoped, and frozen entry indexes retain original adoption generations. These are different invalidation responsibilities; no duplicate row owner to merge.
src/gateway/agent-turn/agent-admission-controller.ts 265 265 0 Retained: one assertAllowed controls admission outcome, and one respondToOutcome already projects abort/timeout/superseded variants. Flags preserve accumulated outcome precedence across revalidation; map membership cannot derive them after reservation replacement.
src/gateway/server-methods/update-report.ts 263 263 0 Retained: three public result variants differ in required versus omitted keys and field order. Preview and submit revalidate connection-bound publication authority; no changed report contract.
src/gateway/server-methods/exec-approvals.ts 262 262 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Shared exact STATE_OWNER_CHANGED error projection with worktrees via local-state-owner. Local get/set keep distinct missing-state/hash behavior and node handler remains one policy/invoke owner. | src/gateway/server-methods/exec-approvals.test.ts
src/gateway/server-methods/sessions-messaging.ts 262 262 0 Retained: send/steer already share handleSessionSend with queue mode. ACK success, cached flag, run id and interrupted flag are intentionally captured before respond can mutate the payload; post-response derivation is not equivalent.
src/gateway/terminal/launch.ts 262 261 1 Applied: use preparedConfig once as the outer commit guard, with explicit pending-restart versus active-config destinations; remove block/return ceremony in the existing resolveForConfig closure. Formatted 262→261 (-1). Both restart/commit restriction buckets, prepared/unpublished versus applied truth and exact Windows/POSIX spawn behavior remain distinct. No config contract changes.
src/gateway/server-methods/chat-broadcast.ts 261 254 7 Applied: one broadcastChatPayload core sends websocket then node delivery. Ordinary frames retain their exact shared opts object; side results keep their original second current-routing lookup. Sequence increment/deletion and error ordering are unchanged.
src/gateway/server-methods/sessions-goal.ts 261 261 0 Retained: update/clear already share owner. Resume delegates accepted input to chat, while direct mutation retains source authorities and its operation fingerprint. Source failure releases acquired authorities in the existing reverse cleanup order.
src/gateway/server-methods/sessions-subscriptions.ts 261 261 0 Retained: provisional subscription and rollback already share a scaffold. Approval replay commit remains outside its catch; ordinary commit remains inside. Retried replay checks remain explicit because each release/await/currentness check belongs to its attempt.
src/gateway/server-methods/chat-history-page-kernel.ts 259 259 0 Retained: shared reply/canvas decoration covers anchored pages and tail reads. Anchored direction excludes source-row siblings while tail owns incremental recovery/byte probing; cost-free boundary traversal cannot reuse cost traversal without additional callback scaffolding.
src/gateway/server-methods/web-search.ts 257 257 0 Retained: status/test preparation repeats four lines, but extracting an awaited preparation result would add a yield after profile assertion; retaining the same live check requires another assertion. Search execution already shares result/answer envelope; provider error normalization stays before final live recheck.
src/gateway/agent-turn/agent-request-routing.ts 256 254 2 Applied: remove the catch assignment of undefined to a fresh currentSessionId local; its only assignment is the final expression of try, so every exception leaves it undefined already. Exact routing, rebound diagnostic and reservation clearing remain unchanged.
src/gateway/session-row-projection-generation.ts 255 255 0 RETAINED: cached source identity versus newly statted file facts are distinct acquisition branches. Shared mutations already route old/current identities through owner matching; old-row invalidation, committed-row replay avoidance and exact new-source publication cannot share one predicate without losing reentrant-commit distinctions.
src/gateway/server-methods/chat-history-delta.ts 251 251 0 Retained: all local/incognito/worker paths share projectChatHistoryDelta and limits. Local precheck avoids acquiring subagent facts for reset deltas; worker path consumes already-prepared facts. Reset outcomes preserve append-only visibility.
src/gateway/server-methods/environments.session.ts 250 250 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read attached environment create/status/destroy. Shared caller owner handles synthetic/operator policy and live session identity. Create additionally owns presentation permission and UI handoff; destroy binds canonical session attachment; status projects null separately. No duplicate attached service owner. | src/gateway/server-methods/environments.session-exec-approval.test.ts;src/gateway/server-methods/environments.session-exec.test.ts;src/gateway/server-methods/environments.session.test.ts
src/gateway/desktop/audio-bridge.ts 249 249 0 RETAINED: pending callback is the latest requested transition, transition promise is active recorder work, captureAbort owns a particular generation. Existing settle already shares listener cleanup and terminal delivery; further merging would change audio authentication readiness or screen-independent close behavior.
src/gateway/server-methods/chat-history-budget.ts 248 248 0 Retained: one byte counter owns memoized message/activity sizes and distinct framing costs. In-flight priority retention has only events requiring suffix search; timestamp/plan/text scalars already use one retainIfWithinBudget core.
src/gateway/server-methods/skills.ts 248 244 4 Applied one skill-card unavailable response with explicit found/readable wording. Files are searched only when skill-card metadata exists, empty-string content still succeeds, and protocol fields remain identical.
src/gateway/agent-turn/agent-delivery-phase.ts 247 241 6 Applied: inside the final wantsDelivery + internal-channel branch, shouldDowngradeDeliveryToSessionOnly reduces exactly to bestEffortDeliver. Keep the earlier catch-path helper because channel selection may have changed resolvedChannel before a later failure. Target binding, fallback and incognito error redaction remain unchanged.
src/gateway/server-methods/approval-visible-record.ts 247 247 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: Shared session/reviewer visibility with lazy source/reviewer suppliers: config read precedes source fields; session authorization precedes reviewer binding read; preserves synchronous reentrancy order | src/gateway/server-methods/approval.test.ts src/gateway/server-methods/approval.request-authority.test.ts src/gateway/server-methods/approval.legacy-authority.test.ts
src/gateway/server-methods/agents-workspace.ts 245 245 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Text/image variants share content selection, unsupported refusal, and final file projection; only image paths await MIME detection, and each retains the same size/decoder gate. | agents-workspace.test.ts (results recorded separately)
src/gateway/server-methods/artifacts-session-resolution.ts 245 245 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: createArtifactSessionAccess is the shared HTTP/RPC release owner. prepareArtifactSessionResolution captures the query, resolves run versus explicit-session addressing and exposes one readCurrent fence used before delivery. artifactResponseIsCurrent only translates its typed error to RespondFn; it does not repeat authorization or facts acquisition. | Full server-methods directory; results recorded separately
src/gateway/server-methods/session-catalog-visibility.ts 242 242 0 RETAINED: pre-provider and post-provider visibility checks need their own reads and synchronous consumer frames. Read/mutate distinction already explicit in access parameter; owner/publication audiences use the shared canonical policy.
src/gateway/desktop/node-source.ts 241 240 1 Applied: redact the successfully selected preauth password once after either explicit VNC/ARD credential branch. Credentials/error text/type narrowing unchanged; redaction still precedes publication and token minting. 241 -> 240 (-1).
src/gateway/server-methods/approval-record-lookup.ts 241 241 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Inline single-use lookup refusal mapper at narrowed none/ambiguous branch; simplify final visibility truth table while retaining all authority and storage checks. | approval-shared.test.ts;approval.legacy-authority.test.ts;plugin-approval.test.ts (results recorded separately)
src/gateway/server-broadcast-live-text.ts 240 240 0 Retained: socket delivery state and source publication are distinct owners. Global pending Set preserves interleaved FIFO while per-group Map serves coalescing lookup, so deriving one from grouped iteration would reorder flushes. inFlight/draining/retired separately guard transport callbacks, recursive drain and terminal failure.
src/gateway/server-methods/models-auth-status-facts.ts 239 239 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Share configured provider tracking after the existing per-source eligibility/normalization checks; same API-key exclusion and OAuth expectation sets. | Existing focused/full test targets: models-auth-status.test.ts models-auth-status-rollup.test.ts
src/gateway/server-methods/plugin-host-hooks.ts 239 239 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Session action validator already shares refusal projection. UI descriptors and action results use distinct schemas/error codes and dynamic scope checks; returning wireResult directly would leak extra plugin fields that current projections omit. | plugin-host-hooks.registry.test.ts (results recorded separately)
src/gateway/server-methods/approval-request-authority.ts 238 238 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read broad then source-narrowed policy capture. Worker grant and native authority intentionally select different guard families, then share assertPolicyCurrent. configRevoked records intermediate revoke/restore transitions and cannot derive from latest config alone. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/chat-origin-routing.ts 236 236 0 Retained: one explicit-origin normalizer and one inherited-route policy. Explicit fields retain omission semantics; inherited route retains present-undefined fields and CLI/main compatibility authority. Shared result factory would need omission flags.
src/gateway/agent-turn/agent-run-subagent.ts 235 235 0 Retained: successor, parent resume and requester-completion paths share false lifecycle flags but transfer distinct owners. A base-result object would be four definition lines plus three spreads versus six literal field lines, increasing LOC. Plugin registration and native reactivation remain independent effects.
src/gateway/server-methods/memory-search.ts 234 234 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: memory.search v1 uses a transient legacy MemorySearchManager, floors/clamps maxResults, exposes searchMode/staleness, and closes the manager in finally; version 2 delegates to memory-provider. memory.get/status are intentional lazy imports. Versioned parameter validation and wire results differ, so merging parsers or provider ownership would change the shipped contract. | src/gateway/server-methods/memory-search.test.ts
src/gateway/server-methods/agent-reset-phase.ts 233 233 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: runAgentResetPhase records reset completion at the reset commit and again after the returned reset identity is known. Post-reset text continues admission; a bare reset instead delivers an acknowledgement, caches its result and records reply failure without replaying reset. The shared performGatewaySessionReset owner already owns the reset itself; the two completion observations protect different failure windows. | Full server-methods directory; results recorded separately
src/gateway/server-methods/conversations.ts 233 224 9 APPLIED: Use the existing validated-method error mapper for conversation listing. Validation, the awaited list operation, three response arguments and Error-versus-String text remain identical; send/turn receipt ownership is unchanged. | conversations.test.ts
src/gateway/server-methods/audit.ts 232 232 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/wizard.ts 232 232 0 Retained: wizardSessionHandler already shares schema/access. Start/next terminal drains are separately awaited before response; PR2 measured combined next-result helper 232→238 (+6). cancel(closeInput), ordinary cancel and status intentionally differ in settlement ownership.
src/gateway/server-methods/cron-runs.ts 231 231 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/chat-metadata-handler.ts 227 227 0 Retained: saved-session and draft reads share current requester policy; saved path additionally holds exact session and worker-placement authority. createPreparedReadHandler already owns asynchronous publication errors and release.
src/gateway/server-methods/device-scope-upgrade.ts 227 227 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: readUpgradeOwner and respondDeviceRequired already serve requestUpgrade and waitUpgrade. RequestUpgrade verifies the paired public key, proposed scopes and current-scope inclusion before creating pairing; waitUpgrade releases an approved token only under the current role ceiling. Request creation and identity-bound waiting are separate coordinator operations, with different public refusal text. | Full server-methods directory; results recorded separately
src/gateway/agent-turn/agent-dedupe.ts 224 224 0 Retained: one canonical single-entry writer handles the batch. Accepted retry and source selection require different status/registration facts; source replay payloads intentionally omit fields that internal terminal records retain.
src/gateway/server-methods/core-handlers.ts 224 224 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated largest static loader table. Each entry binds a distinct literal import/export; lazy ownership and eager-closure discovery require those explicit edges. Existing createLazyCoreHandlers/createLazyPromise already own common loading/rejection policy. Prior generic export selector prototype was 222->262 (+40); no additional executable per-family core remains. | lazy-core-handlers.test.ts;../server-methods-list.test.ts; results recorded separately
src/gateway/server-methods/tools-catalog.ts 224 224 0 Retained: instantiated and declared-but-unresolved tools share appendTool; label/description fallback differs by source. Metadata key retains plugin+tool ownership and no broad plugin registry changes.
src/gateway/server-methods/session-catalog-gateway-copy.ts 223 223 0 RETAINED: one copy flow bounds model choice and transcript initialization. Similar import flow has different source authorization and atomic-initialization contracts; copy notice and history transformations stay distinct.
src/gateway/server-methods/system-agent-setup-wizard.ts 223 223 0 Retained: retry ownership retains predecessor settlements and pending ids separately. Normal and superseded requests intentionally differ in registry publication; existing activation function already supplies shared runner callbacks.
src/gateway/server-methods/chat-webchat-media.ts 221 221 0 Retained: image data URLs and local audio have distinct admission and filesystem contracts. Shared per-payload loop already merges text, directives and ordered blocks; per-media flags are needed for synthetic captions while global sets deduplicate across payloads.
src/gateway/server-methods/memory-provider.ts 221 221 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: handleMemoryProviderRequest already owns search/get/health admission, provider acquisition, response, close, and authority release. parseOperation preserves operation-specific error order; captureMemoryReadAuthority distinguishes admitted synthetic runs from live operator sockets. No second provider-execution pipeline remains. | src/gateway/server-methods/memory-provider.test.ts

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

d01 PR 3 per-file coverage — part 3/5

Reviewed implementation head: 900b74a38d291476a712cfa5c601cf2c269e8eb1.

Gateway server-methods lane d01, PR 3 coverage

Baseline b3196dfda33555857eae9cd52ea29367a91bd9ea. This final lane pass re-evaluated prior rejected and partially simplified files, completed the current server-methods directory, and revisited its adjacent runtime owners.

608 production modules have per-file decisions, including all 427 current server-methods modules and the original exclusions. The implemented production diff removes 693 net lines; no test, protected storage, global-identity, config-retirement, tooling, or changelog paths changed. Existing assertions remain intact.

Counts describe the actual applied source against the original fresh-main base. Measured rejected prototypes are recorded in each relevant row. The PR body records executed validation separately; a named test below is a target unless that validation says it passed.

File Before After Net removed Decision and evidence
src/gateway/server-methods/sessions-groups.ts 221 216 5 Applied: put, rename and delete share error classification with explicit input-error class parameters. Changed authorization still escapes; invalid request messages remain unformatted and unavailable errors remain redacted. Each caller retains its original finally/publication boundary.
src/gateway/session-create-service.types.ts 220 220 0 Retained: public/internal creation options carry distinct title, account, lifecycle, provenance and committed-publication contracts. All fields have real caller or owner use; no protocol/config changes.
src/gateway/server-methods/message-action-context.ts 219 219 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read capability redemption and action guards. Fenced reads, scheduled writes, and delivery attempts intentionally carry separate owner assertions composed by createAgentRuntimeAuthorityGuard. Empty/non-empty context projections differ in authenticated requester selection and signed identity validation. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/session-row-projection-publication.ts 215 215 0 RETAINED: acquirePublishedEntry already shares ordinary entry and ownership-only publication. ACP, removed, stored-entry, sharing-only and uncertain-facts paths change different certified facets; generation renewal is already canonical. Shared facets retain their independent publication owners.
src/gateway/server-methods/cron-creator-authority-admission.ts 214 214 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/cron-input-validation.ts 213 213 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/session-processes.ts 213 213 0 RETAINED: selected-schema prototype reduced 213 -> 212 but TypeBox inference collapsed the structural union to list parameters. An explicit generic adds two lines (214), so the original independently narrowed list/stop checks remain. This prototype was reverted after the lead declaration check found TS2322/TS2339; no casts, suppressions, or test changes.
src/gateway/session-row-projection-context.ts 212 209 3 APPLIED: group all presentation-only switch scopes under one existing return while preserving profile invalidation and broad config/store reset behavior. Registry refresh and per-row presentation remain separate revision consumers; no model/profile cache freshness was broadened.
src/gateway/talk/session-registry.ts 212 212 0 Retained. runTalkConnectionCleanup is the shared reentrant owner. pending fences before callback invocation; failed retains retry custody without a promise; nextRun records replacement cleanup. A single promise or map-membership flag cannot replace those states.
src/gateway/session-row-projection-archive.ts 210 210 0 RETAINED: pinCounts derives incrementally from request pin sets to keep eviction bounded; the request-token map lets disposal invalidate future closures without retaining their page ids. Shared demote/trim/unpin already own the repeated state mutations; cold lineage update deliberately publishes both old and new relatives.
src/gateway/talk/handlers/voice.ts 209 209 0 Retained. Existing authorizeSession core and one success response already parameterize managed/browser voice changes. Managed execution authority and browser storage identity require different live assertions; same target cannot be derived merely from voice ID.
src/gateway/server-methods/models.ts 208 208 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Applied one error response after ordered typed error classification. Unknown provider, sharing authorization, superseded publication retry and account authority retain original instanceof precedence and shapes; unrecognized errors still rethrow. | models.prepared.test.ts;models-list.membership.integration.test.ts;models-list.freshness.integration.test.ts; results recorded separately
src/gateway/server-methods/chat-metadata-session-read.ts 207 207 0 Retained: ordinary reads own database lifecycle resources and prepared predicate refresh; incognito reads stay process-held. Active/resource state and retained predicate state are independent. Both already share currentness and release closures.
src/gateway/server-methods/chat-transcript-inject.ts 207 207 0 Retained: specialized settled-producer append returns early; ordinary append preserves rejectedReason/predicateSkipped semantics. Combining their final projection saves two lines but nests the full ordinary append path under an else and requires shared union state, so less clear.
src/gateway/server-methods/web.ts 203 202 1 Applied head-derived missing-plugin repair selection; removed repeated expectDefined calls and one temporary. Dense hint production verified in official-external-plugin-repair-hints.ts. Exact singleton/multi-hint text, provider binding and QR stop/restart behavior unchanged.
src/gateway/server-methods/cron-history.ts 202 202 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/agent-session-reset.ts 199 199 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: resolveBareSessionResetResult skips delivery when unrequested, prepares the session delivery plan once, rechecks authority after each await, and gives main/global resets their existing best-effort default. buildBareSessionResetResult/Response are separate payload and RPC-envelope builders. No duplicate send execution exists inside the file. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/session-catalog-import.ts 199 199 0 RETAINED: import owns repeatable destination identity, source visibility throughout writes, preserved transcript dedupe and after-commit handling. Gateway-copy shares existing creation/history owners already; no duplicated contiguous side-effect core remains.
src/gateway/server-methods/tools-github.ts 198 198 0 Retained: shared validated-handler and agent selection owners; setup identity expected-state CAS and OAuth start/poll/cancel have different catch text and lifecycle operations. Additional generic wrapper not needed.
src/gateway/server-methods/agents-config-mutations.ts 197 197 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-broadcast-scopes.ts 196 197 -1 Applied common isPlainEventPayload predicate for session invalidation, model metadata invalidation and broadcaster source-skipping. Exact checks retain Proxy rejection before object reflection and exclude nonplain/toJSON objects without invoking getters. Public event scope table and scope decisions unchanged.
src/gateway/server-methods/models-probe.ts 196 196 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: mapProbeResult already shares status/error projection for all probe targets. FAILURE_PRIORITY and PROBE_REASON_MESSAGES are existing tables; safeProbeTargetLabel preserves profile/config/environment labels. models.probe performs one runAuthProbes call with fixed token/concurrency bounds. No repeated provider-specific execution path was found. | src/gateway/server-methods/models-probe.test.ts
src/gateway/server-methods/device-pair-setup.ts 195 195 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Setup code and status share unavailable wrapper but own separate writes versus receipt-only projection. Status confirmed/uncertain payload construction is already shared; setup bootstrap profile variants already use explicit expressions. More strategy plumbing would hide the join-only captured admission and QR fallback boundary. | device-pair-setup.test.ts;../device-pair-setup-completion.test.ts; results recorded separately
src/gateway/server-methods/sessions-shared.ts 195 190 5 Applied: removed duplicate lazy sessions runtime loader and its import; sole production consumer uses the canonical existing gateway lifecycle loader. Preserved all other exports/signatures and all storage/visibility guards.
src/gateway/server-methods/session-typing-state.ts 192 192 0 RETAINED: broadcast throttle and connection TTL both evict oldest entries, but expose different empty-key handling and timer ownership. Existing reset already shares both maps. Further common LRU policy would need a new key-eligibility strategy for two short sites.
src/gateway/server-methods/sessions-search-projected.ts 192 192 0 Retained: selection ownership, physical-store queries, reread and archived materialization are already parameterized. Generation checks before and after awaited preparation protect different snapshots. Search path intentionally remains unchanged.
src/gateway/desktop/computer.worker.ts 190 190 0 RETAINED: shared stop owner already joins accepted operations and driver/provider cleanup. Requests and operations have different abort/drain lifetimes; stopping is already derived from the owning completion promise. Startup and watched availability require different response text and stop semantics.
src/gateway/terminal/output-flow-control.ts 190 190 0 RETAINED 190→190: PR2 already merged hysteresis with explicit periodic reassert. chunks/bufferedBytes represent UTF-8 wire batching, endOffset/emittedOffset separately encode replay and live UTF-16 positions, and desiredPaused plus reassert timer preserve recovery after native pause/resume failure. Deriving these from each other loses detached output, replay, or periodic repair. No second flow-control owner found.
src/gateway/server-methods/cron-list.ts 189 189 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/session-create-idempotency.ts 189 189 0 RETAINED: inflight/completed discriminant is owning state; replay requires original payload plus current fast-mode projection. Owner count is derived while expiring completed entries; inflight entries cannot be expired or released like completed results.
src/gateway/server-chat-live-text.ts 188 188 0 Retained: one shared timer owner already handles agent/chat; cancellation clears before invoking latest callback. Wire text projections differ in client field removal and byte accounting; producer-specific coalescing preserves snapshots/replacements.
src/gateway/server-methods/models-auth-login.ts 188 188 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: models.authLogin shares resolveChoice and assertCurrent across start and use. Wizard browser authorization adds browser lifetime to assertFlowCurrent; post-login model-access selection intentionally uses signal plus operator authority after browser.close. Credential save, config-application failure and auth-refresh failure retain distinct saved-state messages; there is no alternate login flow in this module. | Full server-methods directory; results recorded separately
src/gateway/server-methods/commands-list-result.ts 186 186 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Common final array carries native/plugin entries, but native alias and argument projection differs. A shared wire entry helper would duplicate per-variant input remapping and include optional fields currently omitted. | commands.test.ts (results recorded separately)
src/gateway/server-methods/nodes.pending-work.ts 186 186 0 RETAINED: Re-read drain/enqueue wake sequencing. The explicit type bridge is still necessary because Type.String enum schemas infer string rather than the narrower queue type unions. Shared wakeNodeForReconnect already owns wake stages; drain deletes and enqueue cleanup retain distinct generation guards. | src/gateway/server-methods/nodes.pending-work.test.ts
src/gateway/server-methods/plugins-mutations.ts 186 186 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read shared lifecycleHandler and each mutation callback. One owner already captures publication receipts, persistent authority, lease, runtime warnings and errors. entered distinguishes lease refusal from accepted mutation and cannot derive from application presence. | src/gateway/server-methods/plugins-mutations.test.ts
src/gateway/server-methods/suspend.ts 185 176 9 Applied single-use logDraining inline inside existing shared respondSuspendStatus owner; removed its type plumbing while keeping all log bytes and status/prepare response checks. Status still waits for write custody and rereads after the await.
src/gateway/server-methods/health.ts 184 184 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Cached response requires live delivery/context/event-loop enrichment and stale-field removal before background scheduling; refreshed response obtains those through the health owner. Both project startup/child facts at their original response sites; generic wrapper would need cache metadata and refresh scheduling parameters without removing those distinct operations. | health.owner-routing.test.ts;../server.health.test.ts;../server.health.lifecycle.test.ts; results recorded separately
src/gateway/talk/relay/provider-results.ts 183 183 0 Retained. Common cancellation-result constructor participates in rejected 1999 -> 1998 aggregate prototype. Final submission already shares acceptance/completion tracking, while provider and agent tombstones and working/final maps enforce distinct barriers. No new combined pending state.
src/gateway/server-methods/sessions-sharing-authority.ts 182 182 0 Retained: prepareCurrentSessionSharing already shares role/config/current-profile checks between management and reaction access. Prepared authority must compare membership and source twice around request guards. New shared handler consumes this owner unchanged.
src/gateway/talk/agent-consult.ts 181 167 14 Applied: one unavailable(message) result projection serves missing-run, registration failure, missing-response and pre-ACK rejection paths. Existing supplied ACK errors are returned intact. Exact relay abort still precedes registration-failure projection; post-ACK failure still only logs. No awaited calls, text or wire shape changed. Test: handlers/index.test.ts, handlers/native-consult-target.test.ts.
src/gateway/server-methods/chat-send-setup.ts 180 180 0 Retained: one normalization/preparation/admission path with explicit ownership transfer. loaded versus qualified session is a real lifetime distinction; failure before admission releases the target through one finally.
src/gateway/server-methods/progress-card.ts 180 180 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: resolveProgressCardSession and projectProgressCard already share target and wire identity. progressCard.get retains a scoped read through I/O; refresh passes a guarded reread to refresh dispatch; put owns revision CAS, signal/commit checks, and conditional broadcast. A common read/write callback would need separate authority and publication policies for each operation. | src/gateway/server-methods/progress-card.test.ts
src/gateway/server-methods/agent-cron-continuation.ts 179 179 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: createCronContinuationController.release is the sole claim mutation path; releaseWithRecovery calls it again under an independent retained lifecycle. release distinguishes committed generated work, base-session supersession and rollback to initialEntry. Removing recoveryScheduled or the exact captured claim comparison would allow duplicate recovery owners, so they are not derivable solely from claim presence. | Full server-methods directory; results recorded separately
src/gateway/server-methods/chat-message-get-handler.ts 178 178 0 Retained: pending input and transcript reads share response and current-session publication helpers. Pending namespace must not fall back to transcripts or archived sessions, and only stored transcript output applies model policy.
src/gateway/server-methods/session-repository-workspace-access.ts 178 178 0 RETAINED: inspect already parameterizes every workspace operation. Set alone joins lifecycle/mutation ownership; other operations pin repository revision and may retry transport. Source/session/placement guards remain at every awaited boundary.
src/gateway/server-methods/users-model-account-access.ts 178 178 0 Retained: action capture unifies personal/default/admin access while preserving actor versus owner role semantics. Alias recapture and owner checks follow distinct awaited reads and are not redundant.
src/gateway/server-methods/sessions-read-by-key.ts 176 176 0 Retained: describe is synchronous prepared-row presentation; get awaits transcript I/O then revalidates source/role. Repeated filters intentionally consume different current policy snapshots; no cached filter is safe across the await.
src/gateway/server-methods/chat-aborted-partial.ts 174 174 0 Retained: one snapshot capture and deferred handoff owner. Save-warning projection and deferred producer notification differ in error type/custody; existing withAbortedPartialPersistenceWarning is the shared wire projection.
src/gateway/server-methods/nodes.event.ts 174 174 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Share synchronous pairing-generation connection lookup; event and APNs paths keep independent captured generations and original awaited liveness checks. Fresh client connection reads remain after registry lookup. | src/gateway/server-methods/nodes.event.test.ts src/gateway/server-methods/nodes.apns-registration.test.ts
src/gateway/agent-turn/agent-handler-helpers.ts 173 173 0 Retained: named helpers adapt shipped harness restrictions, cron continuation and ACK behavior, all with actual callers. Existing policy owners are reused; no duplicated feature implementation.
src/gateway/server-methods/chat-history-pages.ts 173 173 0 Retained: process-held CLI, process-held canonical and worker-backed ordinary history share scope/parameter preparation. Shared post-read label projection already exists; combining three routes adds nested branch state without removing reader-specific authority.
src/gateway/server-methods/cron-job-access.ts 173 173 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/chat-metadata-model-list.ts 171 171 0 Retained: prepare caches shared variants; request-local personal account reads preserve link authority and account-selection overlay. Retained requested variants survive generation replacement separately from promises; maps are not duplicate state.
src/gateway/server-methods/session-catalog-list-admission.ts 171 171 0 RETAINED: run delegates to runSteps already; first admission and continuations share queue entry. Active-provider set, queued continuation timing, and outstanding completion encode different facts and preserve FIFO across callback arrivals.
src/gateway/server-methods/sessions-suggestions-dispatch.ts 171 165 6 Applied: inlined private single-use attributedSuggestionClient into its sole dispatch owner. Captures the same client, author id/label and internal overrides immediately before request authority preparation.
src/gateway/server-methods/chat-send-reservation.ts 169 168 1 Applied: capture pending key and client run ID from prepared session, removing two independent caller arguments. Reserve and clear use the same captured key and attempt check; Goal replay remains unchanged.
src/gateway/server-methods/usage-result-cache.ts 169 169 0 Retained: generic usage cache already owns policy, this module selects revisions/keys and folds agent summaries through canonical totals. All-agent and selected-agent inputs differ in discovery universe.
src/gateway/server-methods/usage-session-loading.ts 168 168 0 Retained: shared bounded fanout and usage accumulator own loading. Contiguous family batching uses one accumulator per current family; no independently derived duplicate state.
src/gateway/session-lifecycle-plugin-hooks.ts 167 155 12 Applied: auto-reset and plugin-end payload builders consume one shared set of captured session facts; start builder receives its existing source fields directly with the narrowed sessionId. Builders were inspected: they project only named fields, do not retain/enumerate caller containers. Shutdown tracking keeps its existing explicit snapshot.
src/gateway/session-row-projection-identities.ts 167 167 0 RETAINED: creator contributions, resolved presentation and dirty creator ids track source/order/invalidation separately. The canonical last row and latest labeled row may differ. Private source adapters retain bound-actor versus process-held-store authorization and never feed resident creator state.
src/gateway/server-methods/chat-server-timing.ts 166 153 13 Applied: fold single-use ACK attribute projection into ackReadyEvent and remove its private shape/helper. Field omission, clock sampling and milestone byte shapes remain identical.
src/gateway/server-methods/sessions-fork-runtime-guard.ts 165 165 0 Retained: one readCurrent owns source/harness/creation checks and one assertion adds host runtime restrictions. V2-versus-legacy policy is an explicit strategy; rollback authority intentionally differs after custody transfer.
src/gateway/server-methods/chat-metadata-facts.ts 164 164 0 Retained: captureGenerationFacts and generationFactsMatch form one owner snapshot contract; catalog/auth/commands comparisons already parameterize their genuine differences.
src/gateway/server-methods/session-catalog-list-diagnostics.ts 163 163 0 RETAINED: start already parameterizes wait/CPU phases. First and second CPU reads differ in baseline and subtraction, and both swallow only diagnostic failures. Provider host counters are bounded independent of request phase tracing.
src/gateway/server-methods/transcripts.ts 163 163 0 Retained: transcriptMethod owns all five variants, schema, archive authority and error mapping. Summarize has distinct live checks around summary generation and following library read; provider name cache is shared.
src/gateway/server-methods/claws-packages.ts 161 161 0 RETAINED: Reviewed only. Removal keeps the exact deletion-journal, binding and install/plan digests before package lifecycle dispatch. Runtime receipts and persisted cleanup failure are not equivalent outcomes. | Full server-methods directory; results recorded separately
src/gateway/server-methods/session-discussion.ts 161 161 0 RETAINED: info/open already share one handler via operation parameter; only open performs best-effort title generation. No second provider/error loop remains.
src/gateway/server-methods/session-placement-read-projection.ts 161 161 0 RETAINED: readPlacementFacts already centralizes generation-derived facts; present refreshes only source changes and independently samples disk/runner/runtime availability. Merging snapshot and live reads would change freshness ownership.
src/gateway/server-methods/session-repository-artifacts.ts 160 150 10 APPLIED: browse and search use one selected entry projection with explicit path/name/directory choice. Search still scans all changed files, browse still emits first children, limits/order/presence fields remain unchanged; retained artifacts are never writable.
src/gateway/server-methods/mcp-auth-login.ts 159 159 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: MCP uses startWizardLogin and browser.authorizePrepared common owners. Inner finally is deliberately inside outer catch so browser.close/cancel errors produce saved-aware diagnostic; attemptState is exact OAuth cancellation identity and saved is token-commit evidence, neither derivable from wizard status. | ../server.mcp-auth-login.test.ts; results recorded separately
src/gateway/session-row-projection-backfill.ts 159 158 1 APPLIED: inline a single-use revisions.get binding in the unchanged deep comparison. Pending work, started admission and disposal each encode separate lifecycle state. Exact background priority rechecks and captured revision checks stay before publication, including interrupted requeue behavior.
src/gateway/talk/handoff.ts 158 158 0 Rejected formatted closeHandoff(id, record, reason) core: 158 -> 158. Original map key must remain separate from externally readable record.id. A third helper replaces only two direct event/delete pairs without reducing lines or making lifetime ownership clearer. Test owner inspected: handoff.test.ts.
src/gateway/server-methods/models-list-result.owner.ts 157 157 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: infer internal owner result type from sole producer | Full server-methods directory; results recorded separately
src/gateway/server-methods/sessions-file-assets.ts 156 156 0 Retained: readAsset already shares native/repository result contract with explicit branches. Repository previews have a smaller byte cap; local reads require path and stat authority guards. MIME resolution and total-budget accounting are shared once.
src/gateway/server-methods/message-operation-result.ts 153 159 -6 Applied shared authority-error classification in the existing result owner; internal helper renamed for its wider existing failure responsibility, no new module. Combined send/result surface shrinks 5 lines.
src/gateway/server-methods/users-profile-access.ts 153 153 0 Retained: profile acquisition, self edit and administration have distinct permissions; repeated connection assertion protects different awaited acquisition points. No duplicate storage owner or safe redundant state found.
src/gateway/server-methods/provider-usage-runtime.ts 151 151 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: getProviderUsageRuntimeSnapshot reuses config/store/agent/plugin/auth generations; fingerprintProviderUsageCredentials separately records credentials, direct keys, auth order, lastGood, and selected profile order. resolveDirectApiKeys applies configured-before-env precedence. No duplicated snapshot builder exists; dropping a fingerprint component would reuse usage after account-selection changes. | src/gateway/server-methods/usage.status-cache.test.ts
src/gateway/server-methods/nodes.pending.ts 150 150 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read pending actions. Preserved explicit isNodeCommandAllowed result variable required by hosted security rule. withPendingNodeActions already shares generation/connection checks while its deferred result callback preserves post-await publication. | src/gateway/server-methods/nodes.pending-work.test.ts
src/gateway/server-methods/restart.ts 150 122 28 APPLIED: Share the INVALID_REQUEST envelope across eight stop/restart refusals. Keep each message, response arity, lock check, catch boundary and await in its original position. The prior lock-fence extraction remains unnecessary once the repeated response core is removed. | restart.test.ts; stop.test.ts
src/gateway/session-create-inheritance.ts 150 150 0 Retained: parent preparation, inherited model overrides, spawn ownership and tool policy are distinct operations. Same parent owner is re-read under lifecycle custody; owner fallback is explicit rather than inferred.
src/gateway/server-methods/environments.desktop.ts 149 149 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Shared worker service availability, dispatch, success and error projection for observe/launch; explicit operation retains launch-only typed codes and exact fallback text. Host/node observer credentials path remains separate. | src/gateway/server-methods/environments.desktop.test.ts
src/gateway/server-methods/skills-install.ts 149 146 3 Applied single-use ClawHub dedupe wrapper inline into its only branch, removed the private ClawHubInstallParams type, and destructured resolved config/workspace once. Retained the explicit SkillsInstallParams import and const p alias: the full declaration build showed that the validated Record intersection otherwise retains the upload variant during local-install narrowing. The exact workspace/slug/version/force key, constructed install input, promise reuse and settlement eviction remain identical. Upload retained-authority/rollback and local result handling are untouched. Current source: 149→146 (-3).
src/gateway/server-methods/approval-request-delivery.ts 148 148 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Delivery variants already use startDelivery(run,errorLabel); first-success settlement counter tracks unresolved callbacks independently of completed truthy results. Replacing it with Promise.any requires converting false results to failures and handling empty input, adding rejected promises and more code. | approval-request-delivery.test.ts; results recorded separately
src/gateway/server-methods/sessions-patch-replacement.ts 148 148 0 Retained: replacement projection owns no-op/alias/label semantics, while group writer owns admitted versus detached preparation. Moving their mark/commit paths together would move the snapshot guard relative to writer acquisition.
src/gateway/server-methods/gateway-client-identity.ts 146 146 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Profile/synthetic/fallback sender paths differ in durable identity publication; existing withCommandSenderAuthority owns live scope. Initial profile-pending state and post-sync absence cannot share a single read because sync can replace the profile. No extra mutable state or duplicate authorizer found. | gateway-client-identity.test.ts; results recorded separately
src/gateway/server-methods/sessions-list-diagnostics.ts 146 146 0 Retained: request-local CPU failure disables later probes, phase tracker aggregates repeated phases, and response outcome differs from handler outcome. These states cannot derive from each other; telemetry already has one guarded publication path.
src/gateway/server-methods/sessions-reactions-access.ts 145 145 0 Retained: callback owner already retains sharing facts through reads/write/mirror. Write permission tests are incremental on top of visibility, not equivalent to management authorization; error mapping is intentionally reaction-specific.
src/gateway/server-methods/portals.session.ts 144 144 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: sessionPortalOwner centralizes all session portal operations and captures access plus placement identity. prepareTarget retains session resource authority for bearer connections and releases it after connection.close; list/open/close all consume this owner. General portalOperations lacks that retained session bearer lifetime, so using it here would erase the resource boundary. | Full server-methods directory; results recorded separately
src/gateway/server-methods/sessions-compaction-runner.ts 144 140 4 Applied: inlined single-use legacy compaction predicate into its preflight owner. Model/runtime/context-engine reads preserve order before the transcript try/catch; native/context-engine bypass conditions remain identical.
src/gateway/server-methods/sessions-title.ts 143 143 0 Retained: creation, model-account, operator and runtime authority are distinct admission layers; each yield reacquires its necessary checks. Title no-op branches precede expensive acquisition and preserve response shape.
src/gateway/transcript-image-artifacts.ts 143 143 0 RETAINED: One canonical encoded-reference format, exact re-encoding check and source/sequence/block lookup. Both projector and resolver already reuse imageReference, displayContentField, hasInlineImagePayload and encodeReference. A new shared parser would duplicate the existing canonical reference owner; source identity and persisted IDs must remain byte-identical.
src/gateway/server-methods/chat-send-reply-context.ts 142 142 0 Retained: hydrated reply fields already copy through a fixed field loop. Extraction prioritizes top-level text then string content then block text; distinct ordering and maximum preview bound remain explicit.
src/gateway/server-methods/portals.ts 142 142 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: portalOperations owns optional environment binding and prepareTarget; mutatePortal already combines open/close error mapping and change broadcasting. portal.list is synchronous, applies read-scope redaction and maps selection errors to INVALID_REQUEST/String(error), while mutations map to UNAVAILABLE/error.message. No duplicate mutation controller remains. | Full server-methods directory; results recorded separately
src/gateway/server-methods/presence.ts 142 142 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Presence summary variants already share summarize(query,locations); location batching adds network include only to the preparatory query, then rereads live requester/observations after await. Lookup authority guard uses current owner per call. No duplicate summary core remains. | presence.test.ts; results recorded separately
src/gateway/server-methods/session-create-spawn.ts 142 142 0 RETAINED: permission inheritance accepts cross-agent custody, model inheritance and active forks require same agent. Existing return objects intentionally omit activeParentFork except for accepted forks. Shared error helpers would parameterize only text and add wrapper code.
src/gateway/server-methods/sessions-provider-review.ts 142 142 0 Retained: acknowledgment ownership transfers only at handedOff immediately before chat dispatch. The boolean cannot derive from acknowledgment existence because pre-transfer failures must retire the same receipt.
src/gateway/talk/relay/tool-call-ledger.ts 142 142 0 Retained. mark(callIds, mutate) already consolidates admission and updates. Retained byte count and overflow notification survive cleared terminal facts; deriving from active facts would reopen replay admission. Clear-provider and clear-cancel loops mutate different retained fields.
src/gateway/session-create-target.ts 141 118 23 Applied: move private validateSessionCreateTarget into its sole read owner, removing five-parameter forwarding. Same currentness checks precede both incognito and worker snapshots; existing-row filesystem/active-work refusals and missing-row creation authorization stay ordered. Reuse identical unavailable error result constructor.
src/gateway/terminal/node-relay.ts 140 137 3 Applied: missing raw exit payload and parsed nonrecord payload share the zero-exit result. A conditional parse preserves the empty-string fast path and exact error catch. Formatted 140→137 (-3). Dispatch readiness versus final exit race, pinned connection/pairing authority, early data/exit buffering and UTF-8 input splitting untouched.
src/gateway/server-methods/system-agent-chat-turn.ts 139 139 0 Retained: ordered wizard validation preserves first error when several fields collide; rejoin and ordinary reply project different capabilities. The existing history persistence helper already serves chat callers.
src/gateway/server-methods/chat.ts 138 138 0 Retained: two small public handlers; toolTitles preserves disabled compatibility response and inject owns session lifecycle admission. Inject sequence-zero delivery deliberately does not use ordinary run sequence owner.
src/gateway/server-methods/task-suggestion-acceptance.ts 138 138 0 Retained: rollback validates response plus actual row absence; restore and abandon must differ for retryability. Inline rollback would remove an existing await boundary before claim transition. Shared broadcast owner already serves finish/abandon.
src/gateway/server/client-presence.ts 138 138 0 Retained: live transport snapshots and activity publication have separate ownership; exact activity is written on every accepted interaction, while the weak publication map holds a 30-second per-identity window. Peer timing merge and publication happen at distinct points and retain qualified/raw identity isolation.
src/gateway/server-methods/open-path.ts 137 137 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Inline single-use PowerShell quote escaping at the string-literal construction. Apostrophe doubling and platform lifetimes are unchanged. | src/gateway/server-methods/open-path.test.ts
src/gateway/server-methods/session-create-root.ts 137 137 0 RETAINED: existing prepareRoot callback shares local fork root preparation and avoids second work when roots match. Explicit remote root, implicit default root, and sandbox containment have distinct published contracts.
src/gateway/server-methods/chat-send-diagnostics.ts 136 136 0 Retained: one phase scope and report core handle nested timing. finished cannot derive from active.size because an open request can have no scopes; stage controls disposal and ACK reporting independently.
src/gateway/server-methods/models-list-runtime-choices.ts 136 136 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Alternative runtimes share one filter/map and one live-read closure. Unavailable entries deliberately omit capabilities after stripping identity fields; available entries preserve them. Explicit policy branches already converge on agentRuntime construction and native evaluation. | models-list-result.runtime-choices.test.ts;models-list-result.cli-runtime-availability.test.ts; results recorded separately
src/gateway/desktop/rfb-view-only-filter.ts 135 135 0 RETAINED: all allowed handshake/message phases already share forwarding tail; variable-length parsing validates both header and completed length to reject oversized frames before accumulating payload. A limit-check wrapper adds another parser layer for two three-line checks and no structural owner simplification.
src/gateway/server-methods/agent-subagent-registration.ts 135 135 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: registerPluginSubagentRunFromGateway tries adoptPausedSubagentRunForFollowUp before registration only without an explicit requester, then checks adoptPausedSubagentRunIntoSuccessor after registration to catch a concurrently published pause. resolveTrustedGroupMetadata follows stored, inherited, current-key, parent-key precedence. Removing either adoption point changes audience or race handling. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/session-discovery-access.ts 135 135 0 RETAINED: shared readEntry continuation already owns exact readiness/identity/source-path check across initial and final consumption. Source lifetime and skill revision authorization remain separate from discovery I/O.
src/gateway/talk/relay/voice.ts 135 135 0 Retained. Shared ensureRelayVoiceSession and log owner serve transcript/create/close. Durable voice-record existence cannot derive from live relay registration, and close promise owns async completion. Retry transcript writes preserve exact entry ID and error after all attempts.
src/gateway/server-methods/sessions-diff.ts 134 134 0 Retained: stored/cloud/local sources already converge into one result owner. Local commit scope validates commit before git and omits baseline fields; ordinary scope carries baseline and session id. No equivalent duplicate I/O remains.
src/gateway/methods/registry.ts 133 133 0 RETAINED: normalizeDescriptor already serves core/plugin/channel/aux owners. Post-spread projections preserve inherited and non-enumerable policy fields, explicitly covered by registry.test; removing them would weaken scope/availability handling. Getter contracts are distinct.
src/gateway/server-methods/chat-send-late-followup.ts 133 133 0 Retained: one delivery function handles progress and terminal batches; terminal state fences concurrent/replayed delivery and separate source retry ownership. Progress payload accumulation cannot derive from terminal receipt.
src/gateway/server-methods/chat-history-reply-messages.ts 131 131 0 Retained: one batch original-reference projector and one bounded exact history preview reader. Their retained indexes and ID cache serve different layers; pending input namespace stays excluded.
src/gateway/exec-approval-manager.types.ts 130 130 0 RETAINED: Exact public/internal approval payload, authority, lifecycle and result contracts; manager result types already derive durable store results. No duplicate runtime implementation or unused option established by callers. | manager suites and typecheck
src/gateway/agent-turn/agent-run-admission-revalidation.ts 129 129 0 Retained: synchronous true result preserves acceptance atomicity, while rejected or canceled input joins required cleanup before replay. Two failure variants preserve distinct cleanup-error precedence and cannot move into a common awaited guard.
src/gateway/artifact-download-grants.ts 129 129 0 RETAINED: removeDownload already owns delete-before-release for expiry, capacity, abort and stale-grant refusal. Connection lifetime, grant identity and current disclosure authority are independent facts and cannot derive from only TTL or map membership. No duplicate release implementation remains.
src/gateway/artifact-downloads.ts 128 128 0 RETAINED: One HTTP path owns authorization and response headers. Thumbnail preparation preserves unknown/animated containers, independently limits ranges, and rechecks its connection-bound grant after awaited work. The shared byte-response and thumbnail-cache owners are already used; full and thumbnail work require different input bytes and headers, not a second HTTP response implementation.
src/gateway/server-methods/approval-publication.ts 127 127 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: publishAppliedApprovalResolution already funnels awaited best-effort callbacks through runSideEffect. Internal approvalEvents publication remains synchronous; web push selects expired versus resolved; exec/plugin forwarders and iOS handlers have different typed payloads; system-agent forwards only expired/cancelled outcomes because its decision owner publishes decisions. One generic event cast would weaken those kind-specific contracts. | Full server-methods directory; results recorded separately

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

d01 PR 3 per-file coverage — part 4/5

Reviewed implementation head: 900b74a38d291476a712cfa5c601cf2c269e8eb1.

Gateway server-methods lane d01, PR 3 coverage

Baseline b3196dfda33555857eae9cd52ea29367a91bd9ea. This final lane pass re-evaluated prior rejected and partially simplified files, completed the current server-methods directory, and revisited its adjacent runtime owners.

608 production modules have per-file decisions, including all 427 current server-methods modules and the original exclusions. The implemented production diff removes 693 net lines; no test, protected storage, global-identity, config-retirement, tooling, or changelog paths changed. Existing assertions remain intact.

Counts describe the actual applied source against the original fresh-main base. Measured rejected prototypes are recorded in each relevant row. The PR body records executed validation separately; a named test below is a target unless that validation says it passed.

File Before After Net removed Decision and evidence
src/gateway/server-methods/channels-account.ts 127 127 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Channel account selector already shares explicit/reload/default precedence. Logout rechecks current runtime before credential mutation and only caller authority afterward because logout may publish config; these cannot merge. | channels.status.test.ts;channels.start.test.ts (results recorded separately)
src/gateway/server-methods/chat-send-background.ts 127 120 7 Applied: remove pure scheduleChatDashboardSessionTitle forwarding function; its existing shared implementation now owns the export and both chat-turn and fresh-session callers. Title work remains on independent root custody with the original release/settlement gate.
src/gateway/server-methods/models-auth-order.ts 127 127 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read profile-order validation and saved-write publication. rejectInvalidOrder already shares response construction; post-write publication catch must preserve committed success. No duplicate profile order writer. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/users-auth-connect.ts 126 126 0 Retained: connectHandler already owns all ten methods and exposes explicit scope/service-argument strategies. No duplicate preparation or error owner remains.
src/gateway/server-methods/environments.session-exec.ts 125 119 6 APPLIED: Use the existing validated-method error mapper, removing the nested whole-body catch. Exact execution identity, policy rechecks, approved command snapshot, transportRetry never, reply arity and fallback message remain unchanged. | environments.session-exec.test.ts; environments.session.test.ts; environments.session-exec-approval.test.ts
src/gateway/server-methods/setup-admission.ts 125 125 0 Retained: admitted boolean distinguishes lock acquisition failure from same error thrown by task; pending session settlement preserves lock custody beyond start response. Removing either state loses owner facts.
src/gateway/methods/core-method-policy.ts 123 123 0 Retained original read-sharing projection with descriptor.ts after the 235-to-234-line shared-export prototype changed reachable SDK declarations. All policy table values and existing exports remain unchanged.
src/gateway/server-methods/skills-workshop.ts 123 119 4 Applied shared workshopWriteContext for archive/restore. Measured prototype 123→119 (-4), retained. The exact user actor and captured assertCurrent function are built synchronously at the original admission point; per-action argument shapes stay explicit.
src/gateway/session-row-projection-revisions.ts 123 123 0 REJECTED complete publishRow core with explicit deferred selection strategy is 123 -> 122 (-1). It requires a new callback solely to preserve selection filtering after potentially reentrant facts publication; the two current five-line tails make ordering clearer. No reduction claimed for prototype.
src/gateway/server-methods/plugins-control-ui.ts 122 122 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: captureCatalogAuthority is shared by list and reload. listControlUiPluginCatalog reads current assets; reloadControlUiPluginCatalog mutates one plugin and broadcasts a revision before response. report verifies a connected Control UI and active revision; status projects a bounded sorted client inventory. These operations share registry lifetime but have separate result/error and mutation contracts. | Full server-methods directory; results recorded separately
src/gateway/server-methods/session-recovery-continuation.ts 122 122 0 RETAINED: one trusted fixed-prompt launch carries destination authority; ACK-derived started/rejected outcome and fallback/caught failure are distinct observable outcomes. No alternative launch owner or unused option remains.
src/gateway/server-methods/canvas.ts 121 121 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read stored view and caller preview. respondWithCanvasHtml already owns concurrent HTML/listener acquisition and live host revalidation. Stored CSP/size admission and preview UTF-8 admission retain their differing error contracts. | src/gateway/server-methods/canvas.test.ts
src/gateway/server-methods/chat-abort-descendants.ts 121 121 0 Retained: one beforeKill core seals selection before effects; synchronous cancellation and awaited command settlement retain distinct errors and aggregate precedence. Derived execAborted must include both native commands and descendants.
src/gateway/session-create-existing-selection.ts 121 120 1 Applied: requested and subagent-default resolution share captured selectionPolicy while requested raw/hint differences remain explicit. No awaits are added, and omitted subagentModelHint on the fallback call remains omitted.
src/gateway/session-row-projection-catalog.ts 121 121 0 RETAINED: replacement promise and current pending read represent different model-owner phases. Synchronous publication clears pending before callbacks can reenter refresh; a shared finally would change that ordering. Existing catalog equality predicate and invalidation owner already centralize decisions.
src/gateway/server-methods/chat-pending-inputs.ts 119 119 0 Retained: one pending-message projector serves history and exact lookup. Queued count covers all matching bounded IDs while visible page projects at most 20 entries, so it cannot derive from the displayed slice.
src/gateway/server-methods/cron-visibility.ts 119 119 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/ui-command.ts 119 117 2 Applied existing defineValidatedGatewayMethod error mapper instead of local catch; same Error.message/String projection and synchronous authority/target/broadcast/response ordering. Navigation identity and requester-browser authority remain separate.
src/gateway/server-methods/projects-recents.ts 118 118 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: indexPathProjects owns workspace/path precedence; listProjectRecents owns sorted session selection, deduplication and the eight-item limit. Repository-workspace recents require awaited durable ownership checks and dedupe by URL; project/folder recents use configured path identity and node-qualified folder keys. They converge on one result list after their different identity checks. | Full server-methods directory; results recorded separately
src/gateway/server-methods/diagnostics.ts 117 117 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Applied profileHandler generic core for all three profile RPCs: undefined-to-empty parameter defaulting, unchanged validator/message strategy, lifetime union, authority recheck and common outcome response. Lazy capture imports remain explicit and unchanged; 133->117. | diagnostics.test.ts;diagnostics.cpu-profile.test.ts;diagnostics.heap-profile.test.ts;diagnostics.heap-snapshot.test.ts; results recorded separately
src/gateway/server-methods/fs.ts 117 117 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Node bridge, admin-local and confined workspace variants already share local listing owner; remote declared-command/allowlist/result checks stay separate. Only confined workspace-root result strips parent path. | fs.test.ts (results recorded separately)
src/gateway/server-methods/plugins-lifecycle-error.ts 116 116 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read lease refusal, abort unwrap, persisted error, consent/trust details and runtime receipts. projectPluginRuntimeFailure remains canonical; conditional fields follow distinct accepted-write/failure meanings. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/talk/realtime-run-control.ts 115 115 0 Retained. One enqueue/handleInput core already supports delegation and transcript strategies. prepare captures target before FIFO/readiness waits; reply failures remain outside the execution catch to avoid a second reply. Shared queue sealing/flush remains the close owner.
src/gateway/node-registry.presence.ts 114 98 16 Applied preferActiveNode shared comparator, eliminating per-profile node arrays and the following selection pass. Undefined map entries retain the original first-profile insertion order until the final result excludes inactive groups. Public functions/signatures, source selection, strict tie order and permission checks are unchanged.
src/gateway/server-methods/cron-list-diagnostics.ts 113 113 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/method-authorization.ts 113 113 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: authorizeGatewayMethod is one ordered dispatcher: role validity, node exemption, invalidation, current operator policy, device scope recovery, admin, registered scope, own-session fallback, and exact cron grant. Each early return is a distinct authorization contract; a table would need the same ordered predicates and state-dependent inputs. | src/gateway/server-methods/ (full suite)
src/gateway/methods/descriptor.ts 112 112 0 Retained original read-sharing projection. The paired shared-export prototype reduced the two modules from 235 to 234 lines but introduced a reachable SDK declaration; reverted both own hunks to keep the public surface unchanged.
src/gateway/server-methods/doctor-memory-target.ts 112 112 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: resolveDoctorMemoryAgent validates raw agentId type before any storage-capable resolution, normalizes it and retains requestedAgentId for scope behavior. resolveDoctorMemoryTarget adds only workspace selection; memoryActionHandler already shares target validation for every diary mutation. General agent-id-shared uses different compatibility fallback, normalization and error strings, so it is not an equivalent target owner. | Full server-methods directory; results recorded separately
src/gateway/server-methods/restart-request.ts 112 112 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Reuse existing canonical asSafeIntegerInRange plus trimmed string owner for target pid/port validation; same positive safe pid and1..65535 integer port domain, unchanged output keys. | restart.test.ts;update.test.ts (results recorded separately)
src/gateway/server-methods/sessions-patch-effects.ts 112 112 0 Retained: committed patch effects are already a single ordered loop; cron archive cleanup is reserved adjacent ownership and remains untouched.
src/gateway/managed-image-attachments.custody.ts 111 111 0 RETAINED: One cleanup-claim/file-delete/record-delete sequence and one insertion settlement promise. Unknown insertion outcomes retain file custody; rejected disclosure and definite cleanup each have explicit settlement. Removing the retained settlement promise would duplicate work across callbacks, and merging claim failures with absent files would change recovery behavior.
src/gateway/presence-projection.ts 111 111 0 Retained: incognito topology facts versus already-open database reads must remain distinct read paths, while durable targets use sharing-revision invalidation. Visibility signatures share immutable rosters only after current recipient filtering; key/index dual state connects original references to cache signatures.
src/gateway/server-broadcast-types.ts 110 110 0 Retained: these types describe actual broadcast/receipt/projection lifecycle contracts. No obsolete strategy or unused option found among callers; no SDK or protocol signature changes.
src/gateway/server-methods/computer.ts 110 110 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read caller owner and status/invoke/close. resolveComputerCaller already shares current authority; close selects a cleanup-only purpose before invoking the service. Status fallback is read-only and cannot share invocation unavailable behavior. | src/gateway/server-methods/computer.test.ts
src/gateway/server-methods/system-agent-execution.ts 109 109 0 Retained: one serialized execution owner, setup verification reads applied config before and after probe; activation completion must occur outside queued activation to avoid reload deadlock.
src/gateway/server-methods/agent-expected-session.ts 107 107 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: resolveExpectedExistingSessionConstraint validates backend-only input and constructs the constraint. validateExpectedExistingSessionTarget checks explicit request identity, assertExpectedExistingSession checks the live row, and consumeExpectedSessionWorkAdmission consumes an existing handoff lease. These are parse, compare and ownership-transfer stages; no repeated lease or validator implementation exists. | Full server-methods directory; results recorded separately
src/gateway/server-methods/environments.session-exec-approval.ts 107 107 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Single registered approval and consumeAllowOnce path already shares manager owner. Runtime identity creation, registration, delivery, and one-shot decision are different awaited authority checkpoints. | environments.session-exec-approval.test.ts (results recorded separately)
src/gateway/agent-turn/agent-run-admission-types.ts 105 105 0 Retained: type-only admission contract derives user-turn inputs and encodes mutually exclusive prepared-runtime ownership. No unused variant or implementation duplicate.
src/gateway/server-methods/artifacts-content.ts 105 105 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: resolveBlockDownload has a single source-precedence pipeline: detected data URL, direct base64, safe remote URL, then unsupported. It preserves declared size separately from measured inline payload size. mediaUrlValue and resolveMessageRunId normalize separate field shapes. No parallel media-kind decoder exists to consolidate. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/progress-card-refresh.ts 105 105 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Already shares terminal fallback error projection. Original card revision, dedupe revision and newly read current card are different facts across completion race; accepted receipt is published only after authority checks. No redundant revision state. | progress-card-refresh.test.ts;progress-card-refresh.integration.test.ts;progress-card-refresh.queued.test.ts; results recorded separately
src/gateway/server-methods/sessions-maintenance.ts 105 105 0 Retained: status/run share one explicit method strategy and same authority checks. Cleanup has partial-commit failure semantics and per-store publication that cannot replace maintenance status behavior.
src/gateway/server-methods/users-github.ts 104 104 0 Retained: runPersonalGitHub shares all five actions and preserves synchronous responses versus Promise completion revalidation. Removing Promise distinction would add a yield to synchronous disconnect/cancel.
src/gateway/agent-turn/agent-restart-recovery-context.ts 103 103 0 Retained: exact claim match precedes recovery source presentation and execution identity reconstruction. No audit collection/token semantics changed.
src/gateway/server-methods/doctor-memory-files.ts 103 103 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read remote/local listing and diary fallback. stat ENOENT advances filename while read failure returns the selected filename as missing. Combining catches would need phase state; remote maintenance remains the sole adapter. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/approval-run-cancellation.ts 102 102 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Forwarded each caller-owned private cancellation context into cancelMatchingApprovals while keeping explicit match predicate differences. Exact worker/run identity checks and publication order retained. | src/gateway/server-methods/approval-run-cancellation.test.ts
src/gateway/server-methods/usage-cache.ts 101 101 0 Retained: cache entry owns independent freshness/value/inflight and revision facts; incomplete snapshots and stale responses are deliberately different. Existing load owner shares all cache paths.
src/gateway/server-methods/chat-abort-queued-collector-publication.ts 100 100 0 Retained: one publishSnapshot owner carries pre-cleanup and settled snapshots under captured generation. publishedLastRunId prevents duplicate settled publication independently of row lastRunId.
src/gateway/server-methods/models-auth-status-api-keys.ts 99 99 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One provider loop implements config/reference/environment precedence. Marker suppression and explicit nonenv references are different classifications; common source projection would require optional envVar semantics unchanged. | models-auth-status.test.ts (results recorded separately)
src/gateway/talk/run-ownership.ts 99 99 0 Retained. One currentness closure composes exact voice binding, abort registration, backend attempt and lifecycle. Captured absence and session-versus-call scope survive waits; substituting a current lookup would authorize a later run.
src/gateway/terminal/session-manager.types.ts 99 99 0 RETAINED 99→99: each request/backend/session owner field has real consumers in manager, output, projection and native relay. Pending abort state differs from registered session state; no unused generality found. Exported and protocol-derived signatures preserved.
src/gateway/server-methods/cron-scratch.ts 96 96 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/session-reset-incognito.ts 96 83 13 Applied: use the same unavailable result constructor for terminal drain timeout and changed-row refusal. Terminal release, caller hook, delete parameters and no-archive semantics stay unchanged.
src/gateway/agent-turn/agent-run-dispatch-outcome.ts 94 94 0 Retained: timeout/cancellation result projection is already shared and table-driven. Owner-recorded cancellation differs from a raw provider AbortError; collapsing that distinction changes shipped RPC behavior.
src/gateway/server-methods/validation.ts 94 94 0 Read common options-identity preserving validation owner. Admin measured/rejected generic PushRequestOptions extension (combined -7 but extra options axis + local async-preserving factory); original retained.
src/gateway/session-row-projection-transcript.ts 94 94 0 RETAINED: first/cold lookup must run again after mark can synchronously install a row. The trailing timer starts its successor before refreshing, while pending accepted facts revoke immediately; those are distinct visibility requirements, not duplicate invalidation.
src/gateway/server-methods/artifacts-image-page.ts 93 93 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Invalid cursor construction is already shared. Connection-bound cursor map captures beforeSeq/imageOffset/readWindow/expiry as continuation facts; deriving them from latest page would violate replay window. Cleanup and 128-entry cap retain different bounds. | artifacts.images.test.ts; results recorded separately
src/gateway/server-methods/client-types.ts 93 93 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: GatewayClient projects selected GatewayWsClient fields and adds trusted in-process capabilities. TrustedAgentToolCaller and GatewayNodeInvokeStream describe separate closure-bound authority surfaces. Removing these distinctions or replacing the explicit Pick with the full WebSocket client would widen the handler contract rather than delete a duplicate implementation. | Full server-methods directory; results recorded separately
src/gateway/server-methods/mcp-app-onboarding.ts 93 93 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One plugin lookup/read/dispatch flow. Generic errorShapeFromError prototype93→91 changes diagnostics and database/incognito error mapping, so retained exact Error.message-or-String contract. | mcp-app-onboarding.test.ts (results recorded separately)
src/gateway/server-methods/send-channel-resolution.ts 93 93 0 Retained: send and action use the same channel resolver; poll has distinct unsupported text and permits the internal-channel path. Moving these three flags into a method descriptor keeps the same input fields and adds a descriptor type.
src/gateway/server-methods/sessions-recover.ts 93 93 0 Retained: one recovery call and one continuation owner; archive/source and successor events intentionally omit different agentId keys. No redundant request state remains.
src/gateway/server-methods/inflight.ts 90 90 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Remove the redundant metadata-presence branch: object spread accepts undefined and the cached marker remains the last writer. Zero-line reduction; no replay timing changes. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/agent-run-model-selection.ts 89 89 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One selection callback updates runtime identity then optional exact cron continuation. Set/delete execution-provider branches cannot merge with spread without retaining retired property; cron path unchanged. | sessions-patch-model-selection.test.ts;chat.directive-tags.test.ts (results recorded separately)
src/gateway/server-methods/session-file-read-authority.ts 89 89 0 RETAINED: withHostAuthority owns both admission and response recheck. hostAdmission records a single promise, usedHostRead records actual authorized use, placement records independent live authority; these cannot collapse into one flag.
src/gateway/server-methods/sessions-patch-permissions.runtime.ts 89 89 0 Retained: one captured runtime change and one publication function own apply/finish. Unsupported, ended, changed authority and cancellation failures have different cleanup guarantees; no duplicate write path remains.
src/gateway/server-methods/doctor-memory-provider-status.ts 88 88 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: share success/failure health projection before resource close | Full server-methods directory; results recorded separately
src/gateway/server-methods/chat-account-selection.ts 87 87 0 Retained: current personal-account preparation and synchronous presentation are separate authority responsibilities. Shared/personal/automatic wire shapes intentionally differ in authProfileId visibility.
src/gateway/server-methods/cron-list-projection.ts 87 87 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/sessions-patch-diagnostics.ts 87 87 0 Retained: finished cannot derive from an empty scopes set because newly started diagnostics also has no scopes. Shared mark owns timing and finish owns disposal; fixed phase order preserves log bytes.
src/gateway/server-methods/agent-run-handler.ts 86 86 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: agentRunHandler is already an adapter over createAgentTurnIo, prepareAgentRequestPreflight and createAgentTurnService. Upload admission precedes validation by contract, then runtime authority gates startTurn. Its catch maps SessionMutationAuthorizationChangedError directly and delegates closed-runtime handling; there is no local second turn pipeline to remove. | Full server-methods directory; results recorded separately
src/gateway/server-methods/chat-send-reply-delivery.ts 86 86 0 Retained: prepared transcript start selects exact physical scope; anchor receipt derives missing/pending/delivered from one current snapshot. No duplicate reader or state machine.
src/gateway/server-methods/models-auth-status.types.ts 86 86 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read exported types. Profile health and usage fields already derive with Pick; the remaining fields are distinct public result decorations, with no executable duplication. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/plugins.credentials.ts 86 86 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Authorization/base-hash/declaration refusals already share denied(message). Outer catch intentionally uses a separate UNAVAILABLE bounded error because authored credential data cannot cross that boundary. Two authority calls bracket config I/O and cannot collapse. | plugins.credentials.test.ts; results recorded separately
src/gateway/server-methods/skills-status.ts 86 86 0 Retained: ambient owner resolution precedes workspace selection; watcher admission remains inside withSessionDiscoveryAccess, with remote eligibility shared by card and status. No duplicate execution owner.
src/gateway/server-methods/attach.ts 85 85 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: attach.grant resolves canonical ownership, rejects protected harness entries, ensures loopback runtime, then mints one bounded grant; attach.revoke validates only its token and removes the grant. There is no common acquisition/revocation core, and the harness guard must precede server startup. | src/gateway/server-methods/attach.test.ts
src/gateway/server-methods/nodes.wake-reconnect.ts 84 84 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: wakeNodeForReconnect already parameterizes force and invoke/pending source. It retains one absolute push deadline, bounds reconnect polling to remaining budget and preserves source-specific log text/duration. The overload keeps the no-deadline caller result free of the deadline sentinel; removing it would widen callers without deleting behavior. | Full server-methods directory; results recorded separately
src/gateway/server-methods/workspace-path-containment.ts 84 84 0 Retained: async ancestor probing and synchronous commit revalidation protect separate edges. Both use canonical containment predicate; no second path policy.
src/gateway/talk/relay-session-lifecycle.ts 84 84 0 Retained. Existing generic expiry/connection-close/exact lookup owners already serve both relays. Capacity limits remain independent: realtime counts active plus draining owners, transcription counts registered draining sessions. Prior capacity prototype grew by 17 lines; reread confirms no new repeated work to absorb beyond its explicit limits and messages.
src/gateway/server-methods/users-channel-identities.ts 83 83 0 Retained: identityMutationHandler already parameterizes link/unlink; list must revalidate after its read. Returned mutation-kind check guards the owner-result contract.
src/gateway/agent-turn/types.ts 82 82 0 Retained: wire frames, IO, principal, context and observations are independent used contracts; terminal outcome type derives from the canonical runtime owner.
src/gateway/artifact-download-projection.ts 82 82 0 REJECTED 0: root-prototypes/artifact-download-projection.ts extracts the repeated byte-artifact predicate into a typed guard reused by preparation and response. It removes no lines and adds an internal predicate around two direct conditions; keep direct narrowing next to the digest check. Full/range paths already share response calculation and preserve separately owned exact ArrayBuffer allocation.
src/gateway/server-methods/chat-send-retry-comparison.ts 81 81 0 Retained: one submitted-input snapshot and one validation boundary. Request text/mentions/work context remain compared after exact physical/logical identity checks; no unused comparison mode.
src/gateway/server-methods/sessions-search-scope.ts 81 81 0 Retained: ACP explicit-owner exception and missing configured owner exception are separate clauses feeding the same success target. Repeated fallback discovery is guarded by different configured/persisted facts; search path unchanged.
src/gateway/server-methods/agents-list.ts 79 79 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Rechecked optional-model-catalog helper retains serial scalar fallback, whereas this handler runs all scalar reads concurrently. Prior79→67 helper reuse would change await/concurrency order. | agents-list.test.ts;optional-model-catalog.test.ts (results recorded separately)
src/gateway/server-methods/artifacts-base64.ts 79 79 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read validation, size counting and optional data normalization. Byte buffer avoids large per-character allocations; replacing it with chained regex replacements would trade memory for line count. Encoded length is required without materializing decoded bytes. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/skills-upload.ts 79 79 0 Retained: three operations already share makeUploadHandler. Upload feature refusal must precede schema validation; mapUploadError distinguishes authority errors from request/unavailable failures.
src/gateway/server-methods/catalog.ts 78 78 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Browse and keyword search already share defineCatalogHandler including workspace selection, owner call and error response. Browse-only invalidRequest runs outside catch; replacing it with a general strategy table would merely relocate existing parameters. | catalog.test.ts; results recorded separately
src/gateway/server-methods/chat-send-retry.ts 78 78 0 Retained: one typed failure classifier and bounded retry loop. shouldRetainAcceptedChatSendRetryIdentity is used at both terminalization sites and keeps recovery policy in its owner; inlining would duplicate that policy and require changing direct seam tests.
src/gateway/server-methods/models-list-public-projection.ts 78 78 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: buildPublicModelProjection explicitly allowlists public model fields and conditionally omits details. projectModelServiceTiers intersects a harness response with already-authorized tiers; projectProviderCatalogOutcomes strips provider-private metadata. These project different inputs to different public contracts; spreading source records would leak route/auth fields. | Full server-methods directory; results recorded separately
src/gateway/server-methods/sessions-patch-sandbox.runtime.ts 78 78 0 Retained: shared validator owns initial and commit-edge checks; mandatory sandbox, explicit native consent and active-work refusal have distinct precedence and public errors. No extra state or forwarding API.
src/gateway/server-methods/tools-invoke.ts 77 77 0 Retained: one invoke owner maps success/error variants and approval hints; each distinct payload constructed once.
src/gateway/server-methods/session-activity-summary.ts 76 76 0 RETAINED: batch authorization precedes every ensure. Summary service calls carry exact keyed/agent output rather than arbitrary row spreads. Existing sharing helpers already own policy; no repeated owner operation remains.
src/gateway/server-methods/terminal-upload.ts 76 76 0 Retained: one upload path retains exact live upload commit guard and client-capability projection. Moving connection checks to a helper adds an import and exported seam without shortening shared terminal admission.
src/gateway/server-methods/session-run-settlement.ts 75 75 0 RETAINED: one fan-in joins terminal controllers and reply owners after rejecting competing/live work. Both are independent owners; no redundant liveness source or duplicate await loop remains.
src/gateway/server-methods/agent-identity.ts 74 74 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: agentIdentityGetHandler has one requested-agent resolution path and one awaited avatar projection. It distinguishes malformed session keys from agent-selection errors and asserts mutation authority after avatar preparation. The output is a public avatar projection; there is no alternate identity writer or cache here. | Full server-methods directory; results recorded separately
src/gateway/terminal/agent-session-drain.ts 74 72 2 Applied: express exact owner-kind/key/incarnation/agent matching as one short-circuit predicate. Formatted 74→72 (-2). Receipt Sets, exiting backend Set and active admission map remain separate: settled drains retain admission until every receipt releases.
src/gateway/server-methods/chat-history-page-cursor.ts 73 73 0 Retained: cursor decode and encode share the schema; newer/older projections already use one cursor helper. Their oldest/newest anchor fallback and edge comparisons remain direct.
src/gateway/server/client-human-presence.ts 73 73 0 Retained: active Control UI demand is derived each refresh; present is the last published value, while invalidationSubscriptions separately track clients retained during held policy responses. The initial durable setHumanPresence barrier remains awaited.
src/gateway/server-methods/models-list-capabilities.ts 72 72 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: listDecisionModels deduplicates model IDs in plugin order while retaining plugin attribution; createModelsListProviderFilter builds known provider IDs from manifest contracts/config/catalog using one prepared normalizer. Model enumeration and provider-name admissibility have different inputs and one implementation each. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/session-scoped-read.ts 72 72 0 RETAINED: admission visibility establishes whether scoped retention is needed; current visibility authorizes response after I/O. Same-named calls retain separate current configurations and cannot share a cached policy.
src/gateway/server-methods/sessions-patch-catalog-preparation.ts 72 72 0 Retained: prepare/load/available expose different error contracts over one per-agent promise map. Ordered projection stays within admitted writer sequencing; detached catalog preflight deliberately returns a continuation.
src/gateway/talk/relay/issues.ts 71 71 0 Retained. One category switch projects failover errors and hides opaque routes. Public model and private launch model intentionally differ; sharing them changes credential/route disclosure behavior.
src/gateway/agent-turn/agent-run-execution-lineage.ts 70 70 0 Retained: single one-use lineage consumer and admission serialization owner; audit-adjacent provenance contract untouched.
src/gateway/agent-turn/agent-wait.ts 70 70 0 Retained: queuedResult already shares before/during/after observation. Captured session and source-specific replay barrier survive run-ID reuse and cannot derive from the later live registry.
src/gateway/server-methods/device-management-authz.ts 70 70 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Role checks already share requestsNonOperatorDeviceRole. Device token role loop reads only token.role; passing complete token through request-role parser would additionally interpret hypothetical roles fields and add array allocation. Existing callbacks each contain just normalize and compare. | device-management-authz.test.ts;devices.test.ts;../server.node-pairing-authz.test.ts; results recorded separately
src/gateway/session-viewer-presence.ts 70 66 4 Applied inline single-use normalizedSessionKeys expression in replace. The same trim/deduplicate/sort operation runs after live-client admission; stopped state and declaration map remain separate lifecycle facts. Activity/publication ordering unchanged.
src/gateway/server-methods/chat-send-delivery-authority.ts 69 69 0 Retained: the shared delivery authority owner already serves both finalizers; every delivery and media commit needs current writer authority. Optional unauthorized callback preserves ordinary finalization's terminal response.
src/gateway/server-methods/nodes.handlers.invoke-result.ts 69 69 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read null/nonstring payload normalization, node identity and late result receipt. Normalization owns legacy wire inputs; shared final success response was already consolidated in PR1. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/agent-runtime-authority.ts 67 67 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read has/assert/guard adapters. Canonical hasActive predicate serves boolean, throwing, response and commit adapters used independently by callers. Removing an adapter would only duplicate its required boundary conversion. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/sessions-patch-errors.ts 67 67 0 Retained: one owner maps model, authority, worktree and unexpected failures; createCommitGuard composes it at multiple real callers. Specific error classes retain ordering and different retryability.
src/gateway/talk/session-history.ts 67 67 0 Retained. One read owner rechecks authority around restored history. Raw item bytes and quoted serialized instruction bytes have different limits and ordering, so loops cannot be collapsed without losing a bound.
src/gateway/methods/core-profile-access.ts 66 66 0 RETAINED: exact methods and prefixes intentionally have different coverage. Replacing exact entries with prefixes would require broader profile access for unlisted names; session-method policy remains the canonical first predicate.
src/gateway/server-methods/agent.ts 66 66 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: agent.wait uses one authorizeWait closure before prepared.wait and again on the returned observation, preserving run generation and session visibility. agent dispatch is imported as agentRunHandler rather than reimplemented. The two authorization calls bracket an await and cannot be replaced by a saved pre-wait decision. | Full server-methods directory; results recorded separately
src/gateway/server-methods/claws-removal-journal.ts 66 66 0 RETAINED: Reviewed only. A single journal mutation has a before-dispatch currentness fence and an outcomeUnknown bit after dispatch; that bit records an irreversible boundary and cannot derive from success. | Full server-methods directory
src/gateway/server-methods/prepared-read.ts 66 66 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: withPreparedGatewayRead owns release outcome; createPreparedReadHandler adapts successful response interception without affecting error replies. Merging would duplicate direct/prepared dispatcher logic. | session-row-projection.prepared-read.test.ts;session-row-prepared-read.test.ts (results recorded separately)
src/gateway/server-methods/model-auth-agent-scope.ts 65 65 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Default and explicit agent selection now converge on one successful directory/result projection; preserve distinct invalid input messages and default-selection error mapping. | models-auth-status.test.ts (results recorded separately)
src/gateway/server-methods/model-provider-capabilities.ts 65 65 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read manifest choices and provider aggregation. One Map owns OR accumulation and one resolveProvider normalizes both choices and login options. Models versus non-text setup surfaces remain intentionally filtered. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/config-submission-validation.ts 64 64 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Rejected measured ordered validator-loop prototype 64->63 (-1): one mutable config result plus validator array obscures raw-before-effective validation for a single line. Existing respondInvalid already shares the only duplicated response core. | config.shared-auth.test.ts; results recorded separately
src/gateway/server-methods/session-unread-ack.ts 64 64 0 RETAINED: schema key allowlist is the owner of acknowledgement-only mutation semantics; validation and resolution already share that predicate. Apply/missing/stale reflect distinct result contracts.
src/gateway/talk/session-target.ts 64 64 0 Retained. prepare/assert already share storage target resolution. Captured client key differs from canonical storage key and returned target remains frozen. Late assertion must not consult ambient Talk defaults.
src/gateway/agent-turn/internal-facade.types.ts 63 63 0 Retained: type-only internal entry contracts; numeric timeout and structured dispatch options both have consumers, while wait carries different observation cancellation callbacks.
src/gateway/server-methods/terminal-open-plan.ts 63 63 0 Retained: one node-command authorization core used before and after awaits. Local catalog and remote node plans have different shell ownership; both already use the canonical launch planner where applicable.

@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

d01 PR 3 per-file coverage — part 5/5

Reviewed implementation head: 900b74a38d291476a712cfa5c601cf2c269e8eb1.

Gateway server-methods lane d01, PR 3 coverage

Baseline b3196dfda33555857eae9cd52ea29367a91bd9ea. This final lane pass re-evaluated prior rejected and partially simplified files, completed the current server-methods directory, and revisited its adjacent runtime owners.

608 production modules have per-file decisions, including all 427 current server-methods modules and the original exclusions. The implemented production diff removes 693 net lines; no test, protected storage, global-identity, config-retirement, tooling, or changelog paths changed. Existing assertions remain intact.

Counts describe the actual applied source against the original fresh-main base. Measured rejected prototypes are recorded in each relevant row. The PR body records executed validation separately; a named test below is a target unless that validation says it passed.

File Before After Net removed Decision and evidence
src/gateway/server-methods/agent-id-shared.ts 62 62 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: resolveConfiguredAgentIdOrRespondError performs strict ID normalization and roster membership with the agent-not-found message. resolveAgentIdOrRespondError accepts unknown input, preserves requested spelling, tries legacy compatibility/ambient selection and reports unknown-agent or selection-required messages. Callers rely on these different input and error contracts. | Full server-methods directory; results recorded separately
src/gateway/server/presence-events.ts 62 62 0 Retained: pending spans both scheduled and actively preparing publication. publishedVersion intentionally advances only after readiness, and finally schedules changes that arrive while flushing. Replacing it with timer/scheduler state would lose reentrant publications or disposal behavior.
src/gateway/agent-turn/agent-run-commentary-media.ts 61 61 0 Retained: one lazy custody adapter; mutates the original dispatch object to preserve its private execution-identity binding, so a new copied shared record would change provenance.
src/gateway/agent-turn/agent-run-execution-types.ts 60 60 0 Retained: execution inputs carry accepted provenance, resolved identities and cleanup owners rather than the earlier admission state. Shared service facts reduce caller repetition without expanding the exported type.
src/gateway/server-methods/chat-metadata-contract.ts 60 60 0 Retained: central session metadata field list already drives both type and comparison; current-source assertions and draft account lifetime remain distinct used inputs.
src/gateway/server-methods/chat-tts-markers.ts 60 60 0 Retained: full and media-only marker builders share projection/hash logic; media-only wrapper is a named caller policy used by dispatched replies, while runtime media supports spoken text.
src/gateway/server-methods/environments.session-tool-policy.ts 60 60 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Captured run and inherited policy are admitted caps; current conversation capability is separate live policy. assertAllowed composes both at use-time; collapsing captured/current inputs would grant authority after changes. | environments.session-exec.test.ts; results recorded separately
src/gateway/server-methods/session-catalog-read.ts 60 60 0 RETAINED: one provider read plus post-I/O publication visibility and participant projection. Handler authorization cannot replace the after-I/O check. No duplicate operation or unused parameter remains.
src/gateway/terminal/open-deadline.ts 60 56 4 Applied: inline the private single-use expiration helper into the existing expire callback. Formatted 60→56 (-4). Same error class/name/message, first abort reason, absolute deadline comparison, timeout and abort callbacks, post-run success/failure assertion and async boundaries remain.
src/gateway/server-methods/attachment-normalize.ts 59 59 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: normalizeAttachmentContent handles string, ArrayBuffer view with offset/length, and whole ArrayBuffer through one normalizer. normalizeRpcAttachmentsToChatAttachments combines top-level fields with Anthropic source data and filters only absent content. Optional numeric fields are omitted when invalid while string fields remain present as undefined; generic record copying would change that shape. | Full server-methods directory; results recorded separately
src/gateway/server-methods/models-list-result.default-models.ts 59 59 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Preview computes once and reports executable utility route only for exact sole-agent setting; explicit/auto/disabled variants already select same lazy runtime owner. | models-list-result.configured-static.test.ts;model-discovery-policy.test.ts (results recorded separately)
src/gateway/agent-turn/agent-run-admission-model.ts 58 58 0 Retained: canonical model/runtime owner does selection, and exact lifecycle store resolution is separate. Override request values and restored continuation values retain their existing precedence.
src/gateway/server-methods/artifacts-session-read.ts 58 58 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read selected source and lifecycle guard. One assertCurrent binds physical store/session/lifecycle for both scoped and empty reads. Conditional scope omission is public type shape; current direct early return remains clearer. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/channels-status-issues.ts 58 58 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Per-plugin try/catch isolates diagnostics errors while deferred reload issue is independently appended. Shared collectChannelStatusIssues already owns plugin issue projection; flattening global collection would let one failure suppress later plugins. | channels.status.test.ts; results recorded separately
src/gateway/server-methods/lazy-core-handlers.ts 58 58 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: prepareGatewayRequestHandler resolves nested forwarding wrappers and refreshes dispatch authority; createLazyCoreHandlers retains request-entry lifetime through module loading, releases it before invoking the real handler, and releases again in finally. The forwarding wrapper is the lazy entry boundary, not redundant exported behavior. | src/gateway/server-methods/lazy-core-handlers.test.ts
src/gateway/server-methods/nodes.invoke-talk-events.ts 58 58 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: TALK_PTT_EVENT_TYPES already parameterizes four Talk commands. emitTalkPttNodeEvent is the single capture-id, bounded sequence-map and canonical talk.event projection. Remaining fields encode the wire event, including final=false only for start; no duplicate command handler remains. | Full server-methods directory; results recorded separately
src/gateway/server-methods/nodes.shared.ts 58 58 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Extended pairing error owner with optional operation wording; existing invocation text/default behavior unchanged, pending-work caller supplies its exact prior phrase. Lifecycle-before/after-generation checks remain intact. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/session-create-diagnostics.ts 58 58 0 Retained: one timing owner and one guarded publication. Phase identity, repeated-stage aggregation, thresholds and diagnostic text stay exact.
src/gateway/agent-turn/agent-run-recovery-admission.ts 57 57 0 Retained: one exact admitted recovery attempt; restored marks successful durable restoration, not invocation. Early failures intentionally permit retry with the same captured attempt.
src/gateway/server-methods/chat-human-mentions.ts 57 57 0 Retained: one ordered span normalization loop enforces original-byte selection, NFC boundary and UTF-16 safety. Three rejection points occur before different computations and retain one error constant.
src/gateway/managed-image-attachments.media-kind.ts 56 56 0 RETAINED: One media classification owner and fixed supported-document MIME table. Local AV byte limits, image-specific bounds and SVG rejection are real distinct policy; the existing conditional already parameterizes their shared maximum-size path.
src/gateway/server-methods/sessions-patch-types.ts 56 56 0 Retained: types describe actual inter-module outcome and admission discriminants. Replacing them with repeated inferred property selection would not reduce the owning behavior or improve consumers.
src/gateway/server-methods/commands.ts 55 55 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: commands.list delegates selected-agent validation to resolveAgentIdOrRespondError, session visibility to withSessionDiscoveryAccess and command projection to buildCommandsListResult. This file contributes only the method-specific changed-session error and provider/scope options; it contains no independent command discovery implementation. | Full server-methods directory; results recorded separately
src/gateway/server-methods/device-management-security.ts 55 55 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One trusted event projection hashes actor/target identifiers and records reason in both policy/event intentionally. Device token/pairing callers already parameterize outcome/policy/control. | devices.test.ts;devices.lifecycle.test.ts (results recorded separately)
src/gateway/server-methods/chat-send-reply-session.ts 54 54 0 Retained: one current-session reader and captured start binding, with compatibility lookup only when prepared watermark is absent. Session initialization can publish a SID after admission, so preparation cannot derive from stale session.entry.
src/gateway/server-methods/session-model-catalog-wait.ts 54 54 0 RETAINED: one monotonic deadline across all run calls; settle converts only the same unavailable object. Initial abort versus elapsed deadline precede operation invocation with distinct observability.
src/gateway/server-methods/sessions-sharing-identities.ts 54 54 0 Retained: remember already shares current-actor/creator/profile projection. Later profile data deliberately updates existing identity insertion order and preserves prior label fallback.
src/gateway/server-methods/chat-send-external-entry.ts 53 53 0 Retained: explicit external authority capability adapter; separate dashboard and cron creators consume shared caller facts but preserve distinct policy owners. No changes to cron authority modules.
src/gateway/server-methods/session-file-read.ts 53 53 0 RETAINED: session-contained paths and authorized outside-host handles preserve different root representations; local and external file probing cannot share the same effect sequence. No duplicate path resolver remains.
src/gateway/server-methods/wizard-login.ts 53 53 0 Retained: admission validates before and after await, closes on revoked requester, and shares both terminal cleanup outcomes through one settled callback. No repeated lifetime state.
src/gateway/server-methods/chat-send-admission-context.ts 52 52 0 Retained: existing shared argument owner for route and diagnostics; session target refusal includes cleanup and typed response at the current callback boundary.
src/gateway/talk/handlers/client-legacy-voice-bindings.ts 52 52 0 Retained. Read/write share TTL pruning and key formation. Forget intentionally clears only the matching identity without pruning unrelated rows; shipped legacy clients still consume this contract.
src/gateway/server-methods/chat-history-recovery.ts 51 51 0 Retained: one embedded recovery snapshot resolver plus one typed unavailable response; absent session/owner are independent required exits.
src/gateway/terminal/session-connection-index.ts 51 51 0 RETAINED 51→51: add/remove are already shared, and snapshots must remain copied while manager mutates indexes. Reimplemented typed snapshot helper full-file prototype is 51→57 (+6), so rejected (session-connection-index-alternative.ts).
src/gateway/server-methods/chat-send-agent-dispatch.types.ts 50 50 0 Retained: type-only shared detached dispatch handoff; every field has a live caller/consumer, and turning this into a broad handler type would widen ownership.
src/gateway/talk/relay/agent-consult.ts 50 50 0 Retained. bindReadiness already parameterizes runner/error text. claimForCurrentOwner must invoke the claim even after currentness is false to consume cleanup; short-circuiting the second operation would change custody.
src/gateway/server-methods/chat-send-admission-cleanup.ts 49 49 0 Retained: cleanup callback has mutable media custody until ACK; finishAbortedChatSend retains exact replay write, cleanup and response order. No duplicate owner.
src/gateway/server-methods/session-catalog-result.ts 49 49 0 RETAINED: sole catalog wire projector and error normalizer. Repeated startTerminal capability appears in distinct public nested and top-level fields; neither can be removed.
src/gateway/session-row-projection-access.ts 48 48 0 RETAINED: 48-line registry binds original context ownership while context copies carry its opaque binding. Require/get intentionally expose throw-versus-absence contracts; callback lookup must fetch the current registered owner.
src/gateway/server-methods/agent-timestamp.ts 47 47 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: buildTimestampPrefix already shares timestamp formatting for historic boundary stamps and CLI injection. Wrapper additionally excludes existing envelope/cron clocks and returns original on invalid zone; direct callers require distinct contracts. | server-methods.test.ts; results recorded separately
src/gateway/server-methods/local-state-owner.ts 46 46 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: captureLocalStateMutationGuard captures the physical Gateway state owner and config, rechecks signal/request authority and owner at use time, and optionally checks a source inode. Target inode identity is a separate filesystem boundary, not duplicate state-owner validation. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/nodes.helpers.ts 46 46 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: respondUnavailableOnNodeInvokeError is exported by src/plugin-sdk/gateway-runtime.ts as the two-argument SDK surface; respondUnavailableOnNodeInvokeErrorWithProvenance adds internal dispatch evidence for nodes.invoke/exec-approvals. Removing the wrapper requires changing the public SDK contract/callers outside assignment; error formatting itself already has one implementation. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/nodes.invoke-authority.ts 46 46 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: isForwardedNodeInvokeApprovalAuthorityActive checks the live approval decision. resolveNodeInvokeRuntimeAuthorityError first validates the current agent runtime capability and only then the approval capability, preserving two distinct error messages. A valid stored decision cannot substitute for live run authority, so both checks remain. | Full server-methods directory; results recorded separately
src/gateway/server-methods/skills-workspace-handler.ts 46 46 0 Retained: workspace selection owns normalization/default-selection failures and unknown-agent errors once. It is also consumed by catalog outside this slice; public return signature preserved.
src/gateway/server-methods/chat-send-session-binding.ts 45 45 0 Retained: exact registration, lifecycle, active admission and cancellation facts are separately fenced before SID adoption; all callers need the same binding contract.
src/gateway/server-methods/mentions.ts 44 44 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: one validated list/dismiss inbox flow preserving callback publication | Full server-methods directory; results recorded separately
src/gateway/server-methods/sessions-patch-discovery.ts 44 44 0 Retained: discovery must finish all target resolutions before duplicate rejection, so merging its two loops would change which read errors are observed. Resolver cache and logical-target set serve different jobs.
src/gateway/session-create-key.ts 44 44 0 Retained: content hash and random opaque dashboard identity have different persistence contracts. Canonical key resolver is already one branch over explicit global/unknown versus ordinary keys.
src/gateway/server-methods/optional-model-catalog.ts 43 43 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: REJECTED measured single batch-result Map projector: 43 to 44 (+1), misc-prototypes/optional-model-catalog.ts. Requires typed intermediate results plus tuple allocation; original scalar/batch/catch accumulator stays clearer. | src/gateway/server-methods/optional-model-catalog.test.ts
src/gateway/server-methods/projects-list-diagnostics.ts 43 43 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One stage tracker feeds both diagnostics channel and slow warning; phase records current span to finish. Unlike update.status it starts when either channel subscribers or process flag exist; a shared timing wrapper needs distinct admission and publication policies. | projects.test.ts; results recorded separately
src/gateway/server-methods/cron-error-classification.ts 42 42 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/server-methods/skills-retired.ts 42 42 0 Retained: the new main-owned retirement map is already data-driven. All 17 RPC aliases and exact guidance are a preserved client contract.
src/gateway/session-reset-target.ts 42 42 0 Retained: explicit agent validation precedes global inference and mismatch checks; canonical target discovery occurs once. This is selection policy, not duplicated state.
src/gateway/agent-turn/principal.ts 41 41 0 Retained: explicit field projection excludes request lifetime and transfers two opaque authority owners. Shared observer already gates tool events by exact capability.
src/gateway/desktop/computer-protocol.ts 41 41 0 RETAINED: strict Zod schemas own the actual private process wire protocol; parser functions expose two different schemas. No schema/dependency changes or behavior changes authorized.
src/gateway/methods/read-share-keys.ts 41 41 0 RETAINED: common operator key already owns sorted caller/profile/params facts; cron and model adapters only encode their distinct response-sharing vetoes. No repeated serialization or redundant policy source remains.
src/gateway/server-methods/chat-send-active-leaf.ts 41 41 0 Retained: one exact/ancestor relation policy; allowEmptyAncestor is used only by send admission and must remain unavailable to Stop/recovery. No unused option.
src/gateway/server-methods/chat-startup-requester.ts 41 41 0 Retained: one requester capture; attached profile and email-created profile have different revocation predicates. Final read follows current alias merge without changing the captured requester source.
src/gateway/server-methods/cron-run-log-filters.ts 41 41 0 Excluded: reserved original global-identity, config-retirement or cron owner; unchanged.
src/gateway/talk/relay/cancellation-deadline.ts 41 41 0 Retained. First deadline resumes microphone input while retaining old output fence; second expires only that stale generation. Both exact-owner checks remain necessary and cannot derive from elapsed time.
src/gateway/authenticated-presence-user.ts 40 40 0 Retained: qualified profile and legacy identity projections intentionally differ in identity namespace/avatar and email eligibility. One authoritative projection used by both nodes and client presence; no duplicate metadata owner.
src/gateway/methods/core-descriptor-types.ts 40 40 0 Retained original explicit Pick type. The 40-to-28-line Omit prototype was implemented, then reverted because it changed reachable SDK declarations. Public declaration stability takes precedence over this 12-line reduction.
src/gateway/server-methods/send-account-route.ts 40 40 0 Retained: one explicit-account validator loop shares normalization; default account remains separate from caller-supplied selection so replay identity never becomes delegated authority.
src/gateway/terminal/session-projection.ts 40 40 0 RETAINED 40→40: one summary owner serves list/attach, with attach deliberately omitting attached/createdAtMs and adding replay snapshot/end offset. Recipient copy preserves viewer order and adds a distinct connection owner only once. No duplicated projection.
src/gateway/talk/handlers/mode.ts 39 39 0 Retained. Connected-node check intentionally precedes schema validation, then commit/broadcast stays synchronous. Independent lightweight mode handler avoids loading provider runtime.
src/gateway/server-methods/nodes.handlers.invoke-progress.ts 38 38 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Single validated RPC checks caller identity and byte bound then delegates node-registry owner; no second invoke-progress path or local progress state. | nodes.validation.test.ts; results recorded separately
src/gateway/server-methods/storage.ts 38 38 0 Retained: two single-owner adapters differ in sync catalog versus async probe and unavailable-registry defaults; a strategy factory would add generic plumbing without shared work.
src/gateway/server-methods/hooks-status.ts 37 37 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One report combines registry hook facts and directory loading. These are distinct plugin/workspace ownership inputs, no repeated discovery. | hooks-status.test.ts (results recorded separately)
src/gateway/server-methods/chat-send-goal-retry.ts 36 36 0 Retained: capture dedupe before async receipt lookup; known Goal errors become receipt data and unknown errors propagate. One lookup path, no parallel implementation.
src/gateway/server-methods/node-command-rejection-hint.ts 36 36 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: buildNodeCommandRejectionHint maps policy reasons in order: undeclared command, Talk trust, explicit deny, dangerous allow opt-in, generic allowlist, and pending declared-surface approval. Each return has distinct exact user remediation; no repeated action body accompanies the text branches. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/session-create-initial-turn.ts 36 36 0 RETAINED: message/attachments normalization has one owner and preserves nonempty invalid-attachment rejection. Fresh-send predicate intentionally distinguishes cached started responses. No duplicate parser to merge.
src/gateway/talk/client-agent-consult.types.ts 36 36 0 Retained. Type-only reusable and lifecycle-bound callback contracts derive provider inputs; requester-final/readiness/completion controls intentionally differ. Private options-object prototype is larger and does not alter these exports.
src/gateway/server-methods/chat-send-session-settings.ts 35 35 0 Retained: expectation checks always run; optional freeze happens only when committing. Cannot combine the branch without omitting noncommitting validation.
src/gateway/server-methods/speech-mime.ts 35 35 0 Retained: four ordered MIME rules combine codec-prefix and extension evidence, with mp3 before opus before wav/webm. A regex table risks changing exact suffix behavior around final newlines and adds encoding machinery for four simple predicates.
src/gateway/session-create-fork-entry.ts 35 35 0 Retained: explicit reset/fork field clearing is the persisted data whitelist. Parent CLI bindings use the existing canonical fork projection; no new serializer or data shape.
src/gateway/session-reset-transcript.ts 35 35 0 Retained: one lazy transcript read with empty fallback and precise warning. Entry/sessionId/sessionKey fields map to different transcript fields; API projection is not redundant.
src/gateway/server-methods/native-hook-relay.ts 34 34 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read relay bridge. One call carries explicit generation requirement and requester signal, then maps its only result/error. Existing direct response has no duplicated native owner. | src/gateway/server-methods/native-hook-relay.test.ts
src/gateway/talk/client-gateway-control.types.ts 34 34 0 Retained. Type-only owner contract derives provider control shape while requiring bindControl at the owner boundary. No runtime duplicate.
src/gateway/server-methods/users-mentionable.ts 33 33 0 Retained: one validated callback adapter delegates to mentionInbox; unavailable result is distinct from callback result union. No second execution path.
src/gateway/desktop/observe-requester.ts 32 32 0 RETAINED: one 32-line authenticated connection/display identity adapter. Invalidation, abort and caller callback each establish independent live authority; none is redundant.
src/gateway/server-methods/backup.ts 32 32 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: backup.status parallel-reads backup runs and cron jobs, then projects targets/schedules/storage locations. summarizeBackupSchedules and summarizeBackupTargets are already owned elsewhere, and cron/state changes are excluded. The handler has one read composition and no duplicate branch. | src/gateway/server-methods/backup.test.ts
src/gateway/server-methods/models-auth-refresh.ts 32 32 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: models.authRefresh validates once, resolves explicit or ambient auth owner through resolveModelAuthAgentScope and invokes refreshModelAuthStateAfterMutation under respondUnavailableOnThrow. This is already a single shared refresh call; changing the empty-string agent fallback would change accepted request behavior. | Full server-methods directory; results recorded separately
src/gateway/server-methods/system-agent-session-owner.ts 32 32 0 Retained: delegation, profile-pending rejection, user, device, and connection ownership have ordered distinct prefixes; no duplicated policy.
src/gateway/server-methods/voicewake.ts 32 32 0 Retained: common error helper already used; set requires normalized persistence then broadcast then response. Get does only load/project.
src/gateway/terminal/intro-banner.ts 32 32 0 RETAINED 32→32: fixed ANSI/CRLF banner and art byte array; all text, artwork, spacing and palette are client-visible. Further line reduction would golf literal data or obscure the exact composition.
src/gateway/server-methods/artifacts-transcript-images.ts 31 31 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: findTranscriptImageArtifact prepares the exact session read, queries one image artifact, rechecks authority, and returns the same assertion with the artifact. Missing scope is an early empty lookup; combining it with the successful response would skip or misplace the post-I/O check. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/models-list-context.ts 31 31 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: ModelsListCatalogSource discriminates Gateway catalog loading from a published owner with auth materializations; PreparedModelsListRequest carries request-specific metadata authority. GatewayModelCatalogContext is a narrow Pick used by both. These are capability boundaries, not a manually mirrored function result; the redundant result mirror was removed from models-list-result.owner.ts instead. | Full server-methods directory; results recorded separately
src/gateway/server-methods/session-create-category.ts 31 31 0 RETAINED: one registration operation with source guard before/after and catch-triggered catalog-only refresh. Boolean changed records a possible committed write after failure and cannot be derived from success alone.
src/gateway/server-methods/update-outcome-observation.ts 31 31 0 Retained: one public failure-code sanitizer and final outcome log, no repeated owner or state.
src/gateway/server-methods/user-preference-events.ts 31 31 0 Retained: canonical profile and connected alias selection already share one broadcast owner; no storage write or duplicate loop.
src/gateway/agent-turn/agent-run-diagnostics.ts 30 30 0 Retained: one privacy capture serves runtime output, warning and replay projections with distinct omitted-field contracts. No duplicated incognito policy.
src/gateway/server-methods/nodes-policy.ts 30 30 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: nodeInvokePolicy owns wake/pending constants, pending-pairing read scope and the one private Claude-run rejection. canReadPendingNodePairing shares the admin/pairing rule with node reads; rejectClaudeAgentRun delegates the supported continuation path in its existing error. No second scope or command policy is implemented here. | Full server-methods directory; results recorded separately
src/gateway/server-methods/nodes.invoke-foreground.ts 30 30 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Platform and command gates precede shared structured error marker extraction. No duplicate handler body beyond three explicit camera/screen/talk prefixes. | nodes.invoke-wake.test.ts (results recorded separately)
src/gateway/server-methods/projects-session-store.ts 30 30 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: New30-line adapter explicitly selects canonical combined loader versus already-provided incognito stores; mergeCombinedSessionStore remains the sole projection core. Removing adapter would duplicate this branching in project callers. | src/gateway/server-methods/projects.test.ts
src/gateway/server-methods/session-goal-change.ts 29 29 0 RETAINED: goal writer starts first, projection invalidation runs before the await, and finally joins it even when invalidation throws. Single shared catch keeps notification/log failures from replacing committed outcome.
src/gateway/server-methods/sessions-collaboration-diagnostics.ts 28 28 0 Retained: one timing wrapper with no-emitter fast path and isolated sink failure. Existing owner is already minimal.
src/gateway/server-methods/system-agent-chat-params.ts 28 28 0 Retained: sanitization has exact non-object pass-through and context omission contracts; approved bounded page/plugin projection is already shared.
src/gateway/session-request-error.ts 28 32 -4 Applied: add narrow unavailableSessionRequest(message), symmetric with invalidSessionRequest and using the exact two-argument errorShape call. No optional flags, retryability or details API added; all existing exports unchanged.
src/gateway/server-methods/node-push-transport.ts 26 26 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: resolveNodePushTransport returns relay configuration synchronously within its async function without loading signing material; direct registration awaits APNS auth resolution. Both already return the same ok/error union, but acquiring the two transports through one eager path would read disallowed credentials for relays. | src/gateway/server-methods/ (full suite)
src/gateway/session-create-visibility.ts 26 26 0 Retained: new-row default policy and adopted-row explicit visibility constraints are intentionally different, already handled by one small resolver.
src/gateway/session-reset-notifications.ts 26 26 0 Retained: minimal global lifecycle listener owner; each listener failure is isolated, and committed reset events must notify every remaining listener.
src/gateway/terminal/output-ring.ts 25 25 0 RETAINED 25→25: bounded-buffer owner plus surrogate-aware tail and one replay join. No duplicate buffer/state; output units and whole-chunk eviction are retained behavior.
src/gateway/server-methods/chat-send-external-authority-contract.ts 24 24 0 Retained: type-only exact capability input plus three distinct operations, no executable duplicate.
src/gateway/server-methods/models-auth-status-config.ts 24 24 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read provider config auth references. One Set deduplicates canonical and incompatible-profile references; provider iteration cannot be replaced by direct profile iteration because config owns membership. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/server-methods/response.ts 24 24 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: respondUnavailable is canonical error projection; respondUnavailableOnThrow adds catch with required authority-error rethrow. Both are broadly called and represent separate operations. | ../server.models-voicewake-misc.test.ts; results recorded separately
src/gateway/talk/request-error.ts 24 24 0 Retained. Already the shared PR2 error owner; client, session and legacy-relay strategy preserves classified errors, optional Talk issue details and legacy all-unavailable behavior.
src/gateway/terminal/buffer-text.ts 23 23 0 RETAINED 23→23: ANSI stripping, CR overwrite selection, then control-byte removal are ordered independent normalization responsibilities. No parallel path to consolidate without changing bytes.
src/gateway/terminal/gateway-transport.ts 22 22 0 RETAINED 22→22: one adapter binds targeted connection delivery and data-only dropIfSlow, with socket pressure delegated to its owner. Inlining into manager would cross the transport boundary and repeat policy.
src/gateway/agent-turn/agent-run-dispatch-execution-identity.ts 21 21 0 Retained: WeakMap is the private identity owner; cloning only when binding provenance is deliberate and consumed by commentary dispatch. No alias/wrapper without ownership meaning.
src/gateway/server-methods/chat-send-pre-admission.types.ts 21 21 0 Retained: types preserve loaded versus qualified session boundaries and prepared current authority; narrowing the earlier phase to admitted session would remove lifetime evidence.
src/gateway/server-methods/gateway-personal-caller.ts 21 21 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-evaluated shared-core extraction: isSyntheticGatewayCaller recognizes synthetic clients, delegated tools, runtime identities, and ambient tool callers. isIneligiblePersonalGatewayCaller adds the distinct rule that real shared-secret sockets may carry a system actor plus owner profile. The latter reuses the former instead of duplicating its conditions. | src/gateway/server-methods/ (full suite)
src/gateway/server-methods/session-model-selection-policy.ts 21 21 0 RETAINED: 21-line adapter supplies current config-readonly/admin grant to canonical sticky-model owner. All parameters and conditional scope presence are used.
src/gateway/desktop/host-source-errors.ts 20 20 0 RETAINED: 20-line error hierarchy retains concrete name/detailCode/auth and exact credential UI messages. Both subclasses have callers; collapsing them changes instanceof or class names.
src/gateway/server-methods/nodes.ts 20 20 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Method-family composition and existing wake exports only; deleting facade would require unrelated import cutover and add equivalent registry imports elsewhere. | nodes.invoke-wake.test.ts (results recorded separately)
src/gateway/server-methods/session-goal-request.ts 20 20 0 RETAINED: one canonical recursive object-key order and HMAC keyed by process device identity. Sorting comparison and domain prefix are receipt contract bytes, not duplicated plumbing.
src/gateway/session-row-projection-binding.ts 20 20 0 RETAINED: 20-line singleton class provides cross-source/built instanceof identity and stores exactly two used fields; no duplicate state or general-purpose layer remains.
src/gateway/server-methods/logs.ts 19 19 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One validated handler delegates readConfiguredLogTail; no local file loop/cache. Error prefix is retained transport contract. | ../server.logs-tail.test.ts; results recorded separately
src/gateway/server-methods/system-agent-approvals.ts 19 19 0 Retained: 19-line pending-list adapter uses common approval lookup, preserves optional getCfg only for profiled clients.
src/gateway/talk/nodes.ts 19 19 0 Retained. PR2 already removed the single-use predicate; one current connected-node traversal checks capabilities then commands with original normalization order.
src/gateway/server-methods/chat-startup-projection-contract.ts 18 18 0 Retained: type-only startup read/result contract, ready/current policies and late requester lookup are all used.
src/gateway/server-methods/question.errors.ts 17 17 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One sentinel error class and precise manager-error response mapper. Cannot merge with generic errors without consuming unrelated failures. | question.test.ts (results recorded separately)
src/gateway/desktop/attachment.ts 16 16 0 RETAINED: 16-line exact Unix/TCP transport adapter; both path argument shapes are used and stream attachments intentionally are not connectable.
src/gateway/desktop/host-guidance.ts 16 16 0 RETAINED: 16-line canonical platform guidance data and Linux fallback. Text bytes remain unchanged; table already is the parameterized form.
src/gateway/agent-turn/io.ts 15 15 0 Retained: one emit serves both callbacks and preserves the observable three-versus-four argument response call. No further duplicate code.
src/gateway/server-methods/agent-request-types.ts 15 15 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read schema-derived request type. Three internal fields override protocol types and workspaceDir adds internal context; no runtime or duplicate schema body. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/terminal/backend.ts 15 15 0 RETAINED 15→15: all seven backend operations are used by manager/output and implemented by local/node backends. No unused method or alternate owner.
src/gateway/talk/agent-consult-transcript.ts 14 14 0 Retained. Canonical display projector owns hidden-final behavior. Spoken transcript and lossless model/audit transcript stay distinct; the stop/no-intermediate/no-tool-call predicate is the contract.
src/gateway/terminal/session-limits.ts 14 14 0 RETAINED 14→14: authoritative limits and unit/lifetime explanations; constants are public defaults and all consumed. No config/default change proposed.
src/gateway/desktop/computer-owner.ts 12 12 0 RETAINED: 12-line exact authority tuple serialization binds all run-instance, lifecycle and claim fields. No duplicate body or unused field.
src/gateway/server-methods/connect.ts 12 12 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: One shipped post-handshake refusal with exact text; no branch/state or duplicate owner. | server-methods.test.ts; results recorded separately
src/gateway/desktop/node-source-context.ts 11 11 0 RETAINED: 11-line symbol-keyed context accessor owns its single cast and runtime identity. Inlining would spread the same ownership contract across callers without reduction.
src/gateway/server-methods/sessions.runtime.ts 11 11 0 Retained: named lazy lifecycle barrel exports are used by both reset and creation callers; removing the file would alter the established lazy boundary and test seams without useful reduction.
src/gateway/terminal/session-types.ts 10 10 0 RETAINED 10→10: protocol-derived list/attach contracts encode real owner strings and intentional field omissions. No redundant implementation or removable export.
src/gateway/server-methods/response-types.ts 9 9 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: PR2 full-file shared-core re-evaluation: RespondFn is the sole four-argument protocol-response callback type: success, payload, structured error and internal meta. There is no implementation or parallel declaration within this file to consolidate. | Full server-methods directory; results recorded separately
src/gateway/talk/relay-audio-base64.ts 9 9 0 Retained. Canonical decoder normalizes URL-safe alphabet and keeps label-specific errors. No parallel validator or extra state.
src/gateway/server-methods/voicewake-routing.ts 8 8 0 Retained: eight-line single load/response adapter; no abstraction to remove.
src/gateway/talk/session-target.types.ts 8 8 0 Retained. Eight-line identity contract deliberately keeps storage runtime out of Talk consumer imports. Type-only relocation would not reduce implementation.
src/gateway/server-methods/base-hash.ts 6 6 0 RETAINED: Re-read complete current module; retain the existing structure. Prior owner assessment remains applicable: Re-read six-line multi-caller adapter. Canonical nullable-string normalization owns coercion; removing the adapter would duplicate protocol field extraction across callers. | full subsystem and direct caller tests; lead owns frozen proof
src/gateway/terminal/enabled.ts 6 6 0 RETAINED 6→6: lightweight config predicate serves HTTP/CSP without loading launch policy. Inlining would duplicate policy or expand eager imports. No config change proposed.
src/gateway/server-methods/types.ts 4 4 0 Retained: four-line public type barrel maintains documented import boundary; no production runtime body.
src/gateway/server-methods/chat-transcript-persistence.runtime.ts 2 2 0 Retained: two re-exports are the deliberate lazy abort-persistence import boundary, with no forwarding implementation to remove.
src/gateway/agent-turn/internal-facade.runtime.ts 1 1 0 Retained: one-line maintained lazy runtime entrypoint, no executable forwarding body.

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

These security sensitive changes were made:

  • src/gateway/exec-approval-lifecycle.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

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

clawsweeper Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 8, 2026, 1:02 PM ET / 17:02 UTC.

ClawSweeper review

What this changes

The branch shares Gateway request preparation, response projection, and lifecycle cleanup while preserving existing behavior.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful consolidation with no actionable finding, supported by substantial reported test coverage rather than a demonstrated shipped-entry-point run.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The recorded maintainer-authored internal refactor is outside the external-contributor proof gate. Supplied validation covers Gateway handlers, worker-backed sharing, approvals, desktop, Talk, and terminal owners through existing tests; no separate live-run proof is claimed. Inspection found no changed stored-data format or migration requirement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: The change reduces duplicated production preparation and lifecycle bookkeeping within existing owners. Prior merged area work establishes the same maintainer-directed consolidation intent without changing product contracts.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this maintainer-authored refactor contains useful, distinct consolidation, and review found no concrete introduced correctness or security defect.

Priority: P3
Reviewed head: 900b74a38d291476a712cfa5c601cf2c269e8eb1

Before merge

  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.

Findings

None.

Provenance

  • Session row projection, catalog, and diagnostic projections: original intent not found (unknown: Tree history was available, but the deeper projection string-history search encountered an unavailable promisor blob; exact helper introduction remains unknown.)
  • Terminal, desktop, presence, and Talk lifecycle helpers: original intent not found (unknown: Recent file history and earlier consolidation intent were inspected; older helper introductions were not established after historical blob retrieval failed.)
Agent review details

How this fits together

The Gateway receives requests from OpenClaw clients and coordinates conversations, session storage, approvals, and terminal processes. These changes simplify the handlers that prepare those operations and publish their results.

flowchart TD
  A[Client requests] --> B[Gateway validation]
  B --> C[Prepared session and request facts]
  C --> D[Current authority checks]
  D --> E[Session and runtime owners]
  E --> F[Shared result projection]
  F --> G[Client responses and events]
Loading

Technical review

Best possible solution:

Keep the consolidation in the existing Gateway owners while preserving their current authority, persistence, response, and cleanup contracts.

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

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

Is this the best way to solve the issue?

Yes: the introduced changes reuse existing owners and remove repeated preparation and projection without establishing a competing implementation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • src/gateway/server-methods/sessions-sharing.ts keeps the original intent (8ecd925: Use prepared sharing facts and existing workers while retaining physical-source identity, manager revocation checks, and commit-time authorization.)
  • src/gateway/session-create-target.ts keeps the original intent (5c13ecf: Reject workspace adoption before filesystem preparation when the existing conversation still owns active work.)
  • src/gateway/server-methods/environments.session-exec.ts and request mutation guards keeps the original intent (de4ba75: Consolidate request handling while preserving authority checks, asynchronous boundaries, and explicit variant behavior.)
  • src/gateway/session-reset-service.ts keeps the original intent (3d399ac: Incognito reset must remove its managed worktree after session deletion or report worktreePreserved when safe removal cannot finish.)
  • src/gateway/exec-approval-lifecycle.ts keeps the original intent (unknown: Exact observer-helper introduction could not be resolved because git log -S required an unavailable historical blob. The inspected approval history documents preservation of live authority and observer outcomes across storage waits.)
  • Chat, agent-turn, suggestion, and response preparation owners keeps the original intent (unknown: Exact introductions remain incomplete in the partial history. The inspected earlier server-method consolidation preserves source-versus-dispatched replies, authority-aware results, and explicit per-variant projections.)

Testing

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

Security

None.

Evidence

What I checked:

  • Repository policy and clean checkout: Read root AGENTS.md and both applicable Gateway ancestor policies fully. No maintainer-notes directory exists. Initial and final working-tree status were clean; no tests, builds, or reviewer helpers were executed. (AGENTS.md:1, 900b74a38d29)
  • Introduced patch: Read the complete introduced hunks in bounded subsystem batches against the verified merge base. The change contains no test, workflow, dependency, protocol-schema, or plugin-SDK file edits. (900b74a38d29)
  • Sharing authority remains with its existing owner: The shared handler retains explicit read/mutation mode and disposes prepared access after the operation. Membership writes still receive access.assertCurrent and the original expected-row facts; the access owner rechecks requester, manager role, and session identity. (src/gateway/server-methods/sessions-sharing.ts:165, 900b74a38d29)
  • Approval lifecycle equivalence: Observer registration precedes synchronous closure, and all settlement paths delete the same observer before settling. Raw exact approval lookup still precedes trimming, filtering still stops exact-match fallback, and no approval decision or execution authority is added. (src/gateway/exec-approval-lifecycle.ts:408, 900b74a38d29)
  • Existing authority regression coverage: The unchanged sharing-authority suite exercises real SQLite workers, rejects revoked callers and manager roles at commit admission, and verifies unchanged membership after rejection or session replacement. (src/gateway/server-methods/sessions-sharing.authority.test.ts:133, 900b74a38d29)
  • Supplied validation and source identity: The complete PR body reports 9,787 passing tests across 749 files on implementation snapshot 6e39614, plus focused presence validation after restoring baseline system.ts. This is contributor-reported test validation, not a reviewer-executed live run. Applied-area discussion rows were retrieved through GitHub reads, extending the truncated supplied excerpts. (6e3961495e54)

Likely related people:

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

PR surface

PR surface statistics unavailable: the file list is incomplete.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/gateway/server-methods/doctor.ts, unknown-truncated-pull-files. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Labels

Label changes:

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

Label justifications:

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

Rating scale

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

Workflow

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

@steipete
steipete merged commit 83b060d into main Oct 8, 2026
238 of 241 checks passed
@steipete
steipete deleted the deslop/d01-gateway-server-methods-p3-20261007 branch October 8, 2026 17:10
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
openclaw#167335)

* refactor(gateway): consolidate handler preparation and lifecycle projections

* fix(gateway): preserve narrowing and avoid shadowed locals

* fix(gateway): retain the existing SDK declaration surface

* fix(gateway): preserve validated presence parameter reads
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime 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