Skip to content

fix(responses): consolidate bounded errors, retries and account recovery - #5553

Closed
luvs01 wants to merge 23 commits into
devfrom
stack/request-retry-boundaries
Closed

luvs01 wants to merge 23 commits into
devfrom
stack/request-retry-boundaries

Conversation

@luvs01

@luvs01 luvs01 commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Summary

Keep policy stops, replay permission and account recovery consistent when an upstream response is malformed, oversized or cancelled. This aggregate retains the earlier #5446, #5423 and #5415 contributions and their related compaction-identity, scoped-quota and cold-spawn follow-ups, and now includes all of #5307 plus the Kiro portion of #5310.

  • Bounded replacement decoding preserves a cyber-policy stop despite malformed UTF-8. Quota/reset evidence still requires a complete, display-safe, valid UTF-8 body. The EOF contract also reports validity when fatal decoding is requested.
  • Kiro text-fallback HTTP errors use the shared bounded reader and the originating abort signal. Reader cancellation and retained-budget release are covered without granting another send.
  • Preserve dev's fix(web-search): bound search replay ownership, reset replacement answers, and sidecar sends #5575 replacement-refusal contract and full refusal sentence, including its non-replayable response marker. The original Go reset refusal, deep policy-body snapshots, compaction identity and scoped-account attribution remain included.

The two #5307 commits retain their original authors, dates and source-SHA trailers. Only the three Kiro paths from #5310 are included; its Fernet and Claude skill-marker changes remain separate, so #5310 is not fully superseded by this PR. All sixteen earlier source implementation/follow-up commits remain in the ancestry. The existing changes are independent of #5540 and #5542.

Verification

  • Head cc466ed9c0f89243f84a61f136efff2abe2ca1ef incorporates dev a077087b741a7f7cb1d07b801ec831965d180839. The three reset-refusal merge conflicts take dev's current behavior, as requested in the partial-landing review.
  • Bun 1.4.0 on Windows, through the repository wrapper: seven focused files produced 362 pass / 1 fail. The failure was the new cancellation fixture targeting the fallback factory rather than the error-body reader. The corrected reader-level case passed separately (1 pass); after moving the two added Kiro cases to a size-compliant sibling, those cases and the two layout guards passed (20 pass). These separate runs are not represented as one all-green rerun.
  • The combined malformed-UTF-8/policy-stop/non-replayable regression failed against the pre-carry implementation and passed after integration. Source quota, cyber-policy, bounded-body, Kiro, retry, policy-fallback and physical-send-budget cases are covered by the focused run.
  • TypeScript, structure, privacy and file-size ratchet checks passed. The original Kiro test file equals dev again after relocation; both layout maps register the new sibling. Source patch IDs match both complete Keep malformed UTF-8 from erasing a cyber-policy stop #5307 commits and the three-path Kiro carry; the relocated original regression is unchanged.
  • No timeout, size cap, skip or runtime admission rule was relaxed. Tests use synthetic/loopback fixtures. A full suite across concurrent worktrees was not rerun; exact-head hosted CI, other-platform validation and security review remain outstanding, so this stays draft.

The earlier question about widening spent-replacement refusal was resolved upstream by #5575 and is preserved here. Default Go reset-refusal availability and deep-snapshot resource cost remain review considerations, without a claim of maintainer approval.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Co-authored-by: Epinephrine luvs01@hanmail.net
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

luvs01 and others added 18 commits September 22, 2026 21:58
Per review on #5446: replace the replaySafe source-string count with an execution test that drops the connection before the answer on an opencode.ai/zen/go destination and asserts the 429 upstream_reset_replay_refused with exactly one send.

(cherry picked from commit 92b74ec)
The warm-up child was waited on through Bun.spawnSync, which made the spawn's
own timeout the only bound it could honour — and no bound at all when the
child or the primitive wedged: while a synchronous spawn blocks, the event
loop is dead, so the hook budget and the per-test timeout freeze inside the
same wait and nothing reports anything. Run 35511743422's macos 2/2 leg held
that shape for eighteen silent minutes inside client-connect.test.ts before
the job ceiling cut it and reported cancelled, which the ci gate reads as
failure.

The bound now lives on the parent's live loop: an asynchronous spawn, SIGKILL
at the existing derived deadline, a short reap grace, and the call settles
with or without the child's exit or EOF — so a descendant holding the pipes
or a child that outlives its kill cannot turn a warm-up into an unbounded
wait. A timed-out child now fails the warm-up by name instead of hanging the
job.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit aa9b889)
…electors

compactionRoutingKeepsProviderIdentity evaluated override.sourceModel as the
raw client selector, so a synthetic --fast/--effort form of a policy or combo
selector (ocx/primary--fast) missed resolvePolicyProfileId/resolveComboId and
fell through routeConcreteModel to the default provider. The same fallthrough
swallowed policy aliases renamed or deleted mid-conversation, since
config.routingProfiles is mutated in place. Both cases could wrongly report
identity match and let provider-private compaction state or caller credentials
cross a backend boundary.

Strip synthetic-row suffixes via parseSyntheticRowId before the identity
checks, and treat a source that only routes through the default provider as
unproven: it can never match a concrete identity.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 7e59315)
The scoped-quota re-export grew src/server/responses/core.ts past its committed 210-line cap (213). Collapse the two-name re-export back to one line; the file's export list already carries longer single-line statements.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 559db16)
…main

- record the normalized 429/402 outcome before returning no-alternate on a
  suppressed same-workspace move, so a 5xx-wrapped quota refusal still cools
  the refused account instead of reading as transient
- bind a request-owned `main` alternate by the caller credential's own
  workspace id (chatgpt-account-id header, else the bearer token's account
  claim) via callerCodexWorkspaceAccountId
- apply the same scoped-quota workspace gate to the single bounded alternate
  send in the native /responses/compact path
- cover all three in tests and update the transport doc

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 5267593)
…the size cap

server-auth.test.ts grew to 4684 against a 4589 baseline cap, so the
file-size ratchet failed shard 3/4. The three scoped-quota suppression
cases move byte-for-byte into server-auth-scoped-quota.test.ts, and the
pool-retry harness they share is extracted to
tests/helpers/pool-retry-harness.ts (per-run OPENCODEX_HOME dir, so each
importing file keeps its own module state under bun test --isolate).

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit b391c99)
The workspace classification in shouldRetryCodexScopedQuotaOnAlternate
reads the first response body asynchronously, so a client disconnect can
land after the earlier abort check but before the branch records the
first account, cancels its body, and sends the alternate. Re-check the
abort signal immediately after the await in both paths: compact returns
the 499 client_cancelled response after releasing the alternate lease,
and the regular path releases its permit and lease and returns
no-alternate while still recording the first account's real outcome.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit c52b64b)
The 499 exits around the scoped-quota classification return a fresh
response while the first rejection's body is still open; cancel it so
the abandoned upstream connection and tee resources are released.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 813efcc)
upstream.body.cancel() can wait on a custom or stalled source; awaiting
it at the abort checkpoints would park the 499 reply on cleanup. Fire
it with the request's abort reason and swallow rejection, the same
best-effort shape bufferCompactResponse already uses.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 2d1ee69)
Exercise both operator-granted and default-denied reset paths through policy fallback and the alternate-account eligibility gate. Clarify that retries serialize the original body snapshot while identity metadata is established per attempt, and document synthetic compaction identity and transient replacement refusal.
@coderabbitai

coderabbitai Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@lidge-jun

Copy link
Copy Markdown
Owner

리뷰 · 우선순위 72 / 80

이 PR은 “요청을 다시 보낼까, 말까”와 “같은 계정·같은 백엔드로 이어갈까”를 한 덩어리로 고칩니다. base는 dev이고, 닫힌 #5446·#5423·#5415와 이어서 나온 compaction 신원·scoped-quota 수정을 한 브랜치에 모았습니다. OpenCode Go로 가는 첫 전송도 더 이상 애매한 연결 끊김을 재전송하지 않고, 운영자가 한 번 허용한 재전송 뒤에 잠깐의 5xx가 오면 거부(upstream_reset_replay_refused)로 끝냅니다. 정책 폴백은 처음 읽은 요청 본문을 structuredClone으로 깊은 복사해 두고, 앞 시도에서 본문을 고쳐도 다음 후보에게는 원래 내용만 보냅니다. compaction은 --fast 같은 가짜 선택자·정책/콤보·기본 프로바이더로 떨어진 선택자를 “신원 증명 실패”로 보고, 제공자 전용 compaction 상태를 넘기지 않습니다. scoped quota는 거절 코드만으로 계정 전환을 막지 않고, 실제로 고른 대체 계정의 workspace가 같을 때만 막고, 본문 읽기 뒤에 취소·바디 정리도 다시 확인합니다. 테스트 쪽 cold-spawn warm-up도 부모 이벤트 루프에서 시간 제한을 걸어, 자식이 멈춰도 CI가 같이 멈추지 않게 했습니다. 작성자가 로컬에서 포커스 테스트 604개를 통과했다고 적었고, 지금은 draft이며 보안 체크리스트는 비어 있습니다. 호스트 CI의 큰 테스트 샤드는 아직 pending입니다.

라인 - src/server/responses/passthrough-dispatch.ts: OpenCode Go의 replaySafe 예외를 완전히 제거했습니다. 예전에 Go만 “첫 전송은 한 번 더”였는데, 이제 다른 목적지와 같이 거부합니다. Go가 자주 끊기던 환경이면 사용자 쪽 실패가 늘어날 수 있습니다.
라인 - src/lib/upstream-retry.ts fetchWithResetRetry: 운영자 허용 재전송 뒤 transient 5xx만 거부로 바꿉니다. 408·409·진짜 프로바이더 429는 그대로입니다. PR 본문도 이 범위를 넓힐지 메인테이너에게 물어 두었습니다.
라인 - src/server/responses/policy-fallback.ts: 매 정책 시도마다 본문 깊은 복사입니다. 입력이 아주 크면 CPU·메모리 비용이 커집니다. 동작은 맞고, 비용은 알고 가는 선택입니다.
라인 - src/server/responses/core-codex-account.ts shouldRetryCodexPoolAccountQuota: 429/402에서 예전처럼 scoped 코드로 바로 false를 주지 않고, 대체 계정을 고른 뒤 shouldRetryCodexScopedQuotaOnAlternate로 막습니다. workspace를 모를 때는 예전보다 전환을 더 허용합니다.
라인 - 같은 파일: project_spend_limit_exceeded는 workspace가 같아도 전환을 허용합니다. org 한도와 project 한도를 다르게 본 설계인데, 같은 조직 안 project 한도면 두 번째 계정도 같이 막힐 수 있습니다.
라인 - src/lib/errors.ts / replayRefusalResponse 문구: “connection closed before…” → “did not complete reliably”. 프록시 내부 매칭은 같이 바꿨지만, 바깥에서 옛 문자열을 보던 도구가 있으면 깨집니다.
라인 - 원본 #5446·#5423·#5415는 이미 CLOSED입니다. #5540과는 파일 겹침이 거의 없고, #5542와는 layout.json·structure/transports/responses.md·fixture 정도만 겹칩니다. 합류 순서만 보면 됩니다.
라인 - draft + 보안 체크 미완료 + 호스트 풀스위트 pending. 작성자 말대로 합류 전 게이트입니다.

메인테이너의 판단이 필요한 지점

기본(운영자 허용 없는) 애매한 reset 거부를 모든 목적지에 둘지, OpenCode Go만 다시 예외를 줄지. 운영자 허용 재전송 뒤 거부를 transient 5xx에만 둘지, 408·409·프로바이더 429까지 넓힐지. structuredClone 비용을 그대로 받아들일지. scoped quota에서 project 한도 같은-workspace 전환을 계속 허용할지.

너의 추천

방향은 맞고, 중복 전송·compaction 신원·같은 workspace 무의미 전환을 막는 쪽에 힘이 있습니다. draft를 유지한 채 (1) 호스트 CI 풀스위트가 초록인지 확인하고, (2) reset 거부 기본값·5xx-only 범위를 메인테이너가 한 줄로 확정하고, (3) 이미 닫힌 #5446·#5423·#5415는 이 PR로 대체된 것으로 두고, (4) 보안 체크리스트를 채운 뒤 ready로 올리면 됩니다. 미리보기 배포 이야기는 이 PR과 무관합니다.

이 댓글은 grok-bot이 작성했습니다

@lidge-jun

Copy link
Copy Markdown
Owner

Partial landing note: the reset-replacement commits carried from #5423 landed on dev in #5575 (b7351ddef3), widened. After a spent replacement, every resend-inducing status (307, 308, 401, 402, 408, 409, 413, 429 and every 5xx) settles as the refusal, other errors are marked non-replayable, and the refusal matcher uses the full sentence.

Still only in this PR: the OpenCode Go ambiguous-reset refusal; policy retry body snapshot isolation; compaction policy state and source-selection fixes; scoped quota suppression binding; compact abort cleanup; the cold-spawn warm-up bound; the passthrough-dispatch.ts change; and the moved scoped-quota tests. Rebasing onto dev will conflict in upstream-retry.ts, errors.ts and upstream-retry.test.ts. Take dev's version of those.

…nded-error-recovery

# Conflicts:
#	src/lib/errors.ts
#	src/lib/upstream-retry.ts
#	tests/lib/upstream-retry.test.ts
A caller combining reportUtf8Validity with fatalUtf8 got no utf8Valid field
for a valid body at EOF, breaking the BoundedBodyResult contract. The
reporting branch now runs whenever reporting is requested: a successful fatal
decode already proved validity, while malformed input still throws.

(cherry picked from commit f7f5b4b)
Carry only the Kiro adapter, stream, and regression paths from the source.
Keep request cancellation attached while reading fallback failures through
the shared bounded display-safe reader. Fernet expansion and Claude skill
marker changes from the same source are deliberately not included here.

(cherry picked from commit fe13531)
@luvs01 luvs01 changed the title fix(responses): consolidate retry, compaction and account boundaries fix(responses): consolidate bounded errors, retries and account recovery Sep 22, 2026
@lidge-jun

Copy link
Copy Markdown
Owner

Carried in #5608: fifteen commits are cherry-picked with their authors kept, plus a follow-up that makes the same-workspace one-send test exact. The changes from 35fb727 and 940b318 are already on dev through b7351dd (#5575). The four later commits at the new head are not carried here: #5307 is carried by #5600, and the Kiro part of #5310 is handled with #5310 itself. Closing as superseded. Thank you @luvs01.

@lidge-jun lidge-jun closed this Sep 22, 2026
lidge-jun added a commit that referenced this pull request Sep 22, 2026
…etry metadata

Carries the #5307-related part of cc466ed, which the author added after consolidating #5307 into #5553: a malformed 502 cyber-policy body that was marked non-replayable must keep the marker, carry no Retry-After or quota reset, and still stop the combo. Document the malformed-body contract in the responses structure doc, matching the narrower classification gate this branch implements.

Follow-up to #5307 (via #5553).

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
lidge-jun added a commit that referenced this pull request Sep 23, 2026
…top, reauth unknown_flow, Raycast probe, pool golden, no-renames) (#5600)

* docs: harden branch content classification against renames

* docs: date the no-renames correction and align sibling commands

* test(oauth): exercise configured generic pool validators

* test(oauth): prove the generic null-strategy clear and harden test teardown

* test(oauth): require the strategy property in the cleared response

* fix(integrations): harden Raycast defaults probe

* test(integrations): cover killed defaults probe in Raycast detection

* fix(reauth): stop polling terminal unknown flows

* fix(qoder): preserve offsets in scaffold scanning

* fix(responses): keep a cyber-policy stop when a 5xx body has malformed UTF-8

consumeComboFailure read 5xx bodies with fatalUtf8, so a single malformed
byte rejected the whole read and replaced an otherwise recognizable
cyber-policy refusal with "Provider error <status>". The combo then hopped
instead of stopping.

readBoundedResponseBody gains reportUtf8Validity: it decodes with
replacement characters and reports utf8Valid at EOF (true by construction
when fatalUtf8 is also set). consumeComboFailure keeps every existing trust
rule for malformed 5xx bodies -- no quota evidence, usage, or ordinary
classification -- and only lets the lenient decode through when it
identifies a cyber-policy refusal. The quota agreement with
shouldRetryCodexPoolAccountQuota is unchanged.

Reimplements #5307 with a narrower classification gate.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs: separate the campaign command from the corrected rerun command

The branch and PR classification summaries showed the --no-renames form as though the campaign had used it. State the command that produced the recorded verdicts and the form any rerun must use, matching the correction in 010_method.md.

Follow-up to #5461.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(oauth): restore the pool-validator home even when shutdown throws

A throwing server.stop skipped the OPENCODEX_HOME restore and temp-dir removal, leaking both into later cases. Run cleanup in an inner finally.

Follow-up to #5442.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(integrations): model a killed defaults probe with a type-safe result

The timeout case cast a result with exitCode null directly to typeof Bun.spawnSync, which strict TypeScript can reject, and its empty stdout could not tell an exit-code check from an empty read. Cast through unknown, cover null and non-zero exits, and return "1" on stdout so ignoring the exit code would visibly report Pro.

Follow-up to #5244.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(structure): record the terminal unknown_flow GET in the reauth contract

The dashboard contract said a non-2xx GET keeps cancellation ownership and polling, and that no replacement login POST can appear before DELETE settles. A GET 404 unknown_flow now ends the flow the same way the DELETE path does, so qualify both statements as applying to retryable GET errors and state the exception in the overview.

Follow-up to #5428.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(qoder): keep single-unit Unicode case folding in scaffold scanning

Matching markers with ASCII-only folding kept offsets correct but dropped matches the lowercased scan used to make: U+212A KELVIN SIGN lowercases to an ASCII k, so <invo\u212Ae> tool markup passed through unsuppressed, whole or split across deltas. Fold each code unit as toLowerCase() does when the result is a single code unit; characters that expand, such as U+0130, still cannot shift offsets.

Follow-up to #5366.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(pr-assets): add the reauth unknown_flow GET before/after capture

Main-account card rendered with the dev hook and the branch hook against a mocked management API (Cancel DELETE 503, then GET 404 unknown_flow). Synthetic identity only.

Follow-up to #5428.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(responses): keep a non-replayable malformed cyber stop free of retry metadata

Carries the #5307-related part of cc466ed, which the author added after consolidating #5307 into #5553: a malformed 502 cyber-policy body that was marked non-replayable must keep the marker, carry no Retry-After or quota reset, and still stop the combo. Document the malformed-body contract in the responses structure doc, matching the narrower classification gate this branch implements.

Follow-up to #5307 (via #5553).

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

---------

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
lidge-jun added a commit that referenced this pull request Sep 23, 2026
…y work (#5608)

* docs(devlog): plan the L5 luvs01 Responses and usage bundle

Record the disposition, provenance and ordered carry recipe for #5474, #5305, #5434, #5560, #5542, #5553, #5562 and #5556.

* fix(usage): verify OAuth rotation before withheld attribution

(cherry picked from commit 1ac1ba0)

* test(oauth): cover the eligible-target positive case and gate assertion

(cherry picked from commit f6778bf)

* fix(oauth): require a live two-account roster before withheld attribution

The eligibility probe added for #5434 could report an alternate when the failed account had been removed and one stored account remained, because it skipped the roster-size guard that rotation applies. Read the roster once, apply the same guard, and describe the probe as applying no cooldown rather than as non-mutating.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(adapters): close Grok continuation and normalized tool catalog gaps

Keep the existing request shape, scope external Cursor continuations to the
current user request, repair ctc_ ids for xAI, and rebuild a full replay when
a checkpoint no longer fits the envelope. Invalid or unreadable inputs fail
closed to the previous safe default with debug diagnostics.

This is the net change of two source commits. Their empty-catalog selector
edit to src/adapters/xai-web-search.ts is omitted because dev already carries
that rule (b20acc7, #5376), and the temporary test additions to capped files
are replaced by the final extracted test files.

(cherry picked from commit 71a9fe5)
(cherry picked from commit ffd50f4)
Refs #5350, #5560

* fix(cursor): preserve continuation scope and avoid false repetition recovery

(cherry picked from commit 5a99d4d)
(cherry picked from commit 31f21f0)

* fix(responses): lower undeclared historical custom tools when the destination denies them

Routed lowering collected only current custom declarations, so a compacted or replayed custom_tool_call leaked to xAI-like gateways as the native item type and came back as a misleading 422 missing id. Convert protocol-history items from the top-level input without expanding the live catalog, request full replay for orphan results, and fail closed before serializing leftovers.

Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 5da2883)
(cherry picked from commit a326b67)

* test(responses): split historical custom-tool replay coverage off the passthrough ratchet cap

openai-responses-passthrough.test.ts is already at its 4809-line ceiling. Keep the new wire fixtures in a responses-prefixed file so the layout seed resolves it without raising a cap.

Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 6f43794)
(cherry picked from commit 7e8fb09)

* fix(responses): reject malformed historical custom calls

(cherry picked from commit 52f7448)
(cherry picked from commit 57407be)

* fix(responses): bind historical outputs to custom calls

(cherry picked from commit 5654b41)
(cherry picked from commit c7781bf)

* fix(responses): reject duplicate historical call ids

(cherry picked from commit dc948dc)
(cherry picked from commit fbecefa)

* fix(xai): preserve stateful tool output continuations

(cherry picked from commit 4edc411)
(cherry picked from commit 82a5f6d)

* fix(xai): keep replay-miss reasoning cleanup independent of output repair

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 67ccd8d)
(cherry picked from commit aac783f)

* test(responses): verify combined continuation boundaries

Exercise stateful output-only deltas, independent replay-miss reasoning cleanup,
capability-driven historical lowering, placeholder ordering, native item-ID
repair and preservation of the existing empty-catalog denial. Record the
combined history contract and register the carried and new regression files.

The layout-marker cleanup from e8e179f was
completed while resolving its preceding source commit onto the current map.
The existing dev selector normalization and role-fixture corrections remain
authoritative and are not replaced by weaker or duplicate source changes.

Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>
Co-authored-by: maosisheng <maosisheng@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Epinephrine <luvs01@hanmail.net>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 2ec0cd1)

* fix(responses): normalize wrapped MCP tool names

(cherry picked from commit b4c839b)
(cherry picked from commit f68b32646069d3e385748fc6c36848765c68e02e)
(cherry picked from commit e555e73)

* fix(responses): unwrap default apply patch aliases

(cherry picked from commit 453df76)
(cherry picked from commit d63ff542415895fa25f5599aad9dc632c80de92d)
(cherry picked from commit 7cbbf44)

* docs(structure): record default.-prefixed alias recovery in the freeform contract

The responses owners still claimed only bare exec/apply_patch calls accept alternate-field or outer-fence recovery; compileCodeModeHelperInput now also unwraps provider-invented default. aliases. Update runtime.md, transports/responses.md, providers/{chat-compat,kiro,xai-grok}.md.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 165ddd0)
(cherry picked from commit d0776e703681729e2ea447775e77397faab16f29)
(cherry picked from commit 19a2005)

* fix(responses): compile structured shell payloads sent to code-mode exec

(cherry picked from commit 9430bbd)
(cherry picked from commit 59bc70bc30f954eea5a63f8a6fcf4de4dcbfd865)
(cherry picked from commit 9662528)

* test(responses): verify combined tool normalization boundaries

Verify that default.apply_patch names and patch/content wrappers emit the same executable input through JSON and fragmented SSE. Move the carried decision record to unused ADR-0099 because current dev already owns ADR-0097; preserve both the structured code-mode shell and existing schema-bound flat-shell contracts.

Co-authored-by: kosta <kosta963@gmail.com>
Co-authored-by: Flowershangfromthebranches <152056395+Flowershangfromthebranches@users.noreply.github.com>
(cherry picked from commit 3da6366a60ac5964e8a8de43486125d72729f8c8)
(cherry picked from commit b57d7c5)

* fix(responses): refuse ambiguous OpenCode Go resets

(cherry picked from commit 62ac159)
(cherry picked from commit b8f9a45)

* test(responses): prove OpenCode Go pre-answer reset refusal by execution

Per review on #5446: replace the replaySafe source-string count with an execution test that drops the connection before the answer on an opencode.ai/zen/go destination and asserts the 429 upstream_reset_replay_refused with exactly one send.

(cherry picked from commit 92b74ec)
(cherry picked from commit 808dd85)

* fix(routing): isolate policy retry body snapshot

(cherry picked from commit 8e2a0fe)
(cherry picked from commit db854bf)

* test(routing): pin the retry snapshot against nested input mutation

(cherry picked from commit a240fc9)
(cherry picked from commit b037810)

* fix(responses): isolate policy compaction state

(cherry picked from commit 714119e)
(cherry picked from commit e6f9339)

* fix(tests): bound the cold-spawn warm-up child on a live event loop

The warm-up child was waited on through Bun.spawnSync, which made the spawn's
own timeout the only bound it could honour — and no bound at all when the
child or the primitive wedged: while a synchronous spawn blocks, the event
loop is dead, so the hook budget and the per-test timeout freeze inside the
same wait and nothing reports anything. Run 35511743422's macos 2/2 leg held
that shape for eighteen silent minutes inside client-connect.test.ts before
the job ceiling cut it and reported cancelled, which the ci gate reads as
failure.

The bound now lives on the parent's live loop: an asynchronous spawn, SIGKILL
at the existing derived deadline, a short reap grace, and the call settles
with or without the child's exit or EOF — so a descendant holding the pipes
or a child that outlives its kill cannot turn a warm-up into an unbounded
wait. A timed-out child now fails the warm-up by name instead of hanging the
job.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit aa9b889)
(cherry picked from commit f86a534)

* fix(responses): fail closed on synthetic or stale compaction source selectors

compactionRoutingKeepsProviderIdentity evaluated override.sourceModel as the
raw client selector, so a synthetic --fast/--effort form of a policy or combo
selector (ocx/primary--fast) missed resolvePolicyProfileId/resolveComboId and
fell through routeConcreteModel to the default provider. The same fallthrough
swallowed policy aliases renamed or deleted mid-conversation, since
config.routingProfiles is mutated in place. Both cases could wrongly report
identity match and let provider-private compaction state or caller credentials
cross a backend boundary.

Strip synthetic-row suffixes via parseSyntheticRowId before the identity
checks, and treat a source that only routes through the default provider as
unproven: it can never match a concrete identity.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 7e59315)
(cherry picked from commit 76b40f9)

* fix(codex): bind scoped quota suppression to alternate

(cherry picked from commit 23a3694)
(cherry picked from commit 385f338)

* fix(ci): restore core.ts to file-size ratchet cap

The scoped-quota re-export grew src/server/responses/core.ts past its committed 210-line cap (213). Collapse the two-name re-export back to one line; the file's export list already carries longer single-line statements.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 559db16)
(cherry picked from commit feb0c16)

* fix(codex): record wrapped quota on suppressed moves and bind caller main

- record the normalized 429/402 outcome before returning no-alternate on a
  suppressed same-workspace move, so a 5xx-wrapped quota refusal still cools
  the refused account instead of reading as transient
- bind a request-owned `main` alternate by the caller credential's own
  workspace id (chatgpt-account-id header, else the bearer token's account
  claim) via callerCodexWorkspaceAccountId
- apply the same scoped-quota workspace gate to the single bounded alternate
  send in the native /responses/compact path
- cover all three in tests and update the transport doc

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 5267593)
(cherry picked from commit 466c75c)

* test(server): move scoped-quota auth cases into a sibling file under the size cap

server-auth.test.ts grew to 4684 against a 4589 baseline cap, so the
file-size ratchet failed shard 3/4. The three scoped-quota suppression
cases move byte-for-byte into server-auth-scoped-quota.test.ts, and the
pool-retry harness they share is extracted to
tests/helpers/pool-retry-harness.ts (per-run OPENCODEX_HOME dir, so each
importing file keeps its own module state under bun test --isolate).

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit b391c99)
(cherry picked from commit 9050722)

* fix(codex): re-check abort after the scoped-quota body read

The workspace classification in shouldRetryCodexScopedQuotaOnAlternate
reads the first response body asynchronously, so a client disconnect can
land after the earlier abort check but before the branch records the
first account, cancels its body, and sends the alternate. Re-check the
abort signal immediately after the await in both paths: compact returns
the 499 client_cancelled response after releasing the alternate lease,
and the regular path releases its permit and lease and returns
no-alternate while still recording the first account's real outcome.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit c52b64b)
(cherry picked from commit b2eda92)

* fix(codex): release the discarded compact rejection body on abort

The 499 exits around the scoped-quota classification return a fresh
response while the first rejection's body is still open; cancel it so
the abandoned upstream connection and tee resources are released.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 813efcc)
(cherry picked from commit 1069b54)

* fix(codex): keep compact abort cleanup off the return path

upstream.body.cancel() can wait on a custom or stalled source; awaiting
it at the abort checkpoints would park the 499 reply on cleanup. Fire
it with the request's abort reason and swallow rejection, the same
best-effort shape bufferCompactResponse already uses.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 2d1ee69)
(cherry picked from commit 37a006e)

* test(responses): preserve terminal refusal across recovery boundaries

Exercise both operator-granted and default-denied reset paths through policy fallback and the alternate-account eligibility gate. Clarify that retries serialize the original body snapshot while identity metadata is established per attempt, and document synthetic compaction identity and transient replacement refusal.

(cherry picked from commit be1fee9)

* test(cursor): pin exact host-wrapper classification in continuation scope

The wire carries no provenance for compaction summaries or ambient browser state, and the Codex client detects stored summaries by the same exact prefix. Pin that a user message that is itself an exact wrapper stays in history while the preceding real request remains the labeled one, and document the rule next to the continuation contract.

Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>

* test(server): prove a suppressed same-workspace alternate is never sent

Both credentials in the 5xx-wrapped scoped-quota case carry the same workspace header, so a negative check on the other account id could not fail. Assert the exact one-send sequence, and narrow the transport contract: suppression covers the in-request move, while later requests still select by per-account health.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(devlog): record the L5 responses sequence outcome

* docs(devlog): amend the L5 search and usage plan after review

* fix(responses): isolate Cursor combo shadow calls

(cherry picked from commit 3e5a4dd)
(cherry picked from commit 7f45883)

* fix(responses): repair terminal-less bridged search legs

(cherry picked from commit 1fb6005)
(cherry picked from commit c4fa8c8)

* fix(responses): repair continuation legs and prove behavior in tests

(cherry picked from commit 3948970)
(cherry picked from commit 8d46989)

* fix(responses): close shadow combo intersection and continuation coverage

Apply the existing source-target non-intersection rule before early combo interception, and add production-path behavioral coverage for terminal-less continuation repair.

(cherry picked from commit 4bfcc0a)
(cherry picked from commit 3f3fdf1)

* test(web-search): preserve complete but open bridge-leg coverage

Carry the end-to-end handleResponses regression and transport contracts for repairing both the first and continuation search legs. The corresponding production changes are already preserved by the earlier terminal-repair carries; keep this broader integration coverage without applying that implementation twice.

Source commit: b1044e7
Co-authored-by: Epinephrine <luvs01@hanmail.net>

(cherry picked from commit 973a4ac)

* test(web-search): keep repaired replay within caller and serving scope

(cherry picked from commit bb49c9f)

* test(server): reap fixture ACL workers before removing failover homes

(cherry picked from commit ae52669)

* fix(responses): keep combo shadow interception on the dispatch pick

The carried early intersection check sampled a combo target with routeModel before dispatch. The combo loop then picked again, so the interception decision could follow a different target than the one sent, and a random or round-robin combo advanced its selection state for a probe. Restore the existing combo rule (a shadow call rewritten to a combo enters the combo) and its regression test, and keep the combo-child isolation marker.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(web-search): bind repaired-leg replay to a keyed caller principal

The repaired-leg replay assertion expected a shared keyless loopback principal, which the replay cache refuses by design: keyless loopback callers get no retained replay. Configure an inbound API key, derive the expected principal with the production resolver, pass the full loopback admission, and assert that a keyless caller cannot form a scope.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(usage): restrict legacy -main provider collapse to Codex labels

A -main suffix was stripped from ANY provider name, so a configured provider like openrouter-main silently merged into openrouter in usage summaries and pricing fallback. Restrict the compatibility mapping to the known Codex provider labels (openai/chatgpt/openai-multi-main), matching codexAccountProviders.

(cherry picked from commit 89a9272)
(cherry picked from commit 0f0ef96)

* fix(cli): mark access-key usage unavailable when attribution is absent

Without attributionSince the server is reporting an empty or unreadable usage log, but the table still rendered 0 totals and never-used markers that are indistinguishable from real data. Show an unavailable marker spanning the usage columns instead, matching the ambiguous-union precedent.

(cherry picked from commit 3c3f14b)
(cherry picked from commit 83514c3)

* fix(cli): treat a malformed attributionSince as unavailable

typeof === 'string' accepted any value, so a malformed attributionSince made
usageAvailable true and printed usage cells plus an 'attribution since'
footer. Parse once, derive availability from the validated result, and reuse
it for the footer. Covers the malformed-string regression.

(cherry picked from commit e7584c3)
(cherry picked from commit 1380693)

* fix(gui): keep the app-server status read alive across Models tab switches

(cherry picked from commit 9e6870d)
(cherry picked from commit 5563577)

* fix(usage): bound persisted requestedModel selectors

Selectors are not length-bound at admission, so persist over-long values as a bounded prefix + sha256 digest of the full selector and encode the request-history requested_model filter input identically. Two selectors sharing the bounded prefix stay distinguishable instead of colliding on a truncated prefix.

(cherry picked from commit e3d0f9b)
(cherry picked from commit c8a9d1a)

* fix(spend): enforce ceilings on native chat sends

(cherry picked from commit 347204f)
(cherry picked from commit 823a7d2)

* fix(usage): preserve observation and native reservation boundaries

(cherry picked from commit 22ee516)

* test(usage): isolate native spend regressions within file caps

(cherry picked from commit 1a8d5f7)

* test(usage): drain fixture owners before removing Windows homes

(cherry picked from commit 2241d03)

* test(usage): batch canonical pagination fixture writes

(cherry picked from commit ddfef13)

* fix(cli): accept only an ISO-8601 UTC attributionSince

Date.parse accepts strings such as "0" and rolls impossible dates over, so a malformed attributionSince could still switch the key table to numeric usage and never-used cells. Require the ISO-8601 UTC shape the server emits and an instant that round-trips to the same second.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(usage): state the aliasing limit of the idempotent selector encoding

Encoded requestedModel values must map to themselves because rows are normalized again on read, so a literal selector equal to another selector's persisted form shares its identity. Say so where the encoding is defined, and pin the behavior in the request-history test so the limit is deliberate rather than silent.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(devlog): record the L5 search and usage outcome

* docs(devlog): record the L5 pull request

* docs(structure): keep runtime.md within its 600-line budget

The default.-prefixed freeform wording wrapped one extra line and pushed structure/runtime.md over the structure SSOT budget. Reflow the paragraph; the wording is unchanged.

* refactor(cursor): move current-request selection out of protobuf-request

The carried continuation-scope helpers brought src/adapters/cursor/protobuf-request.ts to 2,000 lines, the file-size threshold for files without a recorded cap. Move the current-request selection and its host-wrapper classification to a sibling module unchanged; the caller passes its text extractor.

Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>

* docs(devlog): record the #5553 re-pin in the L5 plan

* docs(devlog): record the L5 original closures

* fix(usage): keep the native Chat spend estimate out of recorded usage

The native Chat spend reservation reused usageLogInputTokens for its input estimate. That field also feeds attempt usage, so native Chat attempts started recording an estimate-inflated input instead of the provider-reported counts (hosted CI: server-xai-oauth-401-replay and server-key-failover-e2e). Reserve the estimate through a spend-only spendInputEstimateTokens field; the reservation still charges it before each physical send.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(server): identify the suppressed alternate by its credential

Hosted CI showed the send layer retrying the refused account's transient 502 on the same credential, so an exact one-dispatch count was the wrong oracle. Both accounts share a workspace header; record the credential each physical send presents and assert the suppressed alternate's credential never appears.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix: close L5 retry, continuation, and history review gaps

Classify spend refusals on transient retry legs, keep Cursor retry provenance in checkpoint actions, and rebuild legacy history selectors into the bounded projection. Scope policy snapshots and correct warm-up deadline handling, with focused regressions and documentation.

* fix: retain policy fallback for decorated selectors

Normalize supported Fast and effort policy selectors before snapshot gating, restore a real policy-hop fixture, and align Cursor wire assertions with retry provenance guidance.

---------

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>
Co-authored-by: twoimo <twoimo@twoimoui-MacBookPro.local>
Co-authored-by: maosisheng <maosisheng@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Epinephrine <luvs01@hanmail.net>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: kosta <kosta963@gmail.com>
Co-authored-by: Flowershangfromthebranches <152056395+Flowershangfromthebranches@users.noreply.github.com>
Dylan-Liew pushed a commit to Dylan-Liew/opencodex that referenced this pull request Sep 23, 2026
…top, reauth unknown_flow, Raycast probe, pool golden, no-renames) (lidge-jun#5600)

* docs: harden branch content classification against renames

* docs: date the no-renames correction and align sibling commands

* test(oauth): exercise configured generic pool validators

* test(oauth): prove the generic null-strategy clear and harden test teardown

* test(oauth): require the strategy property in the cleared response

* fix(integrations): harden Raycast defaults probe

* test(integrations): cover killed defaults probe in Raycast detection

* fix(reauth): stop polling terminal unknown flows

* fix(qoder): preserve offsets in scaffold scanning

* fix(responses): keep a cyber-policy stop when a 5xx body has malformed UTF-8

consumeComboFailure read 5xx bodies with fatalUtf8, so a single malformed
byte rejected the whole read and replaced an otherwise recognizable
cyber-policy refusal with "Provider error <status>". The combo then hopped
instead of stopping.

readBoundedResponseBody gains reportUtf8Validity: it decodes with
replacement characters and reports utf8Valid at EOF (true by construction
when fatalUtf8 is also set). consumeComboFailure keeps every existing trust
rule for malformed 5xx bodies -- no quota evidence, usage, or ordinary
classification -- and only lets the lenient decode through when it
identifies a cyber-policy refusal. The quota agreement with
shouldRetryCodexPoolAccountQuota is unchanged.

Reimplements lidge-jun#5307 with a narrower classification gate.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs: separate the campaign command from the corrected rerun command

The branch and PR classification summaries showed the --no-renames form as though the campaign had used it. State the command that produced the recorded verdicts and the form any rerun must use, matching the correction in 010_method.md.

Follow-up to lidge-jun#5461.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(oauth): restore the pool-validator home even when shutdown throws

A throwing server.stop skipped the OPENCODEX_HOME restore and temp-dir removal, leaking both into later cases. Run cleanup in an inner finally.

Follow-up to lidge-jun#5442.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(integrations): model a killed defaults probe with a type-safe result

The timeout case cast a result with exitCode null directly to typeof Bun.spawnSync, which strict TypeScript can reject, and its empty stdout could not tell an exit-code check from an empty read. Cast through unknown, cover null and non-zero exits, and return "1" on stdout so ignoring the exit code would visibly report Pro.

Follow-up to lidge-jun#5244.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(structure): record the terminal unknown_flow GET in the reauth contract

The dashboard contract said a non-2xx GET keeps cancellation ownership and polling, and that no replacement login POST can appear before DELETE settles. A GET 404 unknown_flow now ends the flow the same way the DELETE path does, so qualify both statements as applying to retryable GET errors and state the exception in the overview.

Follow-up to lidge-jun#5428.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(qoder): keep single-unit Unicode case folding in scaffold scanning

Matching markers with ASCII-only folding kept offsets correct but dropped matches the lowercased scan used to make: U+212A KELVIN SIGN lowercases to an ASCII k, so <invo\u212Ae> tool markup passed through unsuppressed, whole or split across deltas. Fold each code unit as toLowerCase() does when the result is a single code unit; characters that expand, such as U+0130, still cannot shift offsets.

Follow-up to lidge-jun#5366.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(pr-assets): add the reauth unknown_flow GET before/after capture

Main-account card rendered with the dev hook and the branch hook against a mocked management API (Cancel DELETE 503, then GET 404 unknown_flow). Synthetic identity only.

Follow-up to lidge-jun#5428.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(responses): keep a non-replayable malformed cyber stop free of retry metadata

Carries the lidge-jun#5307-related part of cc466ed, which the author added after consolidating lidge-jun#5307 into lidge-jun#5553: a malformed 502 cyber-policy body that was marked non-replayable must keep the marker, carry no Retry-After or quota reset, and still stop the combo. Document the malformed-body contract in the responses structure doc, matching the narrower classification gate this branch implements.

Follow-up to lidge-jun#5307 (via lidge-jun#5553).

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

---------

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
(cherry picked from commit f7b06bd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants