<!-- task=m-agent-task-runtime-target-selector/04+03_failover_budget plan=18 tag=REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API -->

# Code Review Reference - REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API

> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.

## 개요

date=2026-07-26
task=m-agent-task-runtime-target-selector/04+03_failover_budget, plan=18, tag=REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API

## Roadmap Targets

- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/agent-task-runtime-target-selector.md`
- Milestone link: [Milestone 문서](agent-roadmap/phase/automation-runtime-bridge/milestones/agent-task-runtime-target-selector.md)
- Task ids:
  - `time-route`: local-G07~G08 KST 주야간 최초 target
  - `context-failover`: ordered candidate의 단방향 logical failover와 no-bounce
  - `failure-budget`: target 전환 전후 동일 stage 10회 실패 예산과 성공 reset
  - `selfcheck-policy`: 실제 worker 완료 target 기반 selfcheck
- Completion mode: check-on-pass

## Archive Evidence Snapshot

- 직전 계획: `agent-task/m-agent-task-runtime-target-selector/04+03_failover_budget/plan_local_G08_17.log`.
- 직전 리뷰: `agent-task/m-agent-task-runtime-target-selector/04+03_failover_budget/code_review_cloud_G08_17.log` — FAIL, Required 2 / Suggested 0 / Nit 0.
- 영향 파일: `select_execution_target.py`, `test_select_execution_target.py`, `test_dispatch.py`.
- 검증 evidence: focused selector 26, S07 7, S10/dispatcher 22, 전체 192 tests와 `py_compile`/금지 심볼 검색/`git diff --check`는 PASS했다. 별도 reproducer는 주간 initial이 Gemini quota exhausted로 Laguna를 선택한 뒤 Gemini quota가 회복되면 Laguna의 qualified failure가 Laguna→Gemini 역방향 전환을 만드는 것을 확인했다.
- 남은 carryover: S02/S06/S07/S10과 `time-route`, `context-failover`, `failure-budget`, `selfcheck-policy`의 최종 PASS evidence다.

## 이 파일을 읽는 리뷰 에이전트에게

> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.

각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.

1. 판정을 append한다.
2. `CODE_REVIEW-cloud-G08.md` → `code_review_cloud_G08_18.log`, `PLAN-local-G08.md` → `plan_local_G08_18.log`로 아카이브한다.
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-agent-task-runtime-target-selector/04+03_failover_budget/`로 이동한다. WARN/FAIL이면 code-review skill이 요구하는 다음 filesystem state를 완전히 작성한다.
4. PASS이면 `m-agent-task-runtime-target-selector` 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.

---

## 구현 항목별 완료 여부

| 항목 | 완료 여부 |
|------|---------|
| REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-1 | [x] |
| REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-2 | [x] |

## 구현 체크리스트

- [x] REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-1 failover candidate를 현재 selected rank 이후로 제한하고 reverse-rank no-bounce regression을 추가한다.
- [x] REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-2 실제 재오픈 1+9 invocation과 production 성공 분기의 stage-local reset을 검증한다.
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다.

## 코드리뷰 전용 체크리스트

> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.

- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_cloud_G08_18.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_local_G08_18.log`로 아카이브한다.
- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
- [x] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
- [x] PASS이면 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-agent-task-runtime-target-selector/04+03_failover_budget/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
- [x] PASS이면 `m-agent-task-runtime-target-selector` 완료 이벤트 메타데이터를 보고하고 roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
- [x] PASS split 작업이면 이동 후 `WORK_LOG.md`가 있는 active parent `agent-task/m-agent-task-runtime-target-selector/`를 유지한다.
- [ ] WARN/FAIL이면 code-review skill의 판정에 맞는 다음 filesystem state를 작성하고 `complete.log`를 작성하지 않는다.

## 계획 대비 변경 사항

계획과 동일하게 구현함.

## 주요 설계 결정

- `select_execution_target.py`의 `_failover()`에서 `previous_index = next(index for index, candidate in enumerate(prior["candidates"]) if _target_ref(candidate) == previous)`를 계산하고, candidate 순회 시 `index > previous_index` 조건으로 현재 선택된 target rank 이후의 unused eligible candidate만 선택되도록 제한함. candidate별 `quota_status` 및 `eligibility` 갱신은 전체 candidate에 계속 수행하여 상태 추적성을 유지함.
- `SelectorFailoverContractTests.test_failover_never_returns_to_an_earlier_candidate_rank` 및 `DispatcherCanonicalFailoverIntegrationTest.test_recovered_primary_quota_does_not_reverse_failover`를 추가하여 Gemini quota exhausted로 Laguna가 initial selected가 된 후 Gemini quota가 회복되더라도 qualified failure 발생 시 Gemini로 역행하지 않고 `no_failover_candidate`로 fail-closed됨을 검증함.
- `DynamicFailoverBudgetTest.test_primary_and_alternate_share_budget_across_reopen`에서 reopen mock invocation의 `await_count`가 8, 모든 `AgentSpec`이 Laguna, `final_loc`가 8번째 failure locator임을 직접 assertion하여 첫 Gemini 1회 + Laguna 9회 (총 10회) 실패 예산 소진과 reopen 갱신을 검증함.
- `DynamicFailoverBudgetTest.test_success_resets_only_current_stage_budget`에서 direct helper 호출을 제거하고 `asyncio.run(dispatch.run_escalating(...))` production entry point 성공 분기를 호출하여 worker stage budget만 reset(count 0)되고 review stage budget count 1은 보존됨을 검증함.

## 리뷰어를 위한 체크포인트

- `_failover()`가 quota/eligibility evidence는 전체 candidate에 갱신하되 현재 selected rank 이전 target을 다시 선택하지 않는지 확인한다.
- selector 단위 및 dispatcher integration이 exhausted primary→alternate initial→primary quota recovery 변형을 실제로 fail closed하는지 확인한다.
- reopen test가 첫 invocation과 합친 Gemini 1 + Laguna 9, mock await count/spec, final locator, count 10과 stage 분리를 직접 assertion하는지 확인한다.
- success reset test가 helper 직접 호출이 아니라 `run_escalating()` success branch를 실행하고 review budget을 보존하는지 확인한다.
- S02/S06/S07/S10 focused evidence와 전체 suite 출력이 실제 코드와 일치하는지 확인한다.

## 검증 결과

### Ordered failover no-bounce

```bash
python3 -m unittest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest -v
```

결과 (Exit Code: 0):
```text
test_cross_boundary_failover_resumes_pinned_decision (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests.test_cross_boundary_failover_resumes_pinned_decision) ... ok
test_failover_never_returns_to_an_earlier_candidate_rank (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests.test_failover_never_returns_to_an_earlier_candidate_rank) ... ok
test_generic_failure_and_exhausted_or_used_candidate_fail_closed (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests.test_generic_failure_and_exhausted_or_used_candidate_fail_closed) ... ok
test_qualified_failover_uses_only_unused_eligible_candidate (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests.test_qualified_failover_uses_only_unused_eligible_candidate) ... ok
test_tampered_prior_decision_rejected (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests.test_tampered_prior_decision_rejected) ... ok
test_unknown_is_admitted_once_and_no_bounce_remains (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests.test_unknown_is_admitted_once_and_no_bounce_remains) ... ok
test_cloud_g07_provider_quota_promotes_claude_to_codex_without_no_failover_block (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_cloud_g07_provider_quota_promotes_claude_to_codex_without_no_failover_block) ... ok
test_completing_target_controls_selfcheck_and_reuses_pin (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_completing_target_controls_selfcheck_and_reuses_pin) ... ok
test_day_gemini_failure_continues_on_laguna_with_logical_context (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_day_gemini_failure_continues_on_laguna_with_logical_context) ... ok
test_generic_failure_stays_on_same_target (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_generic_failure_stays_on_same_target) ... ok
test_invalid_logical_context_does_not_commit_or_promote (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_invalid_logical_context_does_not_commit_or_promote) ... ok
test_night_gemini_quota_exhaustion_blocks_without_bounce (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_night_gemini_quota_exhaustion_blocks_without_bounce) ... ok
test_night_laguna_failure_continues_on_available_gemini (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_night_laguna_failure_continues_on_available_gemini) ... ok
test_recovered_primary_quota_does_not_reverse_failover (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest.test_recovered_primary_quota_does_not_reverse_failover) ... ok

----------------------------------------------------------------------
Ran 14 tests in 0.245s

OK
```

### S07 actual invocation과 success reset

```bash
python3 -m unittest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DynamicFailoverBudgetTest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.RouteDecisionPersistenceTest -v
```

결과 (Exit Code: 0):
```text
test_context_package_keeps_artifacts_and_blocks_cross_adapter_native_session (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DynamicFailoverBudgetTest.test_context_package_keeps_artifacts_and_blocks_cross_adapter_native_session) ... ok
test_primary_and_alternate_share_budget_across_reopen (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DynamicFailoverBudgetTest.test_primary_and_alternate_share_budget_across_reopen) ... ok
test_success_resets_only_current_stage_budget (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DynamicFailoverBudgetTest.test_success_resets_only_current_stage_budget) ... ok
test_malformed_or_exhausted_state_blocks_only_its_task (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.RouteDecisionPersistenceTest.test_malformed_or_exhausted_state_blocks_only_its_task) ... ok
test_rejects_tampered_canonical_target_and_selector_load_error (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.RouteDecisionPersistenceTest.test_rejects_tampered_canonical_target_and_selector_load_error) ... ok
test_reopen_body_edit_and_generation_reset_preserve_or_reset_pin (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.RouteDecisionPersistenceTest.test_reopen_body_edit_and_generation_reset_preserve_or_reset_pin) ... ok
test_resume_keeps_pin_across_kst_boundary (agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.RouteDecisionPersistenceTest.test_resume_keeps_pin_across_kst_boundary) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.123s

OK
```

### 최종 검증

```bash
python3 -m unittest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorContractTests agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorRouteMatrixTests agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_select_execution_target.SelectorFailoverContractTests -v
python3 -m unittest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DynamicFailoverBudgetTest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.RouteDecisionPersistenceTest -v
python3 -m unittest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.DispatcherCanonicalFailoverIntegrationTest agent-ops.skills.project.orchestrate-agent-task-loop.tests.test_dispatch.TaskStageTest -v
python3 -m unittest discover -s agent-ops/skills/project/orchestrate-agent-task-loop/tests -p 'test_*.py' -v
python3 -m py_compile agent-ops/skills/project/orchestrate-agent-task-loop/scripts/select_execution_target.py agent-ops/skills/project/orchestrate-agent-task-loop/scripts/dispatch.py agent-ops/skills/project/orchestrate-agent-task-loop/tests/test_select_execution_target.py agent-ops/skills/project/orchestrate-agent-task-loop/tests/test_dispatch.py
rg --sort path -n "selected_candidate|no_failover_candidate|await_count|reset_on_success" agent-ops/skills/project/orchestrate-agent-task-loop/scripts/select_execution_target.py agent-ops/skills/project/orchestrate-agent-task-loop/tests/test_select_execution_target.py agent-ops/skills/project/orchestrate-agent-task-loop/tests/test_dispatch.py
git diff --check
```

결과 (Exit Code: 0):
```text
1. SelectorContractTests / SelectorRouteMatrixTests / SelectorFailoverContractTests: Ran 21 tests in 0.177s, OK.
2. DynamicFailoverBudgetTest / RouteDecisionPersistenceTest: Ran 7 tests in 0.123s, OK.
3. DispatcherCanonicalFailoverIntegrationTest / TaskStageTest: Ran 23 tests in 0.316s, OK.
4. unittest discover: Ran 196 tests in 8.360s, OK.
5. py_compile: Exit code 0, clean output.
6. rg search:
agent-ops/skills/project/orchestrate-agent-task-loop/scripts/select_execution_target.py:767,782,783,784,786
agent-ops/skills/project/orchestrate-agent-task-loop/tests/test_select_execution_target.py:1020,1031,1075
agent-ops/skills/project/orchestrate-agent-task-loop/tests/test_dispatch.py:2320,2475,2639,2664,2684,2710,2775,2776,2818,2848,2881,2907,2930,2952,2989,3114,3333,3334,3427,5461,5724,5798,5857
7. git diff --check: Exit code 0, clean output.
```

---

> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.

## 섹션 소유권

| Section | Owner | Note |
|---------|-------|------|
| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Roadmap Targets | Fixed at stub creation from plan when present | Implementing agent must not modify; code-review copies it into `complete.log` as `Roadmap Completion` only on PASS |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Agent UI Completion | Mixed | Present only for plan-required agent-ui code work; implementing agent fills actual evidence, review agent applies `구현됨` status/evidence update on PASS and copies the section into `complete.log` |
| 구현 항목별 완료 여부 (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| 구현 체크리스트 (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section |
| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text with actual content |
| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Pre-filled from plan |
| 검증 결과 (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `계획 대비 변경 사항` entry |
| 코드리뷰 결과 | Review agent appends | Not included in stub |

## 코드리뷰 결과

- 종합 판정: PASS
- Required: 0
- Suggested: 0
- Nit: 0

### 차원별 평가

| 차원 | 결과 | 근거 |
|------|------|------|
| 정확성 | Pass | `_failover()`가 현재 selected index 이후의 unused eligible candidate만 선택하며, quota가 회복된 앞 rank로 역행하지 않는다. |
| 완전성 | Pass | 두 구현 항목과 구현 소유 evidence가 모두 채워졌고 S02/S06/S07/S10 carryover를 닫았다. |
| 테스트 커버리지 | Pass | selector/dispatcher no-bounce, 재오픈 10회 실패 예산, production 성공 reset과 completing-target selfcheck 회귀가 포함된다. |
| API 계약 | Pass | ordered candidate, persisted decision, stage-local budget과 logical failover 계약이 승인 SDD와 일치한다. |
| 코드 품질 | Pass | 변경 범위에 debug 출력, dead code, TODO, stale symbol 또는 불필요한 형식 변경이 없다. |
| 구현 편차 | Pass | 현재 계획의 수정 파일과 검증 범위를 따랐으며 범위 밖 production 변경이 없다. |
| 검증 신뢰도 | Pass | 제출 명령을 독립 재실행해 focused 21/7/23개와 전체 196개 테스트, `py_compile`, 심볼 검색, `git diff --check` 통과를 확인했다. |
| 스펙 정합성 | Pass | SDD S02/S06/S07/S10 및 Evidence Map이 구현과 테스트 결과로 충족된다. |

### 발견된 문제

- 없음

### 검증 근거

- selector focused: 21 tests, PASS.
- failure budget/route persistence: 7 tests, PASS.
- dispatcher failover/selfcheck: 23 tests, PASS.
- 전체 suite: 196 tests, PASS.
- `py_compile`, 결정적 심볼 검색, `git diff --check`: PASS.

### 다음 단계

- PASS 종결 절차로 현재 PLAN/CODE_REVIEW를 18번 로그로 아카이브하고 `complete.log`를 작성한 뒤 split task 디렉터리를 월별 archive로 이동한다.
