Files
gstack/test/fixtures/eng-initial-selector-043a.json
T
Garry TanandOpenAI Codex 636175d349 v1.87.6.0 fix: make checks reliable and everyday validation faster (#2898)
* fix: acknowledge seeded plans before invoking review skills

* fix: distinguish current plan input from conversation history

* fix: keep hermetic plan reviews on manual permissions

* fix: distinguish tool discovery from file permission ownership

* fix: preserve initial plan mode in observation tests

* fix: wait for scope decisions before writing review findings

* fix: carry autoplan decisions consistently into review artifacts

* test: retain native failure context in periodic assertions

* fix: advance active file permissions before queued questions

* fix: finish red-team attempts before retry and cleanup

* fix: finalize plan format captures and judges before retry

* fix: cancel setup-gbrain SDK attempts before fixture cleanup

* test: select periodic consumers of the bounded attempt helper

* fix native Bash permission cards and queued questions

* fix: preserve independent decisions and review scope

Keep CEO approach, engineering scope and outside-review choices from approving independent remedies together. Carry declared contracts through DX polish and resolve new gaps before editing the plan. Regenerate every host and retain existing stop boundaries.

Validation: 654 focused tests passed across nine files; all-host generation passed. Full free and periodic validation pending.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: require approval before design plan amendments

Align the Design review philosophy and rating recipe with its section protocol: resolve one proposed fix, then apply only that approved decision and retain honest scores for declined fixes.

Validation: 469 focused tests passed across four files; all-host generation passed.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: observe native question completion before transcript persistence

Match owned completion hooks to submitted choices, reject conflicting or late answers, and retain bounded failure evidence.

* test: recognize review posture in acknowledged native questions

Require the selected mode acknowledgement, a completed follow-up question, and its current decoded display while preserving existing posture assertions.

* fix: preserve settled CEO choices and isolate pending remedies

Resolve established approach gates with cited authority and keep independent fixes out of unrelated option commitments and plan amendments.

* fix: carry approved DX choices through later review steps

Choose documentation approaches within the accepted scope and map resolved confusion points without reopening them through a bulk menu.

* test: handle native settings-file edit prompts

Keep one-time owned-file approvals and retain the actual sampled Autoplan permission frame with its matching barrier state.

* test: accept standard CEO reply directives with tuning footers

Recognize the exact trailing preference footer and letter-list directive while preserving current-display and exact acknowledgement checks.

* test: scope split reviewers to their generated plan artifacts

* test: observe native Bash permissions and invocation results

* test: handle owned Bash prompts during mode preference checks

* test: preserve synchronous subprocess rejection in Codex fixture

* Fix periodic review handoff navigation

Recognize review-first and explicit manual-next-step labels while preserving exact action families, manual preference, and ambiguous-menu rejection.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Bind pending file permissions to distinct current targets

Allow one captured file request to own the complete current dialog while unrelated file work is pending. Preserve same-path ambiguity, exact input ownership, and one-time grant checks.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Make paired CEO verification choices genuinely unresolved

Start the positive control with proposed manual checks so its unchanged oracle measures two new coverage decisions. Preserve runtime contracts, targets, count bounds, and all assertions.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep CEO review options and verification within approved scope

Audit every offered option for independent add-ons and keep new verification depth pending until accepted. Preserve already requested coverage and trace plan changes to the actual decision.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Assemble DX review artifacts before appending the final report

Keep early DX evidence above decisions, update artifact sections in place, and append the report using the actual current file suffix. Re-read after deleting an existing report before choosing the append anchor.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep outside plan reviews exclusive and invocation-owned

Follow one preflight-selected backend, terminate failed Codex work before fallback, and allocate extra prompt/output files uniquely. Consume only the current invocation’s completed output.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Select periodic completion evaluations for report writer changes

Register the shared review resolver for eight missing consumers and regress selection for all nine completion cases without changing their IDs or tiers.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep permission ambiguity fixtures on the same normalized target

Use distinct raw spellings of one target in the four negative fixtures so they exercise the normalized duplicate-owner guard after exact current-file disambiguation. Preserve the existing exception, no-input, diagnostic and cleanup assertions.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Clarify preserved contracts in engineering review fixture

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Recognize the offered DX follow-up handoff

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Check independent commitments before presenting review options

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep Codex review output and status in one shell invocation

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Distinguish seeded plans from reports written by a test attempt

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Recover clipped Autoplan file approvals with bounded viewport resizing

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Recover clipped Bash approvals before binding the complete command

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Isolate setup message tests from the shared checkout

Run the real installer in a temporary payload with private config, require successful completion, and guard source and binary contents and mtimes.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Fix periodic native permission and report completion handling

Match the pinned CLI's soft wraps and clipped headings without granting from incomplete frames. Retire completed file requests, retain mode annotations, and ask section captures for a short final acknowledgement after their full report is saved.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Preserve review approvals and validate DX comparison artifacts

Keep independent remedies and approved amendments explicit. Give the synthetic DX review its existing documentation and validate peer comparison as required analysis alongside four native decisions. Add positive and negative semantic calibrations while preserving review counts, model budgets and prompt size limits.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Make the five-finding CEO fixture's application boundary explicit

Materialize the request adapter and service composition used by the synthetic payment application. Explicitly declare the revised unregistered-event and mail-telemetry assumptions while preserving uncaught handler errors, the original invoice path and all five unresolved findings.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep CEO state-path checks scoped to directory preparation

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Use checked ports and bounded cleanup in pair-agent tests

Discover the daemon port from its owned state file, retain startup diagnostics, and await failed-start cleanup. Add occupied-port, early-exit, deadline, and foreign-state regressions while preserving the existing HTTP assertions and hook budgets.

Co-authored-by: Codex <noreply@openai.com>

* Preserve queued edit identity and recover clipped Bash permissions

Distinguish separately queued unfinished edits from mutation of one native tool ID. Keep grants bound to an exact owned request and reject reused IDs, ambiguous inputs, and competing owners.

Support the pinned renderer's literal em dash and request a repaint when only the Bash card's top rule is clipped. Grants still require the complete fresh card and an exact native acknowledgment.

Validation: 413 integrated parser/event tests passed; private repaint controls and joint source review passed. Full canonical suite and native periodic rerun remain pending.

Co-authored-by: Codex <noreply@openai.com>

* Keep periodic reviews within their approved contracts and deliverables

Carry exact approvals through engineering review, preserve declared contracts when amending CEO plans, and keep prioritization at the requested decision level. Materialize the revised synthetic SDK reference contract while retaining the five original documentation gaps.

Accept the observed semicolon in the finite DX handoff menu and register the direct source dependencies used by the engineering cases. Regenerate canonical review documents without changing model budgets, retries, count bands, or native completion assertions.

Validation: all-host generation and 275 review, fixture, selection and parity tests passed. Full free-suite and native periodic validation remain pending.

Co-authored-by: Codex <noreply@openai.com>

* Keep Eng approval cadence and independence guards explicit

* Accept ordinary punctuation in manual review handoffs

* Recover file permissions alongside queued Bash calls

* Carry approved DX work through later review findings

* Clarify the synthetic auth internal failure decision

* Bound the periodic DX fixture to onboarding changes

* Recognize native Design review handoff labels

* Hold scope in the integration-choice review fixture

* Carry approved Design decisions through review evidence

* Capture listener state when feedback reload fails

* Exclude workspace caches before checking deprecated flags

* Verify Design UI scope against a seeded review plan

* Clarify plan review decisions and outside-voice approval flow

* Reject setup menus in the Design UI gate

* docs: require focused repair validation before final acceptance

* fix: separate review commitments within existing prompt budgets

* docs: align generation and contributor validation guidance

* fix: advance native review prompts and count acknowledged findings

* chore: bump version and changelog (v1.87.1.0)

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* chore: enforce cheap checks and side-effect-free validation previews

* fix: handle owned Fetch permissions and oversized native cards

* test: ground review fixtures in independent executable contracts

* fix: preserve review decisions and verify reports before completion

* test: construct the synthetic credential URL without a scanner false positive

* test: materialize DX examples and verify their actual local behavior

* fix: clarify CEO review decisions and execution order

* fix: clarify review workflow ordering and select Design quality checks

* Fix review decision gates and incomplete evaluation fixtures

Persist CEO and engineering commitment ledgers before menus, preserve exact
approvals, and distinguish implementation structure from feature scope.
Route Autoplan through the canonical CEO Step 0 ordering. Classify DX findings
before requesting approval and ground runtime claims in actual evidence.

Complete neutral non-target fixture contracts and accept the captured Design
handoff purpose without relaxing its ownership or acknowledgment checks.
Record runtime-capability verification in AGENTS.md validation discipline.

Validation: 1,335 focused tests passed across 21 files; build, all-host freshness,
skill validation (647 artifacts / 107 tracked), and credential checks passed.
Prior paid failures are preserved; behavioral acceptance remains pending.

* Fix review decision boundaries and owned Read prompts

Preserve exact approvals across review options, compare consistent DX milestones,
and keep proposed implementation separate from review evidence. Bind modern
Read prompts to one immutable native request and wait for its result.

Retain captured regression verdicts, correct fixture error names, improve import
probe diagnostics, and record focused-first validation discipline in AGENTS.md.

* Clarify CEO and engineering review decisions

Use explicit decision steps, one engineering ledger, and clear scope/write transitions. Preserve exact approvals and distinguish pending test requirements. Keep unrelated generated content unchanged.

* Fix review decision ordering and native evaluation interactions

* Clarify engineering decisions and test artifact order

* Clarify pending choices and approvals in CEO reviews

* Make CEO review phases sequential and clarify completion

* Fix Design board submission intent matching

* Seed an existing browser test baseline for Autoplan

* Document decision-log payloads before state initialization

* Preserve exact review scope and decide one change before drafting options

* Require input identity before repeating passing model judges

* Honor permitted storage throughout CEO review completion

* Match complete native permission text within the pinned renderer contract

* Align review approvals, independent choices, and bounded validation

* fix: preserve reopened approvals and declare fixture interfaces

* fix: isolate review artifacts and audit complete questions

* fix: match detector artifact permissions to configured storage

* fix: complete native permissions and review fixture workflows

* fix: order CEO review work and separate engineering guarantees

* fix: preserve native validation and separate review choices

* fix: clarify review decisions and judge complete report context

* fix: constrain review judgments and retain parse failures

* fix: compare each affected value before review decisions

* fix: make engineering review decisions and completion order explicit

* fix: give the complete Autoplan evaluation a bounded chain budget

* fix(cso): diagnose forbidden Docker endpoints before tool lookup

* fix(reviews): reconcile workflow contracts and generated artifacts after main integration

* fix(evals): migrate retained regressions to the native review harness

* fix(tests): close native harness and workflow integration regressions

* fix(evals): preserve complete permission context and native menu contracts

* fix(tests): capture synchronous command output without pipe drain stalls

* fix(reviews): clarify decision and completion ordering

* fix(reviews): separate decision readiness from final completion checks

* refactor(reviews): consolidate decision rules and completion branches

* fix(plan-eng-review): order preparation and clarify decision routing

* fix(plan-eng-review): restore size and question-format guard parity

* fix(plan-eng-review): clarify scope phases and blocked completion

* fix(plan-eng-review): unify review flow and report destination

* fix(plan-eng-review): define bootstrap and question stage ownership

* fix(plan-eng-review): clarify review structure and design lookup

* fix(plan-eng-review): render report examples and show saved decisions

* fix: consolidate Eng review decisions and select their evaluations

* test: cover overlapping terminal attachments and clean merged runner type

* fix: preserve Office Hours relationship closings during review updates

* fix: retain pasted review targets across slash invocations

* docs: preserve validation traces and correct release scope

* test: cover pasted targets in both review skills

* fix: validate report artifacts before recording success

* fix: redact source roots at CSO report boundaries

* fix: bind native Design questions before answering

* test: select report privacy and native recovery regressions

* test: bind rejection predicate in extracted observers

* fix: bind complete boxed native questions

* test: keep the Design UI fixture on native review

* fix: preserve review decisions and evaluation completion outcomes

* fix: clarify CEO approval and report completion order

* fix: align native review evaluation ownership and completion

* fix: bind review evaluators to native decisions and owned artifacts

* fix: validate review decisions against native outcomes

* fix: preserve review evidence and Autoplan phase handoffs

* test: bind review evidence to owned decisions and completion

* fix: retain owned native history across compaction

* fix(evals): validate current review decisions and setup choices

* fix: bind Autoplan reviews and phase completion to current amended input

* fix: reconcile native review evidence and close Autoplan phases

* test: recognize owned whole-candidate complexity decisions

* test: preserve report freshness for approved investigation handoffs

* fix: recognize scoped review findings and isolate dual voice fixtures

* fix: make review handoffs and question dispatch self-contained

* test: recognize complete CEO decisions and procedural pauses

* fix: bind current CEO comparison options and risk intervals

* test: bind engineering decisions and completion to owned evidence

* fix: publish Autoplan phase reports before continuing tools

* test: verify actual Autoplan dual-review dispatch evidence

* test: select dual review when shared evidence fixtures change

* fix: clarify plan review decisions and completion gates

* fix: make CEO review decisions and return paths explicit

* test: keep Autoplan prompt files inside attempt state

* test: preserve source whitespace across permission dialog wraps

* fix: publish Autoplan phase reports before continuing

* test: recognize current CEO comparisons and reject inactive records

* fix: reconcile engineering decision states before completion

* test: recognize complete Design decisions and reports

* test: verify current engineering decisions before navigation

* Recognize source-owned component reduction choices

* fix: recognize current CEO ledger and commitment grids

* test: supply RequestPolicy context to Eng count fixture

* fix: save complete engineering decisions before asking

* fix: bind Autoplan publication to the complete phase readback

* chore: prepare 1.87.5.0 reliability release

* fix: clarify engineering review completion and preserve log failures

* fix: bind CEO saved choices and current section ancestry

* fix(evals): bind review execution and completion evidence

* fix(plan-ceo-review): verify complete decisions before asking

* fix(evals): preserve complete engineering choice records

* fix(evals): preserve complete review outcomes and bounded fixtures

* fix(autoplan): publish phase reports before advancing

* fix(plan-ceo-review): validate option fields before asking

* fix(plan-eng-review): verify current decisions after answers

* fix(evals): bind review decisions and bound fixture scope

* fix(plan-ceo-review): verify decision rows and edit saved checkpoints

* fix(evals): bind review evidence and scope document lookup

* fix(plan-eng-review): update resolution state with its answer

* fix(reviews): preserve complete questions through dispatch

* fix(evals): recognize completed mode declarations

* fix(evals): define cache consistency at wrapper completion

* fix(evals): validate owned initial scope and completed review handoffs

* fix: assemble complete CEO decision fields before saving

* fix: authenticate automatic mode decisions without guessing selectors

* fix: bind engineering coverage to approved regression contracts

* fix(evals): supply review helpers to native Eng capture

* fix(plan-eng-review): preserve the full selected option scope

* fix(evals): recognize owned engineering seed and regression evidence

* fix(evals): bind engineering retry reports to native approvals

* docs: clarify release guarantees (v1.87.5.0)

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix(evals): recognize owned engineering decisions and handoffs

* fix(evals): bind engineering decisions and completion evidence

* fix(tests): align review contracts and selection fixtures

* fix(skills): restore review prompt size limits

* fix(plan-eng-review): clarify review execution and completion

* fix(evals): preserve configured retries through all supervision layers

* Clarify Engineering decisions and report completion

* Keep native decision assertions within their source boundary

* fix: recognize owned engineering decisions and completed navigation

* fix: bind completed auto decisions to their current review

* fix: recognize explicit CEO source attribution

* fix: dispatch verified CEO decisions without recomposing fields

* test: expose existing execution deadlines to review actors

* fix: distinguish CEO decision records from incidental headings

* test: bind split-scope choices to the registered native actor

* test: connect reviewed regressions to required evaluation coverage

* Clarify CEO decision routing and completion stages

* test: expose existing section review deadlines to fixture actors

* test: recognize complete native CEO pacing inventories

* test: exclude answered history from current CEO payloads

* test: detect phase entry through owned skill HOME aliases

* test: validate native review completion and owned report permissions

* fix: make Autoplan close packets carry the parent handoff steps

* test: assess source-bound HOLD decisions within the existing deadline

* fix: keep CEO native decision fields under one formatting authority

* test: register integrated review and permission dependencies

* test: align native review adapters and finding coverage

Preserve explicit AUTO decisions, apply native single-select defaults, and bind complete cropped questions and report permissions to their owned requests. Require seeded review findings instead of crediting setup menus.

Keep captured failure controls and additive selection dependencies. The integrated candidate passed 3,099 focused tests across 65 files; affected paid validation remains required before publication.

* fix(autoplan): require phase reports before advancing

* fix(evals): bind setup and evidence to complete attempts

* fix(evals): bind native answers and pending writes to fixture scope

Preserve complete option rows when native descriptions wrap, retain current
owned Write arguments before journal publication, and keep engineering and
DX answers within their declared fixture interfaces. Add captured free
regressions without increasing model budgets or relaxing completion checks.

* fix(autoplan): verify phase reports across native tool paths

Guard owned methodology reads and reviewer dispatches, detect complete driver
loads through Bash, and distinguish report-only edits from implementation
changes. Follow authenticated native UUID ancestry when journal writes arrive
out of order and verify earlier native content for cached phase reads.

Keep current close acknowledgment and parent publication in order, require CEO
entry before later phases, and register captured failure regressions.

* fix(evals): honor native input and collection lifecycles

Match complete native Edit panes and truncated question borders, reject stderr close before EOF, and stop the CEO split fixture once its acknowledged scope decisions are collected. Keep semantic validation, process failures, report requirements, and absolute deadlines authoritative.

Add captured-event and real-process regressions with selection dependencies. Focused checks pass; final integrated paid and full-suite acceptance remain pending.

* fix(autoplan): retain native session ownership across directory changes

Recover missed native UUID ancestry through the existing strict graph while preserving ordinary event order and legacy scoping. Bind publication hooks to Claude's original project directory while retaining current cwd for requested file paths.

Captured public-event regressions, existing caller checks, and a pinned native CLI loopback verify both fixes. Preserve failed attempts and require fresh paid and final full-suite acceptance.

* docs: align evaluation limits and completion version

* fix(autoplan): allow authenticated phase reads during journal streaming

* fix(evals): bind clipped native questions and owned edit dialogs

* fix: preserve overlay retries and bounded cleanup

* fix: recognize owned planning preludes in native questions

* docs: explain overlay scheduling and cleanup guarantees

* fix: require fresh publication after Autoplan phase reruns

* Release gstack 1.87.6

* fix: preserve CI paths, process identity, and test deadlines

* fix: keep informational setup commands independent of install probes

* fix: clarify plan review decisions and bound source audit reports

* Fix remaining Windows identity and native path CI failures

* Clarify CEO review decision and reviewer-result routing

* test: accept no-install planner in retry supervision

* fix(ceo-review): make review decisions and report completion explicit

* perf(test): add fast PR gates, input-keyed judge reuse and isolated free shards

* fix(test): start isolated CEO smoke from its existing project plan

* fix(test): repair CI fixture races and preserve retry evidence

* fix(ceo-review): clarify approvals, depth and saved completion

---------

Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-09-22 14:57:52 -04:00

417 lines
162 KiB
JSON

{
"status": "ORIGINAL_FAILED_CAPTURE_WITH_EXPLICIT_COUNTERFACTUAL",
"transcript": {
"status": "ready",
"calls": [
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_013nxBar6nJkkrwwvxys8yRa",
"questions": [
{
"question": "D1 \u2014 Add gstack skill routing rules to this project's CLAUDE.md?\nProject/branch/task: main branch of the plan-review fixture repo, one-time gstack setup before the eng review of PLAN.md.\nELI10: gstack works best when your project's CLAUDE.md includes skill routing rules \u2014 a short table telling Claude which /skill to invoke for which kind of request (bugs \u2192 /investigate, architecture \u2192 /plan-eng-review, etc.). Without it you type skill names by hand each time. This is a setup question only; it approves nothing about the auth refactor plan.\nStakes if we pick wrong: Minor either way \u2014 missed auto-routing, or an extra section in CLAUDE.md you did not want. Plan mode is active, so any CLAUDE.md write and commit would happen after plan mode ends, not now.\nRecommendation: A because the routing table is small, boring, and saves a manual skill lookup on every future request.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: convenience of auto-routing vs. keeping CLAUDE.md exactly as it is.",
"header": "Routing",
"multiSelect": false,
"options": [
{
"label": "Add routing rules (recommended)",
"description": "\u2705 Future requests auto-route to the right gstack skill without you naming it\n\u2705 One small appended section, committed as a single chore commit (after plan mode)\n\u274c Adds ~20 lines to CLAUDE.md that you may consider noise in a fixture repo"
},
{
"label": "No thanks, invoke skills manually",
"description": "\u2705 CLAUDE.md stays untouched; no extra commit on this branch\n\u2705 You keep explicit control of when a skill runs\n\u274c routing_declined is set once per project; you re-enable via gstack-config later"
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D1 \u2014 Add gstack skill routing rules to this project's CLAUDE.md?\nProject/branch/task: main branch of the plan-review fixture repo, one-time gstack setup before the eng review of PLAN.md.\nELI10: gstack works best when your project's CLAUDE.md includes skill routing rules \u2014 a short table telling Claude which /skill to invoke for which kind of request (bugs \u2192 /investigate, architecture \u2192 /plan-eng-review, etc.). Without it you type skill names by hand each time. This is a setup question only; it approves nothing about the auth refactor plan.\nStakes if we pick wrong: Minor either way \u2014 missed auto-routing, or an extra section in CLAUDE.md you did not want. Plan mode is active, so any CLAUDE.md write and commit would happen after plan mode ends, not now.\nRecommendation: A because the routing table is small, boring, and saves a manual skill lookup on every future request.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: convenience of auto-routing vs. keeping CLAUDE.md exactly as it is.": "Add routing rules (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:49:40.799Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01Hkuby74WwZmUX8gPh6f3t6",
"questions": [
{
"question": "D2 \u2014 Let gstack search learnings from your other projects on this machine?\nProject/branch/task: main branch, one-time gstack setup before the eng review of PLAN.md (Multi-tenant Auth Refactor).\nELI10: gstack keeps a local notebook of lessons learned per project (pitfalls, command fixes, patterns). It can also read the notebooks of your OTHER projects on this machine to spot patterns that apply here. Nothing leaves your machine. This is a setup question; it approves nothing about the auth plan.\nStakes if we pick wrong: Enabled on a machine with multiple client codebases could surface one client's patterns while working on another. Disabled means this review only sees this project's (currently empty) learnings.\nRecommendation: A because this is a local, read-only search and the fixture repo has zero learnings of its own, so cross-project is the only source of prior signal.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: more prior context for reviews vs. strict per-project isolation.",
"header": "Learnings",
"multiSelect": false,
"options": [
{
"label": "Enable cross-project learnings (recommended)",
"description": "\u2705 Past pitfalls from other local projects can inform this and future reviews\n\u2705 Stays local; no network, no data leaves the machine\n\u274c On multi-client machines, patterns from one codebase can leak into advice for another"
},
{
"label": "Keep learnings project-scoped only",
"description": "\u2705 Strict isolation between codebases; nothing from other projects appears here\n\u2705 Safe default if you consult for multiple clients on this machine\n\u274c This project has zero learnings today, so the review starts cold"
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D2 \u2014 Let gstack search learnings from your other projects on this machine?\nProject/branch/task: main branch, one-time gstack setup before the eng review of PLAN.md (Multi-tenant Auth Refactor).\nELI10: gstack keeps a local notebook of lessons learned per project (pitfalls, command fixes, patterns). It can also read the notebooks of your OTHER projects on this machine to spot patterns that apply here. Nothing leaves your machine. This is a setup question; it approves nothing about the auth plan.\nStakes if we pick wrong: Enabled on a machine with multiple client codebases could surface one client's patterns while working on another. Disabled means this review only sees this project's (currently empty) learnings.\nRecommendation: A because this is a local, read-only search and the fixture repo has zero learnings of its own, so cross-project is the only source of prior signal.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: more prior context for reviews vs. strict per-project isolation.": "Enable cross-project learnings (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:50:52.966Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01MT7i67F7CtzDMFMFEGxNsh",
"questions": [
{
"question": "D3 \u2014 Keep the legacyAuthFlow() rewrite in this PR, or split it into a follow-up behind the new services?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\": a behavior-preserving reorganization that also rewrites legacyAuthFlow() (PLAN.md:36-37) with no regression test planned.\nELI10: The plan does two things at once: build five new auth classes, AND rewrite the old login path (legacyAuthFlow) that real tenants use today. Doing both in one change means if anything breaks for a tenant, you cannot tell whether the new classes or the rewrite caused it. A strangler split lands the new services first (old path untouched), then swaps the old path in a second small PR once the new services are proven in production. This question is scope only: what work is in this PR. Regression coverage for whatever is touched gets its own decision in Test review.\nStakes if we pick wrong: Bundled: a tenant login outage with a 12-file diff to bisect and no clean rollback point. Split: one extra PR and a short window where old and new paths coexist.\nRecommendation: B because the plan's own goal is \"no product behavior change\"; the rewrite is the single riskiest step and it gets cheaper and safer once the new services exist and are exercised.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: one big diff with one deploy vs. two smaller diffs with a clean rollback boundary between them.",
"header": "Scope",
"multiSelect": false,
"options": [
{
"label": "Split: defer rewrite to follow-up PR (recommended)",
"description": "\u2705 This PR becomes purely additive; legacyAuthFlow() keeps serving tenants unchanged, so rollback is \"stop calling the new services\"\n\u2705 Follow-up PR is a small, reviewable swap once AuthBroker/SessionMint have run in prod (human: ~1 day / CC: ~20 min)\n\u274c Two code paths coexist briefly; the follow-up must actually get scheduled or the old path lingers"
},
{
"label": "Bundle: rewrite legacyAuthFlow() in this PR",
"description": "\u2705 One deploy, no interim dual-path state, no follow-up to track\n\u2705 Matches the plan as written; no re-planning of file boundaries\n\u274c A tenant auth regression lands with a 12-file diff and the new classes as suspects; bisecting under incident pressure is slow"
},
{
"label": "Hold: discuss before deciding",
"description": "\u2705 Stops here so you can supply context I lack (deploy cadence, who owns legacyAuthFlow, release freeze dates)\n\u2705 No scope changes applied; the plan stays exactly as written\n\u274c Review cannot proceed to findings until this resolves"
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D3 \u2014 Keep the legacyAuthFlow() rewrite in this PR, or split it into a follow-up behind the new services?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\": a behavior-preserving reorganization that also rewrites legacyAuthFlow() (PLAN.md:36-37) with no regression test planned.\nELI10: The plan does two things at once: build five new auth classes, AND rewrite the old login path (legacyAuthFlow) that real tenants use today. Doing both in one change means if anything breaks for a tenant, you cannot tell whether the new classes or the rewrite caused it. A strangler split lands the new services first (old path untouched), then swaps the old path in a second small PR once the new services are proven in production. This question is scope only: what work is in this PR. Regression coverage for whatever is touched gets its own decision in Test review.\nStakes if we pick wrong: Bundled: a tenant login outage with a 12-file diff to bisect and no clean rollback point. Split: one extra PR and a short window where old and new paths coexist.\nRecommendation: B because the plan's own goal is \"no product behavior change\"; the rewrite is the single riskiest step and it gets cheaper and safer once the new services exist and are exercised.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: one big diff with one deploy vs. two smaller diffs with a clean rollback boundary between them.": "Split: defer rewrite to follow-up PR (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:51:47.113Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01WPZUtPv1ozdKpfozXg1MVA",
"questions": [
{
"question": "D4 \u2014 Class arrangement: keep all 5 new classes, or collapse to 3 (RequestPolicy as a pure function, TokenStore folded into AuthCache)?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; D3 already split the legacyAuthFlow() rewrite out, so this PR is the additive service layer only.\nELI10: The plan adds five classes (PLAN.md:44-45). Two look like classes for the sake of classes. RequestPolicy is described as stateless: \"given already-fetched claims and tenant/request context, it returns allow or deny... adds no policy, network call, cache mutation or state\" (PLAN.md:9-13). That is a function signature, not an object. TokenStore is named once (PLAN.md:44) with no described job, while AuthCache is \"a service-facing facade over that same existing adapter, with one backing cache\" (PLAN.md:20-21); two wrappers over one cache is a DRY smell. This question chooses structure only. The existing cache adapter contract (tenant/issuer/audience/policy-version keys, eviction and invalidation hooks, PLAN.md:16-22) stays fixed in every option. The singleton, try/catch, Promise.all and regression-test remedies stay pending for their own sections.\nStakes if we pick wrong: Too many classes: every future auth change touches more files and more mocks, and TokenStore vs AuthCache drift into two sources of truth for the same cache. Too few: if TokenStore actually holds a distinct responsibility the plan did not write down, folding it makes AuthCache a grab-bag.\nRecommendation: A because the plan's own text gives RequestPolicy no state and TokenStore no role; three classes plus one function covers every described responsibility with fewer seams to test.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: fewer moving parts and one cache wrapper vs. keeping the author's proposed boundaries in case TokenStore has an undocumented reason to exist.",
"header": "Structure",
"multiSelect": false,
"options": [
{
"label": "3 classes + 1 function (recommended)",
"description": "\u2705 AuthBroker, SessionMint, AuthCache as classes; RequestPolicy becomes decideAccess(claims, ctx) in a policy module, trivially unit-testable with no mocks\n\u2705 One cache wrapper (AuthCache) over the one existing adapter; no TokenStore/AuthCache split-brain (human: ~0.5 day less / CC: ~10 min less)\n\u274c If TokenStore was meant to own something AuthCache should not (e.g. refresh-token persistence), that job must be named and placed explicitly during implementation"
},
{
"label": "4 classes: drop TokenStore, keep RequestPolicy class",
"description": "\u2705 Removes the duplicate cache wrapper while keeping RequestPolicy as an injectable seam for future policy variants\n\u2705 Smaller change to the author's proposal than option A\n\u274c A one-method stateless class is ceremony today; the seam buys nothing until a second policy exists"
},
{
"label": "5 classes as proposed",
"description": "\u2705 Matches the author's boundaries exactly; no re-planning of which file owns what\n\u2705 Keeps the option of TokenStore growing a distinct responsibility later\n\u274c Two wrappers over one backing cache and a stateless one-method class are both accidental complexity in a plan that promises no behavior change"
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D4 \u2014 Class arrangement: keep all 5 new classes, or collapse to 3 (RequestPolicy as a pure function, TokenStore folded into AuthCache)?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; D3 already split the legacyAuthFlow() rewrite out, so this PR is the additive service layer only.\nELI10: The plan adds five classes (PLAN.md:44-45). Two look like classes for the sake of classes. RequestPolicy is described as stateless: \"given already-fetched claims and tenant/request context, it returns allow or deny... adds no policy, network call, cache mutation or state\" (PLAN.md:9-13). That is a function signature, not an object. TokenStore is named once (PLAN.md:44) with no described job, while AuthCache is \"a service-facing facade over that same existing adapter, with one backing cache\" (PLAN.md:20-21); two wrappers over one cache is a DRY smell. This question chooses structure only. The existing cache adapter contract (tenant/issuer/audience/policy-version keys, eviction and invalidation hooks, PLAN.md:16-22) stays fixed in every option. The singleton, try/catch, Promise.all and regression-test remedies stay pending for their own sections.\nStakes if we pick wrong: Too many classes: every future auth change touches more files and more mocks, and TokenStore vs AuthCache drift into two sources of truth for the same cache. Too few: if TokenStore actually holds a distinct responsibility the plan did not write down, folding it makes AuthCache a grab-bag.\nRecommendation: A because the plan's own text gives RequestPolicy no state and TokenStore no role; three classes plus one function covers every described responsibility with fewer seams to test.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: fewer moving parts and one cache wrapper vs. keeping the author's proposed boundaries in case TokenStore has an undocumented reason to exist.": "3 classes + 1 function (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:52:13.193Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01XPkmtEcLgvdhUqSsoNExCd",
"questions": [
{
"question": "D5 \u2014 Inject one AuthCache instance into both services, or keep the module-level global export?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; additive service layer (D3), 3 classes + 1 function (D4).\nELI10: The plan puts the shared cache wrapper in a global variable that any file can import and mutate (PLAN.md:28-29). That works until you need two of them: one real, one fake for a test; or one per tenant shard. Passing the instance into each service's constructor (dependency injection, \"hand the thing to the code that needs it instead of letting it reach for a global\") costs a few lines at startup and makes every test able to use a fresh cache without module-cache tricks. Still exactly one backing cache in production.\nStakes if we pick wrong: Global: tests leak cache state across cases, flaky auth tests, and a hidden import graph where any module can mutate the auth cache. Injected: a few extra constructor parameters and a startup wiring file to maintain.\nRecommendation: A because it is the boring, standard fix, costs minutes, and the plan already promises \"one backing cache\", which injection preserves while the global adds nothing but reach.\nCompleteness: A=10/10, B=3/10, C=6/10\nNet: explicit ownership and testability vs. one fewer wiring file.",
"header": "Wiring",
"multiSelect": false,
"options": [
{
"label": "Inject via constructor (recommended)",
"description": "\u2705 Tests construct a fresh AuthCache (or fake) per case; no module-cache reset hacks, no cross-test leakage. \u2705 Mutation surface is explicit: only AuthBroker and SessionMint hold a reference (human: ~2h / CC: ~5 min). \u274c Adds a small composition-root/wiring step and constructor params to maintain."
},
{
"label": "Keep module-level export",
"description": "\u2705 Zero wiring; matches the plan as written. \u2705 Fewer constructor parameters. \u274c Any module can import and mutate the auth cache; test isolation depends on runner module-cache behavior."
},
{
"label": "Module-level export plus a test-only reset hook",
"description": "\u2705 Keeps the plan's shape while giving tests a reset lever. \u2705 Smallest diff from the proposal. \u274c Ships test-only code in production; global mutation surface unchanged; reset hooks are a known smell."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D5 \u2014 Inject one AuthCache instance into both services, or keep the module-level global export?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; additive service layer (D3), 3 classes + 1 function (D4).\nELI10: The plan puts the shared cache wrapper in a global variable that any file can import and mutate (PLAN.md:28-29). That works until you need two of them: one real, one fake for a test; or one per tenant shard. Passing the instance into each service's constructor (dependency injection, \"hand the thing to the code that needs it instead of letting it reach for a global\") costs a few lines at startup and makes every test able to use a fresh cache without module-cache tricks. Still exactly one backing cache in production.\nStakes if we pick wrong: Global: tests leak cache state across cases, flaky auth tests, and a hidden import graph where any module can mutate the auth cache. Injected: a few extra constructor parameters and a startup wiring file to maintain.\nRecommendation: A because it is the boring, standard fix, costs minutes, and the plan already promises \"one backing cache\", which injection preserves while the global adds nothing but reach.\nCompleteness: A=10/10, B=3/10, C=6/10\nNet: explicit ownership and testability vs. one fewer wiring file.": "Inject via constructor (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:54:45.181Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01Jsn9Ex5fiLyJLSi2Bjq5FU",
"questions": [
{
"question": "D6 \u2014 Guard against a session write landing after an invalidation for the same tenant key, or accept the window?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthCache is now an injected single instance (D5).\nELI10: Two things can touch the same cache slot at once: SessionMint finishing a login and writing a fresh entry, and an invalidation hook wiping that entry because the tenant was suspended or the token revoked (PLAN.md:17-18). The plan says nothing orders these (PLAN.md:19). If the write lands second, a suspended tenant's session is back in the cache until it expires. The fix is a guard inside AuthCache's single write path: refuse a write whose inputs predate a later invalidation. Exactly how (a counter, compare-and-set, or a re-check) depends on what the adapter offers, which I could not read.\nStakes if we pick wrong: Unguarded: a revoked or suspended tenant keeps working for up to one TTL; that is a security window, and it is silent. Guarded: a few lines in AuthCache.set() and one concurrency test; risk of over-rejecting legitimate writes if the guard is too coarse.\nRecommendation: A because AuthCache is the one write path by design (PLAN.md:20-21, D4), so this is the cheapest place the guard will ever be, and the failure mode is a silent security hole.\nCompleteness: A=10/10, B=4/10, C=n/a (investigation, no remedy)\nNet: a small guard at the only write path vs. a silent authorization window bounded by TTL.",
"header": "Race",
"multiSelect": false,
"options": [
{
"label": "Guard in AuthCache.set() (recommended)",
"description": "\u2705 Closes the revoke-then-repopulate window at the single write path; adapter and hooks stay untouched. \u2705 One deterministic concurrency test proves it: invalidate between read and write, assert entry absent (human: ~4h / CC: ~10 min). \u274c Mechanism must be picked against the real adapter; a too-coarse guard rejects legitimate writes."
},
{
"label": "Accept the window, document the TTL bound",
"description": "\u2705 No new logic; nothing to get wrong in the guard. \u2705 Acceptable if the TTL is seconds and revocation is rare. \u274c Suspended/revoked tenants stay authorized for up to one TTL, silently."
},
{
"label": "Investigate the adapter's invalidation API first",
"description": "\u2705 Picks the mechanism with evidence rather than a guess. \u2705 Bounded: read the adapter's invalidation hooks and write API. \u274c Leaves this row unresolved at the end of the review; approves nothing."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D6 \u2014 Guard against a session write landing after an invalidation for the same tenant key, or accept the window?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthCache is now an injected single instance (D5).\nELI10: Two things can touch the same cache slot at once: SessionMint finishing a login and writing a fresh entry, and an invalidation hook wiping that entry because the tenant was suspended or the token revoked (PLAN.md:17-18). The plan says nothing orders these (PLAN.md:19). If the write lands second, a suspended tenant's session is back in the cache until it expires. The fix is a guard inside AuthCache's single write path: refuse a write whose inputs predate a later invalidation. Exactly how (a counter, compare-and-set, or a re-check) depends on what the adapter offers, which I could not read.\nStakes if we pick wrong: Unguarded: a revoked or suspended tenant keeps working for up to one TTL; that is a security window, and it is silent. Guarded: a few lines in AuthCache.set() and one concurrency test; risk of over-rejecting legitimate writes if the guard is too coarse.\nRecommendation: A because AuthCache is the one write path by design (PLAN.md:20-21, D4), so this is the cheapest place the guard will ever be, and the failure mode is a silent security hole.\nCompleteness: A=10/10, B=4/10, C=n/a (investigation, no remedy)\nNet: a small guard at the only write path vs. a silent authorization window bounded by TTL.": "Guard in AuthCache.set() (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:55:36.861Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_016MzUAeR1kn8fMPLnovLrr5",
"questions": [
{
"question": "D7 \u2014 Flatten validateAndDispatch() into a three-step pipeline with one error boundary, or keep the nested try/catch blocks?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthBroker orchestrates validate \u2192 decideAccess \u2192 dispatch.\nELI10: Right now the function wraps each step in its own try/catch and each catch quietly eats one kind of error (PLAN.md:32-33). In an auth path, \"quietly eat the error\" is the one thing you must never do: if the validation error is swallowed and execution continues, the request may be dispatched as if it passed. The alternative is three plain steps that throw typed errors, and one catch at the edge that turns each error type into an explicit deny or 5xx plus a log line. Anything unrecognized denies. Same behavior for the happy path; no silent continues.\nStakes if we pick wrong: Nested/swallowing: a fail-open bug hides behind a catch and nobody sees a log line; also each catch is untestable in isolation. Flattened: a short refactor and the error taxonomy must be written down (which is a feature).\nRecommendation: A because swallowed errors in an auth dispatcher are a fail-open risk, and the flat pipeline is fewer lines, not more.\nCompleteness: A=10/10, B=6/10, C=2/10\nNet: explicit error taxonomy with deny-by-default vs. keeping silent catches in the one place they are most dangerous.",
"header": "Errors",
"multiSelect": false,
"options": [
{
"label": "Flatten to pipeline + single error boundary (recommended)",
"description": "\u2705 Every error class has an explicit, testable mapping; unknown errors deny by default, so nothing fails open. \u2705 Three steps read top-to-bottom; each step unit-tests without the others (human: ~3h / CC: ~10 min). \u274c Requires enumerating the three swallowed error classes and deciding each one's user-visible outcome."
},
{
"label": "Keep nested blocks, add logging in each catch",
"description": "\u2705 Minimal diff; swallowed errors at least become visible in logs. \u2705 No change to control flow. \u274c Control flow after a swallow is still \"continue\"; fail-open remains possible and the 60-line nesting stays."
},
{
"label": "Do nothing",
"description": "\u2705 Zero effort. \u2705 Preserves whatever current behavior callers rely on, bugs included. \u274c Three silent catch blocks in the auth path; untestable and a live fail-open risk."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D7 \u2014 Flatten validateAndDispatch() into a three-step pipeline with one error boundary, or keep the nested try/catch blocks?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthBroker orchestrates validate \u2192 decideAccess \u2192 dispatch.\nELI10: Right now the function wraps each step in its own try/catch and each catch quietly eats one kind of error (PLAN.md:32-33). In an auth path, \"quietly eat the error\" is the one thing you must never do: if the validation error is swallowed and execution continues, the request may be dispatched as if it passed. The alternative is three plain steps that throw typed errors, and one catch at the edge that turns each error type into an explicit deny or 5xx plus a log line. Anything unrecognized denies. Same behavior for the happy path; no silent continues.\nStakes if we pick wrong: Nested/swallowing: a fail-open bug hides behind a catch and nobody sees a log line; also each catch is untestable in isolation. Flattened: a short refactor and the error taxonomy must be written down (which is a feature).\nRecommendation: A because swallowed errors in an auth dispatcher are a fail-open risk, and the flat pipeline is fewer lines, not more.\nCompleteness: A=10/10, B=6/10, C=2/10\nNet: explicit error taxonomy with deny-by-default vs. keeping silent catches in the one place they are most dangerous.": "Flatten to pipeline + single error boundary (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:56:34.582Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01CbTquCFiwhD5jigh8CUFGg",
"questions": [
{
"question": "D8 \u2014 How do we protect legacyAuthFlow() and the shared cache adapter from regressions in this PR?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; this PR is additive (D3) but writes to the one adapter legacyAuthFlow() still reads.\nELI10: Even though we are no longer rewriting the old login path in this PR, the new services write into the same cache it reads from (PLAN.md:20-21). Nothing today records what the old path actually does, so if a new entry shape or key collides with it, nobody will know until a tenant reports it. A characterization test (\"record what it does now, assert it keeps doing that\") plus one integration test that runs old and new against the same cache gives us that alarm. The plan explicitly skips both (PLAN.md:23-25). The question is how to cover it, not whether.\nStakes if we pick wrong: Too little: a silent auth behavior change for existing tenants with no failing test to point at it, and the follow-up rewrite PR starts with no baseline. Too much: an afternoon writing tests for code that will be rewritten anyway (but those tests are exactly what makes the rewrite safe).\nRecommendation: A because the follow-up rewrite (D3) needs the characterization baseline anyway, and recording it before any adjacent change is when it is cheapest and most trustworthy.\nCompleteness: A=10/10, B=7/10, C=5/10\nNet: pay for the baseline now while the old path is untouched vs. hope the adapter keys keep the flows apart.",
"header": "Regression",
"multiSelect": false,
"options": [
{
"label": "Characterization tests now + shared-adapter integration test (recommended)",
"description": "\u2705 Baseline of legacyAuthFlow() behavior captured before anything adjacent changes; the follow-up rewrite PR inherits it. \u2705 Integration test proves old and new flows coexist on one adapter with tenant isolation intact (human: ~1 day / CC: ~20 min). \u274c Tests characterize current behavior bugs included; someone must review the recorded outputs for surprises."
},
{
"label": "Shared-adapter integration test only",
"description": "\u2705 Covers the specific new risk this PR introduces (coexistence on one adapter). \u2705 Less test code to maintain. \u274c legacyAuthFlow() outputs stay unrecorded; the follow-up rewrite starts without a baseline."
},
{
"label": "Characterization tests only, deferred to the follow-up PR",
"description": "\u2705 Nothing extra in this PR. \u2705 Baseline written by whoever does the rewrite, closest to the work. \u274c This PR ships with zero proof the new writes do not disturb the old reads; baseline recorded after adjacent code already changed."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D8 \u2014 How do we protect legacyAuthFlow() and the shared cache adapter from regressions in this PR?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; this PR is additive (D3) but writes to the one adapter legacyAuthFlow() still reads.\nELI10: Even though we are no longer rewriting the old login path in this PR, the new services write into the same cache it reads from (PLAN.md:20-21). Nothing today records what the old path actually does, so if a new entry shape or key collides with it, nobody will know until a tenant reports it. A characterization test (\"record what it does now, assert it keeps doing that\") plus one integration test that runs old and new against the same cache gives us that alarm. The plan explicitly skips both (PLAN.md:23-25). The question is how to cover it, not whether.\nStakes if we pick wrong: Too little: a silent auth behavior change for existing tenants with no failing test to point at it, and the follow-up rewrite PR starts with no baseline. Too much: an afternoon writing tests for code that will be rewritten anyway (but those tests are exactly what makes the rewrite safe).\nRecommendation: A because the follow-up rewrite (D3) needs the characterization baseline anyway, and recording it before any adjacent change is when it is cheapest and most trustworthy.\nCompleteness: A=10/10, B=7/10, C=5/10\nNet: pay for the baseline now while the old path is untouched vs. hope the adapter keys keep the flows apart.": "Characterization tests now + shared-adapter integration test (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:57:56.452Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01QDNkQ3nwnRi75PgeD3FuVc",
"questions": [
{
"question": "D9 \u2014 Cache the static IDP documents and parallelize the rest, or just parallelize the 5 calls?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; validate step of the flattened AuthBroker pipeline (D7).\nELI10: Every login currently makes five round trips to the identity provider, one after another (PLAN.md:40-41). Running them at the same time cuts wall-clock time by about 5x, which is what the plan proposes. But at least some of those calls fetch documents that barely change (the provider's discovery config and its public signing keys), which the standard practice says to cache for hours and only refetch when a token shows up signed by an unknown key. Cache those and most logins need zero or one round trip. Parallelizing alone also turns a 5-call trickle into a 5-call burst per login, which is how you hit IDP rate limits on a busy morning.\nStakes if we pick wrong: Parallelize-only: 5x burstier IDP traffic, still 5 network dependencies per login, and Promise.all's fail-fast leaves the other four requests in flight. Cache + parallelize: a small TTL cache with a stale-key refresh path to get right.\nRecommendation: A because the plan's own evidence (5 calls per validation) says the missing piece is caching, not concurrency; it is the standard OIDC pattern and removes the IDP as a per-request dependency for most logins.\nCompleteness: A=10/10, B=7/10, C=2/10\nNet: remove the IDP from the hot path with a boring cache vs. make the hot path five times faster and five times burstier.",
"header": "IDP calls",
"multiSelect": false,
"options": [
{
"label": "Cache static IDP documents + parallelize remaining calls (recommended)",
"description": "\u2705 Steady-state logins need 0-1 IDP round trips instead of 5; IDP outage no longer fails every login that has cached keys. \u2705 Standard OIDC practice; refresh-on-unknown-kid handles key rotation (human: ~1 day / CC: ~20 min). \u274c Must pick TTLs below the IDP's key-rotation overlap window and test the unknown-kid refresh path."
},
{
"label": "Parallelize the 5 calls only (as proposed)",
"description": "\u2705 ~5x lower validation latency with a one-line change. \u2705 No cache invalidation to reason about. \u274c 5 requests per login in a burst; every login still depends on the IDP being up; fail-fast leaves stragglers in flight."
},
{
"label": "Do nothing",
"description": "\u2705 Zero effort; no new failure modes. \u2705 Sequential calls are easy to trace in logs. \u274c ~5 \u00d7 RTT on every login, and the plan already called this out as trivially fixable."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D9 \u2014 Cache the static IDP documents and parallelize the rest, or just parallelize the 5 calls?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; validate step of the flattened AuthBroker pipeline (D7).\nELI10: Every login currently makes five round trips to the identity provider, one after another (PLAN.md:40-41). Running them at the same time cuts wall-clock time by about 5x, which is what the plan proposes. But at least some of those calls fetch documents that barely change (the provider's discovery config and its public signing keys), which the standard practice says to cache for hours and only refetch when a token shows up signed by an unknown key. Cache those and most logins need zero or one round trip. Parallelizing alone also turns a 5-call trickle into a 5-call burst per login, which is how you hit IDP rate limits on a busy morning.\nStakes if we pick wrong: Parallelize-only: 5x burstier IDP traffic, still 5 network dependencies per login, and Promise.all's fail-fast leaves the other four requests in flight. Cache + parallelize: a small TTL cache with a stale-key refresh path to get right.\nRecommendation: A because the plan's own evidence (5 calls per validation) says the missing piece is caching, not concurrency; it is the standard OIDC pattern and removes the IDP as a per-request dependency for most logins.\nCompleteness: A=10/10, B=7/10, C=2/10\nNet: remove the IDP from the hot path with a boring cache vs. make the hot path five times faster and five times burstier.": "Cache static IDP documents + parallelize remaining calls (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T10:59:51.506Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_014GbhwgQB5iSrew939XUz29",
"questions": [
{
"question": "D10 \u2014 Capture the follow-up PR (swap legacyAuthFlow() onto the new services) as a TODO?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; D3 deferred the legacyAuthFlow() rewrite out of this PR.\nELI10: We agreed the old login path stays untouched in this PR and gets swapped in a second PR once AuthBroker/SessionMint have run in production. That second PR does not exist anywhere yet except this review. A TODO entry with the context (why it was split, what the characterization tests from D8 give it, when it is safe to start) keeps it from becoming the dual-path state that lingers for a year. There is no TODOS.md in this repo today; option A would create it after plan mode exits.\nWhat: Swap `legacyAuthFlow()` callers onto `AuthBroker.validateAndDispatch()` and delete the legacy path. Why: closes the dual-path window opened by D3. Pros: small reviewable diff, characterization tests (D8) already exist as the acceptance gate. Cons: needs a production soak of the new services first; someone must own it. Context: see this review's ledger R1/R3. Depends on: this PR merged and soaked; D8 characterization tests green.\nStakes if we pick wrong: Skipped: the split's rationale evaporates and two auth paths coexist indefinitely. Added: one more file in the repo to keep honest.\nRecommendation: A because a deferred rewrite without a written trail is how legacy paths become permanent.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: a written, contextual follow-up vs. relying on memory to finish the migration.",
"header": "TODO",
"multiSelect": false,
"options": [
{
"label": "Add to TODOS.md (recommended)",
"description": "\u2705 Follow-up captured with why/how/when, readable in 3 months by whoever picks it up. \u2705 Ties the D8 characterization tests to their consumer. \u274c Creates TODOS.md in a repo that has none; write happens after plan mode exits."
},
{
"label": "Skip \u2014 not valuable enough",
"description": "\u2705 No new file; the ledger in the review report already records the split. \u2705 Team may track follow-ups elsewhere (issues, tickets). \u274c Nothing in-repo points at the unfinished migration."
},
{
"label": "Build it now in this PR instead",
"description": "\u2705 No dual-path state at all. \u2705 One deploy. \u274c Reverses D3; puts the riskiest change back into the 12-file diff with no production soak of the new services."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D10 \u2014 Capture the follow-up PR (swap legacyAuthFlow() onto the new services) as a TODO?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; D3 deferred the legacyAuthFlow() rewrite out of this PR.\nELI10: We agreed the old login path stays untouched in this PR and gets swapped in a second PR once AuthBroker/SessionMint have run in production. That second PR does not exist anywhere yet except this review. A TODO entry with the context (why it was split, what the characterization tests from D8 give it, when it is safe to start) keeps it from becoming the dual-path state that lingers for a year. There is no TODOS.md in this repo today; option A would create it after plan mode exits.\nWhat: Swap `legacyAuthFlow()` callers onto `AuthBroker.validateAndDispatch()` and delete the legacy path. Why: closes the dual-path window opened by D3. Pros: small reviewable diff, characterization tests (D8) already exist as the acceptance gate. Cons: needs a production soak of the new services first; someone must own it. Context: see this review's ledger R1/R3. Depends on: this PR merged and soaked; D8 characterization tests green.\nStakes if we pick wrong: Skipped: the split's rationale evaporates and two auth paths coexist indefinitely. Added: one more file in the repo to keep honest.\nRecommendation: A because a deferred rewrite without a written trail is how legacy paths become permanent.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: a written, contextual follow-up vs. relying on memory to finish the migration.": "Add to TODOS.md (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T11:00:51.358Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_018qdnrhAWxH9Ad8ykqnqBHJ",
"questions": [
{
"question": "D11 \u2014 Next step after this eng review?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; eng review CLEAR, 0 unresolved decisions, 9 tasks (T1-T9) in the reviewed plan.\nELI10: The review is done and saved. Navigation only: this picks what happens next and approves no new implementation change. No UI scope was found, so a design review does not apply; the plan changes no product behavior, so a CEO review is optional and not suggested.\nStakes if we pick wrong: None material; you can run any other review later.\nRecommendation: Ready to implement \u2014 this is the only applicable option; the plan's tasks and lanes are recorded.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: proceed to implementation vs. pause.",
"header": "Next",
"multiSelect": false,
"options": [
{
"label": "Ready to implement (recommended)",
"description": "\u2705 All relevant reviews complete; lanes A-D can start in parallel worktrees, then E. \u2705 Run /ship when the work is done. \u274c No further review gate before coding; the deferred CLAUDE.md/TODOS.md writes happen right after plan mode exits."
},
{
"label": "Pause here",
"description": "\u2705 Nothing further happens; the saved report stands. \u2705 Resume any time with /context-restore. \u274c Deferred CLAUDE.md routing rules and TODOS.md entry stay unwritten."
}
]
}
],
"answered": true,
"failed": false,
"answers": {
"D11 \u2014 Next step after this eng review?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; eng review CLEAR, 0 unresolved decisions, 9 tasks (T1-T9) in the reviewed plan.\nELI10: The review is done and saved. Navigation only: this picks what happens next and approves no new implementation change. No UI scope was found, so a design review does not apply; the plan changes no product behavior, so a CEO review is optional and not suggested.\nStakes if we pick wrong: None material; you can run any other review later.\nRecommendation: Ready to implement \u2014 this is the only applicable option; the plan's tasks and lanes are recorded.\nNote: options differ in kind, not coverage \u2014 no completeness score.\nNet: proceed to implementation vs. pause.": "Ready to implement (recommended)"
},
"unansweredQuestionIndices": [],
"answeredAt": "2026-09-16T11:04:01.560Z"
}
],
"assistantMessages": [
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Scope gate: plan mode \u2014 auto-selected B (reviewing `PLAN.md`: \"Plan: Multi-tenant Auth Refactor\").",
"timestamp": "2026-09-16T10:49:19.211Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Noted: routing rules approved. Plan mode blocks the CLAUDE.md write and commit right now; I'll carry it as a deferred follow-up after the review exits plan mode.",
"timestamp": "2026-09-16T10:49:45.217Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "No design doc; the user pre-declined `/office-hours`, so I'm skipping that offer. Now reading the plan and the review section.",
"timestamp": "2026-09-16T10:50:08.257Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "No prior learnings. Aside is not installed, so I'll run the Scope Challenge search check through WebSearch.",
"timestamp": "2026-09-16T10:51:03.297Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Scope decisions recorded: legacyAuthFlow() rewrite split out (D3), 3 classes + 1 function (D4). Saving the report file with the ledger before findings.",
"timestamp": "2026-09-16T10:53:04.284Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Record R4 saved and verified. Dispatching D5.",
"timestamp": "2026-09-16T10:54:35.466Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "**Section 2: Code Quality findings**\n\n| # | Sev | Conf | Source | Finding | Disposition |\n|---|---|---|---|---|---|\n| C1 | P1 | 9/10 | PLAN.md:32-33 | 60-line `validateAndDispatch()` with three nested try/catch, each swallowing an error class: fail-open risk, untestable catches | **Accepted** (D7: flat pipeline, one deny-by-default boundary) |\n| C2 | P2 | 8/10 | PLAN.md:44 vs :20-21 | DRY: `TokenStore` and `AuthCache` both wrap one backing cache | **Resolved** by D4 |\n| C3 | P3 | 7/10 | PLAN.md:12-13 | Stateless one-method class (`RequestPolicy`) is ceremony | **Resolved** by D4 (`decideAccess()` fn) |\n| C4 | P3 | 6/10 | PLAN.md (whole) | No diagrams in the plan or planned for code; `AuthBroker` pipeline and `AuthCache` guard are exactly the non-obvious behavior that needs inline ASCII comments | Included as documentation task; no approval needed |\n\n**Section 3: Test review.** Framework detection: no `package.json`, no test config, 0 test files in the repo. Framework **unknown**; the plan's `Promise.all` implies a JS/TS runtime, so tests below assume a Jest/Vitest-style layout and must be re-mapped to the real project's convention.\n\nCoverage diagram (plan-level; every path is a GAP today because no tests exist in the repo):\n\n```\nCODE PATHS USER FLOWS\n[+] auth/AuthBroker.ts [+] Tenant login (bearer token)\n \u2514\u2500\u2500 validateAndDispatch() \u251c\u2500\u2500 [GAP] [\u2192E2E] valid token \u2192 allow \u2192 dispatched\n \u251c\u2500\u2500 [GAP] validate: happy path \u251c\u2500\u2500 [GAP] [\u2192E2E] expired token \u2192 deny, clear error\n \u251c\u2500\u2500 [GAP] validate: IDP timeout \u2192 typed err \u2192 deny \u251c\u2500\u2500 [GAP] [\u2192E2E] revoked mid-session \u2192 next request denied\n \u251c\u2500\u2500 [GAP] validate: IDP 5xx \u2192 typed err \u2192 5xx \u2514\u2500\u2500 [GAP] [\u2192E2E] tenant suspended \u2192 next request denied\n \u251c\u2500\u2500 [GAP] validate: malformed/expired token \u2192 deny\n \u251c\u2500\u2500 [GAP] decideAccess() deny \u2192 deny (no dispatch) [+] Error states\n \u251c\u2500\u2500 [GAP] dispatch throws \u2192 mapped, logged \u251c\u2500\u2500 [GAP] IDP down \u2192 user sees 5xx, not hang\n \u2514\u2500\u2500 [GAP] unknown error \u2192 deny by default (D7) \u251c\u2500\u2500 [GAP] slow IDP (10s) \u2192 timeout path, not silent\n[+] auth/policy.ts \u2514\u2500\u2500 [GAP] double-submit login \u2192 one session, no dup mint\n \u2514\u2500\u2500 decideAccess(claims, ctx)\n \u251c\u2500\u2500 [GAP] allow / deny table for existing policy [+] Regression (D8, CRITICAL)\n \u251c\u2500\u2500 [GAP] claims tenant \u2260 ctx tenant \u2192 deny (A3) \u251c\u2500\u2500 [GAP] [\u2192E2E] legacyAuthFlow() characterization\n \u2514\u2500\u2500 [GAP] missing/empty claims \u2192 deny \u2514\u2500\u2500 [GAP] [\u2192E2E] legacy + new on one adapter, tenant isolation\n[+] auth/AuthCache.ts\n \u251c\u2500\u2500 get(): [GAP] hit / miss / expired-evicted\n \u251c\u2500\u2500 set(): [GAP] normal write persists\n \u251c\u2500\u2500 set(): [GAP] write after invalidation dropped (D6 proof)\n \u251c\u2500\u2500 [GAP] key = (tenant from CLAIMS, issuer, audience, policyVersion)\n \u2514\u2500\u2500 [GAP] adapter throws \u2192 surfaced, not swallowed\n[+] auth/SessionMint.ts\n \u251c\u2500\u2500 [GAP] mint \u2192 AuthCache.set() called once with correct key\n \u2514\u2500\u2500 [GAP] mint during suspension \u2192 no entry (D6)\n\nCOVERAGE: 0/27 paths tested (0%) | Code paths: 0/18 (0%) | User flows: 0/9 (0%)\nQUALITY: \u2605\u2605\u2605:0 \u2605\u2605:0 \u2605:0 | GAPS: 27 (7 E2E, 0 eval)\n```\n\nLegend: \u2605\u2605\u2605 behavior + edge + error | \u2605\u2605 happy path | \u2605 smoke | [\u2192E2E] integration test. No LLM/prompt scope in this plan; no eval needed.\n\n**REGRESSION RULE** applies: PLAN.md:23-25 explicitly excludes compatibility assertions while the new services write to the adapter `legacyAuthFlow()` reads. Record R3 saved and verified; one dedicated question.",
"timestamp": "2026-09-16T10:57:45.162Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Now writing the remaining review output and the terminal report.",
"timestamp": "2026-09-16T11:01:09.479Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Read-back gate passes: last `##` heading is `## GSTACK REVIEW REPORT` (line 573), final line is the sentinel, 0 pending records. Writing the Review Log.",
"timestamp": "2026-09-16T11:03:06.526Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "```\n+====================================================================+\n| REVIEW READINESS DASHBOARD |\n+====================================================================+\n| Review | Runs | Last Run | Status | Required |\n|-----------------|------|---------------------|-----------|----------|\n| Eng Review | 1 | 2026-09-16 11:03 | CLEAR (PLAN) | YES |\n| CEO Review | 0 | \u2014 | \u2014 | no |\n| Design Review | 0 | \u2014 | \u2014 | no |\n| Adversarial | 0 | \u2014 | \u2014 | no |\n| Outside Voice | 1 | 2026-09-16 11:00 | DISABLED | no |\n+--------------------------------------------------------------------+\n| VERDICT: CLEARED \u2014 Eng Review passed (plan-tier, commit dc3b5e2) |\n+====================================================================+\n```\nOutside voice: provider codex, phase plan-review, `outside_status: disabled` (config opt-out). No native fallback ran. Not counted as coverage.\n\n**Completion summary** (saved in the report)\n- Step 0: Scope Challenge \u2014 scope reduced per recommendation (D3 split `legacyAuthFlow()` rewrite out; D4 3 classes + `decideAccess()` fn)\n- Architecture Review: 4 issues found\n- Code Quality Review: 4 issues found\n- Test Review: diagram produced, 29 gaps identified (0 tests exist in repo; framework unknown)\n- Performance Review: 2 issues found\n- NOT in scope: written \u00b7 What already exists: written\n- TODOS.md updates: 1 item proposed (accepted; not persisted until plan mode exits)\n- Failure modes: 0 critical gaps after accepted remedies\n- Unresolved decisions: 0\n- Outside voice: codex, disabled\n- Parallelization: 5 lanes, 4 parallel / 1 sequential\n- Lake Score: 5/5\n\nArtifacts: full reviewed plan + report at `/tmp/g-q50pz9gl/gstack-paid-shard-uzvErm/tmp/gstack-e2e-plan-eng-piEYOe/gstack-test-plan-eng.md`; QA test plan and tasks JSONL under `~/.gstack/projects/gstack-plan-count-eecImF/`.\n\nNext steps: this is a backend-only auth refactor with no UI scope, so no design review applies. It is a behavior-preserving refactor, not a product change, so CEO review is optional and not suggested.",
"timestamp": "2026-09-16T11:03:52.178Z"
},
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"text": "Gate passes on all five checks. Running telemetry and cache refresh.",
"timestamp": "2026-09-16T11:04:48.870Z"
}
],
"planReadyRequests": [
{
"sessionId": "52fc1353-eb16-4fbb-961f-d2368b35069a",
"toolUseId": "toolu_01JWZvmDUGhq7yHreNxeuZZe",
"timestamp": "2026-09-16T11:05:05.744Z",
"failed": false,
"source": "pre_tool_use"
}
]
},
"originalPlan": "# Plan: Multi-tenant Auth Refactor (reviewed)\n\nReviewed target: `PLAN.md` (\"Plan: Multi-tenant Auth Refactor\") in repo `gstack-plan-count-eecImF`, branch `main`, commit `dc3b5e2`.\nReview: `/plan-eng-review`, 2026-09-16. Report destination: this file (explicitly requested by the user).\nRuntime evidence note: the repository under review contains only `CLAUDE.md` and `PLAN.md`. No implementation source, tests, or test framework are present. Every finding below is a plan-level finding quoting `PLAN.md:line`; runtime behavior of `legacyAuthFlow()`, the cache adapter, and the IDP calls is **unknown** and must be verified against the real codebase at implementation time.\n\n## Context (from the plan author)\n\nThe goal is to reorganize existing tenant-auth orchestration without changing its product behavior (PLAN.md:8-9). RequestPolicy groups the existing per-request access decision: given already-fetched claims and tenant/request context, it returns allow or deny under the existing access policy. AuthBroker.validateAndDispatch() calls it after validation and before dispatch. It adds no policy, network call, cache mutation or state (PLAN.md:9-13).\n\n## Existing contracts retained (unchanged by this review)\n\n- The existing cache adapter keys entries by tenant ID, issuer, audience, and policy version (PLAN.md:16-17).\n- It evicts expired tokens and invalidates entries on logout, token revocation, or tenant suspension (PLAN.md:17-18).\n- AuthCache is a service-facing facade over that same existing adapter, with one backing cache (PLAN.md:20-21). The adapter, its invalidation hooks, and their existing tests remain in use unchanged (PLAN.md:21-22).\n- The adapter does not serialize mutations (PLAN.md:19).\n\n## Scope as amended by this review\n\n| Item | Original plan | Reviewed plan | Decision |\n|---|---|---|---|\n| `legacyAuthFlow()` rewrite | In this PR, no regression test (PLAN.md:36-37) | **Deferred to a follow-up PR.** This PR is additive: new services land, `legacyAuthFlow()` keeps serving tenants unchanged. | D3 |\n| New classes | 5: AuthBroker, TokenStore, SessionMint, AuthCache, RequestPolicy (PLAN.md:44-45) | **3 classes + 1 function:** `AuthBroker`, `SessionMint`, `AuthCache`; `RequestPolicy` becomes a pure function `decideAccess(claims, ctx)` in a policy module; `TokenStore` folded into `AuthCache` (one wrapper over the one backing cache). If implementation discovers a responsibility that must not live in `AuthCache` (e.g. refresh-token persistence), name it explicitly and raise it, do not silently re-add `TokenStore`. | D4 |\n| Files touched | 12 (PLAN.md:44) | Expected to drop with the two cuts above; re-count at implementation. | D3, D4 |\n\n## Architecture (reviewed)\n\nProposed data flow for this PR (additive layer; `legacyAuthFlow()` untouched):\n\n```\n request (tenant ctx, bearer token)\n |\n v\n +---------------------------+\n | AuthBroker |\n | validateAndDispatch() |\n | 1. validate token -----+----> IDP (discovery / JWKS / introspection ...)\n | 2. decideAccess() -----+----> policy module (pure fn, no I/O)\n | 3. dispatch |\n +------------+--------------+\n | reads/writes\n v\n SessionMint ---------> AuthCache (facade) ---------> existing cache adapter\n (mints sessions, one instance, keys: tenant, issuer,\n writes entries) one backing cache audience, policyVersion\n invalidation hooks:\n logout / revoke / suspend\n ^\n | (still reads/writes the SAME adapter today)\n legacyAuthFlow() [unchanged in this PR]\n```\n\nOriginal proposal (PLAN.md:28-29): AuthBroker and SessionMint share a global mutable AuthCache instance via module-level export; both services mutate it. Reviewed disposition: see Section 1 findings and the decision ledger.\n\n## Code quality (reviewed)\n\nOriginal proposal (PLAN.md:32-33): `validateAndDispatch()` is 60 lines with three nested try/catch blocks; each catch swallows a different error class. Reviewed disposition: see Section 2 findings and the decision ledger.\n\n## Tests (reviewed)\n\nOriginal proposal (PLAN.md:23-25, 36-37): unit and integration coverage for the new components' success/error paths; that coverage does not exercise `legacyAuthFlow()` or assert compatibility with its prior behavior; no regression test planned. Reviewed disposition: see Section 3 (test review, coverage diagram, regression contract) and the decision ledger.\n\n## Performance (reviewed)\n\nOriginal proposal (PLAN.md:40-41): token validation issues 5 sequential API calls to the IDP; parallelize via Promise.all (calls are independent). Reviewed disposition: see Section 4 findings and the decision ledger.\n\n## Decision ledger\n\nSetup questions (not remedies): D1 routing rules \u2192 A (add; deferred until plan mode exits). D2 cross-project learnings \u2192 A (enabled).\n\n### R1: Scope of `legacyAuthFlow()` rewrite in this PR\nFinding: Scope Challenge S1, P1, confidence 9/10, PLAN.md:36-37 (\"The existing `legacyAuthFlow()` will get rewritten as part of this work; no regression test for the prior behavior is planned.\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 rewrite in this PR.\nRuntime evidence: unknown; no source in repo. `legacyAuthFlow()` callers and current behavior unverified.\nComparison grid (initial scope selector; no pre-answer grid required):\n\n| Choice | Current | A Split | B Bundle | C Hold |\n|---|---|---|---|---|\n| R1 rewrite in this PR | yes, pending | no; follow-up PR | yes | undecided |\n| R3 regression contract (Test review) | pending | pending | pending | pending |\n\nQuestion D3: Keep the legacyAuthFlow() rewrite in this PR, or split it into a follow-up behind the new services? Recommendation: Split (recommended) because the plan's own goal is \"no product behavior change\"; the rewrite is the single riskiest step and it gets cheaper and safer once the new services exist and are exercised. (Note: the brief's prose line said \"B\" while the `(recommended)` label sat on the Split option; the user selected the labeled Split option.)\nHeader: Scope\nOptions:\nA) Split: defer rewrite to follow-up PR (recommended)\nB) Bundle: rewrite legacyAuthFlow() in this PR\nC) Hold: discuss before deciding\n\nState: approved\nActual answer: A \u2014 \"Split: defer rewrite to follow-up PR (recommended)\" (answer to D3)\nAccepted scope: this PR does not modify `legacyAuthFlow()`; its rewrite/swap moves to a follow-up PR after the new services are exercised. Regression coverage remains a separate pending choice (R3).\nHistory: none.\n\n### R2: Class arrangement for the new service layer\nFinding: Scope Challenge S2, P2, confidence 8/10, PLAN.md:44-45 (\"introduces 5 new classes (AuthBroker, TokenStore, SessionMint, AuthCache, RequestPolicy)\") with PLAN.md:12-13 (RequestPolicy \"adds no policy, network call, cache mutation or state\") and PLAN.md:20-21 (AuthCache \"facade over that same existing adapter, with one backing cache\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 5 classes.\nRuntime evidence: unknown; no source in repo.\nComparison grid (initial scope selector):\n\n| Choice | Current | A | B | C |\n|---|---|---|---|---|\n| R2 arrangement | 5 classes | AuthBroker, SessionMint, AuthCache + `decideAccess()` fn | AuthBroker, SessionMint, AuthCache, RequestPolicy class | 5 classes as proposed |\n| cache adapter contract (PLAN.md:16-22) | fixed | fixed | fixed | fixed |\n| R-singleton, R-trycatch, R-perf, R3 tests | pending | pending | pending | pending |\n\nQuestion D4: Class arrangement: keep all 5 new classes, or collapse to 3 (RequestPolicy as a pure function, TokenStore folded into AuthCache)? Recommendation: A because the plan's own text gives RequestPolicy no state and TokenStore no role; three classes plus one function covers every described responsibility with fewer seams to test.\nHeader: Structure\nOptions:\nA) 3 classes + 1 function (recommended)\nB) 4 classes: drop TokenStore, keep RequestPolicy class\nC) 5 classes as proposed\n\nState: approved\nActual answer: A \u2014 \"3 classes + 1 function (recommended)\" (answer to D4)\nAccepted scope: `AuthBroker`, `SessionMint`, `AuthCache` as classes; `RequestPolicy` implemented as pure function `decideAccess(claims, ctx)`; `TokenStore` not created, its role (if any) absorbed by `AuthCache`; cache adapter contract unchanged.\nHistory: none.\n\n### R4: How AuthBroker and SessionMint obtain the shared AuthCache instance\nFinding: Architecture A1, P1, confidence 8/10, PLAN.md:28-29 (\"Two new services (`AuthBroker` and `SessionMint`) share a global mutable `AuthCache` instance via module-level export. Both services mutate it.\"), reviewer: plan-eng-review (Claude). Web research [Layer 1]: module-level mutable singletons break test isolation (Jest module-cache resets, no per-test reset) and risk cross-request leakage in server runtimes.\nPlan baseline: original proposal \u2014 module-level exported instance.\nRuntime evidence: unknown; no source in repo. Whether the codebase already has a composition root / DI container is unverified.\nComparison grid:\n\n| Choice | Current | A Inject | B Keep export | C Export + reset hook |\n|---|---|---|---|---|\n| R4 wiring of AuthCache | module-level export, mutated by both | one `AuthCache` constructed at the composition root, passed to `AuthBroker` and `SessionMint` constructors; no module-level export | module-level export as proposed | module-level export plus `__resetForTests()` |\n| single backing cache (PLAN.md:21) | fixed | fixed (one instance) | fixed | fixed |\n| adapter contract (PLAN.md:16-22) | fixed | fixed | fixed | fixed |\n| R2 arrangement | approved D4 | held | held | held |\n| R5 invalidation race, R6 try/catch, R3 tests, R7 perf | pending | pending | pending | pending |\n\nQuestion D5:\nD5 \u2014 Inject one AuthCache instance into both services, or keep the module-level global export?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; additive service layer (D3), 3 classes + 1 function (D4).\nELI10: The plan puts the shared cache wrapper in a global variable that any file can import and mutate (PLAN.md:28-29). That works until you need two of them: one real, one fake for a test; or one per tenant shard. Passing the instance into each service's constructor (dependency injection, \"hand the thing to the code that needs it instead of letting it reach for a global\") costs a few lines at startup and makes every test able to use a fresh cache without module-cache tricks. Still exactly one backing cache in production.\nStakes if we pick wrong: Global: tests leak cache state across cases, flaky auth tests, and a hidden import graph where any module can mutate the auth cache. Injected: a few extra constructor parameters and a startup wiring file to maintain.\nRecommendation: A because it is the boring, standard fix, costs minutes, and the plan already promises \"one backing cache\", which injection preserves while the global adds nothing but reach.\nCompleteness: A=10/10, B=3/10, C=6/10\nPros / cons:\nA) Inject via constructor (recommended)\n \u2705 Tests construct a fresh AuthCache (or fake) per case; no module-cache reset hacks, no cross-test leakage\n \u2705 Mutation surface is explicit: only AuthBroker and SessionMint hold a reference (human: ~2h / CC: ~5 min)\n \u274c Adds a small composition-root/wiring step and constructor params to maintain\nB) Keep module-level export\n \u2705 Zero wiring; matches the plan as written\n \u2705 Fewer constructor parameters\n \u274c Any module can import and mutate the auth cache; test isolation depends on runner module-cache behavior\nC) Module-level export plus a test-only reset hook\n \u2705 Keeps the plan's shape while giving tests a reset lever\n \u2705 Smallest diff from the proposal\n \u274c Ships test-only code in production; global mutation surface unchanged; reset hooks are a known smell\nNet: explicit ownership and testability vs. one fewer wiring file.\nHeader: Wiring\nOptions:\nA) Inject via constructor (recommended)\n\u2705 Tests construct a fresh AuthCache (or fake) per case; no module-cache reset hacks, no cross-test leakage. \u2705 Mutation surface is explicit: only AuthBroker and SessionMint hold a reference (human: ~2h / CC: ~5 min). \u274c Adds a small composition-root/wiring step and constructor params to maintain.\nB) Keep module-level export\n\u2705 Zero wiring; matches the plan as written. \u2705 Fewer constructor parameters. \u274c Any module can import and mutate the auth cache; test isolation depends on runner module-cache behavior.\nC) Module-level export plus a test-only reset hook\n\u2705 Keeps the plan's shape while giving tests a reset lever. \u2705 Smallest diff from the proposal. \u274c Ships test-only code in production; global mutation surface unchanged; reset hooks are a known smell.\n\nState: approved\nActual answer: A \u2014 \"Inject via constructor (recommended)\" (answer to D5)\nAccepted scope: one `AuthCache` instance constructed at the composition root and passed to `AuthBroker` and `SessionMint` constructors; no module-level exported instance; unit tests construct a fresh `AuthCache` (or fake) per case. Same single backing adapter in production.\nHistory: none.\n\n### R5: Cache write racing an invalidation (SessionMint write after logout/revocation/suspension)\nFinding: Architecture A2, P2, confidence 6/10 (medium: adapter semantics unverified), PLAN.md:19 (\"they do not serialize mutations\") together with PLAN.md:29 (\"Both services mutate it.\") and PLAN.md:17-18 (\"invalidates entries on logout, token revocation, or tenant suspension\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 no ordering guarantee between a SessionMint write and an invalidation for the same key.\nRuntime evidence: unknown; no source in repo. Whether the adapter exposes a generation/version or compare-and-set is unverified.\nComparison grid:\n\n| Choice | Current | A Guard in facade | B Accept + document | C Investigate first |\n|---|---|---|---|---|\n| R5 late-write behavior | unspecified: a mint that started before an invalidation may write after it and re-populate a revoked/suspended entry | `AuthCache.set()` is the only write path and drops a write when an invalidation for that key (tenant, issuer, audience, policyVersion) arrived after the value was produced; mechanism chosen against the adapter (generation counter, CAS, or re-check of suspension/revocation before write) | window accepted; documented in AuthCache with the TTL bound as the maximum stale exposure | unchanged, pending; bounded probe of the adapter's invalidation API before deciding |\n| adapter contract (PLAN.md:16-22) | fixed | fixed (facade-side guard, adapter untouched) | fixed | fixed |\n| R4 injection | approved D5 | held | held | held |\n| R6 try/catch, R3 tests, R7 perf | pending | pending | pending | pending |\n\nQuestion D6:\nD6 \u2014 Guard against a session write landing after an invalidation for the same tenant key, or accept the window?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthCache is now an injected single instance (D5).\nELI10: Two things can touch the same cache slot at once: SessionMint finishing a login and writing a fresh entry, and an invalidation hook wiping that entry because the tenant was suspended or the token revoked (PLAN.md:17-18). The plan says nothing orders these (PLAN.md:19). If the write lands second, a suspended tenant's session is back in the cache until it expires. The fix is a guard inside AuthCache's single write path: refuse a write whose inputs predate a later invalidation. Exactly how (a counter, compare-and-set, or a re-check) depends on what the adapter offers, which I could not read.\nStakes if we pick wrong: Unguarded: a revoked or suspended tenant keeps working for up to one TTL; that is a security window, and it is silent. Guarded: a few lines in AuthCache.set() and one concurrency test; risk of over-rejecting legitimate writes if the guard is too coarse.\nRecommendation: A because AuthCache is the one write path by design (PLAN.md:20-21, D4), so this is the cheapest place the guard will ever be, and the failure mode is a silent security hole.\nCompleteness: A=10/10, B=4/10, C=n/a (investigation, no remedy)\nPros / cons:\nA) Guard in AuthCache.set() (recommended)\n \u2705 Closes the revoke-then-repopulate window at the single write path; adapter and hooks stay untouched\n \u2705 One deterministic concurrency test proves it: invalidate between read and write, assert entry absent (human: ~4h / CC: ~10 min)\n \u274c Mechanism must be picked against the real adapter; a too-coarse guard rejects legitimate writes\nB) Accept the window, document the TTL bound\n \u2705 No new logic; nothing to get wrong in the guard\n \u2705 Acceptable if the TTL is seconds and revocation is rare\n \u274c Suspended/revoked tenants stay authorized for up to one TTL, silently\nC) Investigate the adapter's invalidation API first\n \u2705 Picks the mechanism with evidence rather than a guess\n \u2705 Bounded: read the adapter's invalidation hooks and write API\n \u274c Leaves this row unresolved at the end of the review; approves nothing\nNet: a small guard at the only write path vs. a silent authorization window bounded by TTL.\nHeader: Race\nOptions:\nA) Guard in AuthCache.set() (recommended)\n\u2705 Closes the revoke-then-repopulate window at the single write path; adapter and hooks stay untouched. \u2705 One deterministic concurrency test proves it: invalidate between read and write, assert entry absent (human: ~4h / CC: ~10 min). \u274c Mechanism must be picked against the real adapter; a too-coarse guard rejects legitimate writes.\nB) Accept the window, document the TTL bound\n\u2705 No new logic; nothing to get wrong in the guard. \u2705 Acceptable if the TTL is seconds and revocation is rare. \u274c Suspended/revoked tenants stay authorized for up to one TTL, silently.\nC) Investigate the adapter's invalidation API first\n\u2705 Picks the mechanism with evidence rather than a guess. \u2705 Bounded: read the adapter's invalidation hooks and write API. \u274c Leaves this row unresolved at the end of the review; approves nothing.\n\nState: approved\nActual answer: A \u2014 \"Guard in AuthCache.set() (recommended)\" (answer to D6)\nAccepted scope: `AuthCache.set()` is the only write path for the new services and drops a write when an invalidation for the same key (tenant, issuer, audience, policyVersion) arrived after the value was produced. Mechanism (generation counter, compare-and-set, or pre-write re-check of revocation/suspension) is selected at implementation against the real adapter API; adapter and hooks unchanged. Required proof: deterministic concurrency test (invalidate between read and write, assert entry absent; also assert a normal write with no intervening invalidation succeeds).\nHistory: none.\n\n### R6: Error handling shape of `validateAndDispatch()`\nFinding: Code Quality C1, P1, confidence 9/10, PLAN.md:32-33 (\"The `validateAndDispatch()` function is 60 lines with three nested try/catch blocks; each catch swallows a different error class.\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 three nested try/catch blocks, each swallowing a distinct error class.\nRuntime evidence: unknown; no source in repo. Which error classes are swallowed, and what the function returns after a swallow, is unverified.\nComparison grid:\n\n| Choice | Current | A Flatten + boundary | B Keep + log | C Do nothing |\n|---|---|---|---|---|\n| R6 structure | 60 lines, 3 nested try/catch | three explicit steps `validate \u2192 decideAccess \u2192 dispatch`, each throwing a typed error; one catch at the function boundary maps error class \u2192 deny/5xx + structured log; nothing swallowed | nested blocks kept; each catch logs before swallowing | as proposed |\n| fail-open on swallowed auth error | possible (unknown) | impossible: unmapped error \u2192 deny | possible | possible |\n| R2 D4 (`decideAccess` fn), R4 D5, R5 D6 | approved | held | held | held |\n| R3 tests, R7 perf | pending | pending | pending | pending |\n\nQuestion D7:\nD7 \u2014 Flatten validateAndDispatch() into a three-step pipeline with one error boundary, or keep the nested try/catch blocks?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthBroker orchestrates validate \u2192 decideAccess \u2192 dispatch.\nELI10: Right now the function wraps each step in its own try/catch and each catch quietly eats one kind of error (PLAN.md:32-33). In an auth path, \"quietly eat the error\" is the one thing you must never do: if the validation error is swallowed and execution continues, the request may be dispatched as if it passed. The alternative is three plain steps that throw typed errors, and one catch at the edge that turns each error type into an explicit deny or 5xx plus a log line. Anything unrecognized denies. Same behavior for the happy path; no silent continues.\nStakes if we pick wrong: Nested/swallowing: a fail-open bug hides behind a catch and nobody sees a log line; also each catch is untestable in isolation. Flattened: a short refactor and the error taxonomy must be written down (which is a feature).\nRecommendation: A because swallowed errors in an auth dispatcher are a fail-open risk, and the flat pipeline is fewer lines, not more.\nCompleteness: A=10/10, B=6/10, C=2/10\nPros / cons:\nA) Flatten to pipeline + single error boundary (recommended)\n \u2705 Every error class has an explicit, testable mapping; unknown errors deny by default, so nothing fails open\n \u2705 Three steps read top-to-bottom; each step unit-tests without the others (human: ~3h / CC: ~10 min)\n \u274c Requires enumerating the three swallowed error classes and deciding each one's user-visible outcome\nB) Keep nested blocks, add logging in each catch\n \u2705 Minimal diff; swallowed errors at least become visible in logs\n \u2705 No change to control flow\n \u274c Control flow after a swallow is still \"continue\"; fail-open remains possible and the 60-line nesting stays\nC) Do nothing\n \u2705 Zero effort\n \u2705 Preserves whatever current behavior callers rely on, bugs included\n \u274c Three silent catch blocks in the auth path; untestable and a live fail-open risk\nNet: explicit error taxonomy with deny-by-default vs. keeping silent catches in the one place they are most dangerous.\nHeader: Errors\nOptions:\nA) Flatten to pipeline + single error boundary (recommended)\n\u2705 Every error class has an explicit, testable mapping; unknown errors deny by default, so nothing fails open. \u2705 Three steps read top-to-bottom; each step unit-tests without the others (human: ~3h / CC: ~10 min). \u274c Requires enumerating the three swallowed error classes and deciding each one's user-visible outcome.\nB) Keep nested blocks, add logging in each catch\n\u2705 Minimal diff; swallowed errors at least become visible in logs. \u2705 No change to control flow. \u274c Control flow after a swallow is still \"continue\"; fail-open remains possible and the 60-line nesting stays.\nC) Do nothing\n\u2705 Zero effort. \u2705 Preserves whatever current behavior callers rely on, bugs included. \u274c Three silent catch blocks in the auth path; untestable and a live fail-open risk.\n\nState: approved\nActual answer: A \u2014 \"Flatten to pipeline + single error boundary (recommended)\" (answer to D7)\nAccepted scope: `validateAndDispatch()` becomes three explicit steps (`validate` \u2192 `decideAccess` \u2192 `dispatch`), each throwing a typed error; one catch at the function boundary maps each known error class to an explicit deny or 5xx plus a structured log entry; unknown errors deny. The three error classes currently swallowed must be enumerated during implementation and each given an explicit outcome. Required proof: one unit test per mapped error class, one for the unknown-error deny default, one happy-path test.\nHistory: none.\n\n### R3: Regression contract for existing behavior at risk (shared adapter, `legacyAuthFlow()` compatibility)\nFinding: Test T1, P1 (CRITICAL, Iron Rule), confidence 8/10, PLAN.md:23-25 (\"That coverage does not exercise legacyAuthFlow() or assert compatibility with its prior behavior.\") with PLAN.md:20-22 (\"one backing cache. The adapter, its invalidation hooks, and their existing tests remain in use unchanged.\"), reviewer: plan-eng-review (Claude). Web research [Layer 1]: characterization / golden-master tests are the standard scaffold before touching legacy auth code.\nPlan baseline: original proposal \u2014 no regression coverage; D3 deferred the rewrite but the new services still write to the same adapter `legacyAuthFlow()` reads from today.\nRuntime evidence: unknown; no source or tests in repo. `legacyAuthFlow()` callers, its cache usage and existing adapter tests are unverified.\nBehavior to preserve: (1) `legacyAuthFlow()` allow/deny results and cache side effects for its current inputs; (2) adapter entries written by `SessionMint`/`AuthBroker` via `AuthCache` are keyed and shaped so `legacyAuthFlow()` reads them as it reads its own (or never sees them, if keys differ) \u2014 no cross-flow corruption; (3) tenant isolation: an entry for tenant A is never returned for tenant B (A3). Intentional changes: none in this PR (D3).\nComparison grid:\n\n| Choice | Current | A Characterize + shared-adapter integration | B Shared-adapter integration only | C Characterize only, in follow-up PR |\n|---|---|---|---|---|\n| R3 regression coverage | none | characterization tests of `legacyAuthFlow()` recorded now (allow/deny + cache effects for representative inputs, boundary and error cases) AND an integration test running legacy + new services against one adapter instance asserting (1)-(3) | integration test asserting (2)-(3) only; `legacyAuthFlow()` outputs not recorded | characterization tests written when the follow-up rewrite PR starts; nothing in this PR |\n| D3 split, D4 arrangement, D5 injection, D6 guard, D7 pipeline | approved | held | held | held |\n| R7 perf | pending | pending | pending | pending |\n\nQuestion D8:\nD8 \u2014 How do we protect legacyAuthFlow() and the shared cache adapter from regressions in this PR?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; this PR is additive (D3) but writes to the one adapter legacyAuthFlow() still reads.\nELI10: Even though we are no longer rewriting the old login path in this PR, the new services write into the same cache it reads from (PLAN.md:20-21). Nothing today records what the old path actually does, so if a new entry shape or key collides with it, nobody will know until a tenant reports it. A characterization test (\"record what it does now, assert it keeps doing that\") plus one integration test that runs old and new against the same cache gives us that alarm. The plan explicitly skips both (PLAN.md:23-25). The question is how to cover it, not whether.\nStakes if we pick wrong: Too little: a silent auth behavior change for existing tenants with no failing test to point at it, and the follow-up rewrite PR starts with no baseline. Too much: an afternoon writing tests for code that will be rewritten anyway (but those tests are exactly what makes the rewrite safe).\nRecommendation: A because the follow-up rewrite (D3) needs the characterization baseline anyway, and recording it before any adjacent change is when it is cheapest and most trustworthy.\nCompleteness: A=10/10, B=7/10, C=5/10\nPros / cons:\nA) Characterization tests now + shared-adapter integration test (recommended)\n \u2705 Baseline of legacyAuthFlow() behavior captured before anything adjacent changes; the follow-up rewrite PR inherits it\n \u2705 Integration test proves old and new flows coexist on one adapter with tenant isolation intact (human: ~1 day / CC: ~20 min)\n \u274c Tests characterize current behavior bugs included; someone must review the recorded outputs for surprises\nB) Shared-adapter integration test only\n \u2705 Covers the specific new risk this PR introduces (coexistence on one adapter)\n \u2705 Less test code to maintain\n \u274c legacyAuthFlow() outputs stay unrecorded; the follow-up rewrite starts without a baseline\nC) Characterization tests only, deferred to the follow-up PR\n \u2705 Nothing extra in this PR\n \u2705 Baseline written by whoever does the rewrite, closest to the work\n \u274c This PR ships with zero proof the new writes do not disturb the old reads; baseline recorded after adjacent code already changed\nNet: pay for the baseline now while the old path is untouched vs. hope the adapter keys keep the flows apart.\nHeader: Regression\nOptions:\nA) Characterization tests now + shared-adapter integration test (recommended)\n\u2705 Baseline of legacyAuthFlow() behavior captured before anything adjacent changes; the follow-up rewrite PR inherits it. \u2705 Integration test proves old and new flows coexist on one adapter with tenant isolation intact (human: ~1 day / CC: ~20 min). \u274c Tests characterize current behavior bugs included; someone must review the recorded outputs for surprises.\nB) Shared-adapter integration test only\n\u2705 Covers the specific new risk this PR introduces (coexistence on one adapter). \u2705 Less test code to maintain. \u274c legacyAuthFlow() outputs stay unrecorded; the follow-up rewrite starts without a baseline.\nC) Characterization tests only, deferred to the follow-up PR\n\u2705 Nothing extra in this PR. \u2705 Baseline written by whoever does the rewrite, closest to the work. \u274c This PR ships with zero proof the new writes do not disturb the old reads; baseline recorded after adjacent code already changed.\n\nState: approved\nActual answer: A \u2014 \"Characterization tests now + shared-adapter integration test (recommended)\" (answer to D8)\nAccepted scope: (a) characterization tests of `legacyAuthFlow()` recorded in this PR before any adjacent change: representative allow/deny inputs, boundary cases (expired token, missing claims, unknown tenant), current error behavior, and cache side effects (which keys are read/written); (b) an integration test that runs `legacyAuthFlow()` and the new `AuthBroker`/`SessionMint` against one adapter instance and asserts: legacy results unchanged with new entries present; entries written via `AuthCache` never returned to a different tenant; key tenant component comes from validated claims, not request context. Intentional behavior changes in this PR: none. These tests are CRITICAL and block ship.\nHistory: none.\n\n### R7: Token validation's 5 IDP round trips\nFinding: Performance P1, P2, confidence 8/10, PLAN.md:40-41 (\"Token validation issues 5 sequential API calls to the IDP; they could be parallelized via Promise.all trivially (calls are independent).\"), reviewer: plan-eng-review (Claude). Web research [Layer 1]: OIDC discovery and JWKS documents are meant to be cached for hours/days and refreshed on unknown `kid`; per-request fetches are the anti-pattern.\nPlan baseline: original proposal \u2014 parallelize the 5 calls with `Promise.all`.\nRuntime evidence: unknown; no source in repo. Which 5 calls these are (discovery, JWKS, introspection, userinfo, tenant lookup?) is unverified; whether any are already cached is unverified.\nComparison grid:\n\n| Choice | Current | A Cache + parallelize | B Parallelize only | C Do nothing |\n|---|---|---|---|---|\n| R7 per-validation IDP calls | 5 sequential | cache the static documents (discovery, JWKS) in-process with TTL and refresh on unknown `kid`, then run the remaining per-token calls concurrently; per-call timeout; first failure maps to one typed error, no dangling awaits | 5 concurrent via `Promise.all`; per-call timeout; first rejection maps to one typed error | 5 sequential |\n| latency per validation | ~5 \u00d7 RTT | ~0-1 \u00d7 RTT steady state | ~1 \u00d7 RTT | ~5 \u00d7 RTT |\n| IDP load per validation | 5 requests | 1-2 requests steady state | 5 requests, burst | 5 requests |\n| D3-D8 approvals | approved | held | held | held |\n\nQuestion D9:\nD9 \u2014 Cache the static IDP documents and parallelize the rest, or just parallelize the 5 calls?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; validate step of the flattened AuthBroker pipeline (D7).\nELI10: Every login currently makes five round trips to the identity provider, one after another (PLAN.md:40-41). Running them at the same time cuts wall-clock time by about 5x, which is what the plan proposes. But at least some of those calls fetch documents that barely change (the provider's discovery config and its public signing keys), which the standard practice says to cache for hours and only refetch when a token shows up signed by an unknown key. Cache those and most logins need zero or one round trip. Parallelizing alone also turns a 5-call trickle into a 5-call burst per login, which is how you hit IDP rate limits on a busy morning.\nStakes if we pick wrong: Parallelize-only: 5x burstier IDP traffic, still 5 network dependencies per login, and Promise.all's fail-fast leaves the other four requests in flight. Cache + parallelize: a small TTL cache with a stale-key refresh path to get right.\nRecommendation: A because the plan's own evidence (5 calls per validation) says the missing piece is caching, not concurrency; it is the standard OIDC pattern and removes the IDP as a per-request dependency for most logins.\nCompleteness: A=10/10, B=7/10, C=2/10\nPros / cons:\nA) Cache static IDP documents + parallelize remaining calls (recommended)\n \u2705 Steady-state logins need 0-1 IDP round trips instead of 5; IDP outage no longer fails every login that has cached keys\n \u2705 Standard OIDC practice; refresh-on-unknown-kid handles key rotation (human: ~1 day / CC: ~20 min)\n \u274c Must pick TTLs below the IDP's key-rotation overlap window and test the unknown-kid refresh path\nB) Parallelize the 5 calls only (as proposed)\n \u2705 ~5x lower validation latency with a one-line change\n \u2705 No cache invalidation to reason about\n \u274c 5 requests per login in a burst; every login still depends on the IDP being up; fail-fast leaves stragglers in flight\nC) Do nothing\n \u2705 Zero effort; no new failure modes\n \u2705 Sequential calls are easy to trace in logs\n \u274c ~5 \u00d7 RTT on every login, and the plan already called this out as trivially fixable\nNet: remove the IDP from the hot path with a boring cache vs. make the hot path five times faster and five times burstier.\nHeader: IDP calls\nOptions:\nA) Cache static IDP documents + parallelize remaining calls (recommended)\n\u2705 Steady-state logins need 0-1 IDP round trips instead of 5; IDP outage no longer fails every login that has cached keys. \u2705 Standard OIDC practice; refresh-on-unknown-kid handles key rotation (human: ~1 day / CC: ~20 min). \u274c Must pick TTLs below the IDP's key-rotation overlap window and test the unknown-kid refresh path.\nB) Parallelize the 5 calls only (as proposed)\n\u2705 ~5x lower validation latency with a one-line change. \u2705 No cache invalidation to reason about. \u274c 5 requests per login in a burst; every login still depends on the IDP being up; fail-fast leaves stragglers in flight.\nC) Do nothing\n\u2705 Zero effort; no new failure modes. \u2705 Sequential calls are easy to trace in logs. \u274c ~5 \u00d7 RTT on every login, and the plan already called this out as trivially fixable.\n\nState: approved\nActual answer: A \u2014 \"Cache static IDP documents + parallelize remaining calls (recommended)\" (answer to D9)\nAccepted scope: in the `validate` step, cache the static IDP documents (discovery configuration, JWKS) in-process with a TTL below the IDP's key-rotation overlap window and refresh on unknown `kid`; run the remaining per-token IDP calls concurrently with a per-call timeout; the first failure maps to one typed validation error (D7 boundary) and no result is consumed from the remaining calls. Implementation must first enumerate which of the 5 calls are static-document fetches vs. per-token calls (unknown from the plan). Required proof: unit tests for cache hit, TTL expiry, unknown-kid refresh, per-call timeout \u2192 typed error, and one concurrent-call failure \u2192 single mapped error.\nHistory: none.\n\n### TODO decision (D10)\nQuestion D10: Capture the follow-up PR (swap legacyAuthFlow() onto the new services) as a TODO? Recommendation: A. Header: TODO. Options: A) Add to TODOS.md (recommended); B) Skip; C) Build it now in this PR instead.\nState: approved. Actual answer: A \u2014 \"Add to TODOS.md (recommended)\" (answer to D10). Accepted scope: the TODO item below is written to the repo's `TODOS.md` after plan mode exits (plan mode forbids repo writes now; content presented as **not persisted**).\n\nApproval readiness: PASS \u2014 R1 (D3: A), R2 (D4: A), R4 (D5: A), R5 (D6: A), R6 (D7: A), R3 (D8: A), R7 (D9: A), TODO (D10: A). Setup D1/D2 are not remedies. No pending records.\n\n## Review findings (all sections)\n\nConfidence per finding follows the calibration table; medium-confidence items carry a caveat.\n\n### Scope Challenge\n- S1 [P1] (confidence: 9/10) PLAN.md:36-37 \u2014 live `legacyAuthFlow()` rewrite bundled into a 12-file refactor with no regression test. Accepted: split to follow-up PR (D3).\n- S2 [P2] (confidence: 8/10) PLAN.md:44-45, :12-13, :20-21 \u2014 5 classes where RequestPolicy is stateless and TokenStore duplicates AuthCache over one backing cache. Accepted: 3 classes + `decideAccess()` function (D4).\n- S3 [P3] (confidence: 7/10) web research [Layer 1] \u2014 module-level mutable singleton is a documented Node/TS footgun. Carried to A1.\n- S4 [P3] (confidence: 7/10) web research [Layer 1] \u2014 JWKS/discovery should be cached; 5 calls/validation implies missing caching. Carried to P1.\n- Completeness check: original plan is a test shortcut (PLAN.md:23-25). Resolved in Section 3. Distribution check: no new artifact. TODOS.md: absent.\n\n### 1. Architecture\n- A1 [P1] (confidence: 8/10) PLAN.md:28-29 \u2014 global mutable `AuthCache` via module-level export, mutated by two services. Accepted: inject one instance via constructors (D5).\n- A2 [P2] (confidence: 6/10, medium: verify adapter semantics) PLAN.md:19, :29, :17-18 \u2014 unordered mint-write vs. invalidation can re-populate a revoked/suspended tenant's entry until TTL. Accepted: guard in `AuthCache.set()` (D6).\n- A3 [P2] (confidence: 5/10, medium: verify this is actually an issue) PLAN.md:16-17 \u2014 plan does not state whether the tenant component of the cache key comes from validated claims or request context; cross-tenant read possible if the latter. Folded into D8 acceptance assertions.\n- A4 [P2] (confidence: 7/10) PLAN.md:40 \u2014 IDP is a per-request single point of failure with 5 calls per validation and no timeouts mentioned. Resolved by D9 (cached static docs, per-call timeout).\n- Production failure scenarios: AuthBroker \u2014 IDP timeout swallowed by a nested catch (D7 fixes); SessionMint \u2014 write after suspension (D6 fixes); AuthCache \u2014 adapter write throws (D7 boundary surfaces it; test required); `decideAccess()` \u2014 wrong-tenant claims (D8 assertion).\n\n### 2. Code quality\n- C1 [P1] (confidence: 9/10) PLAN.md:32-33 \u2014 60-line `validateAndDispatch()`, three nested try/catch each swallowing an error class: fail-open risk, untestable. Accepted: flat pipeline + single deny-by-default boundary (D7).\n- C2 [P2] (confidence: 8/10) PLAN.md:44 vs :20-21 \u2014 DRY: two wrappers over one cache. Resolved by D4.\n- C3 [P3] (confidence: 7/10) PLAN.md:12-13 \u2014 stateless one-method class. Resolved by D4.\n- C4 [P3] (confidence: 6/10) \u2014 no diagrams planned; `AuthBroker` pipeline and `AuthCache` guard need inline ASCII comments (see Diagrams).\n\n### 3. Tests\n- Framework: unknown (repo has no `package.json`, no test config, 0 test files). Plan's `Promise.all` implies JS/TS; file names below assume `*.test.ts` and must be mapped to the real convention.\n- T1 [P1 CRITICAL] (confidence: 8/10) PLAN.md:23-25 \u2014 no regression coverage while new services write to the adapter `legacyAuthFlow()` reads. Accepted: characterization + shared-adapter integration tests (D8).\n- T2 [P1] (confidence: 9/10) \u2014 0/27 paths covered. Required proof enumerated in Implementation Tasks.\n- T3 [P2] (confidence: 7/10) \u2014 tenant-isolation assertion absent. Folded into D8.\n- T4 [P3] (confidence: 6/10) \u2014 double-submit login / idempotent mint untested. NOT in scope (behavior change).\n\nCoverage diagram (plan-level; no tests exist in the repo today):\n\n```\nCODE PATHS USER FLOWS\n[+] auth/AuthBroker.ts [+] Tenant login (bearer token)\n \u2514\u2500\u2500 validateAndDispatch() \u251c\u2500\u2500 [GAP] [\u2192E2E] valid token \u2192 allow \u2192 dispatched\n \u251c\u2500\u2500 [GAP] validate: happy path \u251c\u2500\u2500 [GAP] [\u2192E2E] expired token \u2192 deny, clear error\n \u251c\u2500\u2500 [GAP] validate: IDP timeout \u2192 typed err \u2192 deny \u251c\u2500\u2500 [GAP] [\u2192E2E] revoked mid-session \u2192 next request denied\n \u251c\u2500\u2500 [GAP] validate: IDP 5xx \u2192 typed err \u2192 5xx \u2514\u2500\u2500 [GAP] [\u2192E2E] tenant suspended \u2192 next request denied\n \u251c\u2500\u2500 [GAP] validate: malformed/expired token \u2192 deny\n \u251c\u2500\u2500 [GAP] decideAccess() deny \u2192 deny (no dispatch) [+] Error states\n \u251c\u2500\u2500 [GAP] dispatch throws \u2192 mapped, logged \u251c\u2500\u2500 [GAP] IDP down \u2192 user sees 5xx, not hang\n \u2514\u2500\u2500 [GAP] unknown error \u2192 deny by default (D7) \u251c\u2500\u2500 [GAP] slow IDP (10s) \u2192 timeout path, not silent\n[+] auth/policy.ts \u2514\u2500\u2500 [GAP] IDP key rotation \u2192 login still works (D9)\n \u2514\u2500\u2500 decideAccess(claims, ctx)\n \u251c\u2500\u2500 [GAP] allow / deny table for existing policy [+] Regression (D8, CRITICAL)\n \u251c\u2500\u2500 [GAP] claims tenant \u2260 ctx tenant \u2192 deny (A3) \u251c\u2500\u2500 [GAP] [\u2192E2E] legacyAuthFlow() characterization\n \u2514\u2500\u2500 [GAP] missing/empty claims \u2192 deny \u2514\u2500\u2500 [GAP] [\u2192E2E] legacy + new on one adapter, tenant isolation\n[+] auth/AuthCache.ts\n \u251c\u2500\u2500 get(): [GAP] hit / miss / expired-evicted\n \u251c\u2500\u2500 set(): [GAP] normal write persists\n \u251c\u2500\u2500 set(): [GAP] write after invalidation dropped (D6 proof)\n \u251c\u2500\u2500 [GAP] key = (tenant from CLAIMS, issuer, audience, policyVersion)\n \u2514\u2500\u2500 [GAP] adapter throws \u2192 surfaced, not swallowed\n[+] auth/SessionMint.ts\n \u251c\u2500\u2500 [GAP] mint \u2192 AuthCache.set() called once with correct key\n \u2514\u2500\u2500 [GAP] mint during suspension \u2192 no entry (D6)\n[+] auth/idp-client.ts (D9)\n \u251c\u2500\u2500 [GAP] discovery/JWKS cache hit, TTL expiry, unknown-kid refresh\n \u2514\u2500\u2500 [GAP] concurrent per-token calls: one failure \u2192 single typed error, per-call timeout\n\nCOVERAGE: 0/29 paths tested (0%) | Code paths: 0/20 (0%) | User flows: 0/9 (0%)\nQUALITY: \u2605\u2605\u2605:0 \u2605\u2605:0 \u2605:0 | GAPS: 29 (7 E2E, 0 eval)\n```\n\nLegend: \u2605\u2605\u2605 behavior + edge + error | \u2605\u2605 happy path | \u2605 smoke | [\u2192E2E] integration test. No LLM/prompt scope; no eval.\n\nTest Plan artifact: `~/.gstack/projects/gstack-plan-count-eecImF/vercel-sandbox-main-eng-review-test-plan-20260916-105826.md`.\n\n### 4. Performance\n- P1 [P2] (confidence: 8/10) PLAN.md:40-41 \u2014 5 sequential IDP calls; `Promise.all` alone misses static-document caching and fail-fast stragglers. Accepted: cache discovery/JWKS + parallelize remainder with per-call timeout (D9).\n- P2 [P3] (confidence: 6/10) PLAN.md:16-18 \u2014 adapter access pattern unchanged; no N+1 visible; JWKS cache memory negligible. No action.\n\n### Outside Voice\nCodex review skipped: `codex_reviews` is `disabled`. Recorded `outside_status: disabled`. No native replacement (disabled is an opt-out, not a provider failure). Re-enable: `gstack-config set codex_reviews enabled`.\n\n### Suppressed findings (confidence \u2264 4)\n- (4/10) Whether `SessionMint` and `AuthBroker` need to share the cache at all, or whether `SessionMint` only writes and `AuthBroker` only reads \u2014 if so, a read-only view for `AuthBroker` would shrink the mutation surface further. Unverifiable without source.\n\n## NOT in scope\n- `legacyAuthFlow()` rewrite / caller swap \u2014 deferred to a follow-up PR (D3); tracked in the TODO below.\n- Idempotent session mint (double-submit protection) \u2014 would change behavior; this PR is behavior-preserving.\n- Changes to the existing cache adapter, its keying, eviction, or invalidation hooks \u2014 retained contract (PLAN.md:16-22).\n- Any change to the access policy itself \u2014 `decideAccess()` groups the existing decision; no new rules.\n- Distribution/CI changes \u2014 no new artifact is produced by this plan.\n- Cross-model outside review \u2014 disabled by config.\n\n## What already exists\n- The cache adapter with tenant/issuer/audience/policy-version keys, eviction, and invalidation hooks, plus its tests (PLAN.md:16-22): **reused unchanged** via the `AuthCache` facade. The plan's `TokenStore` would have rebuilt a second wrapper over it; cut by D4.\n- The existing per-request access decision (PLAN.md:9-13): **reused** as the body of `decideAccess()`; no new policy.\n- `legacyAuthFlow()`: **left running** in this PR; becomes the characterization baseline (D8) for its own later replacement.\n- Existing IDP client calls (PLAN.md:40): reused; D9 adds a cache in front of the static-document fetches rather than rewriting the client.\n\n## Diagrams\nPlan-level data flow is in the Architecture section above. Inline ASCII comments should ship in:\n- `AuthBroker.validateAndDispatch()` \u2014 the three-step pipeline and the error boundary mapping table (error class \u2192 outcome).\n- `AuthCache.set()` \u2014 the read \u2192 invalidation \u2192 write ordering the guard protects against (D6).\n- `idp-client` (D9) \u2014 cache lifecycle: hit / TTL expiry / unknown-kid refresh.\n- Characterization test file \u2014 a short comment stating these tests record current behavior, bugs included, and are the acceptance gate for the follow-up rewrite.\n\n## Failure modes\n| Codepath | Realistic failure | Test | Error handling | User sees | Critical gap? |\n|---|---|---|---|---|---|\n| `validate` (IDP) | IDP timeout / 5xx | required (D7, D9) | typed error \u2192 5xx (D7) | explicit error, retry | no (after D7/D9) |\n| `validate` | key rotation, unknown `kid` | required (D9) | refresh JWKS once, else deny | login works or explicit deny | no |\n| `decideAccess()` | claims tenant \u2260 ctx tenant | required (D8) | deny | 403 | no |\n| `dispatch` | downstream throws | required (D7) | mapped at boundary | explicit error | no |\n| `AuthCache.set()` | write after invalidation | required (D6) | write dropped | next request re-validates | no |\n| `AuthCache.set()` | adapter throws | required | surfaced via boundary | explicit error | no |\n| `legacyAuthFlow()` coexistence | key/shape collision with new entries | required (D8) | n/a (test-only detection) | would be silent without D8 | no (after D8) |\n| Unknown error anywhere in pipeline | unmapped exception | required (D7) | deny by default | 403/5xx | no |\n\nCritical gaps flagged: **0** after accepted remedies. Before this review, the coexistence and swallowed-error rows were both untested, unhandled, and silent.\n\n## Worktree parallelization strategy\n| Step | Modules touched | Depends on |\n|---|---|---|\n| W1 Characterization tests for `legacyAuthFlow()` (D8a) | tests/auth (legacy) | \u2014 |\n| W2 `AuthCache` facade + set() guard + tests (D4, D6) | auth/cache | \u2014 |\n| W3 `decideAccess()` policy module + tests (D4) | auth/policy | \u2014 |\n| W4 IDP client cache + parallel calls + tests (D9) | auth/idp-client | \u2014 |\n| W5 `AuthBroker` pipeline + boundary + `SessionMint` + composition root (D5, D7) | auth/broker, auth/session, app wiring | W2, W3, W4 |\n| W6 Shared-adapter integration test (D8b) | tests/auth (integration) | W1, W5 |\n\nLanes: `Lane A: W1 (independent)` / `Lane B: W2 (independent)` / `Lane C: W3 (independent)` / `Lane D: W4 (independent)` / `Lane E: W5 \u2192 W6 (sequential, waits on A-D)`.\nExecution order: launch A, B, C, D in parallel worktrees; merge all four; then E. Conflict flags: W5 touches app wiring that W2/W4 constructors define; keep constructor signatures agreed before launching B and D, or expect a small merge fix in W5.\n\n## Implementation Tasks\nSynthesized from this review's findings. Each task derives from a specific finding above. Run with Claude Code or Codex; checkbox as you ship. Effort assumption: tests ~50x, architecture ~5x, features ~30x human\u00f7CC.\n\n- [ ] **T1 (P1, human: ~1 day / CC: ~20 min)** \u2014 tests/auth \u2014 Record characterization tests for `legacyAuthFlow()` before any adjacent change\n - Surfaced by: Test review \u2014 T1 / D8 (PLAN.md:23-25)\n - Files: new `legacyAuthFlow.characterization.test.*` (map to project convention)\n - Verify: tests pass against current `main` with zero production changes\n- [ ] **T2 (P1, human: ~0.5 day / CC: ~10 min)** \u2014 auth/cache \u2014 Implement `AuthCache` facade (absorbing `TokenStore` role) with invalidation-aware `set()` guard\n - Surfaced by: Architecture A2 / D6; Scope S2 / D4 (PLAN.md:19-21, :29)\n - Files: `auth/AuthCache.*`; adapter untouched\n - Verify: unit tests: hit/miss/expired, normal write persists, write-after-invalidation dropped, adapter throw surfaced\n- [ ] **T3 (P1, human: ~0.5 day / CC: ~10 min)** \u2014 auth/broker \u2014 Flatten `validateAndDispatch()` into validate \u2192 decideAccess \u2192 dispatch with one deny-by-default error boundary; enumerate the three swallowed error classes\n - Surfaced by: Code quality C1 / D7 (PLAN.md:32-33)\n - Files: `auth/AuthBroker.*`\n - Verify: one test per mapped error class, unknown-error deny, happy path\n- [ ] **T4 (P1, human: ~2h / CC: ~5 min)** \u2014 auth/policy \u2014 Implement `decideAccess(claims, ctx)` as a pure function grouping the existing decision\n - Surfaced by: Scope S2 / D4 (PLAN.md:9-13)\n - Files: `auth/policy.*`\n - Verify: allow/deny table, tenant mismatch \u2192 deny, empty claims \u2192 deny\n- [ ] **T5 (P1, human: ~2h / CC: ~5 min)** \u2014 app wiring \u2014 Construct one `AuthCache` at the composition root; inject into `AuthBroker` and `SessionMint`; remove module-level export\n - Surfaced by: Architecture A1 / D5 (PLAN.md:28-29)\n - Files: composition root / app bootstrap, `AuthBroker`, `SessionMint` constructors\n - Verify: grep confirms no module-level `AuthCache` instance export; unit tests construct fresh instances\n- [ ] **T6 (P1, human: ~1 day / CC: ~20 min)** \u2014 tests/auth \u2014 Shared-adapter integration test: legacy + new services on one adapter; legacy results unchanged; tenant isolation; key tenant from claims\n - Surfaced by: Test review T1, T3; Architecture A3 / D8\n - Files: new `auth.coexistence.integration.test.*`\n - Verify: passes with new entries present; fails if a cross-tenant read occurs\n- [ ] **T7 (P2, human: ~1 day / CC: ~20 min)** \u2014 auth/idp-client \u2014 Cache discovery/JWKS with TTL + unknown-kid refresh; run per-token calls concurrently with per-call timeout; first failure \u2192 single typed error\n - Surfaced by: Performance P1 / D9; Architecture A4 (PLAN.md:40-41)\n - Files: `auth/idp-client.*`\n - Verify: tests for cache hit, TTL expiry, kid refresh, timeout \u2192 typed error, one failure \u2192 single error\n- [ ] **T8 (P2, human: ~1h / CC: ~3 min)** \u2014 auth \u2014 Inline ASCII diagrams in `AuthBroker`, `AuthCache.set()`, idp-client\n - Surfaced by: Code quality C4\n - Files: same as T2, T3, T7\n - Verify: diagrams match implemented control flow at PR review\n- [ ] **T9 (P3, human: ~15 min / CC: ~2 min)** \u2014 repo \u2014 Add `TODOS.md` entry for the follow-up `legacyAuthFlow()` swap (after plan mode exits)\n - Surfaced by: Scope S1 / D3, D10\n - Files: `TODOS.md`\n - Verify: file present with the item below\n\n_No new tasks from Performance beyond T7._\n\n### TODO item (accepted D10; **not persisted** \u2014 write to `TODOS.md` after plan mode exits)\n```markdown\n# TODOS\n\n## Auth\n\n### Swap legacyAuthFlow() onto AuthBroker and delete the legacy path\n\n**What:** Point all `legacyAuthFlow()` callers at `AuthBroker.validateAndDispatch()` and remove `legacyAuthFlow()`.\n\n**Why:** The multi-tenant auth refactor (2026-09-16 eng review, decision D3) landed the new services additively to keep rollback trivial. Until this swap ships, two auth paths coexist and write to one cache adapter.\n\n**Context:** Acceptance gate is the characterization test suite recorded in that PR (decision D8): the swapped path must produce the same allow/deny results and cache effects for the recorded inputs, or each difference must be an intentional, documented change. Start after the new services have soaked in production. Start point: the characterization test file and `AuthBroker.validateAndDispatch()`.\n\n**Effort:** M\n**Priority:** P1\n**Depends on:** Auth refactor PR merged and soaked; characterization tests green.\n```\n\n## Unresolved decisions that may bite you later\nNone. All nine remedy/scope choices (D3-D10) have actual answers; D1/D2 were setup.\n\n## Completion summary\n- Step 0: Scope Challenge \u2014 scope reduced per recommendation (D3 split, D4 3 classes + 1 fn)\n- Architecture Review: 4 issues found (2 accepted remedies, 1 folded into D8, 1 resolved by D9)\n- Code Quality Review: 4 issues found (1 accepted remedy, 2 resolved by D4, 1 documentation task)\n- Test Review: diagram produced, 29 gaps identified (0 tests exist; framework unknown)\n- Performance Review: 2 issues found (1 accepted remedy, 1 no action)\n- NOT in scope: written\n- What already exists: written\n- TODOS.md updates: 1 item proposed to user (accepted, not persisted until plan mode exits)\n- Failure modes: 0 critical gaps flagged (after accepted remedies)\n- Unresolved decisions: 0 in this review\n- Outside voice: codex, disabled (codex_reviews=disabled); no native replacement\n- Parallelization: 5 lanes, 4 parallel / 1 sequential\n- Lake Score: 5/5 (D5, D6, D7, D8, D9 all selected the 10/10 option; D3, D4, D10 differ in kind)\n- Deferred host-mode follow-ups: D1 routing rules \u2192 append to `CLAUDE.md` and commit; D10 \u2192 create `TODOS.md`. Both blocked by plan mode during this review.\n\n## GSTACK REVIEW REPORT\n\n| Review | Trigger | Why | Runs | Status | Findings |\n|--------|---------|-----|------|--------|----------|\n| CEO Review | `/plan-ceo-review` | Scope & strategy | 0 | \u2014 | \u2014 |\n| Outside Review | codex via `/plan-eng-review` | Independent 2nd opinion | 1 | DISABLED (skipped, outside_status: disabled, phase: plan-review, host: claude) | \u2014 |\n| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 1 | CLEAR (PLAN, SCOPE_REDUCED) | 14 issues, 0 critical gaps |\n| Design Review | `/plan-design-review` | UI/UX gaps | 0 | \u2014 | \u2014 |\n| DX Review | `/plan-devex-review` | Developer experience gaps | 0 | \u2014 | \u2014 |\n\n- **OUTSIDE COVERAGE:** provider codex, phase plan-review, disabled by `codex_reviews` config; no outside process ran; no native replacement; no findings. Not counted as clean coverage.\n- **VERDICT:** ENG CLEARED \u2014 ready to implement (scope reduced per D3/D4; all remedies approved).\n\nNO UNRESOLVED DECISIONS\n",
"correctedQuestionsPlan": "# Plan: Multi-tenant Auth Refactor (reviewed)\n\nReviewed target: `PLAN.md` (\"Plan: Multi-tenant Auth Refactor\") in repo `gstack-plan-count-eecImF`, branch `main`, commit `dc3b5e2`.\nReview: `/plan-eng-review`, 2026-09-16. Report destination: this file (explicitly requested by the user).\nRuntime evidence note: the repository under review contains only `CLAUDE.md` and `PLAN.md`. No implementation source, tests, or test framework are present. Every finding below is a plan-level finding quoting `PLAN.md:line`; runtime behavior of `legacyAuthFlow()`, the cache adapter, and the IDP calls is **unknown** and must be verified against the real codebase at implementation time.\n\n## Context (from the plan author)\n\nThe goal is to reorganize existing tenant-auth orchestration without changing its product behavior (PLAN.md:8-9). RequestPolicy groups the existing per-request access decision: given already-fetched claims and tenant/request context, it returns allow or deny under the existing access policy. AuthBroker.validateAndDispatch() calls it after validation and before dispatch. It adds no policy, network call, cache mutation or state (PLAN.md:9-13).\n\n## Existing contracts retained (unchanged by this review)\n\n- The existing cache adapter keys entries by tenant ID, issuer, audience, and policy version (PLAN.md:16-17).\n- It evicts expired tokens and invalidates entries on logout, token revocation, or tenant suspension (PLAN.md:17-18).\n- AuthCache is a service-facing facade over that same existing adapter, with one backing cache (PLAN.md:20-21). The adapter, its invalidation hooks, and their existing tests remain in use unchanged (PLAN.md:21-22).\n- The adapter does not serialize mutations (PLAN.md:19).\n\n## Scope as amended by this review\n\n| Item | Original plan | Reviewed plan | Decision |\n|---|---|---|---|\n| `legacyAuthFlow()` rewrite | In this PR, no regression test (PLAN.md:36-37) | **Deferred to a follow-up PR.** This PR is additive: new services land, `legacyAuthFlow()` keeps serving tenants unchanged. | D3 |\n| New classes | 5: AuthBroker, TokenStore, SessionMint, AuthCache, RequestPolicy (PLAN.md:44-45) | **3 classes + 1 function:** `AuthBroker`, `SessionMint`, `AuthCache`; `RequestPolicy` becomes a pure function `decideAccess(claims, ctx)` in a policy module; `TokenStore` folded into `AuthCache` (one wrapper over the one backing cache). If implementation discovers a responsibility that must not live in `AuthCache` (e.g. refresh-token persistence), name it explicitly and raise it, do not silently re-add `TokenStore`. | D4 |\n| Files touched | 12 (PLAN.md:44) | Expected to drop with the two cuts above; re-count at implementation. | D3, D4 |\n\n## Architecture (reviewed)\n\nProposed data flow for this PR (additive layer; `legacyAuthFlow()` untouched):\n\n```\n request (tenant ctx, bearer token)\n |\n v\n +---------------------------+\n | AuthBroker |\n | validateAndDispatch() |\n | 1. validate token -----+----> IDP (discovery / JWKS / introspection ...)\n | 2. decideAccess() -----+----> policy module (pure fn, no I/O)\n | 3. dispatch |\n +------------+--------------+\n | reads/writes\n v\n SessionMint ---------> AuthCache (facade) ---------> existing cache adapter\n (mints sessions, one instance, keys: tenant, issuer,\n writes entries) one backing cache audience, policyVersion\n invalidation hooks:\n logout / revoke / suspend\n ^\n | (still reads/writes the SAME adapter today)\n legacyAuthFlow() [unchanged in this PR]\n```\n\nOriginal proposal (PLAN.md:28-29): AuthBroker and SessionMint share a global mutable AuthCache instance via module-level export; both services mutate it. Reviewed disposition: see Section 1 findings and the decision ledger.\n\n## Code quality (reviewed)\n\nOriginal proposal (PLAN.md:32-33): `validateAndDispatch()` is 60 lines with three nested try/catch blocks; each catch swallows a different error class. Reviewed disposition: see Section 2 findings and the decision ledger.\n\n## Tests (reviewed)\n\nOriginal proposal (PLAN.md:23-25, 36-37): unit and integration coverage for the new components' success/error paths; that coverage does not exercise `legacyAuthFlow()` or assert compatibility with its prior behavior; no regression test planned. Reviewed disposition: see Section 3 (test review, coverage diagram, regression contract) and the decision ledger.\n\n## Performance (reviewed)\n\nOriginal proposal (PLAN.md:40-41): token validation issues 5 sequential API calls to the IDP; parallelize via Promise.all (calls are independent). Reviewed disposition: see Section 4 findings and the decision ledger.\n\n## Decision ledger\n\nSetup questions (not remedies): D1 routing rules \u2192 A (add; deferred until plan mode exits). D2 cross-project learnings \u2192 A (enabled).\n\n### R1: Scope of `legacyAuthFlow()` rewrite in this PR\nFinding: Scope Challenge S1, P1, confidence 9/10, PLAN.md:36-37 (\"The existing `legacyAuthFlow()` will get rewritten as part of this work; no regression test for the prior behavior is planned.\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 rewrite in this PR.\nRuntime evidence: unknown; no source in repo. `legacyAuthFlow()` callers and current behavior unverified.\nComparison grid (initial scope selector; no pre-answer grid required):\n\n| Choice | Current | A Split | B Bundle | C Hold |\n|---|---|---|---|---|\n| R1 rewrite in this PR | yes, pending | no; follow-up PR | yes | undecided |\n| R3 regression contract (Test review) | pending | pending | pending | pending |\n\nQuestion D3: Keep the legacyAuthFlow() rewrite in this PR, or split it into a follow-up behind the new services? Recommendation: Split (recommended) because the plan's own goal is \"no product behavior change\"; the rewrite is the single riskiest step and it gets cheaper and safer once the new services exist and are exercised. (Note: the brief's prose line said \"B\" while the `(recommended)` label sat on the Split option; the user selected the labeled Split option.)\nHeader: Scope\nOptions:\nA) Split: defer rewrite to follow-up PR (recommended)\nB) Bundle: rewrite legacyAuthFlow() in this PR\nC) Hold: discuss before deciding\n\nState: approved\nActual answer: A \u2014 \"Split: defer rewrite to follow-up PR (recommended)\" (answer to D3)\nAccepted scope: this PR does not modify `legacyAuthFlow()`; its rewrite/swap moves to a follow-up PR after the new services are exercised. Regression coverage remains a separate pending choice (R3).\nHistory: none.\n\n### R2: Class arrangement for the new service layer\nFinding: Scope Challenge S2, P2, confidence 8/10, PLAN.md:44-45 (\"introduces 5 new classes (AuthBroker, TokenStore, SessionMint, AuthCache, RequestPolicy)\") with PLAN.md:12-13 (RequestPolicy \"adds no policy, network call, cache mutation or state\") and PLAN.md:20-21 (AuthCache \"facade over that same existing adapter, with one backing cache\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 5 classes.\nRuntime evidence: unknown; no source in repo.\nComparison grid (initial scope selector):\n\n| Choice | Current | A | B | C |\n|---|---|---|---|---|\n| R2 arrangement | 5 classes | AuthBroker, SessionMint, AuthCache + `decideAccess()` fn | AuthBroker, SessionMint, AuthCache, RequestPolicy class | 5 classes as proposed |\n| cache adapter contract (PLAN.md:16-22) | fixed | fixed | fixed | fixed |\n| R-singleton, R-trycatch, R-perf, R3 tests | pending | pending | pending | pending |\n\nQuestion D4: Class arrangement: keep all 5 new classes, or collapse to 3 (RequestPolicy as a pure function, TokenStore folded into AuthCache)? Recommendation: A because the plan's own text gives RequestPolicy no state and TokenStore no role; three classes plus one function covers every described responsibility with fewer seams to test.\nHeader: Structure\nOptions:\nA) 3 classes + 1 function (recommended)\nB) 4 classes: drop TokenStore, keep RequestPolicy class\nC) 5 classes as proposed\n\nState: approved\nActual answer: A \u2014 \"3 classes + 1 function (recommended)\" (answer to D4)\nAccepted scope: `AuthBroker`, `SessionMint`, `AuthCache` as classes; `RequestPolicy` implemented as pure function `decideAccess(claims, ctx)`; `TokenStore` not created, its role (if any) absorbed by `AuthCache`; cache adapter contract unchanged.\nHistory: none.\n\n### R4: How AuthBroker and SessionMint obtain the shared AuthCache instance\nFinding: Architecture A1, P1, confidence 8/10, PLAN.md:28-29 (\"Two new services (`AuthBroker` and `SessionMint`) share a global mutable `AuthCache` instance via module-level export. Both services mutate it.\"), reviewer: plan-eng-review (Claude). Web research [Layer 1]: module-level mutable singletons break test isolation (Jest module-cache resets, no per-test reset) and risk cross-request leakage in server runtimes.\nPlan baseline: original proposal \u2014 module-level exported instance.\nRuntime evidence: unknown; no source in repo. Whether the codebase already has a composition root / DI container is unverified.\nComparison grid:\n\n| Choice | Current | A Inject | B Keep export | C Export + reset hook |\n|---|---|---|---|---|\n| R4 wiring of AuthCache | module-level export, mutated by both | one `AuthCache` constructed at the composition root, passed to `AuthBroker` and `SessionMint` constructors; no module-level export | module-level export as proposed | module-level export plus `__resetForTests()` |\n| single backing cache (PLAN.md:21) | fixed | fixed (one instance) | fixed | fixed |\n| adapter contract (PLAN.md:16-22) | fixed | fixed | fixed | fixed |\n| R2 arrangement | approved D4 | held | held | held |\n| R5 invalidation race, R6 try/catch, R3 tests, R7 perf | pending | pending | pending | pending |\n\nQuestion D5:\nD5 \u2014 Inject one AuthCache instance into both services, or keep the module-level global export?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; additive service layer (D3), 3 classes + 1 function (D4).\nELI10: The plan puts the shared cache wrapper in a global variable that any file can import and mutate (PLAN.md:28-29). That works until you need two of them: one real, one fake for a test; or one per tenant shard. Passing the instance into each service's constructor (dependency injection, \"hand the thing to the code that needs it instead of letting it reach for a global\") costs a few lines at startup and makes every test able to use a fresh cache without module-cache tricks. Still exactly one backing cache in production.\nStakes if we pick wrong: Global: tests leak cache state across cases, flaky auth tests, and a hidden import graph where any module can mutate the auth cache. Injected: a few extra constructor parameters and a startup wiring file to maintain.\nRecommendation: A because it is the boring, standard fix, costs minutes, and the plan already promises \"one backing cache\", which injection preserves while the global adds nothing but reach.\nCompleteness: A=10/10, B=3/10, C=6/10\nNet: explicit ownership and testability vs. one fewer wiring file.\nHeader: Wiring\nOptions:\nA) Inject via constructor (recommended)\n\u2705 Tests construct a fresh AuthCache (or fake) per case; no module-cache reset hacks, no cross-test leakage. \u2705 Mutation surface is explicit: only AuthBroker and SessionMint hold a reference (human: ~2h / CC: ~5 min). \u274c Adds a small composition-root/wiring step and constructor params to maintain.\nB) Keep module-level export\n\u2705 Zero wiring; matches the plan as written. \u2705 Fewer constructor parameters. \u274c Any module can import and mutate the auth cache; test isolation depends on runner module-cache behavior.\nC) Module-level export plus a test-only reset hook\n\u2705 Keeps the plan's shape while giving tests a reset lever. \u2705 Smallest diff from the proposal. \u274c Ships test-only code in production; global mutation surface unchanged; reset hooks are a known smell.\n\nState: approved\nActual answer: A \u2014 \"Inject via constructor (recommended)\" (answer to D5)\nAccepted scope: one `AuthCache` instance constructed at the composition root and passed to `AuthBroker` and `SessionMint` constructors; no module-level exported instance; unit tests construct a fresh `AuthCache` (or fake) per case. Same single backing adapter in production.\nHistory: none.\n\n### R5: Cache write racing an invalidation (SessionMint write after logout/revocation/suspension)\nFinding: Architecture A2, P2, confidence 6/10 (medium: adapter semantics unverified), PLAN.md:19 (\"they do not serialize mutations\") together with PLAN.md:29 (\"Both services mutate it.\") and PLAN.md:17-18 (\"invalidates entries on logout, token revocation, or tenant suspension\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 no ordering guarantee between a SessionMint write and an invalidation for the same key.\nRuntime evidence: unknown; no source in repo. Whether the adapter exposes a generation/version or compare-and-set is unverified.\nComparison grid:\n\n| Choice | Current | A Guard in facade | B Accept + document | C Investigate first |\n|---|---|---|---|---|\n| R5 late-write behavior | unspecified: a mint that started before an invalidation may write after it and re-populate a revoked/suspended entry | `AuthCache.set()` is the only write path and drops a write when an invalidation for that key (tenant, issuer, audience, policyVersion) arrived after the value was produced; mechanism chosen against the adapter (generation counter, CAS, or re-check of suspension/revocation before write) | window accepted; documented in AuthCache with the TTL bound as the maximum stale exposure | unchanged, pending; bounded probe of the adapter's invalidation API before deciding |\n| adapter contract (PLAN.md:16-22) | fixed | fixed (facade-side guard, adapter untouched) | fixed | fixed |\n| R4 injection | approved D5 | held | held | held |\n| R6 try/catch, R3 tests, R7 perf | pending | pending | pending | pending |\n\nQuestion D6:\nD6 \u2014 Guard against a session write landing after an invalidation for the same tenant key, or accept the window?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthCache is now an injected single instance (D5).\nELI10: Two things can touch the same cache slot at once: SessionMint finishing a login and writing a fresh entry, and an invalidation hook wiping that entry because the tenant was suspended or the token revoked (PLAN.md:17-18). The plan says nothing orders these (PLAN.md:19). If the write lands second, a suspended tenant's session is back in the cache until it expires. The fix is a guard inside AuthCache's single write path: refuse a write whose inputs predate a later invalidation. Exactly how (a counter, compare-and-set, or a re-check) depends on what the adapter offers, which I could not read.\nStakes if we pick wrong: Unguarded: a revoked or suspended tenant keeps working for up to one TTL; that is a security window, and it is silent. Guarded: a few lines in AuthCache.set() and one concurrency test; risk of over-rejecting legitimate writes if the guard is too coarse.\nRecommendation: A because AuthCache is the one write path by design (PLAN.md:20-21, D4), so this is the cheapest place the guard will ever be, and the failure mode is a silent security hole.\nCompleteness: A=10/10, B=4/10, C=n/a (investigation, no remedy)\nNet: a small guard at the only write path vs. a silent authorization window bounded by TTL.\nHeader: Race\nOptions:\nA) Guard in AuthCache.set() (recommended)\n\u2705 Closes the revoke-then-repopulate window at the single write path; adapter and hooks stay untouched. \u2705 One deterministic concurrency test proves it: invalidate between read and write, assert entry absent (human: ~4h / CC: ~10 min). \u274c Mechanism must be picked against the real adapter; a too-coarse guard rejects legitimate writes.\nB) Accept the window, document the TTL bound\n\u2705 No new logic; nothing to get wrong in the guard. \u2705 Acceptable if the TTL is seconds and revocation is rare. \u274c Suspended/revoked tenants stay authorized for up to one TTL, silently.\nC) Investigate the adapter's invalidation API first\n\u2705 Picks the mechanism with evidence rather than a guess. \u2705 Bounded: read the adapter's invalidation hooks and write API. \u274c Leaves this row unresolved at the end of the review; approves nothing.\n\nState: approved\nActual answer: A \u2014 \"Guard in AuthCache.set() (recommended)\" (answer to D6)\nAccepted scope: `AuthCache.set()` is the only write path for the new services and drops a write when an invalidation for the same key (tenant, issuer, audience, policyVersion) arrived after the value was produced. Mechanism (generation counter, compare-and-set, or pre-write re-check of revocation/suspension) is selected at implementation against the real adapter API; adapter and hooks unchanged. Required proof: deterministic concurrency test (invalidate between read and write, assert entry absent; also assert a normal write with no intervening invalidation succeeds).\nHistory: none.\n\n### R6: Error handling shape of `validateAndDispatch()`\nFinding: Code Quality C1, P1, confidence 9/10, PLAN.md:32-33 (\"The `validateAndDispatch()` function is 60 lines with three nested try/catch blocks; each catch swallows a different error class.\"), reviewer: plan-eng-review (Claude).\nPlan baseline: original proposal \u2014 three nested try/catch blocks, each swallowing a distinct error class.\nRuntime evidence: unknown; no source in repo. Which error classes are swallowed, and what the function returns after a swallow, is unverified.\nComparison grid:\n\n| Choice | Current | A Flatten + boundary | B Keep + log | C Do nothing |\n|---|---|---|---|---|\n| R6 structure | 60 lines, 3 nested try/catch | three explicit steps `validate \u2192 decideAccess \u2192 dispatch`, each throwing a typed error; one catch at the function boundary maps error class \u2192 deny/5xx + structured log; nothing swallowed | nested blocks kept; each catch logs before swallowing | as proposed |\n| fail-open on swallowed auth error | possible (unknown) | impossible: unmapped error \u2192 deny | possible | possible |\n| R2 D4 (`decideAccess` fn), R4 D5, R5 D6 | approved | held | held | held |\n| R3 tests, R7 perf | pending | pending | pending | pending |\n\nQuestion D7:\nD7 \u2014 Flatten validateAndDispatch() into a three-step pipeline with one error boundary, or keep the nested try/catch blocks?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; AuthBroker orchestrates validate \u2192 decideAccess \u2192 dispatch.\nELI10: Right now the function wraps each step in its own try/catch and each catch quietly eats one kind of error (PLAN.md:32-33). In an auth path, \"quietly eat the error\" is the one thing you must never do: if the validation error is swallowed and execution continues, the request may be dispatched as if it passed. The alternative is three plain steps that throw typed errors, and one catch at the edge that turns each error type into an explicit deny or 5xx plus a log line. Anything unrecognized denies. Same behavior for the happy path; no silent continues.\nStakes if we pick wrong: Nested/swallowing: a fail-open bug hides behind a catch and nobody sees a log line; also each catch is untestable in isolation. Flattened: a short refactor and the error taxonomy must be written down (which is a feature).\nRecommendation: A because swallowed errors in an auth dispatcher are a fail-open risk, and the flat pipeline is fewer lines, not more.\nCompleteness: A=10/10, B=6/10, C=2/10\nNet: explicit error taxonomy with deny-by-default vs. keeping silent catches in the one place they are most dangerous.\nHeader: Errors\nOptions:\nA) Flatten to pipeline + single error boundary (recommended)\n\u2705 Every error class has an explicit, testable mapping; unknown errors deny by default, so nothing fails open. \u2705 Three steps read top-to-bottom; each step unit-tests without the others (human: ~3h / CC: ~10 min). \u274c Requires enumerating the three swallowed error classes and deciding each one's user-visible outcome.\nB) Keep nested blocks, add logging in each catch\n\u2705 Minimal diff; swallowed errors at least become visible in logs. \u2705 No change to control flow. \u274c Control flow after a swallow is still \"continue\"; fail-open remains possible and the 60-line nesting stays.\nC) Do nothing\n\u2705 Zero effort. \u2705 Preserves whatever current behavior callers rely on, bugs included. \u274c Three silent catch blocks in the auth path; untestable and a live fail-open risk.\n\nState: approved\nActual answer: A \u2014 \"Flatten to pipeline + single error boundary (recommended)\" (answer to D7)\nAccepted scope: `validateAndDispatch()` becomes three explicit steps (`validate` \u2192 `decideAccess` \u2192 `dispatch`), each throwing a typed error; one catch at the function boundary maps each known error class to an explicit deny or 5xx plus a structured log entry; unknown errors deny. The three error classes currently swallowed must be enumerated during implementation and each given an explicit outcome. Required proof: one unit test per mapped error class, one for the unknown-error deny default, one happy-path test.\nHistory: none.\n\n### R3: Regression contract for existing behavior at risk (shared adapter, `legacyAuthFlow()` compatibility)\nFinding: Test T1, P1 (CRITICAL, Iron Rule), confidence 8/10, PLAN.md:23-25 (\"That coverage does not exercise legacyAuthFlow() or assert compatibility with its prior behavior.\") with PLAN.md:20-22 (\"one backing cache. The adapter, its invalidation hooks, and their existing tests remain in use unchanged.\"), reviewer: plan-eng-review (Claude). Web research [Layer 1]: characterization / golden-master tests are the standard scaffold before touching legacy auth code.\nPlan baseline: original proposal \u2014 no regression coverage; D3 deferred the rewrite but the new services still write to the same adapter `legacyAuthFlow()` reads from today.\nRuntime evidence: unknown; no source or tests in repo. `legacyAuthFlow()` callers, its cache usage and existing adapter tests are unverified.\nBehavior to preserve: (1) `legacyAuthFlow()` allow/deny results and cache side effects for its current inputs; (2) adapter entries written by `SessionMint`/`AuthBroker` via `AuthCache` are keyed and shaped so `legacyAuthFlow()` reads them as it reads its own (or never sees them, if keys differ) \u2014 no cross-flow corruption; (3) tenant isolation: an entry for tenant A is never returned for tenant B (A3). Intentional changes: none in this PR (D3).\nComparison grid:\n\n| Choice | Current | A Characterize + shared-adapter integration | B Shared-adapter integration only | C Characterize only, in follow-up PR |\n|---|---|---|---|---|\n| R3 regression coverage | none | characterization tests of `legacyAuthFlow()` recorded now (allow/deny + cache effects for representative inputs, boundary and error cases) AND an integration test running legacy + new services against one adapter instance asserting (1)-(3) | integration test asserting (2)-(3) only; `legacyAuthFlow()` outputs not recorded | characterization tests written when the follow-up rewrite PR starts; nothing in this PR |\n| D3 split, D4 arrangement, D5 injection, D6 guard, D7 pipeline | approved | held | held | held |\n| R7 perf | pending | pending | pending | pending |\n\nQuestion D8:\nD8 \u2014 How do we protect legacyAuthFlow() and the shared cache adapter from regressions in this PR?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; this PR is additive (D3) but writes to the one adapter legacyAuthFlow() still reads.\nELI10: Even though we are no longer rewriting the old login path in this PR, the new services write into the same cache it reads from (PLAN.md:20-21). Nothing today records what the old path actually does, so if a new entry shape or key collides with it, nobody will know until a tenant reports it. A characterization test (\"record what it does now, assert it keeps doing that\") plus one integration test that runs old and new against the same cache gives us that alarm. The plan explicitly skips both (PLAN.md:23-25). The question is how to cover it, not whether.\nStakes if we pick wrong: Too little: a silent auth behavior change for existing tenants with no failing test to point at it, and the follow-up rewrite PR starts with no baseline. Too much: an afternoon writing tests for code that will be rewritten anyway (but those tests are exactly what makes the rewrite safe).\nRecommendation: A because the follow-up rewrite (D3) needs the characterization baseline anyway, and recording it before any adjacent change is when it is cheapest and most trustworthy.\nCompleteness: A=10/10, B=7/10, C=5/10\nNet: pay for the baseline now while the old path is untouched vs. hope the adapter keys keep the flows apart.\nHeader: Regression\nOptions:\nA) Characterization tests now + shared-adapter integration test (recommended)\n\u2705 Baseline of legacyAuthFlow() behavior captured before anything adjacent changes; the follow-up rewrite PR inherits it. \u2705 Integration test proves old and new flows coexist on one adapter with tenant isolation intact (human: ~1 day / CC: ~20 min). \u274c Tests characterize current behavior bugs included; someone must review the recorded outputs for surprises.\nB) Shared-adapter integration test only\n\u2705 Covers the specific new risk this PR introduces (coexistence on one adapter). \u2705 Less test code to maintain. \u274c legacyAuthFlow() outputs stay unrecorded; the follow-up rewrite starts without a baseline.\nC) Characterization tests only, deferred to the follow-up PR\n\u2705 Nothing extra in this PR. \u2705 Baseline written by whoever does the rewrite, closest to the work. \u274c This PR ships with zero proof the new writes do not disturb the old reads; baseline recorded after adjacent code already changed.\n\nState: approved\nActual answer: A \u2014 \"Characterization tests now + shared-adapter integration test (recommended)\" (answer to D8)\nAccepted scope: (a) characterization tests of `legacyAuthFlow()` recorded in this PR before any adjacent change: representative allow/deny inputs, boundary cases (expired token, missing claims, unknown tenant), current error behavior, and cache side effects (which keys are read/written); (b) an integration test that runs `legacyAuthFlow()` and the new `AuthBroker`/`SessionMint` against one adapter instance and asserts: legacy results unchanged with new entries present; entries written via `AuthCache` never returned to a different tenant; key tenant component comes from validated claims, not request context. Intentional behavior changes in this PR: none. These tests are CRITICAL and block ship.\nHistory: none.\n\n### R7: Token validation's 5 IDP round trips\nFinding: Performance P1, P2, confidence 8/10, PLAN.md:40-41 (\"Token validation issues 5 sequential API calls to the IDP; they could be parallelized via Promise.all trivially (calls are independent).\"), reviewer: plan-eng-review (Claude). Web research [Layer 1]: OIDC discovery and JWKS documents are meant to be cached for hours/days and refreshed on unknown `kid`; per-request fetches are the anti-pattern.\nPlan baseline: original proposal \u2014 parallelize the 5 calls with `Promise.all`.\nRuntime evidence: unknown; no source in repo. Which 5 calls these are (discovery, JWKS, introspection, userinfo, tenant lookup?) is unverified; whether any are already cached is unverified.\nComparison grid:\n\n| Choice | Current | A Cache + parallelize | B Parallelize only | C Do nothing |\n|---|---|---|---|---|\n| R7 per-validation IDP calls | 5 sequential | cache the static documents (discovery, JWKS) in-process with TTL and refresh on unknown `kid`, then run the remaining per-token calls concurrently; per-call timeout; first failure maps to one typed error, no dangling awaits | 5 concurrent via `Promise.all`; per-call timeout; first rejection maps to one typed error | 5 sequential |\n| latency per validation | ~5 \u00d7 RTT | ~0-1 \u00d7 RTT steady state | ~1 \u00d7 RTT | ~5 \u00d7 RTT |\n| IDP load per validation | 5 requests | 1-2 requests steady state | 5 requests, burst | 5 requests |\n| D3-D8 approvals | approved | held | held | held |\n\nQuestion D9:\nD9 \u2014 Cache the static IDP documents and parallelize the rest, or just parallelize the 5 calls?\nProject/branch/task: main branch, PLAN.md \"Multi-tenant Auth Refactor\"; validate step of the flattened AuthBroker pipeline (D7).\nELI10: Every login currently makes five round trips to the identity provider, one after another (PLAN.md:40-41). Running them at the same time cuts wall-clock time by about 5x, which is what the plan proposes. But at least some of those calls fetch documents that barely change (the provider's discovery config and its public signing keys), which the standard practice says to cache for hours and only refetch when a token shows up signed by an unknown key. Cache those and most logins need zero or one round trip. Parallelizing alone also turns a 5-call trickle into a 5-call burst per login, which is how you hit IDP rate limits on a busy morning.\nStakes if we pick wrong: Parallelize-only: 5x burstier IDP traffic, still 5 network dependencies per login, and Promise.all's fail-fast leaves the other four requests in flight. Cache + parallelize: a small TTL cache with a stale-key refresh path to get right.\nRecommendation: A because the plan's own evidence (5 calls per validation) says the missing piece is caching, not concurrency; it is the standard OIDC pattern and removes the IDP as a per-request dependency for most logins.\nCompleteness: A=10/10, B=7/10, C=2/10\nNet: remove the IDP from the hot path with a boring cache vs. make the hot path five times faster and five times burstier.\nHeader: IDP calls\nOptions:\nA) Cache static IDP documents + parallelize remaining calls (recommended)\n\u2705 Steady-state logins need 0-1 IDP round trips instead of 5; IDP outage no longer fails every login that has cached keys. \u2705 Standard OIDC practice; refresh-on-unknown-kid handles key rotation (human: ~1 day / CC: ~20 min). \u274c Must pick TTLs below the IDP's key-rotation overlap window and test the unknown-kid refresh path.\nB) Parallelize the 5 calls only (as proposed)\n\u2705 ~5x lower validation latency with a one-line change. \u2705 No cache invalidation to reason about. \u274c 5 requests per login in a burst; every login still depends on the IDP being up; fail-fast leaves stragglers in flight.\nC) Do nothing\n\u2705 Zero effort; no new failure modes. \u2705 Sequential calls are easy to trace in logs. \u274c ~5 \u00d7 RTT on every login, and the plan already called this out as trivially fixable.\n\nState: approved\nActual answer: A \u2014 \"Cache static IDP documents + parallelize remaining calls (recommended)\" (answer to D9)\nAccepted scope: in the `validate` step, cache the static IDP documents (discovery configuration, JWKS) in-process with a TTL below the IDP's key-rotation overlap window and refresh on unknown `kid`; run the remaining per-token IDP calls concurrently with a per-call timeout; the first failure maps to one typed validation error (D7 boundary) and no result is consumed from the remaining calls. Implementation must first enumerate which of the 5 calls are static-document fetches vs. per-token calls (unknown from the plan). Required proof: unit tests for cache hit, TTL expiry, unknown-kid refresh, per-call timeout \u2192 typed error, and one concurrent-call failure \u2192 single mapped error.\nHistory: none.\n\n### TODO decision (D10)\nQuestion D10: Capture the follow-up PR (swap legacyAuthFlow() onto the new services) as a TODO? Recommendation: A. Header: TODO. Options: A) Add to TODOS.md (recommended); B) Skip; C) Build it now in this PR instead.\nState: approved. Actual answer: A \u2014 \"Add to TODOS.md (recommended)\" (answer to D10). Accepted scope: the TODO item below is written to the repo's `TODOS.md` after plan mode exits (plan mode forbids repo writes now; content presented as **not persisted**).\n\nApproval readiness: PASS \u2014 R1 (D3: A), R2 (D4: A), R4 (D5: A), R5 (D6: A), R6 (D7: A), R3 (D8: A), R7 (D9: A), TODO (D10: A). Setup D1/D2 are not remedies. No pending records.\n\n## Review findings (all sections)\n\nConfidence per finding follows the calibration table; medium-confidence items carry a caveat.\n\n### Scope Challenge\n- S1 [P1] (confidence: 9/10) PLAN.md:36-37 \u2014 live `legacyAuthFlow()` rewrite bundled into a 12-file refactor with no regression test. Accepted: split to follow-up PR (D3).\n- S2 [P2] (confidence: 8/10) PLAN.md:44-45, :12-13, :20-21 \u2014 5 classes where RequestPolicy is stateless and TokenStore duplicates AuthCache over one backing cache. Accepted: 3 classes + `decideAccess()` function (D4).\n- S3 [P3] (confidence: 7/10) web research [Layer 1] \u2014 module-level mutable singleton is a documented Node/TS footgun. Carried to A1.\n- S4 [P3] (confidence: 7/10) web research [Layer 1] \u2014 JWKS/discovery should be cached; 5 calls/validation implies missing caching. Carried to P1.\n- Completeness check: original plan is a test shortcut (PLAN.md:23-25). Resolved in Section 3. Distribution check: no new artifact. TODOS.md: absent.\n\n### 1. Architecture\n- A1 [P1] (confidence: 8/10) PLAN.md:28-29 \u2014 global mutable `AuthCache` via module-level export, mutated by two services. Accepted: inject one instance via constructors (D5).\n- A2 [P2] (confidence: 6/10, medium: verify adapter semantics) PLAN.md:19, :29, :17-18 \u2014 unordered mint-write vs. invalidation can re-populate a revoked/suspended tenant's entry until TTL. Accepted: guard in `AuthCache.set()` (D6).\n- A3 [P2] (confidence: 5/10, medium: verify this is actually an issue) PLAN.md:16-17 \u2014 plan does not state whether the tenant component of the cache key comes from validated claims or request context; cross-tenant read possible if the latter. Folded into D8 acceptance assertions.\n- A4 [P2] (confidence: 7/10) PLAN.md:40 \u2014 IDP is a per-request single point of failure with 5 calls per validation and no timeouts mentioned. Resolved by D9 (cached static docs, per-call timeout).\n- Production failure scenarios: AuthBroker \u2014 IDP timeout swallowed by a nested catch (D7 fixes); SessionMint \u2014 write after suspension (D6 fixes); AuthCache \u2014 adapter write throws (D7 boundary surfaces it; test required); `decideAccess()` \u2014 wrong-tenant claims (D8 assertion).\n\n### 2. Code quality\n- C1 [P1] (confidence: 9/10) PLAN.md:32-33 \u2014 60-line `validateAndDispatch()`, three nested try/catch each swallowing an error class: fail-open risk, untestable. Accepted: flat pipeline + single deny-by-default boundary (D7).\n- C2 [P2] (confidence: 8/10) PLAN.md:44 vs :20-21 \u2014 DRY: two wrappers over one cache. Resolved by D4.\n- C3 [P3] (confidence: 7/10) PLAN.md:12-13 \u2014 stateless one-method class. Resolved by D4.\n- C4 [P3] (confidence: 6/10) \u2014 no diagrams planned; `AuthBroker` pipeline and `AuthCache` guard need inline ASCII comments (see Diagrams).\n\n### 3. Tests\n- Framework: unknown (repo has no `package.json`, no test config, 0 test files). Plan's `Promise.all` implies JS/TS; file names below assume `*.test.ts` and must be mapped to the real convention.\n- T1 [P1 CRITICAL] (confidence: 8/10) PLAN.md:23-25 \u2014 no regression coverage while new services write to the adapter `legacyAuthFlow()` reads. Accepted: characterization + shared-adapter integration tests (D8).\n- T2 [P1] (confidence: 9/10) \u2014 0/27 paths covered. Required proof enumerated in Implementation Tasks.\n- T3 [P2] (confidence: 7/10) \u2014 tenant-isolation assertion absent. Folded into D8.\n- T4 [P3] (confidence: 6/10) \u2014 double-submit login / idempotent mint untested. NOT in scope (behavior change).\n\nCoverage diagram (plan-level; no tests exist in the repo today):\n\n```\nCODE PATHS USER FLOWS\n[+] auth/AuthBroker.ts [+] Tenant login (bearer token)\n \u2514\u2500\u2500 validateAndDispatch() \u251c\u2500\u2500 [GAP] [\u2192E2E] valid token \u2192 allow \u2192 dispatched\n \u251c\u2500\u2500 [GAP] validate: happy path \u251c\u2500\u2500 [GAP] [\u2192E2E] expired token \u2192 deny, clear error\n \u251c\u2500\u2500 [GAP] validate: IDP timeout \u2192 typed err \u2192 deny \u251c\u2500\u2500 [GAP] [\u2192E2E] revoked mid-session \u2192 next request denied\n \u251c\u2500\u2500 [GAP] validate: IDP 5xx \u2192 typed err \u2192 5xx \u2514\u2500\u2500 [GAP] [\u2192E2E] tenant suspended \u2192 next request denied\n \u251c\u2500\u2500 [GAP] validate: malformed/expired token \u2192 deny\n \u251c\u2500\u2500 [GAP] decideAccess() deny \u2192 deny (no dispatch) [+] Error states\n \u251c\u2500\u2500 [GAP] dispatch throws \u2192 mapped, logged \u251c\u2500\u2500 [GAP] IDP down \u2192 user sees 5xx, not hang\n \u2514\u2500\u2500 [GAP] unknown error \u2192 deny by default (D7) \u251c\u2500\u2500 [GAP] slow IDP (10s) \u2192 timeout path, not silent\n[+] auth/policy.ts \u2514\u2500\u2500 [GAP] IDP key rotation \u2192 login still works (D9)\n \u2514\u2500\u2500 decideAccess(claims, ctx)\n \u251c\u2500\u2500 [GAP] allow / deny table for existing policy [+] Regression (D8, CRITICAL)\n \u251c\u2500\u2500 [GAP] claims tenant \u2260 ctx tenant \u2192 deny (A3) \u251c\u2500\u2500 [GAP] [\u2192E2E] legacyAuthFlow() characterization\n \u2514\u2500\u2500 [GAP] missing/empty claims \u2192 deny \u2514\u2500\u2500 [GAP] [\u2192E2E] legacy + new on one adapter, tenant isolation\n[+] auth/AuthCache.ts\n \u251c\u2500\u2500 get(): [GAP] hit / miss / expired-evicted\n \u251c\u2500\u2500 set(): [GAP] normal write persists\n \u251c\u2500\u2500 set(): [GAP] write after invalidation dropped (D6 proof)\n \u251c\u2500\u2500 [GAP] key = (tenant from CLAIMS, issuer, audience, policyVersion)\n \u2514\u2500\u2500 [GAP] adapter throws \u2192 surfaced, not swallowed\n[+] auth/SessionMint.ts\n \u251c\u2500\u2500 [GAP] mint \u2192 AuthCache.set() called once with correct key\n \u2514\u2500\u2500 [GAP] mint during suspension \u2192 no entry (D6)\n[+] auth/idp-client.ts (D9)\n \u251c\u2500\u2500 [GAP] discovery/JWKS cache hit, TTL expiry, unknown-kid refresh\n \u2514\u2500\u2500 [GAP] concurrent per-token calls: one failure \u2192 single typed error, per-call timeout\n\nCOVERAGE: 0/29 paths tested (0%) | Code paths: 0/20 (0%) | User flows: 0/9 (0%)\nQUALITY: \u2605\u2605\u2605:0 \u2605\u2605:0 \u2605:0 | GAPS: 29 (7 E2E, 0 eval)\n```\n\nLegend: \u2605\u2605\u2605 behavior + edge + error | \u2605\u2605 happy path | \u2605 smoke | [\u2192E2E] integration test. No LLM/prompt scope; no eval.\n\nTest Plan artifact: `~/.gstack/projects/gstack-plan-count-eecImF/vercel-sandbox-main-eng-review-test-plan-20260916-105826.md`.\n\n### 4. Performance\n- P1 [P2] (confidence: 8/10) PLAN.md:40-41 \u2014 5 sequential IDP calls; `Promise.all` alone misses static-document caching and fail-fast stragglers. Accepted: cache discovery/JWKS + parallelize remainder with per-call timeout (D9).\n- P2 [P3] (confidence: 6/10) PLAN.md:16-18 \u2014 adapter access pattern unchanged; no N+1 visible; JWKS cache memory negligible. No action.\n\n### Outside Voice\nCodex review skipped: `codex_reviews` is `disabled`. Recorded `outside_status: disabled`. No native replacement (disabled is an opt-out, not a provider failure). Re-enable: `gstack-config set codex_reviews enabled`.\n\n### Suppressed findings (confidence \u2264 4)\n- (4/10) Whether `SessionMint` and `AuthBroker` need to share the cache at all, or whether `SessionMint` only writes and `AuthBroker` only reads \u2014 if so, a read-only view for `AuthBroker` would shrink the mutation surface further. Unverifiable without source.\n\n## NOT in scope\n- `legacyAuthFlow()` rewrite / caller swap \u2014 deferred to a follow-up PR (D3); tracked in the TODO below.\n- Idempotent session mint (double-submit protection) \u2014 would change behavior; this PR is behavior-preserving.\n- Changes to the existing cache adapter, its keying, eviction, or invalidation hooks \u2014 retained contract (PLAN.md:16-22).\n- Any change to the access policy itself \u2014 `decideAccess()` groups the existing decision; no new rules.\n- Distribution/CI changes \u2014 no new artifact is produced by this plan.\n- Cross-model outside review \u2014 disabled by config.\n\n## What already exists\n- The cache adapter with tenant/issuer/audience/policy-version keys, eviction, and invalidation hooks, plus its tests (PLAN.md:16-22): **reused unchanged** via the `AuthCache` facade. The plan's `TokenStore` would have rebuilt a second wrapper over it; cut by D4.\n- The existing per-request access decision (PLAN.md:9-13): **reused** as the body of `decideAccess()`; no new policy.\n- `legacyAuthFlow()`: **left running** in this PR; becomes the characterization baseline (D8) for its own later replacement.\n- Existing IDP client calls (PLAN.md:40): reused; D9 adds a cache in front of the static-document fetches rather than rewriting the client.\n\n## Diagrams\nPlan-level data flow is in the Architecture section above. Inline ASCII comments should ship in:\n- `AuthBroker.validateAndDispatch()` \u2014 the three-step pipeline and the error boundary mapping table (error class \u2192 outcome).\n- `AuthCache.set()` \u2014 the read \u2192 invalidation \u2192 write ordering the guard protects against (D6).\n- `idp-client` (D9) \u2014 cache lifecycle: hit / TTL expiry / unknown-kid refresh.\n- Characterization test file \u2014 a short comment stating these tests record current behavior, bugs included, and are the acceptance gate for the follow-up rewrite.\n\n## Failure modes\n| Codepath | Realistic failure | Test | Error handling | User sees | Critical gap? |\n|---|---|---|---|---|---|\n| `validate` (IDP) | IDP timeout / 5xx | required (D7, D9) | typed error \u2192 5xx (D7) | explicit error, retry | no (after D7/D9) |\n| `validate` | key rotation, unknown `kid` | required (D9) | refresh JWKS once, else deny | login works or explicit deny | no |\n| `decideAccess()` | claims tenant \u2260 ctx tenant | required (D8) | deny | 403 | no |\n| `dispatch` | downstream throws | required (D7) | mapped at boundary | explicit error | no |\n| `AuthCache.set()` | write after invalidation | required (D6) | write dropped | next request re-validates | no |\n| `AuthCache.set()` | adapter throws | required | surfaced via boundary | explicit error | no |\n| `legacyAuthFlow()` coexistence | key/shape collision with new entries | required (D8) | n/a (test-only detection) | would be silent without D8 | no (after D8) |\n| Unknown error anywhere in pipeline | unmapped exception | required (D7) | deny by default | 403/5xx | no |\n\nCritical gaps flagged: **0** after accepted remedies. Before this review, the coexistence and swallowed-error rows were both untested, unhandled, and silent.\n\n## Worktree parallelization strategy\n| Step | Modules touched | Depends on |\n|---|---|---|\n| W1 Characterization tests for `legacyAuthFlow()` (D8a) | tests/auth (legacy) | \u2014 |\n| W2 `AuthCache` facade + set() guard + tests (D4, D6) | auth/cache | \u2014 |\n| W3 `decideAccess()` policy module + tests (D4) | auth/policy | \u2014 |\n| W4 IDP client cache + parallel calls + tests (D9) | auth/idp-client | \u2014 |\n| W5 `AuthBroker` pipeline + boundary + `SessionMint` + composition root (D5, D7) | auth/broker, auth/session, app wiring | W2, W3, W4 |\n| W6 Shared-adapter integration test (D8b) | tests/auth (integration) | W1, W5 |\n\nLanes: `Lane A: W1 (independent)` / `Lane B: W2 (independent)` / `Lane C: W3 (independent)` / `Lane D: W4 (independent)` / `Lane E: W5 \u2192 W6 (sequential, waits on A-D)`.\nExecution order: launch A, B, C, D in parallel worktrees; merge all four; then E. Conflict flags: W5 touches app wiring that W2/W4 constructors define; keep constructor signatures agreed before launching B and D, or expect a small merge fix in W5.\n\n## Implementation Tasks\nSynthesized from this review's findings. Each task derives from a specific finding above. Run with Claude Code or Codex; checkbox as you ship. Effort assumption: tests ~50x, architecture ~5x, features ~30x human\u00f7CC.\n\n- [ ] **T1 (P1, human: ~1 day / CC: ~20 min)** \u2014 tests/auth \u2014 Record characterization tests for `legacyAuthFlow()` before any adjacent change\n - Surfaced by: Test review \u2014 T1 / D8 (PLAN.md:23-25)\n - Files: new `legacyAuthFlow.characterization.test.*` (map to project convention)\n - Verify: tests pass against current `main` with zero production changes\n- [ ] **T2 (P1, human: ~0.5 day / CC: ~10 min)** \u2014 auth/cache \u2014 Implement `AuthCache` facade (absorbing `TokenStore` role) with invalidation-aware `set()` guard\n - Surfaced by: Architecture A2 / D6; Scope S2 / D4 (PLAN.md:19-21, :29)\n - Files: `auth/AuthCache.*`; adapter untouched\n - Verify: unit tests: hit/miss/expired, normal write persists, write-after-invalidation dropped, adapter throw surfaced\n- [ ] **T3 (P1, human: ~0.5 day / CC: ~10 min)** \u2014 auth/broker \u2014 Flatten `validateAndDispatch()` into validate \u2192 decideAccess \u2192 dispatch with one deny-by-default error boundary; enumerate the three swallowed error classes\n - Surfaced by: Code quality C1 / D7 (PLAN.md:32-33)\n - Files: `auth/AuthBroker.*`\n - Verify: one test per mapped error class, unknown-error deny, happy path\n- [ ] **T4 (P1, human: ~2h / CC: ~5 min)** \u2014 auth/policy \u2014 Implement `decideAccess(claims, ctx)` as a pure function grouping the existing decision\n - Surfaced by: Scope S2 / D4 (PLAN.md:9-13)\n - Files: `auth/policy.*`\n - Verify: allow/deny table, tenant mismatch \u2192 deny, empty claims \u2192 deny\n- [ ] **T5 (P1, human: ~2h / CC: ~5 min)** \u2014 app wiring \u2014 Construct one `AuthCache` at the composition root; inject into `AuthBroker` and `SessionMint`; remove module-level export\n - Surfaced by: Architecture A1 / D5 (PLAN.md:28-29)\n - Files: composition root / app bootstrap, `AuthBroker`, `SessionMint` constructors\n - Verify: grep confirms no module-level `AuthCache` instance export; unit tests construct fresh instances\n- [ ] **T6 (P1, human: ~1 day / CC: ~20 min)** \u2014 tests/auth \u2014 Shared-adapter integration test: legacy + new services on one adapter; legacy results unchanged; tenant isolation; key tenant from claims\n - Surfaced by: Test review T1, T3; Architecture A3 / D8\n - Files: new `auth.coexistence.integration.test.*`\n - Verify: passes with new entries present; fails if a cross-tenant read occurs\n- [ ] **T7 (P2, human: ~1 day / CC: ~20 min)** \u2014 auth/idp-client \u2014 Cache discovery/JWKS with TTL + unknown-kid refresh; run per-token calls concurrently with per-call timeout; first failure \u2192 single typed error\n - Surfaced by: Performance P1 / D9; Architecture A4 (PLAN.md:40-41)\n - Files: `auth/idp-client.*`\n - Verify: tests for cache hit, TTL expiry, kid refresh, timeout \u2192 typed error, one failure \u2192 single error\n- [ ] **T8 (P2, human: ~1h / CC: ~3 min)** \u2014 auth \u2014 Inline ASCII diagrams in `AuthBroker`, `AuthCache.set()`, idp-client\n - Surfaced by: Code quality C4\n - Files: same as T2, T3, T7\n - Verify: diagrams match implemented control flow at PR review\n- [ ] **T9 (P3, human: ~15 min / CC: ~2 min)** \u2014 repo \u2014 Add `TODOS.md` entry for the follow-up `legacyAuthFlow()` swap (after plan mode exits)\n - Surfaced by: Scope S1 / D3, D10\n - Files: `TODOS.md`\n - Verify: file present with the item below\n\n_No new tasks from Performance beyond T7._\n\n### TODO item (accepted D10; **not persisted** \u2014 write to `TODOS.md` after plan mode exits)\n```markdown\n# TODOS\n\n## Auth\n\n### Swap legacyAuthFlow() onto AuthBroker and delete the legacy path\n\n**What:** Point all `legacyAuthFlow()` callers at `AuthBroker.validateAndDispatch()` and remove `legacyAuthFlow()`.\n\n**Why:** The multi-tenant auth refactor (2026-09-16 eng review, decision D3) landed the new services additively to keep rollback trivial. Until this swap ships, two auth paths coexist and write to one cache adapter.\n\n**Context:** Acceptance gate is the characterization test suite recorded in that PR (decision D8): the swapped path must produce the same allow/deny results and cache effects for the recorded inputs, or each difference must be an intentional, documented change. Start after the new services have soaked in production. Start point: the characterization test file and `AuthBroker.validateAndDispatch()`.\n\n**Effort:** M\n**Priority:** P1\n**Depends on:** Auth refactor PR merged and soaked; characterization tests green.\n```\n\n## Unresolved decisions that may bite you later\nNone. All nine remedy/scope choices (D3-D10) have actual answers; D1/D2 were setup.\n\n## Completion summary\n- Step 0: Scope Challenge \u2014 scope reduced per recommendation (D3 split, D4 3 classes + 1 fn)\n- Architecture Review: 4 issues found (2 accepted remedies, 1 folded into D8, 1 resolved by D9)\n- Code Quality Review: 4 issues found (1 accepted remedy, 2 resolved by D4, 1 documentation task)\n- Test Review: diagram produced, 29 gaps identified (0 tests exist; framework unknown)\n- Performance Review: 2 issues found (1 accepted remedy, 1 no action)\n- NOT in scope: written\n- What already exists: written\n- TODOS.md updates: 1 item proposed to user (accepted, not persisted until plan mode exits)\n- Failure modes: 0 critical gaps flagged (after accepted remedies)\n- Unresolved decisions: 0 in this review\n- Outside voice: codex, disabled (codex_reviews=disabled); no native replacement\n- Parallelization: 5 lanes, 4 parallel / 1 sequential\n- Lake Score: 5/5 (D5, D6, D7, D8, D9 all selected the 10/10 option; D3, D4, D10 differ in kind)\n- Deferred host-mode follow-ups: D1 routing rules \u2192 append to `CLAUDE.md` and commit; D10 \u2192 create `TODOS.md`. Both blocked by plan mode during this review.\n\n## GSTACK REVIEW REPORT\n\n| Review | Trigger | Why | Runs | Status | Findings |\n|--------|---------|-----|------|--------|----------|\n| CEO Review | `/plan-ceo-review` | Scope & strategy | 0 | \u2014 | \u2014 |\n| Outside Review | codex via `/plan-eng-review` | Independent 2nd opinion | 1 | DISABLED (skipped, outside_status: disabled, phase: plan-review, host: claude) | \u2014 |\n| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 1 | CLEAR (PLAN, SCOPE_REDUCED) | 14 issues, 0 critical gaps |\n| Design Review | `/plan-design-review` | UI/UX gaps | 0 | \u2014 | \u2014 |\n| DX Review | `/plan-devex-review` | Developer experience gaps | 0 | \u2014 | \u2014 |\n\n- **OUTSIDE COVERAGE:** provider codex, phase plan-review, disabled by `codex_reviews` config; no outside process ran; no native replacement; no findings. Not counted as clean coverage.\n- **VERDICT:** ENG CLEARED \u2014 ready to implement (scope reduced per D3/D4; all remedies approved).\n\nNO UNRESOLVED DECISIONS\n"
}