Skip to content

refactor: consolidate provider and plugin processing - #167750

Merged
steipete merged 6 commits into
mainfrom
deslop/d28-p2-20261007
Oct 9, 2026
Merged

steipete merged 6 commits into
mainfrom
deslop/d28-p2-20261007

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Provider processing, Policy diagnostics and Workboard projections repeated the same internal work across closely related variants.

User Impact

No user-visible change relative to current main. Provider request/response shapes, model IDs, config keys, CLI flags, protocol and persisted data shapes, and user-visible text remain unchanged. No migration or operator action is required.

Why This Change Was Made

Shared schema traversal and normalization now take explicit profiles for real provider differences. The same approach consolidates stream handling, ordered catalog metadata, Policy scope/evidence resolution and repair construction, and Workboard projections. Validation order, fallback precedence, sparse arrays, identity reuse, authority checks and transaction boundaries remain with their existing owners.

This second deep pass removes 637 net production lines across 53 files: AI 330, OpenAI 91, Policy 173 and Workboard 43 (1,177 additions; 1,814 deletions). Tests, fixtures, generated files and declarations are excluded. No tests, fixtures or declarations were changed by this PR; the generated assertion baseline only shrinks by twelve allowances across nine entries.

This uses the campaign's 500–999-line exception with a coverage log after more than two hours of implementation. Prior rejected/partial candidates were revisited first, followed by uncovered and adjacent owners. Implemented experiments that increased size or cost were discarded. Together with #167227, this would remove 1,845 lines (2.08% of the measured 88,655-line starting baseline), leaving 815 lines to reach the original 3% target.

Evidence

Candidate head: d5c1a6e9edd6ba528af90ac25cf2cf7c1518272a; base: c0a28dde4602681fa17b5f273be7702d39505fdf; tree: e0a6fe2846a520f6f9334fde4a95d1261363cec6.

The latest rebase was required by a hosted baseline finding. It completed without conflicts: all five previous commits are patch-identical by range-diff, and dependency manifests/lockfile are unchanged. The only additional commit decreases one stale session-reader assertion allowance from 3 to 2. Native generation also proposed an unrelated upstream allowance; only its generated decreases to existing entries were retained. No allowance or source assertion was added. The unchanged full native ratchet passes. The protected session implementation is untouched.

The earlier conflict resolution preserved main's missing-usage fallback and bounded warning in the shared Completions append. Buffered deltas are detached before replay. Main independently removed three overlapping lines during that rebase, leaving the final 637-line production reduction.

  • Latest source: AI prompt-role/replay tests passed 10 cases; OpenAI Responses policy tests passed four; lint-suppression tests passed all three. Production typechecks passed for AI and all three plugins. Runtime cycles are zero in standard and supplemental AI roots; standard Madge is zero and the three AI static components exactly match clean current base.
  • Independent review has no accepted/actionable findings. The new baseline repair is scoped-clean. The prior Google error-precedence finding remains recorded and was rejected against source and 65 passing existing tests: prompt-feedback blocks throw immediately, and a recorded generation error always implies the terminal flag is set.
  • Reused proof for the patch-identical production changes on head 22dc0b2655fea76474b40be9b1d5a04cbd693310: full AI 139 files / 2,521 tests; Policy 16 / 428; Workboard 53 / 646 across backend/root and browser runs. Focused Completions passed 59 cases; Google passed 65. Native changed-file core lint passed all 28 existing changed AI files. The first 20 native changed-check stages and all nine post-extension guards passed, including formatting, ratchets, Doctor contracts, plugin boundaries, script lint, legacy stores, sidecar loaders, cycles, webhook and pairing rules.
  • Native Plugin SDK API comparison from d2475357ab82931d7421f235febe5dc9fd06728c to 22dc0b2655fea76474b40be9b1d5a04cbd693310 passed with no API changes. This is retained prior-head proof for the unchanged provider patches; it is not a claim that the comparison was rerun after the latest rebase.

Hosted attempt 1, run 37911107458, had two root failures:

  1. checks-fast-baseline-ratchets: stale session-reader assertion allowance, 3 recorded versus 2 actual. Since this PR edits the generated baseline, treated as ours and fixed by the shrink-only maintenance above.
  2. check-test-types-core-1: TS2554 in untouched src/cli/update-cli.windows-lifecycle.test.ts, calling a SIGINT listener without its required argument. Reproduced on clean current base c0a28dde4602681fa17b5f273be7702d39505fdf using node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.cli-update.json; exit 2 at line 545 (line 508 in the earlier tested merge). Candidate and clean-base file blobs match. This unrelated updater test is unchanged by the PR. Main fixed it in 3223e13a514c6134e10ee7f585627434d245fd20 by passing "SIGINT"; the latest hosted merge includes that fix.

The failed CI gate aggregates those root failures. No test/check job in the ready CI run was cancelled. Five earlier metadata cancellations have successful same-head replacements; the original cancelled runs are not passing proof. Fresh hosted run 37913257396 passed on exact head d5c1a6e9edd6ba528af90ac25cf2cf7c1518272a, including the CI gate. Its preflight captured this head merged with 3223e13a514c6134e10ee7f585627434d245fd20, so both earlier failures are resolved in the tested merge.

Local limitations remain explicit. On the preceding patch-identical provider source, OpenAI passed two database transport files / 18 tests and 86 provider files / 1,219 tests, with six timing failures in two files. Two oversized streaming error-response cases returned AbortError, and four ordinary/telephony speech watchdog cases reached their two-second deadlines. All six reproduced on clean d2475357ab82931d7421f235febe5dc9fd06728c with the same Node 26.5 and dependencies (35 passed / 6 failed). The tests and wire implementation are unchanged, but speech-provider.ts is touched, so this does not automatically qualify an overlapping hosted failure for admin merge.

An initial Workboard directory run hit the unchanged 120-second no-output watchdog after 27 sessions-board cases. Subsequent complete coverage passed in separate sessions-board, remaining backend/root, and browser runs; the interrupted attempt is retained and is not claimed repaired by replay. The old lint-suppression run had a stale Cron allowlist failure reproduced on its clean base; main fixed it in 2997d800d7d, and the latest run passes all three cases.

Earlier global core lint reached its unchanged 900-second limit; focused core lint passed. Extension lint could not start because required SDK declaration preparation reached its unchanged 300-second limit. Knip production and full-tree scans reached unchanged 600-second limits, including a bounded serialized attempt; the script scan passed with zero entries. A broad wrapper attempt hit three 120-second deadlines; only the first was separately reproduced on the earlier clean main. Dedicated source-closure (three tests) and shadow guards (20 tests) passed. Older proof also includes all 27 core-test type shards and extension test types under the earlier base. These limits and historical results are not relabeled current-head success. No assertions, timeouts, retries, skips, ignores or budgets were weakened.

Remote preparation was cancelled before the twenty-minute allocation limit and before any lease or remote command started; native cleanup was verified. The exact-head hosted run passed; no admin exception is needed.

File-by-file coverage and retained differences

The generated config/assertion-safety-baseline.txt was pruned by its native checker: 2,884 to 2,883 recorded files and 6,885 to 6,873 allowances, with no increase or new path. This maintenance file is excluded from production LOC.

Implementation ran from 00:05 UTC through after 02:13 UTC on 2026-10-09. The records below describe reviewed owners; final totals above supersede intermediate measurements. A shared Anthropic header assembler added one line, contract-preserving function-tool shaping added five, and a browser optional-field projector added seven: all were rejected. Generated browser event-label keys lost exhaustive typing and were restored. A broader automation normalization rewrite passed output comparisons but increased per-record cost; manual automation parsing is retained and only diagnostic normalization is shared.

ai

File Implemented / retained contract Formatted production delta
transports/openai-completions-stream.ts One direct text/thinking reference replaces two mutually exclusive references. Shared typed content append lifecycle retains source-specific text boundaries, signature creation, thinking append facts, text phase confirmation, per-mode partial snapshots and post-tool buffering. Queue flush and ordinary append call the same typed owner. Read full production, sole production caller and direct/managed structured-content/stream tests; tests untouched. −18
providers/openai-tool-projection.ts One descriptor snapshot try/catch carries the exact current read path. Getter reads remain single and ordered; unreadable array entry, name and parameters keep existing diagnostic paths and optional name field; missing name still differs from unreadable name. Schema projection remains outside that catch; optional description retains its independent exception boundary. Read whole production and all projection tests. −14
transports/openai-completions-params.ts Shared direct/managed Completions reasoning and routing by replacing openai-completions-direct-policy.ts with openai-completions-policy.ts. Explicit profile preserves direct-only ZAI/DeepSeek binary fields, Qwen preserve_thinking, direct empty scalar effort handling and direct routing; managed cache application remains at its original position. Both old source owners and relevant provider/managed/legacy parameter cases read. −15 across owner and caller including replacement module
  • openai-completions.test.ts, openai-completions.legacy-function-call.test.ts, managed completions params/stream/integration, structured-content parity and DSML tests; preserve stream event sequence, buffering and thinking/refusal/text phases.

ai-anthropic

File Net delta Implemented responsibility change
providers/anthropic.ts -74 Client construction now owns injected-client selection and request-derived defaults, removing five mirrored setup variables and the argument/assignment handoff. Thinking enabled, interleaved thinking, eager-tool compatibility, then option headers are snapshotted in the original call-argument order. Simple request thinking uses the shared resolver in transport-options. SDK auth/header assembly remains unchanged.
transports/anthropic-transport-options.ts +14 One thinking-option resolver serves simple SDK and managed transport paths. Explicit profile retains managed legacy max-to-high budgets, positive model-limit normalization, and provider-only restoration of the caller output cap when thinking does not fit. Required/optional adaptive thinking and off normalization stay identical. Combined with the provider change, this removes code rather than adding a parallel owner.
transports/anthropic-messages.ts -25 Removed the one-use convertAnthropicTools wrapper. Canonical tool projection feeds generation directly, with context.tools read twice before eager-streaming eligibility, matching the original call-argument order, and policy prepared before asynchronous conversion. Wire names, schema references, description fields, order and choice reconciliation remain identical. Tool-result text presence is derived from the emitted blocks instead of mirrored boolean state.
transports/anthropic-payload-policy.ts -18 Cached and uncached system block normalization share traversal and text-block validation. Cache-enabled paths still split/cache/splice; uncached paths only strip boundary bytes on the records and never splice the array.
transports/anthropic-stream-reducer.ts -12 One text/thinking end-event emitter receives explicit deferText. Native managed text and fallback text still defer; compatible sidecar endings remain immediate; complete thinking signatures install before end events and tool calls stay sealed until terminal validation.
providers/anthropic-auth-headers.ts -5 Folded the private one-use bearer-header predicate into the Foundry routing decision; exact provider, authHeader, case-insensitive Authorization and bearer-token conditions preserved.
File Decision
transports/anthropic-transport-stream.ts Header experiment reverted as measured above. SDK and fetch body parsing still have distinct error-frame, buffer-cap, JSON repair and cancellation contracts. No parser merge without changing those contracts.
providers/anthropic-model-contract.ts Retained model-family resolution order and independent feature sets. A family table would move predicates and require capability flags without deleting a repeated lifecycle. No model ID, default or replay identity changed.
providers/anthropic-tool-projection.ts Retained canonical schema projection and quarantine owner; removed only its redundant conversion wrapper from messages. Schema keyword recursion and tuple normalization are different JSON-schema operations.
providers/anthropic-usage.ts Prior P1 shared usage read/assignment is already present. No second cleanup or feature-policy change. Billing and context snapshots remain distinct.
transports/anthropic-compaction-replay.ts Retained capture, validation, newest-checkpoint selection and projection. Each serves a different persisted replay lifecycle stage; merging with suppression would blur validity and identity rules.
providers/anthropic-server-fallback.ts Retained fallback identity, cost scaling and content-boundary operations. Public model strings and exact diagnostics remain unchanged.
providers/anthropic-thinking-replay.ts Retained binding controls, diagnostic drop reporting and active-tool-turn matching. Their inputs and outputs are not variants of one operation.
providers/anthropic-refusal.ts Retained compact normalization and diagnostic construction; helper parameters would add rather than remove code.
  • packages/ai/src/providers/anthropic.test.ts
  • packages/ai/src/providers/anthropic-tool-projection.test.ts
  • packages/ai/src/transports/anthropic-transport-stream.test.ts
  • packages/ai/src/transports/anthropic-payload-policy.test.ts
  • packages/ai/src/anthropic-cache-transport-parity.test.ts
  • packages/ai/src/anthropic-cache-carrier-parity.test.ts
  • packages/ai/src/anthropic-client-identity-parity.test.ts
  • packages/ai/src/anthropic-binding-transport-parity.test.ts
  • packages/ai/src/anthropic-sonnet-55-transport-parity.test.ts
  • packages/ai/src/transports/anthropic-stream-fairness.test.ts

ai-google

Files Structural change and preserved distinctions
agent-tools-parameter-schema.ts; openai-tool-schema.ts; openai-tool-schema-compat.ts; new tool-schema-normalization.ts One recursive normalizer supplies strict, compatibility and OpenAPI profiles, including literal-name map profiles. Strict still walks arbitrary nested values and retains properties-aware root depth. Compatibility still uses modern/legacy applicator sets, retains invalid null constraints, only promotes an empty root and infers unambiguous shapes. OpenAPI keeps its smaller applicator sets, literal/default/components exclusions, nullable enum/union conversion and changed-sibling composition-array copies. Getter snapshots remain one Object.entries pass and unchanged schema identity remains intact. Existing package public exports and cache ownership unchanged.
schema-walk.ts; schema-keyword-strip.ts; clean-for-gemini.ts Shared heap-stack generator primitive/cycle/array scaffolding. Preserve sparse-array holes, array length snapshot, path-local ancestor cleanup and Gemini fresh raw-descent scope for expanded references. Object callbacks retain all cleaner-specific keyword, reference, enum, union and required-property policies. Named composition arrays still bypass adding that array itself to ancestors, exactly as before. Sorted modern nested-key inventory shared by normalization and diagnostics without changing traversal order.
google.ts; google-vertex.ts; new google-http-options.ts Shared SDK HTTP construction with explicit generative-ai/vertex profiles. Fetch policy still precedes endpoint/header handling. Standard Google keeps raw version-bearing URL and case-insensitive header merge; Vertex trims/rejects template endpoints, keeps COLLECTION scope and version detection, and uses case-sensitive header spread. Ordinary Google still resolves its key after HTTP preparation; Vertex still resolves credentials before HTTP preparation.
google-stream.ts Missing-finish and observed terminal errors share final metadata/throw handling, after endCurrentBlock and abort precedence. Error strings, codes, types and SDK/managed metadata differences unchanged.
tool-schema-refs.ts Root-ref preservation reuses the existing local-reference resolver with no local definition tables; removed its duplicate root-only parsing wrapper. Pointer decoding, missing-reference result, scope resolution and caller checks unchanged.

ai-chatgpt

File Before/after responsibility and preserved distinctions Net LOC
transports/openai-responses-stream-internal.ts Shared tool-argument delta/done lookup, unmatched-event reliability handling, and delta emission. Incremental geometric parsing versus authoritative done parsing remain separate; empty incremental deltas still emit and empty done suffixes do not. Shared summary/direct reasoning delta admission while only summary events update summary parts. Shared text-block construction and output-slot registration preserve tracker-before-registration-before-start ordering and phase-dependent signatures. -21
transports/openai-responses-replay-internal.ts Shared wire-event recovery facts with websocket recovery: failure projection, response-output presence, and startup-event classification. Output before the rejection gate stays distinct from event admission afterward. HTTP retry lifecycle, source-versus-hook errors, cancellation, attempt kinds and lazy full history rebuild stay owned here. -3
transports/openai-responses-websocket-recovery.ts Consumes the shared recovery facts while retaining websocket-specific safe rejection and active-response gates, acceptance state, tier fallback, transport switching, and closure ordering. -19
transports/openai-responses-stream-slots-internal.ts One map owns indexed/unindexed registration and retirement. The undefined key represents the sole unindexed slot; exact error strings remain. values() explicitly preserves indexed-first ordering and deduplication, independent of admission order. -5
providers/openai-chatgpt-responses-events.ts Parameterized identical direct/nested string precedence for code and message. Empty-string precedence, event payloads and error formatting remain identical. -7
providers/openai-chatgpt-responses-websocket-authority.ts Inlined one-use authority-construction wrapper into resolver; SSE still skips header construction entirely and websocket URL resolution occurs after header preparation. -6
  • openai-chatgpt-responses.ts: d28p1 completion/processing consolidation retained. Current mid-stream connection expiry reclassification remains untouched. SSE/WS retry boundaries, caller versus request signals, acceptance timing and cached raw wire equality are real differences.
  • openai-chatgpt-responses-protocol.ts: current byte scanner handles bounded retained frames, mixed/chunk-split CR/LF, EOF dispatch, consumer errors, and nonsettling cancellation. Replacing it with SDK SSE decoding would change DONE handling, errors and cancellation; retained.
  • openai-chatgpt-responses-websocket-state.ts: cached-entry compare-and-set protects concurrent replacement; weak references allow global cleanup without retaining runtime hosts. One-session versus all-session fallback-clear/close ordering retained.
  • openai-responses-websocket.ts: SDK iterator listeners are installed eagerly and retained across steering handoff. Cached/transient leases, automatic versus required-input steering, post-dispatch error classification, and cooldown ownership remain distinct. Existing loop and cleanup shapes retained.
  • openai-responses-stream-terminal-internal.ts: d28p1 terminal appendText/tool ID cleanup is already present. Streamed item-done versus terminal snapshot completion has different null-content semantics, saved collapse candidates, delta emission, and tracker/event ordering; no safe whole-handler replacement.

openai

  • openai-provider.ts (1,007): read end to end, read all 1,917 lines of provider tests plus dynamic model, Codex discovery and API-key catalog suites. One ordered metadata table now supplies the five shared forward-compat template selections and synthetic-catalog augmentation models. Dynamic patches still consume only id/templateIds; augmentation still consumes id/contextWindow/contextTokens. Order, exact model IDs, template search precedence, context values and object key presence are unchanged. -41 LOC before formatting.
  • speech-provider.ts (277): read complete source and all 652 lines of boundary tests, plus tts/audio-transcription owners. Unified raw/resolved config normalization with explicit source mode. Raw input still unwraps provider records, resolves secret input and strips URL trailing slashes; resolved input still reads direct values and preserves its endpoint string. Defaults, extra_body fallback, speed policy, format validation, directive and Talk routes unchanged. -12 LOC before formatting.
  • image-generation-provider.ts (902): complete current read. Prior merged edit already unifies generation/edit request options and errors. Subscription transport has deliberate sequential response-model retries, per-image count requests and a differently scoped timeout/auth owner; REST generation/edit has multipart versus JSON body. No further shared core justified yet.
  • realtime-quicksilver-bridge.ts (714): complete read. Direct public transcript drain spans cancelled generation; GA/legacy tool continuations depend on owner callbacks and terminal readiness ordering.
  • realtime-quicksilver-gateway-bridge.ts (671): complete read. WebRTC versus direct sockets share sideband connect/adoption already; peer late completion, pending raw/decoded audio, resource limits and server finalization have distinct owners from direct bridge.
  • realtime-quicksilver-wire.ts (602): complete read. Route-specific call ID validation, allocation before SDP parsing, multipart/JSON payload and precise auth/error redaction rules remain distinct.
  • realtime-voice-session-policy.ts (552): complete read. Platform/OAuth capability, presence and resolution differ; browser/GA format/default differences are preserved. No flattening of these contracts.
  • realtime-quicksilver-protocol.ts (216): complete read. Public session.closed acknowledgement and legacy synchronous closure intentionally have different completion/error precedence; retained.
  • realtime-live-api.ts (101): complete read. Public Live allocation must precede SDP schema check; GA header allocation differs. Hangup resembles GA but attribution default-header authority differs; do not silently unify.
  • realtime-quicksilver-events.ts (204): complete read. Transcript mapping has small duplicate transforms; reviewing common parser with explicit per-protocol shape next.
  • realtime-quicksilver-peer.runtime.ts (271): complete read. Credited worker messages share a pattern with socket adapter but request completion versus EventEmitter closure, transferable audio and deadline handling are deliberately different.
  • realtime-quicksilver-socket.ts (318): complete read. Same assessment; preserving FIFO-close semantics and ack order.
  • openai-chatgpt-provider.ts (578): complete read. Native context patching, offline fallback, browser/device-code UI and identity projection remain distinct; smaller image-capability normalization candidate under review.
  • usage.ts (260): complete read. Request fetch pagination already shared; costs permit empty records while completion records reject them. No profitable common accumulator beyond existing SDK owners.
  • tts.ts (196): complete read. Existing host optional capture contract and SSRF deadline are retained.
  • audio-transcription.ts (126): complete read. Subscription fallback occurs exclusively before upload and explicit config owns billing. Preserve auth/protocol shapes.
  • openai-chatgpt-provider.ts: folded the sole image-capability helper and its sole predicate directly into the existing normalizeResolvedModel owner. Kept the transport-normalized name/id checks, unchanged-object identity, and input-array replacement behavior. Read complete 359-line hook tests; existing provider and dynamic-model boundary tests already read. -17 LOC.
  • realtime-voice-events.ts: one call-scoped rejection closure owns itemId/callId and observer/result emission for the four argument-validation failures. Removed the private argument-bag method; exact reason codes, message strings, checks, and observer order retained. Read complete bridge-tools and terminal-outcomes tests plus protocol parent. -20 LOC.
  • speech-provider.ts: self-review caught the edge where an environment base URL consisting only of slashes normalizes to empty; eliminated accidental double normalization so both raw/resolved paths preserve that prior result. No tests weakened or altered. Formatted delta now -13 LOC.
  • realtime-voice-protocol.ts (478): complete read. Continuation IDs, response preparation/in-flight/manual IDs and output generation protect separate reentrant boundaries; removing retained state cannot be justified by linear-only reasoning.
  • provider-policy-api.ts (678): complete current read. Considered normalizing authored facts once, but preserving route/error precedence requires the same decisions plus an additional intermediate shape. Prior p1 reduction already removes the useful route duplication.
  • openai-chatgpt-oauth-flow.runtime.ts (245): complete read. Manual callback/prompt completion priority and cancellation behavior intentionally differ, with missing code requiring a final prompt; retained.
  • token-sharing-oauth.runtime.ts (444): complete read. Authority checks remain on both sides of awaits and signature/registration verification is a distinct owner from browser Codex flow; shared callback core already in SDK.
  • openai-chatgpt-device-code.ts (446): complete read. Poll success, retryable HTTP status, network and operation timeout each have different pacing/error semantics. Shared HTTP lease owner already used; no generalized policy bag.
  • realtime-quicksilver-session.ts (705): complete read. Prior p1 common call allocation remains the worthwhile overlap. GA bridge and native controller paths have different construction, authority, cleanup and response-delivery lifetimes.
  • realtime-session-retirement.ts (172): complete read. Existing common lease owns retirement/disposal/retry ordering and retains original retirement promise for reentrant cancellation. Private type explicitly projects ReadonlyMap; removing it would widen ownership surface.
  • realtime-quicksilver-sideband.ts (249): complete read. Opening listeners transfer terminal observation; discarded sockets retain error swallowing. Existing wait helper already owns late/aborted promises.
  • realtime-quicksilver-audio.worker.ts (170): complete read. Message credits for audio, RTP and media errors differ in retained payload and coalescing. A generic queue would add policy and leave almost all transport logic.
  • realtime-quicksilver-socket.runtime.ts (325): complete read. Audio drops oldest while control overflows terminally; one FIFO ordering and credited event owner already shared. Cannot flatten separate counters without recomputing payload sizes on hot paths.
  • realtime-quicksilver-media.runtime.ts (528): complete read. Considered deriving codec-free flags by clearing owner slots, but each slot would need an alias to preserve clear-before-free/reentry semantics; no simplification after measurement by construction. RTP sequence/reorder/PLC distinctions retained.
  • codex-client-version.runtime.ts (116): new since first pass, read complete. Already one request/cache/pending owner; success/failure TTLs and stale last-good retention are distinct.
  • embedding-batch.ts (252): complete current read. Group retries, provider deadline and live diagnostic contracts already parameterize SDK owners. No worthwhile adjacent owner duplication.
  • realtime-provider-shared.ts (118), model-service-tiers.ts (57): complete read. Existing transport/normalization/projectors retained; profile trimming differs from direct fallback outcomes and cannot be silently reused there.

policy

File Implemented or retained decision
src/doctor/fix-metadata.ts Retained. Prior PR already unified descriptors; remaining lines are externally visible per-check descriptions, hints and targets, with distinct registration/ID iteration orders.
src/policy-conformance.ts Implemented reuse of scope traversal and selector normalization from the existing scope owner. Kept shape/scoped/value diagnostic order, claim keys, weaker-override handling, URI projection and parser errors.
src/doctor/automatic-repairs.ts Implemented shared fixed-path copy/update/report core for elevated, Control UI, remote and telemetry repairs. Callers retain distinct scoped guards and exact-path admission; remote retains current-value requirement; telemetry still replaces object-form captureContent as before. No-change returns original config. Array/quoted-path repair traversal remains separate.
src/cli.ts Retained. Check/watch/compare have distinct flags, JSON key order/omission, text, exit rules and watch lifecycle. Serializer was consolidated in PR1; merging report writers adds variant callbacks without removing responsibility.
src/policy-state-data.ts Retained. Secret path matching already parameterized; memory default/local/legacy selection differs in explicitness and source URI and must stay visible. Auth metadata builder optional fields retain property order.
src/doctor/exec-approval-findings.ts Implemented one field-aware resolver for global and scoped agent evidence, replacing duplicated four-path call plumbing. Missing/invalid artifact scope dedup, allowlist ordering and target/message construction remain unchanged.
src/doctor/evaluation.ts Implemented one ordered tool metadata call. Retained schema-before-attestation routing, cached evaluation ownership, workspace reads and optional evidence inclusion.
src/doctor/metadata.ts Retained. Named boolean/allowlist/denylist constructors already share records; remaining table fields are policy vocabulary and strictness contracts. Further generic list construction increased argument machinery.
src/policy-state-ingress.ts Implemented one effective/fallback wildcard mention resolver, keeping container-major precedence and enabled/value checks. Account credential sets, nested container inheritance, disabled entries, recursion and fallback source URIs remain distinct and unchanged.
src/doctor/tool-findings.ts Implemented ordered metadata checks with one renderer, retaining separate risk-missing then risk-unknown passes, tool-major sensitivity diagnostics and owner-last scheduling. Reused scoped evidence matching with explicit global-source condition. AlsoAllow symmetric difference and expanded deny groups retained.
src/policy-state-tool-posture.ts Retained. Scalar/list/mode cores already shared. alsoAllow replaces on array presence; allow/deny append; elevated false dominates inheritance; exec mode owns paired posture fields. Merging these would obscure meaningful differences.
src/doctor/strictness.ts Implemented one normalization/invalid-input gate for allowlist, denylist and exact-list comparisons. Empty-disabled semantics, tool-group expansion, case sensitivity and duplicate cardinality remain explicit branches. Routing canonicalization intentionally differs from shape validation on raw-vs-trimmed duplicate IDs.
src/doctor/sandbox-findings.ts Retained. Shared rule renderer already owns output construction. Scoped suppression additionally depends on backend/browser availability and bind/network/profile identity, unlike generic kind-only inheritance.
src/doctor/policy-scope.ts Implemented common selector normalization/overlay traversal shared with conformance; one inherited-evidence matcher parameterized by each caller's default-entry condition; one later-scope state write after strictness check. No selector or finding order changes.
src/policy-state-sandbox.ts Retained. Docker/browser bind collector is already parameterized with separate output/config surfaces. Browser explicit disable and absent source-range evidence differ; shared scope ignores local container values.
src/doctor/data-auth-findings.ts Implemented reuse of inherited-evidence matcher while preserving memory's exact legacy default-evidence ID condition. Data redaction invariant, secret provenance and shape gating retained.
src/doctor/posture-shapes.ts Retained. Existing validation-sequence table derives keys from metadata and preserves distinct first-error order and custom list text/normalization.
src/doctor/ordered-shape.ts Retained. Owns shared primitive diagnostics and template interpolation; array-hole policy differs between conformance validity and diagnostic scanning.
src/policy-state-core.ts Retained. Existing fixed network path table shares lookup/source; model recursive scan and explicit allowlist scan identify different owned inputs. URL evidence redaction remains at producer.
src/doctor/policy-runtime.ts Retained. JSON5 policy parsing versus strict JSON version admission and shared workspace-file handling have separate error contracts. No asynchronous/state/storage semantic change.
src/policy-state-gateway.ts Retained. Existing boolean, endpoint-input and node-list loops already parameterize variants; bind/custom host/auth defaults and optional evidence fields differ deliberately.
src/policy-state-types.ts Retained. PR1 already shared source/scoped-value bases. Exported evidence shape, readonly/optional modifiers untouched.
src/doctor/scoped-policy-shape.ts Retained. Validation sequencing and selector duplicate locations are externally visible first-diagnostic contracts; no schema changes.
src/policy-state-tools.ts Retained. Markdown section/fence/local-note state machines protect distinct parsing phases; capability syntax and line numbers preserved.
src/doctor/access-shapes.ts Retained. Ingress/approvals/scoped-data shape schedules already use common primitives, but supported sections/hints/default-admission differ.
src/doctor/scopes/gateway.ts Retained. Shared boolean rule core; HTTP endpoint, URL allowlist and exact node-deny comparisons have different operand and finding multiplicity contracts.
src/doctor/exec-approval-rules.ts Implemented combined global/scoped security / autoAllowSkills evidence resolution. Security preserves malformed exact configured values and wildcard-source fallback; autoAllowSkills falls to defaults when neither supplies a boolean. Synthetic fallback now private. Allowlist parser/identity unchanged.
src/policy-state-workspace.ts Retained. Prepared ordered deny sources already shared; source precedence and sandbox-applicability gate retained.
src/doctor/ingress-findings.ts Retained. Shared rule renderer; longest applicable group-policy source chooses disable suppression, unlike simple scoped ID matching.
src/doctor/review-required-repairs.ts Implemented one preview object/effect constructor after exact per-variant target checks, removing forwarding helpers. Bind/customBindHost and node-command regex validation retain exact action/target/text.
src/doctor/routing-shapes.ts Retained. Ordered shape primitives and peer loops already shared. Diagnostic uniqueness normalizes differently from strictness; merging changes accepted data.
src/doctor/policy-shape.ts Retained. Existing allow/deny generator owns duplicate section structure; global section schedule intentionally explicit.
src/policy-state-exec-approvals.ts Retained. Evidence admission is strict version1; allowlist output index differs from source index for invalid rows. Optional field order/configured-vs-valid distinction preserved.
src/doctor/data-auth-shapes.ts Retained. All/first diagnostics intentionally differ; common primitive owner already removes parsing duplication.
src/doctor/agent-workspace-findings.ts Implemented shared inherited matcher with explicit defaults condition. Access-before-deny ordering and disabled-sandbox source selection unchanged.
src/policy-routing.ts Retained. Resolver adapter includes readonly-to-mutable role array projection and redacts peers from evidence; no new public seam.
src/doctor/scopes/model-network.ts Retained. PR1 already unified provider/ref and denied/unapproved outputs; MCP case-sensitive IDs differ from normalized provider IDs.
src/doctor/routing-findings.ts Retained. Four outputs have distinct targets/requirements; extra renderer parameters would recreate object fields while losing readability.
src/doctor/access-findings.ts Retained. Unsupported-key pass intentionally precedes channel rule validity; metadata validation already shares ordered list primitive.
src/policy-state.ts Retained. Optional collectors preserve omitted-vs-empty fields and public evidence construction order.
src/doctor/checks.ts Retained. Descriptor registration/repair owner dispatch already consolidated; channel repair retains its separate opt-in warning and result shape.
src/doctor/check-ids.ts Retained. Stable ID values and registry order are external contracts.
src/doctor/policy-evidence-finding.ts Retained. Existing single ordered finding renderer is used throughout Policy.
src/policy-state-helpers.ts Retained. Configured-agent normalization/source selection and inherited scalar facts already shared; evidence URI escaping deliberately differs from Doctor requirement URI escaping.
src/policy-state-attestation.ts Retained. Stable serializer/hashes preserve array order, object sort and undefined behavior.
src/doctor/policy-constants.ts Retained. Stable vocabulary/order.
src/doctor/shape-helpers.ts Retained. Small finding/key primitives; channel deny rule guard is the owner.
src/doctor/utils.ts Retained. Optional list versus empty list, raw/lowercase and quoted URI parsing are explicit behavior.
src/doctor/register.ts Retained. Registrar identity cache and hostless check lookup are different idempotency contracts.
src/doctor/types.ts Retained. Small evaluation contract.
src/cli-output-mode.ts Retained. Narrow static CLI metadata and machine-output rule.
src/policy-value.ts Retained. Canonical record path owner.
src/tool-policy-conformance.ts Retained. Narrow SDK matcher/group-expansion adapters.
src/exec-approvals-uri.ts Retained. Public evidence URI identity survives storage migration.
index.ts / cli-metadata.ts / api.ts Retained. Runtime vs metadata-only registration and lazy CLI boundary stay separate.
package.json / openclaw.plugin.json Retained. No dependencies, public config, schema or activation changes.

workboard

File Re-evaluation and implementation
store-normalizers.ts Read complete; optional field descriptor alternative retained as candidate but previous 2-line result demands simpler core. Bounded collection normalization already shared. Distinct fresh/retained identity allocation, malformed record filtering and exact messages remain.
store-core.ts Read complete. Implemented one dependency-link builder with explicit parent/child direction and target id. Both link arrays still prepared before first write, parent first, UUID generation remains lazy only for a missing link. Existing CAS rereads/compensation untouched. Formatted reduction 9 lines. Read dependency caps/cycles, terminal-child and concurrent compensation tests before edit.
sqlite-store-kernel.ts Read complete. Board/subscription/attachment registration and deletion have materially different SQL preparation/transactions/authority; reconsidered shared read-only mapper as a smaller candidate. No query/schema edits.
sqlite-store-records.ts Read complete. Re-evaluating optional child-row decoding core; native extraction must finish before decode and all child queries precede parent JSON decode. No representation changes permitted.
sqlite-store-write.ts Read complete; field binding shared already. Getter deferral relative to native prepare means simple eager records cannot replace callbacks.
store-enrichment.ts / store-workflow.ts Read complete. Existing first-PR run settlement remains canonical. Reconsidering common claimed mutation entry around action-specific patch construction without moving authority checks or rereads.
store-card-helpers.ts Read complete. Reconsidering common append and execution-event construction; preserve append identity timing, metadata caps and event precedence.
sessions-board.ts Read complete. Cache generation, source revision, observation and expiry are separately necessary; duplicate facts construction under re-evaluation with common fields explicit.
store-runtime.ts / store-compensation.ts Read complete; operation admission and mutation queues independent lifetimes; canonical/rollback traversal handles deliberate absent-vs-undefined and host adoption. No broad state collapse.
tools.ts / tools-orchestration.ts Read complete. Existing claimed/scoped mutation owner already removes per-tool lifecycle; public schemas/descriptions unchanged.
packages/workboard-contract/src/sessions-board.ts Read adjacent owner after primary rejects. Existing record/choices validators already shared; public type derivation and exact-error contracts make schema abstraction a poor candidate. No edits.

workboard-browser

File Implemented or rejected
lib/workboard/metadata-contract-normalization.ts / metadata-normalization.ts Implemented a broad automation/diagnostic rewrite, then rejected it after higher per-record cost. Final code preserves manual automation parsing and reuses the sparse-object/tolerant-array owner only for diagnostic actions. Exact malformed-input acceptance, workspace authority projection, omission and property order retained. Actual-source baseline/current differential passed 9672 cases incl sparse arrays, NaN/infinity/-0, malformed primitives, unknown kinds, full field combinations.
lib/workboard/derived.ts / pages/workboard/view.ts / widgets/render.ts Share identical status bucketing with explicit input card list and status order. No DOM/template changes.
lib/workboard/runtime.ts Connection reset calls existing invalidation owner after setting disconnected readiness. Extra conditional writes set the same existing false values; retained draftSaving behavior, generation advancement and pending request detachment.
pages/workboard/view-helpers.ts Implemented event-name derivation, measured -16, then rejected/restored original mapping. Object.fromEntries loses exhaustive enum key type under noUncheckedIndexedAccess; repairing this with an assertion/fallback would weaken the contract, and a direct per-render derivation obscures unsupported-kind behavior. Explicit locale key mapping retained.

@clawsweeper

clawsweeper Bot commented Oct 9, 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.

@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 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Consolidates repeated model-provider processing, Policy checks and repairs, and Workboard task projections without intended user-visible changes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, coherent cleanup with substantial reported subsystem validation, but confidence rests on source and harness evidence rather than a shipped-entry-point demonstration.
Proof confidence 🦐 gold shrimp (3/6) The verified repository administrator and established area contributor is outside the ordinary external-contributor proof gate. Reported validation exercises provider, Policy and Workboard owners through subsystem harnesses; source comparison verifies unchanged stored formats and repair outputs, with no migration required.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: An established area owner is continuing a documented consolidation effort. Removing repeated processing has maintenance value without adding product or configuration surface.

Merge readiness

✅ Ready for maintainer review

Keep open: this owner-directed cleanup remains distinct from current main, and source review found no concrete introduced defect. Hosted check failures remain unattributed because their detailed logs were unavailable.

Priority: P3
Reviewed head: 22dc0b2655fea76474b40be9b1d5a04cbd693310

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied validation does not demonstrate this exact consolidation through a shipped CLI, Gateway or browser entry point.
Agent review details

How this fits together

Model providers convert agent messages and tool definitions into requests and streamed replies. The Policy plugin evaluates operator rules and prepares repairs, while Workboard stores and displays tasks.

flowchart TD
  A[Agent messages and tool definitions] --> B[Shared provider processing]
  B --> C[Provider requests and streamed replies]
  D[Operator configuration and rules] --> E[Policy checks and repairs]
  F[Stored task records] --> G[Workboard task projections]
Loading

Technical review

Best possible solution:

Keep consolidation within the existing owners, retaining explicit provider profiles and existing configuration, storage and authority contracts.

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

Not applicable: this PR consolidates internal processing rather than repairing a reported user-visible defect.

Is this the best way to solve the issue?

Yes: the patch removes replaced processing paths and uses explicit profiles to preserve meaningful provider differences, without expanding public configuration or SDK contracts.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduced changes: Inspected the merge-base-to-head changes across providers, transports, Policy, Workboard and the assertion baseline. The whitespace check passed, and the checkout remained clean; no builds or tests were executed. (22dc0b2655fe)
  • Verified owner involvement: GitHub confirms steipete has repository admin permission. Current-main history independently connects this author to prior provider, Policy and Workboard consolidations, supporting the recorded cleanup direction.
  • Current main still has separate normalization: Fetched main retains the separate strict-schema recursive normalizer; the new shared normalization module is not present there. The earlier merged consolidation at refactor: consolidate provider streams and plugin feature internals #167227 covers different internal work. (packages/ai/src/providers/openai-tool-schema.ts:67, cff1f4fcb901)
  • Explicit schema contracts: The shared normalizer retains distinct strict, compatibility and OpenAPI profiles, literal map-name handling, root promotion rules, annotation exclusions and unchanged-object identity. Existing schema regression tests are unchanged. (packages/ai/src/providers/tool-schema-normalization.ts:48, 22dc0b2655fe)
  • Repair compatibility: Policy preserves workspace-repair opt-in, scoped-repair exclusions, exact target admission and original-config identity when nothing changes. The shared setter produces the same fixed-path updates as the base implementation, without a configuration-format change. (extensions/policy/src/doctor/automatic-repairs.ts:182, 22dc0b2655fe)
  • Stored-data and authority preservation: Workboard shares dependency-link construction and row projection while retaining stored link fields, SQL queries, mutation admission, compare-and-set writes and compensation. WebSocket authority construction is inlined without changing its host, headers, URL or lifetime. (extensions/workboard/src/store-core.ts:902, 22dc0b2655fe)

PR surface

Source -637, Other -1. Total -638 across 54 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 53 1174 1811 -637
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 7 8 -1
Total 54 1181 1819 -638

Review metrics

Metric Value Why it matters
Production versus tests Production −637 lines; tests unchanged Shared processing reduces maintenance code without adding test scaffolding or product surface.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is internal maintenance with no established urgent user-facing 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-09T09:33:13.016Z sha 22dc0b2 :: needs maintainer review before merge. :: none

Reviewed October 9, 2026, 5:42 AM ET / 09:42 UTC (Revision 2).

@steipete
steipete force-pushed the deslop/d28-p2-20261007 branch from 22dc0b2 to d5c1a6e Compare October 9, 2026 09:44
@steipete
steipete merged commit 9490c11 into main Oct 9, 2026
144 checks passed
@steipete
steipete deleted the deslop/d28-p2-20261007 branch October 9, 2026 09:58
steipete added a commit that referenced this pull request Oct 9, 2026
Refresh the immutable JS and CSS generation pointers after the Workboard
browser input changes in #167750. Generated with pnpm plugins:assets:build
on Linux using the frozen dependency lockfile.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
* refactor: share provider schema and stream processing

* refactor: share Policy resolution and repair mechanics

* refactor: share OpenAI catalog and request normalization

* refactor: share Workboard projections and dependency links

* chore: prune provider assertion allowances

* chore: prune stale session assertion allowance
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
Refresh the immutable JS and CSS generation pointers after the Workboard
browser input changes in openclaw#167750. Generated with pnpm plugins:assets:build
on Linux using the frozen dependency lockfile.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui extensions: openai extensions: policy P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. plugin: workboard rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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