Reuse-first reconstruction program: refreshed audit matrix (Stage A) #150

Closed
opened 2026-09-28 00:12:18 +00:00 by kilo · 2 comments
Member

Purpose

Durable anchor for the owner-authorized reuse-first reconstruction program (ZCode, GLM-5.3-Flash). Stage A revalidated the prior adversarial reuse audit's hypotheses against canonical develop @ f574e51ce5300fbadaf3a4645a0df5e30969ce73 (2026-09-28), with upstream evidence pinned at exact revisions. Work is isolated in the scarcity-router-reuse-program worktree; slices land as separate issues/branches/PRs targeting develop.

Refreshed reuse matrix (Stage A)

Subsystem Current files Upstream candidate (exact revision) License Reuse mode Decision
Perishable quota/reset state resource_state.py, scarcity.py, capacity.py weave-os/router internal/proxy/usage @ e5133a68f30985fd4677f6e2a78375bc4becbd1e Apache-2.0 PORT semantics + TEST-REUSE of usage_test.go invariants (Go→Python; not vendored) ADOPT semantics: reset-crossed quota facts are obsolete — mirrors ExhaustedAsOf ("a window whose ResetAt has passed is no longer exhausted even at 100% cached") and reset-bounded retention. Implemented in Slice A.
Z.ai quota parsing providers/zai.py CodexBar Sources/CodexBarCore/Resources/Plugins/zai.js @ 491ae688a89a3b7dacecff1587351bd3c05d8de0 (v0.68.0-line HEAD) MIT COPY semantics + TEST-REUSE fixtures (no credential code) Partially adopted (reset plausibility, Slice A). Remaining evidence extension (CREDIT_LIMIT, (unit=1,number=30) 30-day window, TIME_LIMIT (5,1) monthly sentinel) is a serialized capacity-vocabulary/evidence decision → owner gate, see below.
Outbound HTTP transport providers/openai_http_adapter.py (~300 lines over http.client) httpx 0.28.1 @ 26d48e06 (current stable; 21-month stable gap, 1.0 beta churn) BSD-3 REJECT KEEP ours. httpx: public verify=False + trust_env, unconditional response decompression (no off switch), no response size bounds, no absolute deadline, no sync cancellation event, httpcore suppresses ambiguous mid-request write errors (httpcore 1.0.9 _sync/http11.py:89-95), +5-6 transitive deps into a stdlib-only core. Our invariants (verified TLS, no bypass, loopback-only plain HTTP, redirect refusal, marker-based loop prevention, ambiguity taxonomy, bounded reads, deadline/cancellation interleaving) are cheaper to keep than re-derive.
SSE parsing SseStreamParser in providers/openai_http_core.py (~110 lines) httpx-sse 0.4.3 @ e8fcd9e1; sseclient-py 1.9.0 @ 456873c1; requests-sse 0.5.3 MIT/Apache-2.0 REJECT (TEST-REUSE optional) KEEP ours. No upstream candidate is fail-closed on truncation, bounded per-event/total, or strict-UTF-8 (httpx-sse uses errors="replace"; requests-sse silently reconnects = hidden re-execution). httpx-sse's pure decoder is a possible future differential-test oracle (dev-only; not scheduled).
Codex App Server protocol worker_codex_adapter.py, providers/openai_codex*.py openai/codex stable rust-v0.157.1 @ 36650394 (pin: rust-v0.155.1) Apache-2.0 KEEP + re-pin evidence Every surface the adapter touches (turn/start, turn/interrupt, turn/completed, item/agentMessage/delta, thread/tokenUsage/updated, account/read, account/rateLimits/read, both approval requests, token-usage schema, turn-status vocabulary) is unchanged through 0.157.1 — evidence re-pin is zero-cost. Lifecycle/sandbox/CODEX_HOME isolation stay ours.
Client-owned tool round trip (planned, #132 child E) — openai/codex item/tool/call + thread/start.dynamicTools (present since 0.155.1, tagged experimental) Apache-2.0 ARCHITECTURE-REUSE evidence for child E Official protocol DOES support the exact intended lifecycle (client executes; returns contentItems+success). Constraints: requires experimentalApi opt-in at initialize; protocol has NO timeout (app must impose one); interrupt resolves pending calls with turnTransition. Decisive input for #132 child E; implementation belongs there, not to this program.
Cross-program evidence for #136 (effective limits) — openai/codex TurnStartParams/Model schema @ rust-v0.157.1 Apache-2.0 evidence only NO output-token limit control exists anywhere in the official protocol (verified turn.rs, ModelListResponse.json) — confirms #136's fail-closed normalization-above-proven-hard-max direction. Context window is only client-visible via thread/tokenUsage/updated.modelContextWindow.
Protocol translation gateway_openai.py, gateway_adapters.py, providers/openai_http_core.py (~1.9k lines strict fail-closed) CLIProxyAPI @ 4a2c8186 (MIT); LiteLLM v1.102.1 @ 1ceeefbf (MIT) MIT REJECT both Their design center is the opposite of ours: silent role conversion (system→user), silent thinking-block drops, silent tool renaming, silent model substitution, hidden retries/fallbacks. One bounded PORT candidate recorded for a future bridging surface: LiteLLM _build_anthropic_tool_name_maps (collision-safe reversible tool-name normalization) — no current consumer (no Anthropic Messages bridge exists), so not implemented per the no-speculative-layers rule.
Routing/capability/policy core selector.py, routing_core.py, policy.py, eligibility.py — — KEEP No comparable upstream implements capability × capacity × owner-policy intersection with fail-closed evidence semantics; this is the differentiated core.

Deletion estimate

No mass deletion is supported. The audited custom code is ~300 lines (transport), ~110 lines (SSE), thin translation seams — each KEEP decision above is affirmative, not default. The genuine reduction is in maintenance risk (evidence re-pin, adopted test invariants), not LOC. The prior 60%-deletion hypothesis is unsupported against current develop.

Owner decision items (recorded, not silently implemented)

  1. Z.ai evidence allowlist extension (D-057 candidate): adopt CodexBar-corroborated evidence — CREDIT_LIMIT (fixtures at (3,5)/(6,1) with usage/remaining/percentage), (unit=1,number=30) rolling-30-day window, TIME_LIMIT (5,1) monthly-MCP sentinel — as Scarcity Router provider evidence. Requires a capacity-vocabulary position (new resource="credits" value vs resource="unknown" + kind/duration) because diagnostic/resource sets are closed serialized contracts, and a routing-economics position (credits entering D-037 strategic/tactical roles changes blending). Needs dedicated comparative tests per the "any routing-preference change" rule.
  2. Codex client-owned tools: evidence above is decisive, but implementation is #132 child E (security-critical, own review gate).

Slices

  • Slice A (active): reset-aware quota state + Z.ai reset plausibility — own issue.
  • Slice B (SSE) / Slice C (transport) / Slice D (Codex schema): closed as KEEP with affirmative evidence; only the evidence re-pin action remains, folded into Slice A's docs or a later docs-only slice.
  • Slice E/F: deferred to #132 child E with recorded evidence.

Rules

Branch from develop, PRs target develop, left open for human review; bounded review lifecycle; never merged by agents.

## Purpose Durable anchor for the owner-authorized reuse-first reconstruction program (ZCode, GLM-5.3-Flash). Stage A revalidated the prior adversarial reuse audit's hypotheses against canonical `develop` @ `f574e51ce5300fbadaf3a4645a0df5e30969ce73` (2026-09-28), with upstream evidence pinned at exact revisions. Work is isolated in the `scarcity-router-reuse-program` worktree; slices land as separate issues/branches/PRs targeting `develop`. ## Refreshed reuse matrix (Stage A) | Subsystem | Current files | Upstream candidate (exact revision) | License | Reuse mode | Decision | |---|---|---|---|---|---| | Perishable quota/reset state | `resource_state.py`, `scarcity.py`, `capacity.py` | weave-os/router `internal/proxy/usage` @ `e5133a68f30985fd4677f6e2a78375bc4becbd1e` | Apache-2.0 | PORT semantics + TEST-REUSE of `usage_test.go` invariants (Go→Python; not vendored) | ADOPT semantics: reset-crossed quota facts are obsolete — mirrors `ExhaustedAsOf` ("a window whose ResetAt has passed is no longer exhausted even at 100% cached") and reset-bounded retention. Implemented in Slice A. | | Z.ai quota parsing | `providers/zai.py` | CodexBar `Sources/CodexBarCore/Resources/Plugins/zai.js` @ `491ae688a89a3b7dacecff1587351bd3c05d8de0` (v0.68.0-line HEAD) | MIT | COPY semantics + TEST-REUSE fixtures (no credential code) | Partially adopted (reset plausibility, Slice A). Remaining evidence extension (CREDIT_LIMIT, `(unit=1,number=30)` 30-day window, `TIME_LIMIT (5,1)` monthly sentinel) is a serialized capacity-vocabulary/evidence decision → owner gate, see below. | | Outbound HTTP transport | `providers/openai_http_adapter.py` (~300 lines over `http.client`) | httpx 0.28.1 @ `26d48e06` (current stable; 21-month stable gap, 1.0 beta churn) | BSD-3 | REJECT | KEEP ours. httpx: public `verify=False` + `trust_env`, unconditional response decompression (no off switch), no response size bounds, no absolute deadline, no sync cancellation event, httpcore suppresses ambiguous mid-request write errors (`httpcore 1.0.9 _sync/http11.py:89-95`), +5-6 transitive deps into a stdlib-only core. Our invariants (verified TLS, no bypass, loopback-only plain HTTP, redirect refusal, marker-based loop prevention, ambiguity taxonomy, bounded reads, deadline/cancellation interleaving) are cheaper to keep than re-derive. | | SSE parsing | `SseStreamParser` in `providers/openai_http_core.py` (~110 lines) | httpx-sse 0.4.3 @ `e8fcd9e1`; sseclient-py 1.9.0 @ `456873c1`; requests-sse 0.5.3 | MIT/Apache-2.0 | REJECT (TEST-REUSE optional) | KEEP ours. No upstream candidate is fail-closed on truncation, bounded per-event/total, or strict-UTF-8 (httpx-sse uses `errors="replace"`; requests-sse silently reconnects = hidden re-execution). httpx-sse's pure decoder is a possible future differential-test oracle (dev-only; not scheduled). | | Codex App Server protocol | `worker_codex_adapter.py`, `providers/openai_codex*.py` | openai/codex stable `rust-v0.157.1` @ `36650394` (pin: `rust-v0.155.1`) | Apache-2.0 | KEEP + re-pin evidence | Every surface the adapter touches (turn/start, turn/interrupt, turn/completed, item/agentMessage/delta, thread/tokenUsage/updated, account/read, account/rateLimits/read, both approval requests, token-usage schema, turn-status vocabulary) is unchanged through 0.157.1 — evidence re-pin is zero-cost. Lifecycle/sandbox/CODEX_HOME isolation stay ours. | | Client-owned tool round trip (planned, #132 child E) | — | openai/codex `item/tool/call` + `thread/start.dynamicTools` (present since 0.155.1, tagged experimental) | Apache-2.0 | ARCHITECTURE-REUSE evidence for child E | Official protocol DOES support the exact intended lifecycle (client executes; returns `contentItems`+`success`). Constraints: requires `experimentalApi` opt-in at initialize; protocol has NO timeout (app must impose one); interrupt resolves pending calls with `turnTransition`. Decisive input for #132 child E; implementation belongs there, not to this program. | | Cross-program evidence for #136 (effective limits) | — | openai/codex `TurnStartParams`/`Model` schema @ `rust-v0.157.1` | Apache-2.0 | evidence only | NO output-token limit control exists anywhere in the official protocol (verified `turn.rs`, `ModelListResponse.json`) — confirms #136's fail-closed normalization-above-proven-hard-max direction. Context window is only client-visible via `thread/tokenUsage/updated.modelContextWindow`. | | Protocol translation | `gateway_openai.py`, `gateway_adapters.py`, `providers/openai_http_core.py` (~1.9k lines strict fail-closed) | CLIProxyAPI @ `4a2c8186` (MIT); LiteLLM v1.102.1 @ `1ceeefbf` (MIT) | MIT | REJECT both | Their design center is the opposite of ours: silent role conversion (`system`→`user`), silent thinking-block drops, silent tool renaming, silent model substitution, hidden retries/fallbacks. One bounded PORT candidate recorded for a future bridging surface: LiteLLM `_build_anthropic_tool_name_maps` (collision-safe reversible tool-name normalization) — no current consumer (no Anthropic Messages bridge exists), so not implemented per the no-speculative-layers rule. | | Routing/capability/policy core | `selector.py`, `routing_core.py`, `policy.py`, `eligibility.py` | — | — | KEEP | No comparable upstream implements capability × capacity × owner-policy intersection with fail-closed evidence semantics; this is the differentiated core. | ## Deletion estimate No mass deletion is supported. The audited custom code is ~300 lines (transport), ~110 lines (SSE), thin translation seams — each KEEP decision above is affirmative, not default. The genuine reduction is in *maintenance risk* (evidence re-pin, adopted test invariants), not LOC. The prior 60%-deletion hypothesis is unsupported against current `develop`. ## Owner decision items (recorded, not silently implemented) 1. **Z.ai evidence allowlist extension (D-057 candidate):** adopt CodexBar-corroborated evidence — `CREDIT_LIMIT` (fixtures at `(3,5)`/`(6,1)` with `usage`/`remaining`/`percentage`), `(unit=1,number=30)` rolling-30-day window, `TIME_LIMIT (5,1)` monthly-MCP sentinel — as Scarcity Router provider evidence. Requires a capacity-vocabulary position (new `resource="credits"` value vs `resource="unknown"` + kind/duration) because diagnostic/resource sets are closed serialized contracts, and a routing-economics position (credits entering D-037 strategic/tactical roles changes blending). Needs dedicated comparative tests per the "any routing-preference change" rule. 2. **Codex client-owned tools:** evidence above is decisive, but implementation is #132 child E (security-critical, own review gate). ## Slices - Slice A (active): reset-aware quota state + Z.ai reset plausibility — own issue. - Slice B (SSE) / Slice C (transport) / Slice D (Codex schema): closed as KEEP with affirmative evidence; only the evidence re-pin action remains, folded into Slice A's docs or a later docs-only slice. - Slice E/F: deferred to #132 child E with recorded evidence. ## Rules Branch from `develop`, PRs target `develop`, left open for human review; bounded review lifecycle; never merged by agents.
Author
Member

Numbering correction: D-057 has been consumed by #136 (gateway effective limits, commit cdf4ac6 on gateway/effective-limits, 2026-09-28). The Z.ai evidence-allowlist extension decision item above ("D-057 candidate") should be read as the next free decision number, currently D-058. No other content of this matrix changes.

Numbering correction: D-057 has been consumed by #136 (gateway effective limits, commit `cdf4ac6` on `gateway/effective-limits`, 2026-09-28). The Z.ai evidence-allowlist extension decision item above ("D-057 candidate") should be read as the next free decision number, currently **D-058**. No other content of this matrix changes.
Author
Member

Stage A+ — audit-completeness and adversarial keep-challenge report

Base: develop @ 6fec46ca82901a5fb8761909778c16d8322bbb97 (2026-09-28), verified against canonical Forgejo; includes D-057, D-058 (#136/#152), D-059 (#154/#155) and Slice A (#151/#153, merged e25de16b). Worktree note: the owner's post-merge cleanup removed the program worktree mid-task; it was recreated non-destructively, detached at the same SHA, with no data loss (reuse/reset-aware-quota-state was already merged and its deletion expected). All external evidence lives under /tmp/scarcity-router-reuse-audit/ with pinned SHAs; no production file was modified.

This pass re-opened the prior KEEP conclusions with the burden of proof on KEEP. Method: the 7 previously-unassessed seed repositories were assessed at source level; the covered seeds were re-pinned and deepened per-mechanism; a disposable failure-injection experiment and an SSE differential probe were run outside the tree; a 2026 ecosystem sweep was performed. Every claim below carries a pinned SHA and file-level citation in the working notes.


A. Coverage ledger — every original seed

Seed Prior state This pass Evidence (inspected @ SHA)
weave-os/router COMPLETE (e5133a6, usage pkg) COMPLETE; Slice A merged; deeper mechanics re-checked — no remaining portable state mechanics e5133a6 Apache-2.0
wr/quota-router MISSING COMPLETED → REJECT (KEEP-OURS) 0e3c41af MIT — passive rollout-JSONL probe with fail-closed rollover semantics; strictly weaker than our app-server Codex collector
dennisonbertram/claw-router MISSING COMPLETED → REJECT 36d68450 MIT — bash account rotator; persisted credentials + bearer-in-argv violate our credential-transiency invariant
Gods-light/cliproxyapi PARTIAL (owner path unrecorded) COMPLETED: identity resolved — stale pure fork (0 own commits) of canonical router-for-me/CLIProxyAPI; prior pin 4a2c8186 is a canonical commit (2026-09-27) fork 4b681031; canonical acdace936 MIT
suparious/claude-code-proxy MISSING COMPLETED → REJECT (framework) + COPY candidate 45f4fa5f MIT — ~70-line conservative tool-sequence repair (core/anthropic/conversion.py:142-211) + 805-line test file
i-am-logger/claude-code-proxy MISSING COMPLETED → REJECT EARLY 84027634 CC BY-NC-SA 4.0 (incompatible) + silent conversation flattening discards tool traffic
0324wy/claude-code-proxy-codex MISSING COMPLETED → REJECT EARLY 3e8a033e — no LICENSE file (package.json MIT metadata does not authorize copying), stale, OAuth persistence, heuristic tool-call synthesis
VictorMinemu/CC-Router MISSING COMPLETED → KEEP-OURS (reference value) 555980dd MIT — account-pooling product with plaintext token persistence; Anthropic unified-ratelimit header names (server.ts:222-233) + stale-utilization cooldown sweep (token-pool.ts:33-84) = evidence for a future Anthropic collector
ypollak2/llm-router MISSING COMPLETED → REJECT d4125870 MIT — 139k LOC LiteLLM delegate; quota guessed at 50%/0.0 under failure; claude.ai browser scraping
official LiteLLM COMPLETE (1ceeefbf) EXTENDED per-mechanism @ current HEAD 2c9b0e00 (v1.104.0-line) — see matrix MIT
steipete/CodexBar COMPLETE (491ae68) RE-PINNED to HEAD 14bdca166 (ancestor confirmed; vocabulary unchanged; reset-plausibility now independently implemented upstream) MIT
openai/codex COMPLETE (36650394 = rust-v0.157.1) EXTENDED — schema-artifact discovery + field-by-field drift check Apache-2.0
httpx / httpx-sse / sseclient-py / requests-sse COMPLETE (source-cited) EXTENDED with experiments (failure injection + 18-case differential, disposable, under /tmp) BSD/MIT

New 2026 candidates found and assessed: KarpelesLab/teamclaude 9418c667 (PORT candidate, quota pressure), supermemoryai/llm-bridge 9ebb7c70 (design+vectors), onllm-dev/onwatch 3e5ed15 (GPL-3.0 — ideas-only), ndycode/codex-multi-auth f3b176f (reference), HJunLong601/codex-client-provider b7516c0 (independent protocol-shape cross-check of our Codex adapter), openchamber 25c28a4 + guyinwonder168/opencode-glm-quota f31d4f2 (Z.ai evidence sources), CodexMonitor/EchoBird/Zai-Gateway (CC BY-NC)/OmniRoute/tuxevil-rotator (REJECT EARLY with evidence). No seed disappeared silently.

B. Authoritative reuse matrix (one row per mechanism)

Mechanism Ours Strongest upstream (pinned) Decision
Outbound HTTP transport openai_http_adapter.py 893 ln httpx 0.28.1/httpcore 1.0.9 failure-injection-tested: taxonomy maps cleanly (Connect*/Pool → not-dispatched; pre-Response Read*/RemoteProtocolError → ambiguous; iter-phase → response-started); no request retries at retries=0; except WriteError: pass verified at http11.py:89-95 KEEP — thin-adapter viability is real but costs 5-6 transitive deps into a stdlib-only core for zero correctness gain; 2 portable mechanisms recorded below
SSE parsing SseStreamParser ~110 ln 18-case differential: ours strictly stronger — correct split-boundary UTF-8 (httpx-sse corrupts), fail-closed truncation (httpx-sse silently DROPS the truncated final event; sseclient-py DISPATCHES it = fabricated completion), bounded frame/total (both candidates unbounded) KEEP (affirmative evidence)
Codex App Server schemas hand-maintained ~25 types rust-v0.157.1 now ships JSON Schema trees + generate-json-schema CLI + official generated SDK; zero drift vs our consumed surface; no output-token control anywhere (D-058 premise re-confirmed) KEEP runtime schemas; COPY/PORT the evidence layer (vendor pinned bundle + machine diff test, Apache-2.0 provenance)
Codex lifecycle/sandbox/CODEX_HOME/approval refusal worker_codex_adapter.py official SDK manages its own lifecycle (bundles its own binary) KEEP (D-056)
Translation (Chat↔Responses, Anthropic↔internal, streaming, finish/stop, errors) openai_http_core.py + gateway_openai.py strict fail-closed LiteLLM: silent developer→system, role folding, drop_params pops, unmapped-finish→"stop", "error"→"stop", reasoning dropped in Responses direction, conversation leaked into errors; llm-bridge: thinking→text merge, SSE catch-continue, end_turn defaults; CLIProxyAPI: developer→user, reasoning_effort silent default REJECT all conversion code — confirmed per-mechanism, not per-product; bounded COPY/PORT exceptions below
Tool-result alignment / tool-name normalization none (we fail closed on malformed sequences) CLIProxyAPI internal/translator/common/ (3 algorithms + 629 lines of tests, conservative, "never rewritten or stolen" guarantees); LiteLLM _build_anthropic_tool_name_maps (collision-safe reversible maps, transformation.py:190-268); suparious _repair_openai_tool_message_sequence PORT/COPY candidates, consumer-gated (recorded for a future bridge; no current consumer → no speculative layer)
Wire-format fixture corpora hand-built anthropic-sdk-python tests/lib/streaming/fixtures/ (16 raw SSE transcripts incl. padded/truncated JSON, MIT); llm-bridge malformed-shape checklist; LiteLLM finish-reason token inventory COPY as test properties (with notices)
Perishable quota state Slice A merged (e25de16b) teamclaude band-decision.js: passed-reset = known zero (identical to our obsolescence rule); non-finite-utilization absence variant (equivalent to our strict validation) A (state mechanics): nothing left to port
Scarcity/ranking economics D-026 penalty, D-037 blend — frozen reset-blind teamclaude pressure=spendable/seconds; lower-bound ranking for unknown-reset B: KEEP (frozen policy) — both are concrete, well-specified candidate mechanisms recorded as owner decision items; they would change frozen ranking semantics, and this audit changes no routing policy
Z.ai parsing providers/zai.py CodexBar HEAD + onwatch + openchamber + real payloads KEEP + evidence upgrade: CREDIT_LIMIT now sufficiently evidenced (below)
Worker dispatch protocol worker_protocol.py/worker_endpoint.py Remote Execution API documents "MAY execute the action multiple times"; google.longrunning = polling with best-effort cancel; go-plugin magic cookie explicitly "not a security measure"; Docker ExecInspect = second delivery path KEEP every mechanism — one real gap found (below)
Persistence/migrations server_store.py (~25 ln migration machinery) alembic/yoyo = runtime deps; user_version loses provenance; WAL unneeded (no concurrent readers; identity store already correctly uses WAL) KEEP
UI/tray/packaging/diagnostics D-052 dispatcher + pystray optional adapter + doctor pystray already reused at the right boundary (LGPL extra); installer frameworks delete nothing; Sigstore+SHA256SUMS ordering already exceeds copyable patterns KEEP

C. Kill List

Empty. Affirmative justification per subsystem: transport (893 ln) — httpx would add deps and only yield ~40 lines of exception mapping we can port in ~20; SSE (110 ln) — every candidate is semantically unsafe for execution (silent drop or fabricated completion on truncation); Codex schemas (~25 types) — the generated alternative is a 13k-line pydantic module behind a new dependency; scoring core — no upstream implements capability ∩ channel ∩ owner-policy with fail-closed evidence; worker protocol — every candidate documents weaker guarantees (REAPI explicitly permits duplicate execution); persistence — a migration dependency to replace ~25 transactional lines. The prior 60%-deletion hypothesis remains unsupported; this pass found no wholesale replacement either.

D. Reuse List (exact, evidence-based)

  1. PORT — transport suppress-and-read write-error semantics (httpcore _sync/http11.py:89-95, verified at 1.0.9): on OSError during request-body send, still attempt getresponse(); a received response is a definitive outcome, silence stays ambiguous. Our _send currently mislabels a definitive early-4xx-with-undrained-body (common oversized-request provider behavior) as ambiguous. ~10 lines.
  2. PORT — connect-phase "not-dispatched" classification (optional): ConnectError-class failures (refused/unreachable/TLS-before-write) are provably not dispatched; ours classifies them ambiguous (safe but imprecise). Enables a future bounded retry policy without touching D-043's no-blind-retry rule.
  3. COPY — parser test properties from anthropic-sdk-python (4421d56a, MIT): whitespace-padded JSON, empty partial_json fragments, ping events, mid-stream truncation, usage-absent honesty → OpenAI-shaped fixtures asserting SseStreamParser/ToolCallAccumulator behavior. MIT notice + provenance required.
  4. COPY — llm-bridge malformed-shape checklist inverted into gateway refusal tests (9ebb7c70, MIT): shapes llm-bridge asserts silent defaults for become our explicit-4xx tests.
  5. USE — LiteLLM finish-reason token inventory (core_helpers.py:197-250) as documented-drift test evidence: each real provider token asserted to remain an explicit refusal in normalize_finish_reason.
  6. COPY/PORT — Codex schema bundle for the evidence layer (rust-v0.157.1 codex-rs/app-server-protocol/schema/json/ + precomputed/, Apache-2.0, provenance header): machine-diff our consumed method/field list in a test (mirroring upstream schema_fixtures_tests.rs) — converts the recurring manual re-pin into a mechanical check.
  7. PORT — bounded per-attempt chunk buffer (worker_endpoint.py:222,226-229): _chunks grows unbounded if a consumer stalls (chunk size and attempt count are capped, chunk count is not); cap with fail-closed overflow, ~10 lines. The one genuine gap found in the worker challenge.
  8. Deferred, consumer-gated (no current surface → per the no-speculative-layers rule): CLIProxyAPI common/ alignment algorithms + tests (Go→Python, MIT); LiteLLM _build_anthropic_tool_name_maps; suparious _repair_openai_tool_message_sequence; SQLite backup()/quick_check hardening; CC-Router's Anthropic unified-ratelimit header names (evidence for a future Anthropic collector).

E. Keep List (affirmative justification, current-source grounded)

  • HTTP transport — stdlib-only core; the experiment shows the taxonomy survives with httpx only behind a pinned-configuration adapter whose constraints (verified TLS, no env proxies, no redirects, identity encoding, bounded reads, deadline/cancel interleave, marker refusal) are exactly the invariants our adapter already enforces; the two portable mechanisms (D.1/D.2) are taken without the dependency.
  • SSE parser — strictly stronger than all candidates on every dimension the task listed; both candidate failure modes (silent drop / fabricated dispatch) are precisely what at-most-once execution cannot tolerate.
  • Codex runtime schemas + lifecycle — zero drift at 0.157.1; generated models add pydantic and weaken fail-closed posture; lifecycle/sandbox/isolation stay ours by D-056; the maintenance burden moves to the mechanized evidence layer (D.6), which is where it belongs.
  • Translation core — every framework candidate silently degrades somewhere material; our refusal-not-rewrite semantics are stricter than the entire sampled ecosystem.
  • Scoring core (selector/routing/eligibility/scarcity/policy) — the differentiated product; D-058's pre-ranking output eligibility (route_output_code) and effective-limit intersection have no upstream analog.
  • Quota state — Slice A adopted the load-bearing reusable mechanic; remaining upstream variants are equivalent or ranking-policy (owner-gated).
  • Worker protocol, persistence, UI/packaging/diagnostics — each KEEP carries its per-mechanism affirmative reason in the matrix.

F. Rejected Reuse List (with concrete reasons)

  • httpx-as-transport: dependency weight + no correctness gain (experiment-verified).
  • httpx-sse / sseclient-py as parsers: silent truncation drop / truncated-event dispatch; unbounded accumulation; split-boundary UTF-8 corruption (httpx-sse).
  • LiteLLM Chat↔Responses bridge + Anthropic conversion + streaming/finish mapping + error taxonomy: silent degradation enumerated per mechanism with line cites; conversation text leaked into errors.
  • llm-bridge parsers/emitters/converter: thinking→text merge; catch-continue SSE; silent defaults asserted by their own tests.
  • CLIProxyAPI framework: 97.6k-LOC Go translator registry; persisted OAuth pooling (credential-transiency conflict).
  • i-am-logger/claude-code-proxy: license (CC BY-NC-SA) + design.
  • 0324wy/claude-code-proxy-codex: no license grant; settings-file patching; synthesized tool calls.
  • onwatch: GPL-3.0 (incompatible) — observations recorded as evidence only.
  • ypollak2/llm-router: fabricated 50%/0.0 quota under failure; browser-scraped telemetry; 139k-LOC integration.
  • claw-router / CC-Router / codex-multi-auth / tuxevil-rotator / OmniRoute / EchoBird / Zai-Gateway (CC BY-NC) / CodexMonitor: account-pooling or rotator products, plaintext credential persistence, ToS-sensitive mechanisms we deliberately do not build.
  • Remote Execution API / google.longrunning / go-plugin / Docker-exec / capnproto / tmate as worker-protocol donors: weaker guarantees (documented duplicate execution), wrong trust shape, or second delivery paths contradicting D-043.
  • alembic/yoyo, user_version swap, WAL-for-server-store: dependency or churn for no property we lack.
  • Inno Setup/WiX installers: add fragility, delete nothing; MSIX remains the recorded signing seam.

G. Updated target architecture (smallest core after maximal sensible reuse)

Unchanged in shape — the stdlib+mcp-only core stands: presets → openai_http_adapter (transport + suppress-and-read + ND classification) → openai_http_core (translation + SSE + reasoning carrier [decision-gated]) → gateway_* (intersection + effective limits) → selector/routing/scarcity/policy (frozen scoring) → resource_state (reset-aware state) → providers/* (Z.ai incl. future CREDIT_LIMIT lane; Codex adapter with mechanized schema evidence) → worker_* (dispatch protocol + bounded chunk buffer) → server_store (explicit migrations). Net effect of this pass: +1 contract-level capability (reasoning carrier, owner-gated), +~30 lines of transport/worker hardening, +1 evidence-automation test, +1 test-vector batch — and the recurring Codex re-pin labor drops to a mechanical step.

H. Deletion estimate

No forced number. Mass deletion is unsupported: 0% of custom subsystem LOC is replaceable by any assessed upstream at equal-or-better semantics. The honest reduction is in maintenance risk (mechanized Codex schema re-pin; adopted test corpora), not LOC — roughly a 0–5% LOC effect, and in the wrong direction if the two small hardening ports land. The prior 60% hypothesis, and any 5–15% reading, are both unsupported against current develop.

I. Ordered implementation candidates (recorded for the owner; no issues created)

  1. Hardening batch (non-contract, small): D.1 suppress-and-read; D.7 bounded chunk buffer; SSE UnicodeDecodeError → typed TranslationError typing gap (the docstring already promises fail-closed via TranslationError; the coordinator catch-all contains the raw error today as unexpected_error — gateway_coordinator.py:775) + UTF-8 BOM strip hardening (all three compared parsers silently drop a BOM-prefixed first event; the spec says strip); D.2 ND classification (optional).
  2. Reasoning carrier (contract addition → needs a decision): our response direction silently ignores delta.reasoning_content (DeepSeek, Z.ai) and delta.reasoning (OpenRouter); the chunk vocabulary cannot express reasoning — this violates our own "reasoning must never be silently dropped" rule (openai_http_core.py:783-822, :514-564, gateway_adapters.py:106-116). Represent-or-refuse, with llm-bridge universal.ts:63-98 + LiteLLM transformation.py:2605-2634 as design references (never their code). Frozen-contract addition → backwards-compat or versioned migration decision required.
  3. Codex schema evidence mechanization (D.6): vendor pinned bundle + diff test; Apache-2.0 provenance.
  4. Test-vector batch (D.3/D.4/D.5): parser hardening fixtures, gateway refusal tests, finish-reason drift inventory. MIT notices where required.
  5. Z.ai CREDIT_LIMIT adoption (owner decision, evidence bar now met): three independent parsers + two independent real payloads + Max/Pro-tier sightings (CodexBar #2724, onwatch #122, openchamber, oh-my-pi #8644). Requires the recorded capacity-vocabulary position (credit points ≠ tokens: distinct resource/kind, not the token vocabulary) and the routing-economics position (D-037 blending), with comparative tests per the routing-preference rule. Legacy TOKENS_LIMIT/TIME_LIMIT accounts still exist in parallel and must keep parsing. The 30-day (1,30) window remains UNKNOWN (synthetic evidence only); TIME_LIMIT monthly sentinel remains diagnostics-only.
  6. Consumer-gated ports (deferred until their surface exists): D.8 items.

J. Stop / Start / Continue (against current develop, incl. D-058/D-059)

  • Stop: re-auditing rejected frameworks wholesale (per-mechanism granularity is now the unit of analysis); treating README/star-level signals as evidence; manual Codex protocol re-verification once D.6 lands.
  • Start: the hardening batch and the reasoning-carrier decision; the CREDIT_LIMIT vocabulary/economics decision (evidence complete); using the failure-injection + differential probes under /tmp/scarcity-router-reuse-audit/http-probes/ as disposable oracles when the transport/SSE surfaces next change.
  • Continue: the two-mode product boundary and its custom core; evidence-pinned upstream tracking (CodexBar/Codex/campaign docs); the slice-per-PR program discipline.

Final verdict

INCREMENTAL_EVOLUTION_SUPPORTED.

Why did a broad reuse-first audit fail to find large amounts of replaceable custom code?

Because the ecosystem's center of gravity is semantically opposite to this product, not merely less polished — specific, verified differences: (1) at-most-once discipline — the one mature protocol with our problem shape (Remote Execution API) explicitly documents that it MAY execute an action multiple times, and every cloud job API resolves ambiguity by polling durable state we deliberately do not keep; silent retry/relabel is default behavior in LiteLLM ("error"→"stop", unmapped→"stop") and llm-bridge (catch-continue SSE, end_turn default) — each occurrence is a place where our frozen D-043/D-044 guarantees would break, not a style difference. (2) Fail-closed evidence semantics — every quota-touching candidate fabricates state under uncertainty (llm-router 50%, onwatch drop heuristics, LiteLLM drop_params), while our collectors are contractually forbidden from guessing missing telemetry; adopting their mechanics would fail our own capacity-model rules. (3) Credential transiency — every subscription-pooling candidate persists OAuth/refresh tokens by design (CLIProxyAPI object store, CC-Router plaintext accounts.json, claw-router keychain write-back); our invariant admits only D-044's bounded gateway store. (4) The differentiated core has no analog — capability × channel × owner-policy intersection with provenance-carrying UNKNOWN discipline (now incl. D-058's effective limits) exists in none of the ~20 assessed repositories; what they route is traffic, not scarcity-under-evidence. (5) Scale economics run the wrong way — our replaceable custom surfaces are small (transport ~300, SSE ~110, schemas ~25 types, migrations ~25), so a replacement must be more correct to win, and the more correct mechanisms found are ~10–300 line algorithms — which are now precisely enumerated as port candidates (section D), not wholesale dependencies. The audit's reusable yield is real but bounded: two transport refinements, one worker buffer bound, one contract decision (reasoning), one evidence mechanization, three test-corpus adoptions, and one evidenced vocabulary decision (CREDIT_LIMIT). That is incremental evolution, recorded at mechanism granularity.

## Stage A+ — audit-completeness and adversarial keep-challenge report **Base:** `develop` @ `6fec46ca82901a5fb8761909778c16d8322bbb97` (2026-09-28), verified against canonical Forgejo; includes D-057, D-058 (#136/#152), D-059 (#154/#155) and Slice A (#151/#153, merged `e25de16b`). Worktree note: the owner's post-merge cleanup removed the program worktree mid-task; it was recreated non-destructively, detached at the same SHA, with no data loss (`reuse/reset-aware-quota-state` was already merged and its deletion expected). All external evidence lives under `/tmp/scarcity-router-reuse-audit/` with pinned SHAs; no production file was modified. This pass re-opened the prior KEEP conclusions with the burden of proof on KEEP. Method: the 7 previously-unassessed seed repositories were assessed at source level; the covered seeds were re-pinned and deepened per-mechanism; a disposable failure-injection experiment and an SSE differential probe were run outside the tree; a 2026 ecosystem sweep was performed. Every claim below carries a pinned SHA and file-level citation in the working notes. --- ### A. Coverage ledger — every original seed | Seed | Prior state | This pass | Evidence (inspected @ SHA) | |---|---|---|---| | weave-os/router | COMPLETE (`e5133a6`, usage pkg) | COMPLETE; Slice A merged; deeper mechanics re-checked — no remaining portable state mechanics | `e5133a6` Apache-2.0 | | wr/quota-router | MISSING | **COMPLETED → REJECT (KEEP-OURS)** | `0e3c41af` MIT — passive rollout-JSONL probe with fail-closed rollover semantics; strictly weaker than our app-server Codex collector | | dennisonbertram/claw-router | MISSING | **COMPLETED → REJECT** | `36d68450` MIT — bash account rotator; persisted credentials + bearer-in-argv violate our credential-transiency invariant | | Gods-light/cliproxyapi | PARTIAL (owner path unrecorded) | **COMPLETED: identity resolved** — stale pure fork (0 own commits) of canonical `router-for-me/CLIProxyAPI`; prior pin `4a2c8186` is a canonical commit (2026-09-27) | fork `4b681031`; canonical `acdace936` MIT | | suparious/claude-code-proxy | MISSING | **COMPLETED → REJECT (framework) + COPY candidate** | `45f4fa5f` MIT — ~70-line conservative tool-sequence repair (`core/anthropic/conversion.py:142-211`) + 805-line test file | | i-am-logger/claude-code-proxy | MISSING | **COMPLETED → REJECT EARLY** | `84027634` **CC BY-NC-SA 4.0** (incompatible) + silent conversation flattening discards tool traffic | | 0324wy/claude-code-proxy-codex | MISSING | **COMPLETED → REJECT EARLY** | `3e8a033e` — **no LICENSE file** (package.json MIT metadata does not authorize copying), stale, OAuth persistence, heuristic tool-call synthesis | | VictorMinemu/CC-Router | MISSING | **COMPLETED → KEEP-OURS (reference value)** | `555980dd` MIT — account-pooling product with plaintext token persistence; Anthropic unified-ratelimit header names (`server.ts:222-233`) + stale-utilization cooldown sweep (`token-pool.ts:33-84`) = evidence for a future Anthropic collector | | ypollak2/llm-router | MISSING | **COMPLETED → REJECT** | `d4125870` MIT — 139k LOC LiteLLM delegate; quota guessed at 50%/0.0 under failure; claude.ai browser scraping | | official LiteLLM | COMPLETE (`1ceeefbf`) | **EXTENDED per-mechanism** @ current HEAD `2c9b0e00` (v1.104.0-line) — see matrix | MIT | | steipete/CodexBar | COMPLETE (`491ae68`) | **RE-PINNED** to HEAD `14bdca166` (ancestor confirmed; vocabulary unchanged; reset-plausibility now independently implemented upstream) | MIT | | openai/codex | COMPLETE (`36650394` = rust-v0.157.1) | **EXTENDED** — schema-artifact discovery + field-by-field drift check | Apache-2.0 | | httpx / httpx-sse / sseclient-py / requests-sse | COMPLETE (source-cited) | **EXTENDED with experiments** (failure injection + 18-case differential, disposable, under `/tmp`) | BSD/MIT | **New 2026 candidates found and assessed:** KarpelesLab/teamclaude `9418c667` (PORT candidate, quota pressure), supermemoryai/llm-bridge `9ebb7c70` (design+vectors), onllm-dev/onwatch `3e5ed15` (**GPL-3.0 — ideas-only**), ndycode/codex-multi-auth `f3b176f` (reference), HJunLong601/codex-client-provider `b7516c0` (independent protocol-shape cross-check of our Codex adapter), openchamber `25c28a4` + guyinwonder168/opencode-glm-quota `f31d4f2` (Z.ai evidence sources), CodexMonitor/EchoBird/Zai-Gateway (CC BY-NC)/OmniRoute/tuxevil-rotator (REJECT EARLY with evidence). No seed disappeared silently. ### B. Authoritative reuse matrix (one row per mechanism) | Mechanism | Ours | Strongest upstream (pinned) | Decision | |---|---|---|---| | Outbound HTTP transport | `openai_http_adapter.py` 893 ln | httpx 0.28.1/httpcore 1.0.9 **failure-injection-tested**: taxonomy maps cleanly (Connect*/Pool → not-dispatched; pre-Response Read*/RemoteProtocolError → ambiguous; iter-phase → response-started); no request retries at `retries=0`; `except WriteError: pass` verified at http11.py:89-95 | **KEEP** — thin-adapter viability is real but costs 5-6 transitive deps into a stdlib-only core for zero correctness gain; 2 portable mechanisms recorded below | | SSE parsing | `SseStreamParser` ~110 ln | 18-case differential: ours strictly stronger — correct split-boundary UTF-8 (httpx-sse corrupts), fail-closed truncation (httpx-sse silently DROPS the truncated final event; sseclient-py DISPATCHES it = fabricated completion), bounded frame/total (both candidates unbounded) | **KEEP** (affirmative evidence) | | Codex App Server schemas | hand-maintained ~25 types | rust-v0.157.1 now ships JSON Schema trees + `generate-json-schema` CLI + official generated SDK; **zero drift** vs our consumed surface; no output-token control anywhere (D-058 premise re-confirmed) | **KEEP runtime schemas; COPY/PORT the evidence layer** (vendor pinned bundle + machine diff test, Apache-2.0 provenance) | | Codex lifecycle/sandbox/CODEX_HOME/approval refusal | `worker_codex_adapter.py` | official SDK manages its own lifecycle (bundles its own binary) | **KEEP** (D-056) | | Translation (Chat↔Responses, Anthropic↔internal, streaming, finish/stop, errors) | `openai_http_core.py` + `gateway_openai.py` strict fail-closed | LiteLLM: silent developer→system, role folding, drop_params pops, unmapped-finish→`"stop"`, `"error"→"stop"`, reasoning dropped in Responses direction, conversation leaked into errors; llm-bridge: thinking→text merge, SSE catch-continue, `end_turn` defaults; CLIProxyAPI: developer→user, reasoning_effort silent default | **REJECT all conversion code** — confirmed per-mechanism, not per-product; bounded COPY/PORT exceptions below | | Tool-result alignment / tool-name normalization | none (we fail closed on malformed sequences) | CLIProxyAPI `internal/translator/common/` (3 algorithms + 629 lines of tests, conservative, "never rewritten or stolen" guarantees); LiteLLM `_build_anthropic_tool_name_maps` (collision-safe reversible maps, `transformation.py:190-268`); suparious `_repair_openai_tool_message_sequence` | **PORT/COPY candidates, consumer-gated** (recorded for a future bridge; no current consumer → no speculative layer) | | Wire-format fixture corpora | hand-built | anthropic-sdk-python `tests/lib/streaming/fixtures/` (16 raw SSE transcripts incl. padded/truncated JSON, MIT); llm-bridge malformed-shape checklist; LiteLLM finish-reason token inventory | **COPY as test properties** (with notices) | | Perishable quota state | Slice A merged (`e25de16b`) | teamclaude `band-decision.js`: passed-reset = known zero (identical to our obsolescence rule); non-finite-utilization absence variant (equivalent to our strict validation) | **A (state mechanics): nothing left to port** | | Scarcity/ranking economics | D-026 penalty, D-037 blend — frozen reset-blind | teamclaude pressure=spendable/seconds; lower-bound ranking for unknown-reset | **B: KEEP (frozen policy)** — both are concrete, well-specified candidate mechanisms recorded as owner decision items; they would change frozen ranking semantics, and this audit changes no routing policy | | Z.ai parsing | `providers/zai.py` | CodexBar HEAD + onwatch + openchamber + real payloads | **KEEP + evidence upgrade**: CREDIT_LIMIT now sufficiently evidenced (below) | | Worker dispatch protocol | `worker_protocol.py`/`worker_endpoint.py` | Remote Execution API documents "MAY execute the action multiple times"; google.longrunning = polling with best-effort cancel; go-plugin magic cookie explicitly "not a security measure"; Docker ExecInspect = second delivery path | **KEEP every mechanism** — one real gap found (below) | | Persistence/migrations | `server_store.py` (~25 ln migration machinery) | alembic/yoyo = runtime deps; `user_version` loses provenance; WAL unneeded (no concurrent readers; identity store already correctly uses WAL) | **KEEP** | | UI/tray/packaging/diagnostics | D-052 dispatcher + pystray optional adapter + doctor | pystray already reused at the right boundary (LGPL extra); installer frameworks delete nothing; Sigstore+SHA256SUMS ordering already exceeds copyable patterns | **KEEP** | ### C. Kill List **Empty.** Affirmative justification per subsystem: transport (893 ln) — httpx would *add* deps and only yield ~40 lines of exception mapping we can port in ~20; SSE (110 ln) — every candidate is semantically unsafe for execution (silent drop or fabricated completion on truncation); Codex schemas (~25 types) — the generated alternative is a 13k-line pydantic module behind a new dependency; scoring core — no upstream implements capability ∩ channel ∩ owner-policy with fail-closed evidence; worker protocol — every candidate documents weaker guarantees (REAPI explicitly permits duplicate execution); persistence — a migration dependency to replace ~25 transactional lines. The prior 60%-deletion hypothesis remains unsupported; this pass found no wholesale replacement either. ### D. Reuse List (exact, evidence-based) 1. **PORT — transport suppress-and-read write-error semantics** (httpcore `_sync/http11.py:89-95`, verified at 1.0.9): on OSError during request-body send, still attempt `getresponse()`; a received response is a definitive outcome, silence stays ambiguous. Our `_send` currently mislabels a definitive early-4xx-with-undrained-body (common oversized-request provider behavior) as ambiguous. ~10 lines. 2. **PORT — connect-phase "not-dispatched" classification** (optional): ConnectError-class failures (refused/unreachable/TLS-before-write) are provably not dispatched; ours classifies them ambiguous (safe but imprecise). Enables a future bounded retry policy without touching D-043's no-blind-retry rule. 3. **COPY — parser test properties from anthropic-sdk-python** (`4421d56a`, MIT): whitespace-padded JSON, empty `partial_json` fragments, ping events, mid-stream truncation, usage-absent honesty → OpenAI-shaped fixtures asserting `SseStreamParser`/`ToolCallAccumulator` behavior. MIT notice + provenance required. 4. **COPY — llm-bridge malformed-shape checklist inverted into gateway refusal tests** (`9ebb7c70`, MIT): shapes llm-bridge asserts silent defaults for become our explicit-4xx tests. 5. **USE — LiteLLM finish-reason token inventory** (`core_helpers.py:197-250`) as documented-drift test evidence: each real provider token asserted to remain an explicit refusal in `normalize_finish_reason`. 6. **COPY/PORT — Codex schema bundle for the evidence layer** (rust-v0.157.1 `codex-rs/app-server-protocol/schema/json/` + `precomputed/`, Apache-2.0, provenance header): machine-diff our consumed method/field list in a test (mirroring upstream `schema_fixtures_tests.rs`) — converts the recurring manual re-pin into a mechanical check. 7. **PORT — bounded per-attempt chunk buffer** (`worker_endpoint.py:222,226-229`): `_chunks` grows unbounded if a consumer stalls (chunk size and attempt count are capped, chunk count is not); cap with fail-closed overflow, ~10 lines. The one genuine gap found in the worker challenge. 8. **Deferred, consumer-gated** (no current surface → per the no-speculative-layers rule): CLIProxyAPI `common/` alignment algorithms + tests (Go→Python, MIT); LiteLLM `_build_anthropic_tool_name_maps`; suparious `_repair_openai_tool_message_sequence`; SQLite `backup()`/`quick_check` hardening; CC-Router's Anthropic unified-ratelimit header names (evidence for a future Anthropic collector). ### E. Keep List (affirmative justification, current-source grounded) - **HTTP transport** — stdlib-only core; the experiment shows the taxonomy survives with httpx only behind a pinned-configuration adapter whose constraints (verified TLS, no env proxies, no redirects, identity encoding, bounded reads, deadline/cancel interleave, marker refusal) are exactly the invariants our adapter already enforces; the two portable mechanisms (D.1/D.2) are taken without the dependency. - **SSE parser** — strictly stronger than all candidates on every dimension the task listed; both candidate failure modes (silent drop / fabricated dispatch) are precisely what at-most-once execution cannot tolerate. - **Codex runtime schemas + lifecycle** — zero drift at 0.157.1; generated models add pydantic and weaken fail-closed posture; lifecycle/sandbox/isolation stay ours by D-056; the maintenance burden moves to the mechanized evidence layer (D.6), which is where it belongs. - **Translation core** — every framework candidate silently degrades somewhere material; our refusal-not-rewrite semantics are stricter than the entire sampled ecosystem. - **Scoring core (selector/routing/eligibility/scarcity/policy)** — the differentiated product; D-058's pre-ranking output eligibility (`route_output_code`) and effective-limit intersection have no upstream analog. - **Quota state** — Slice A adopted the load-bearing reusable mechanic; remaining upstream variants are equivalent or ranking-policy (owner-gated). - **Worker protocol, persistence, UI/packaging/diagnostics** — each KEEP carries its per-mechanism affirmative reason in the matrix. ### F. Rejected Reuse List (with concrete reasons) - httpx-as-transport: dependency weight + no correctness gain (experiment-verified). - httpx-sse / sseclient-py as parsers: silent truncation drop / truncated-event dispatch; unbounded accumulation; split-boundary UTF-8 corruption (httpx-sse). - LiteLLM Chat↔Responses bridge + Anthropic conversion + streaming/finish mapping + error taxonomy: silent degradation enumerated per mechanism with line cites; conversation text leaked into errors. - llm-bridge parsers/emitters/converter: thinking→text merge; catch-continue SSE; silent defaults asserted by their own tests. - CLIProxyAPI framework: 97.6k-LOC Go translator registry; persisted OAuth pooling (credential-transiency conflict). - i-am-logger/claude-code-proxy: license (CC BY-NC-SA) + design. - 0324wy/claude-code-proxy-codex: no license grant; settings-file patching; synthesized tool calls. - onwatch: GPL-3.0 (incompatible) — observations recorded as evidence only. - ypollak2/llm-router: fabricated 50%/0.0 quota under failure; browser-scraped telemetry; 139k-LOC integration. - claw-router / CC-Router / codex-multi-auth / tuxevil-rotator / OmniRoute / EchoBird / Zai-Gateway (CC BY-NC) / CodexMonitor: account-pooling or rotator products, plaintext credential persistence, ToS-sensitive mechanisms we deliberately do not build. - Remote Execution API / google.longrunning / go-plugin / Docker-exec / capnproto / tmate as worker-protocol donors: weaker guarantees (documented duplicate execution), wrong trust shape, or second delivery paths contradicting D-043. - alembic/yoyo, `user_version` swap, WAL-for-server-store: dependency or churn for no property we lack. - Inno Setup/WiX installers: add fragility, delete nothing; MSIX remains the recorded signing seam. ### G. Updated target architecture (smallest core after maximal sensible reuse) Unchanged in shape — the stdlib+mcp-only core stands: presets → `openai_http_adapter` (transport + suppress-and-read + ND classification) → `openai_http_core` (translation + SSE + reasoning carrier [decision-gated]) → `gateway_*` (intersection + effective limits) → `selector/routing/scarcity/policy` (frozen scoring) → `resource_state` (reset-aware state) → `providers/*` (Z.ai incl. future CREDIT_LIMIT lane; Codex adapter with mechanized schema evidence) → `worker_*` (dispatch protocol + bounded chunk buffer) → `server_store` (explicit migrations). Net effect of this pass: +1 contract-level capability (reasoning carrier, owner-gated), +~30 lines of transport/worker hardening, +1 evidence-automation test, +1 test-vector batch — and the recurring Codex re-pin labor drops to a mechanical step. ### H. Deletion estimate **No forced number.** Mass deletion is unsupported: 0% of custom subsystem LOC is replaceable by any assessed upstream at equal-or-better semantics. The honest reduction is in **maintenance risk** (mechanized Codex schema re-pin; adopted test corpora), not LOC — roughly a 0–5% LOC effect, and in the wrong direction if the two small hardening ports land. The prior 60% hypothesis, and any 5–15% reading, are both unsupported against current `develop`. ### I. Ordered implementation candidates (recorded for the owner; no issues created) 1. **Hardening batch (non-contract, small):** D.1 suppress-and-read; D.7 bounded chunk buffer; SSE `UnicodeDecodeError` → typed `TranslationError` typing gap (the docstring already promises fail-closed via `TranslationError`; the coordinator catch-all contains the raw error today as `unexpected_error` — `gateway_coordinator.py:775`) + UTF-8 BOM strip hardening (all three compared parsers silently drop a BOM-prefixed first event; the spec says strip); D.2 ND classification (optional). 2. **Reasoning carrier (contract addition → needs a decision):** our response direction silently ignores `delta.reasoning_content` (DeepSeek, **Z.ai**) and `delta.reasoning` (OpenRouter); the chunk vocabulary cannot express reasoning — this violates our own "reasoning must never be silently dropped" rule (`openai_http_core.py:783-822`, `:514-564`, `gateway_adapters.py:106-116`). Represent-or-refuse, with llm-bridge `universal.ts:63-98` + LiteLLM `transformation.py:2605-2634` as design references (never their code). Frozen-contract addition → backwards-compat or versioned migration decision required. 3. **Codex schema evidence mechanization (D.6):** vendor pinned bundle + diff test; Apache-2.0 provenance. 4. **Test-vector batch (D.3/D.4/D.5):** parser hardening fixtures, gateway refusal tests, finish-reason drift inventory. MIT notices where required. 5. **Z.ai CREDIT_LIMIT adoption (owner decision, evidence bar now met):** three independent parsers + two independent real payloads + Max/Pro-tier sightings (CodexBar #2724, onwatch #122, openchamber, oh-my-pi #8644). Requires the recorded capacity-vocabulary position (credit points ≠ tokens: distinct `resource`/`kind`, not the token vocabulary) and the routing-economics position (D-037 blending), with comparative tests per the routing-preference rule. Legacy TOKENS_LIMIT/TIME_LIMIT accounts still exist in parallel and must keep parsing. The 30-day `(1,30)` window remains UNKNOWN (synthetic evidence only); TIME_LIMIT monthly sentinel remains diagnostics-only. 6. **Consumer-gated ports (deferred until their surface exists):** D.8 items. ### J. Stop / Start / Continue (against current `develop`, incl. D-058/D-059) - **Stop:** re-auditing rejected frameworks wholesale (per-mechanism granularity is now the unit of analysis); treating README/star-level signals as evidence; manual Codex protocol re-verification once D.6 lands. - **Start:** the hardening batch and the reasoning-carrier decision; the CREDIT_LIMIT vocabulary/economics decision (evidence complete); using the failure-injection + differential probes under `/tmp/scarcity-router-reuse-audit/http-probes/` as disposable oracles when the transport/SSE surfaces next change. - **Continue:** the two-mode product boundary and its custom core; evidence-pinned upstream tracking (CodexBar/Codex/campaign docs); the slice-per-PR program discipline. --- ### Final verdict **`INCREMENTAL_EVOLUTION_SUPPORTED`.** > Why did a broad reuse-first audit fail to find large amounts of replaceable custom code? Because the ecosystem's center of gravity is semantically opposite to this product, not merely less polished — specific, verified differences: (1) **at-most-once discipline** — the one mature protocol with our problem shape (Remote Execution API) explicitly documents that it MAY execute an action multiple times, and every cloud job API resolves ambiguity by polling durable state we deliberately do not keep; silent retry/relabel is default behavior in LiteLLM (`"error"→"stop"`, unmapped→`"stop"`) and llm-bridge (catch-continue SSE, `end_turn` default) — each occurrence is a place where our frozen D-043/D-044 guarantees would break, not a style difference. (2) **Fail-closed evidence semantics** — every quota-touching candidate fabricates state under uncertainty (llm-router 50%, onwatch drop heuristics, LiteLLM `drop_params`), while our collectors are contractually forbidden from guessing missing telemetry; adopting their mechanics would fail our own capacity-model rules. (3) **Credential transiency** — every subscription-pooling candidate persists OAuth/refresh tokens by design (CLIProxyAPI object store, CC-Router plaintext accounts.json, claw-router keychain write-back); our invariant admits only D-044's bounded gateway store. (4) **The differentiated core has no analog** — capability × channel × owner-policy intersection with provenance-carrying UNKNOWN discipline (now incl. D-058's effective limits) exists in none of the ~20 assessed repositories; what they route is traffic, not scarcity-under-evidence. (5) **Scale economics run the wrong way** — our replaceable custom surfaces are small (transport ~300, SSE ~110, schemas ~25 types, migrations ~25), so a replacement must be *more* correct to win, and the more correct mechanisms found are ~10–300 line algorithms — which are now precisely enumerated as port candidates (section D), not wholesale dependencies. The audit's reusable yield is real but bounded: two transport refinements, one worker buffer bound, one contract decision (reasoning), one evidence mechanization, three test-corpus adoptions, and one evidenced vocabulary decision (CREDIT_LIMIT). That is incremental evolution, recorded at mechanism granularity.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Creatidy/scarcity-router#150
No description provided.