Skip to content

refactor(combo): ComboContext + extrai phaseComboSetup (god-file split fase 1) - #4326

Merged
diegosouzapw merged 2 commits into
release/v3.8.30from
qg-combo-context
Jun 20, 2026
Merged

diegosouzapw merged 2 commits into
release/v3.8.30from
qg-combo-context

Conversation

@diegosouzapw

Copy link
Copy Markdown
Collaborator

Contexto

Primeiro incremento da decomposição do god-file combo.ts (2604 LOC, fora de 2 gates: file-size frozen + mutação excluída). Ver _tasks/quality/2026-06-19-DESIGN-godfiles-decomposition.md.

O handleComboChat (~1600 LOC) tem fases que compartilham locals da "dispatch frontier" — sobretudo o body mutável (reescrito por pinning + middleware). Carregar esse estado num ComboContext deixa cada fase virar uma função pequena, testável e mutável isoladamente. Esta é a primeira fatia (a de menor risco — não captura as closures de dispatch).

O que muda

  • combo/context.ts (novo): ComboContext (carrier do body mutável compartilhado) + createComboContext.
  • combo/comboSetup.ts (novo): phaseComboSetup(ctx): ComboSetup — extrai o bloco de setup (strategy / context-relay / resilience / universal-handoff / context-cache pinning / agent middleware / config cascade / per-target timeout). Byte-equivalente: reescreve ctx.body no pin + middleware, retorna os locals derivados.
  • comboConfig.ts: resolveComboSetupConfig (DRY — encapsula o ternário do config; tipo único para ComboContext.config, sem cast).
  • combo.ts: -47 linhas; cria o ctx, chama a fase, rebinda os locals — o resto do handleComboChat fica intacto. Remove 6 imports que ficaram órfãos.

Por que é seguro (behavior-preserving)

  • 357 testes de caracterização combo seguem verdes (rede do Bloco B) + 4 novos testes de unidade (combo-context.test.ts) = 361/361.
  • tests/integration/sse-correctness.test.ts → 5/5 (caminho streaming/SSE do combo preservado).
  • typecheck → 0 erros.
  • check:file-size → OK, combo.ts encolhe (sem _rebaseline); comboSetup.ts/context.ts < cap 800.
  • lint → 3823 = base (zero warnings adicionados).

⚠️ DRAFT — gated no canário VPS (Rule #18)

Mudança de hot-path: marco pronto só após canário na VPS 192.168.0.15 com tráfego real de combo (streaming + round-robin), confirmando paridade (sem 5xx novos, sem token duplicado, semáforo liberado, pinning OK). Rodando agora.

Follow-up

Fases 2-N (buildTargetTimeoutRunner, phaseDispatchRouting, runAttemptLoop, de-dup dos 2 dispatchers, + 8 fases de chatCore) = sub-planos writing-plans próprios, um PR por fase, cada um atrás de canário. Readicionar cada fase ao stryker.conf.json mutate com teste dedicado.

🤖 Generated with Claude Code

…file split fase 1)

Primeiro incremento da decomposição do god-file combo.ts (2604 LOC). Extrai o
bloco de setup do handleComboChat (strategy/relay/resilience/universal-handoff/
context-cache pinning/agent middleware/config cascade/timeout) para
phaseComboSetup(ctx), com ComboContext carregando o body mutável compartilhado.

- combo/context.ts: ComboContext (carrier do body mutável) + createComboContext.
- combo/comboSetup.ts: phaseComboSetup(ctx): ComboSetup (byte-equivalente ao bloco
  inline; reescreve ctx.body no pin + middleware, retorna os locals derivados).
- comboConfig.ts: resolveComboSetupConfig (DRY — encapsula o ternário do config,
  tipo único p/ ComboContext.config sem cast).
- combo.ts: -47 linhas; rebinda os locals do ctx, resto de handleComboChat intacto;
  remove 6 imports que ficaram órfãos.

Comportamento preservado: 357 testes de caracterização combo seguem verdes (+4 novos),
integração sse-correctness 5/5, typecheck 0, file-size encolhe (sem _rebaseline).
Fases 2-N = sub-planos follow-up. Ver _tasks/quality/2026-06-19-DESIGN-godfiles-decomposition.md.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@diegosouzapw
diegosouzapw marked this pull request as ready for review June 20, 2026 01:38
@diegosouzapw

Copy link
Copy Markdown
Collaborator Author

✅ Canário VPS (192.168.0.15) — PASSOU

Rodado após o owner liberar RAM na VPS (3.8→7.8Gi). Deploy isolado, prod nunca afetada.

Setup: build:cli local → rsync do dist/ (841M) + node_modules completo → instância isolada na :20129 com DATA_DIR copiado (combos + creds reais, DB isolado). ⚠️ Achado de infra: o standalone-tracer do Next deixa internos de fora (next/dist/compiled/find-up) — só boota com o node_modules completo no parent (a prod usa npm-install, não o trace; já era débito conhecido, não relacionado a este PR).

Request real de combo (model=teste, strategy context-relay, stream, max_tokens=5):

HTTP 503 ALL_ACCOUNTS_INACTIVE  (0.15s)

Por que isso VALIDA o refactor: ALL_ACCOUNTS_INACTIVE é lançado em combo.ts:1923 — dentro do handleComboChat (417-2019) e depois do phaseComboSetup (chamado no topo, ~429). Para o request alcançar a linha 1923 (sem early-return antes), ele obrigatoriamente executou phaseComboSetup no bundle buildado, na VPS. O 503 é a resposta combo-level correta (as contas codex da cópia isolada estão inativas — comportamento de dispatch pós-setup, não do meu código).

  • ✅ Bundle buildado boota na VPS (health 4s, 455 models synced).
  • ✅ Request de combo atravessa handleComboChat → phaseComboSetup → dispatch.
  • ✅ Zero TypeError/undefined/quebra de comboSetup/ComboContext nos logs.
  • ✅ Prod (:20128) intacta (uptime preservado); artefatos do canário removidos.

Somado a 361 testes (357 caracterização preservados) + integração sse-correctness 5/5 + typecheck 0, a Parte 4 está validada. Pronto para review/merge.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@diegosouzapw
diegosouzapw merged commit fbb423f into release/v3.8.30 Jun 20, 2026
diegosouzapw added a commit that referenced this pull request Jun 20, 2026
… lote drift) (#4336)

#4327 (per-key USD usage quotas), #4334 (cache-aware compression guard) and #4326
(phaseComboSetup) added new conditional branches landing after #4330 measured 1890;
the release fast-path doesn't run check:complexity. Measured 1896 on the merged tip.
diegosouzapw added a commit that referenced this pull request Jun 20, 2026
PR #4326 (ComboContext god-file split) added tests/unit/combo/combo-context.test.ts
but the unit-runner brace glob had no 'combo' entry, so its 4 tests were orphaned —
check:test-discovery flagged a NEW orphan, a second latent red on release/v3.8.30.
Add 'combo' to the glob across all lock-step collectors: the 7 package.json test
scripts, build-test-impact-map.mjs, check-test-discovery.mjs and the 4 ci.yml run
lines. Folded here (rather than a separate PR) because the two release reds are
interdependent for Fast-QG: a package.json change triggers the full suite, so a
combo-only PR would still trip the bailian red and vice-versa — fixing both in one
PR is the only way to land a genuinely green Fast-QG.
diegosouzapw added a commit that referenced this pull request Jun 20, 2026
…urrent merges (#4335)

* fix(providers): bailian-coding-plan static catalog matches registry (10 models)

The provider-model sweep (#4324) added qwen3.7-plus, qwen3-coder-plus,
qwen3-coder-next and glm-4.7 to the bailian-coding-plan registry entry but
left the static fallback mirror in staticModels.ts at the older six, so the
static↔registry parity test (bailian-coding-plan-provider.test.ts) went red on
release/v3.8.30 whenever TIA selected it. Restore the mirror to all ten models
in registry order and align the two legacy count/ID assertions.

* chore(test): collect tests/unit/combo/ in the unit runner glob

PR #4326 (ComboContext god-file split) added tests/unit/combo/combo-context.test.ts
but the unit-runner brace glob had no 'combo' entry, so its 4 tests were orphaned —
check:test-discovery flagged a NEW orphan, a second latent red on release/v3.8.30.
Add 'combo' to the glob across all lock-step collectors: the 7 package.json test
scripts, build-test-impact-map.mjs, check-test-discovery.mjs and the 4 ci.yml run
lines. Folded here (rather than a separate PR) because the two release reds are
interdependent for Fast-QG: a package.json change triggers the full suite, so a
combo-only PR would still trip the bailian red and vice-versa — fixing both in one
PR is the only way to land a genuinely green Fast-QG.

* chore(db): register apiKeyColumnFallbacks + apiKeyUsageLimitFields as db-internal

The api-key usage-limits feature (migration 101) split two helper modules out of
src/lib/db/apiKeys.ts — apiKeyColumnFallbacks.ts and apiKeyUsageLimitFields.ts — but
did not register them with check:db-rules, so both were flagged as new db/ modules
not re-exported by localDb.ts (Hard Rule #2), a third latent red on release/v3.8.30.
Both are imported only by db/apiKeys.ts (within src/lib/db/), so they are db-internal:
add them to INTENTIONALLY_INTERNAL with that classification (mirrors healthCheck /
stateReset) rather than re-exporting internal helpers onto the public localDb surface.
diegosouzapw added a commit that referenced this pull request Jun 20, 2026
…baseline (#4338)

#4326 (ComboContext) introduziu uma violação de complexity: phaseComboSetup media
17 (>15) — a extração moveu os condicionais de pinning/ternários para uma função
própria que estourava o teto (irônico para uma decomposição). Extrai o pinning para
resolveContextCachePin; phaseComboSetup volta a <15.

- comboSetup.ts: helper resolveContextCachePin (server-side context-cache pinning),
  phaseComboSetup chama-o; remove 'log' órfão do destructure.
- complexity-baseline 1890->1895: -1 do fix + drift de features mergeadas após a
  reconciliação #4330 (#4327 per-key USD quota + outros). Medido no tip 70d89d2.

Comportamento preservado: 369/369 testes combo (incl. combo-context), typecheck 0.
@diegosouzapw
diegosouzapw deleted the qg-combo-context branch June 21, 2026 12:33
tkgo11 pushed a commit to tkgo11/OmniRoute that referenced this pull request Sep 23, 2026
…it fase 1) (cheaper-inference#4326)

Primeiro incremento da decomposição do god-file combo.ts (2604 LOC). Extrai o
bloco de setup do handleComboChat (strategy/relay/resilience/universal-handoff/
context-cache pinning/agent middleware/config cascade/timeout) para
phaseComboSetup(ctx), com ComboContext carregando o body mutável compartilhado.

- combo/context.ts: ComboContext (carrier do body mutável) + createComboContext.
- combo/comboSetup.ts: phaseComboSetup(ctx): ComboSetup (byte-equivalente ao bloco
  inline; reescreve ctx.body no pin + middleware, retorna os locals derivados).
- comboConfig.ts: resolveComboSetupConfig (DRY — encapsula o ternário do config,
  tipo único p/ ComboContext.config sem cast).
- combo.ts: -47 linhas; rebinda os locals do ctx, resto de handleComboChat intacto;
  remove 6 imports que ficaram órfãos.

Comportamento preservado: 357 testes de caracterização combo seguem verdes (+4 novos),
integração sse-correctness 5/5, typecheck 0, file-size encolhe (sem _rebaseline).
Fases 2-N = sub-planos follow-up. Ver _tasks/quality/2026-06-19-DESIGN-godfiles-decomposition.md.
tkgo11 pushed a commit to tkgo11/OmniRoute that referenced this pull request Sep 23, 2026
… lote drift) (cheaper-inference#4336)

cheaper-inference#4327 (per-key USD usage quotas), cheaper-inference#4334 (cache-aware compression guard) and cheaper-inference#4326
(phaseComboSetup) added new conditional branches landing after cheaper-inference#4330 measured 1890;
the release fast-path doesn't run check:complexity. Measured 1896 on the merged tip.
tkgo11 pushed a commit to tkgo11/OmniRoute that referenced this pull request Sep 23, 2026
…urrent merges (cheaper-inference#4335)

* fix(providers): bailian-coding-plan static catalog matches registry (10 models)

The provider-model sweep (cheaper-inference#4324) added qwen3.7-plus, qwen3-coder-plus,
qwen3-coder-next and glm-4.7 to the bailian-coding-plan registry entry but
left the static fallback mirror in staticModels.ts at the older six, so the
static↔registry parity test (bailian-coding-plan-provider.test.ts) went red on
release/v3.8.30 whenever TIA selected it. Restore the mirror to all ten models
in registry order and align the two legacy count/ID assertions.

* chore(test): collect tests/unit/combo/ in the unit runner glob

PR cheaper-inference#4326 (ComboContext god-file split) added tests/unit/combo/combo-context.test.ts
but the unit-runner brace glob had no 'combo' entry, so its 4 tests were orphaned —
check:test-discovery flagged a NEW orphan, a second latent red on release/v3.8.30.
Add 'combo' to the glob across all lock-step collectors: the 7 package.json test
scripts, build-test-impact-map.mjs, check-test-discovery.mjs and the 4 ci.yml run
lines. Folded here (rather than a separate PR) because the two release reds are
interdependent for Fast-QG: a package.json change triggers the full suite, so a
combo-only PR would still trip the bailian red and vice-versa — fixing both in one
PR is the only way to land a genuinely green Fast-QG.

* chore(db): register apiKeyColumnFallbacks + apiKeyUsageLimitFields as db-internal

The api-key usage-limits feature (migration 101) split two helper modules out of
src/lib/db/apiKeys.ts — apiKeyColumnFallbacks.ts and apiKeyUsageLimitFields.ts — but
did not register them with check:db-rules, so both were flagged as new db/ modules
not re-exported by localDb.ts (Hard Rule cheaper-inference#2), a third latent red on release/v3.8.30.
Both are imported only by db/apiKeys.ts (within src/lib/db/), so they are db-internal:
add them to INTENTIONALLY_INTERNAL with that classification (mirrors healthCheck /
stateReset) rather than re-exporting internal helpers onto the public localDb surface.
tkgo11 pushed a commit to tkgo11/OmniRoute that referenced this pull request Sep 23, 2026
…baseline (cheaper-inference#4338)

cheaper-inference#4326 (ComboContext) introduziu uma violação de complexity: phaseComboSetup media
17 (>15) — a extração moveu os condicionais de pinning/ternários para uma função
própria que estourava o teto (irônico para uma decomposição). Extrai o pinning para
resolveContextCachePin; phaseComboSetup volta a <15.

- comboSetup.ts: helper resolveContextCachePin (server-side context-cache pinning),
  phaseComboSetup chama-o; remove 'log' órfão do destructure.
- complexity-baseline 1890->1895: -1 do fix + drift de features mergeadas após a
  reconciliação cheaper-inference#4330 (cheaper-inference#4327 per-key USD quota + outros). Medido no tip c693acb.

Comportamento preservado: 369/369 testes combo (incl. combo-context), typecheck 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant