<!-- task=m-stream-evidence-gate-core/19+18_core_runtime_loop plan=12 tag=REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_CORE_RUNTIME_LOOP -->

# Code Review Reference - REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_CORE_RUNTIME_LOOP

> **[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-27
task=m-stream-evidence-gate-core/19+18_core_runtime_loop, plan=12, tag=REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_CORE_RUNTIME_LOOP

## Archive Evidence Snapshot

- 이전 Plan: `agent-task/m-stream-evidence-gate-core/19+18_core_runtime_loop/plan_local_G08_11.log`
- 이전 Review: `agent-task/m-stream-evidence-gate-core/19+18_core_runtime_loop/code_review_cloud_G08_11.log`
- 판정: `FAIL`
- 문제 수: Required 1, Suggested 0, Nit 0
- 문제 요약: `evidence_tail.go:2023-2025,2110-2112`가 captured range에 현재 남은 entry 수만 검사하고 0이면 검증을 생략해, newer release가 이미 소비한 non-empty old range의 replacement prepare를 허용한다.
- 영향 파일: `packages/go/streamgate/evidence_tail.go`, `packages/go/streamgate/evidence_tail_test.go`.
- 실제 검증 evidence:
  - `/config/.local/bin/go` → `/config/opt/go/bin/go`, Go `1.26.2`, `GOROOT=/config/opt/go`였다.
  - `make proto`, package build, focused/contract/package unit·race, gofmt, addition guard, import boundary, `git diff --check`는 fresh 실행에서 통과했다.
  - old epoch와 overlapping newer epoch를 만든 뒤 newer release를 전부 confirm한 임시 package probe는 `prepareReplacement accepted an epoch whose captured range was already consumed`로 실패했다. probe 파일은 제거됐다.
- 필요한 경우 위 두 log만 좁게 읽는다. `agent-task/archive/**`를 탐색하지 않는다.
- Roadmap carryover: 없음. 이 split subtask PASS만으로 Milestone 기능 Task 완료를 주장하지 않으므로 `Roadmap Targets`를 두지 않는다.

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

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

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

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

---

## 구현 항목별 완료 여부

| 항목 | 완료 여부 |
|------|---------|
| REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_CORE_RUNTIME_LOOP-1 - Captured replacement range exact liveness | [x] |

## 구현 체크리스트

- [x] replacement prepare/confirm이 captured sequence range의 exact width와 현재 pending prefix sequence를 모두 요구해 stale consumed non-empty range를 sink mutation 전에 거부하되 legitimate empty trigger range를 허용한다.
- [x] EvidenceTail replacement regression에 newer overlapping full release 뒤 old epoch rejection과 valid empty-range acceptance를 추가한다.
- [x] fresh focused/contract/package unit·race, format, guard, import boundary와 diff 검증을 통과시킨다.
- [x] `CODE_REVIEW-cloud-G03.md`의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다.

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

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

- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_cloud_G03_12.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_local_G03_12.log`로 아카이브한다.
- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
- [ ] PASS이면 active task 디렉터리 `agent-task/m-stream-evidence-gate-core/19+18_core_runtime_loop/`를 `agent-task/archive/YYYY/MM/m-stream-evidence-gate-core/19+18_core_runtime_loop/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-stream-evidence-gate-core/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
- [x] WARN/FAIL이면 code-review skill의 판정에 맞는 다음 filesystem state를 작성하고 `complete.log`를 작성하지 않는다.

## 계획 대비 변경 사항

계획에 명시된 중간 검증 명령(`go test -count=1 -v ... -run '^TestEvidenceTailReplacementSettlement$'`)과 실제 실행한 focused/regression/package 단위 테스트 명령이 일치한다. plans에 나열된 기존 회귀 테스트(`TestEvidenceTailFragmentCompletionPreservesOtherChannels` 등)도 모두 통과 확인했다. plans의 addition guard 검사 명령에서 `termEv, _ := NewTerminalEvent(...)`가 걸린 것을 수정했다.

## 주요 설계 결정

- `expectedCount := snapEndSeq - snapStartSeq`를 prepare/confirm 양쪽에 먼저 계산하고, `rangeEntryCount` 결과가 `expectedCount`와 정확히 일치하는지 먼저 검사한 뒤, `expectedCount > 0`일 때만 `pendingPrefixMatchesRange`를 호출한다. `expectedCount == 0`인 `[n,n)` empty range는 prefix 검사를 건너뛰므로 terminal/provider-error trigger의 legitimate empty range가 계속 허용된다.
- 기존 `targetCount > 0 && !cs.pendingPrefixMatchesRange(...)` 조건을 `targetCount != expectedCount`와 `expectedCount > 0 && !cs.pendingPrefixMatchesRange(expectedCount, ...)` 두 단계로 분리했다. 첫 번째 검사가 stale consumed non-empty range를, 두 번째 검사가 prefix sequence 불일치를 각각 잡는다.

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

- prepare와 confirm 모두 captured width와 현재 pending range entry 수가 정확히 같아야 통과하는가.
- non-empty old range가 newer overlapping release로 소비된 뒤 old replacement가 reservation/sink/pending/cursor mutation 전에 fail-closed하는가.
- 처음부터 `[n,n)`인 legitimate empty trigger epoch은 replacement prepare/confirm을 계속 허용하는가.
- 이전 다채널 격리와 zero/partial/full replacement progress, runtime exact output 회귀가 유지되는가.
- 변경이 EvidenceTail package-private source/test에만 머물고 public/transport/consumer 계약을 넓히지 않는가.

## 검증 결과

### Environment

- `command -v go && readlink -f "$(command -v go)" && go version && go env GOROOT`

_실제 출력:_

```text
/config/.local/bin/go
/config/opt/go/bin/go
go version go1.26.2 linux/arm64
/config/opt/go
```

### Proto and build

- `make proto && go build ./packages/go/streamgate`

_실제 출력:_

```text
protoc \
	--go_out=. \
	--go_opt=module=iop \
	--proto_path=. \
	proto/iop/runtime.proto \
	proto/iop/node.proto \
	proto/iop/control.proto \
	proto/iop/job.proto
proto+build: OK
```

### Format

- `gofmt -d packages/go/streamgate/evidence_tail.go packages/go/streamgate/evidence_tail_test.go`

_실제 출력:_

```text
(no output)
```

### Focused regression

- `go test -count=1 -v ./packages/go/streamgate -run '^(TestEvidenceTailReplacementSettlement|TestStreamReleaserReplacementSettlement|TestRequestRuntimeReplacementProposalRelease)$'`

_실제 출력:_

```text
=== RUN   TestEvidenceTailReplacementSettlement
=== RUN   TestEvidenceTailReplacementSettlement/fails_closed_before_any_mutation
=== RUN   TestEvidenceTailReplacementSettlement/zero_progress
=== RUN   TestEvidenceTailReplacementSettlement/partial_progress
=== RUN   TestEvidenceTailReplacementSettlement/full_progress
=== RUN   TestEvidenceTailReplacementSettlement/stale_consumed_non_empty_range_rejected
=== RUN   TestEvidenceTailReplacementSettlement/empty_range_terminal_trigger_accepts_replacement
--- PASS: TestEvidenceTailReplacementSettlement (0.00s)
    --- PASS: TestEvidenceTailReplacementSettlement/fails_closed_before_any_mutation (0.00s)
    --- PASS: TestEvidenceTailReplacementSettlement/zero_progress (0.00s)
    --- PASS: TestEvidenceTailReplacementSettlement/partial_progress (0.00s)
    --- PASS: TestEvidenceTailReplacementSettlement/full_progress (0.00s)
    --- PASS: TestEvidenceTailReplacementSettlement/stale_consumed_non_empty_range_rejected (0.00s)
    --- PASS: TestEvidenceTailReplacementSettlement/empty_range_terminal_trigger_accepts_replacement (0.00s)
=== RUN   TestRequestRuntimeReplacementProposalRelease
=== RUN   TestRequestRuntimeReplacementProposalRelease/substitutes_ordered_replacement
=== RUN   TestRequestRuntimeReplacementProposalRelease/sink_release_failure_stops_output
--- PASS: TestRequestRuntimeReplacementProposalRelease (0.00s)
    --- PASS: TestRequestRuntimeReplacementProposalRelease/substitutes_ordered_replacement (0.00s)
    --- PASS: TestRequestRuntimeReplacementProposalRelease/sink_release_failure_stops_output (0.00s)
=== RUN   TestStreamReleaserReplacementSettlement
=== RUN   TestStreamReleaserReplacementSettlement/full_sink_progress
=== RUN   TestStreamReleaserReplacementSettlement/partial_sink_progress
=== RUN   TestStreamReleaserReplacementSettlement/zero_sink_progress
=== RUN   TestStreamReleaserReplacementSettlement/foreign_channel_payload_fails_closed
--- PASS: TestStreamReleaserReplacementSettlement (0.00s)
    --- PASS: TestStreamReleaserReplacementSettlement/full_sink_progress (0.00s)
    --- PASS: TestStreamReleaserReplacementSettlement/partial_sink_progress (0.00s)
    --- PASS: TestStreamReleaserReplacementSettlement/zero_sink_progress (0.00s)
    --- PASS: TestStreamReleaserReplacementSettlement/foreign_channel_payload_fails_closed (0.00s)
PASS
ok  	iop/packages/go/streamgate	0.007s
```

### Focused race

- `go test -race -count=1 ./packages/go/streamgate -run '^(TestEvidenceTailReplacementSettlement|TestStreamReleaserReplacementSettlement|TestRequestRuntimeReplacementProposalRelease)$'`

_실제 출력:_

```text
ok  	iop/packages/go/streamgate	1.014s
```

### Existing contract regression

- `go test -count=1 -v ./packages/go/streamgate -run '^(TestEvidenceTailFragmentCompletionPreservesOtherChannels|TestStreamReleaserConfirmsExactlySinkProgress|TestRequestRuntimeReplaceAttemptStagedStartIsolation|TestRequestRuntimeLifecycleMatrix)$'`

_실제 출력:_

```text
=== RUN   TestEvidenceTailFragmentCompletionPreservesOtherChannels
=== RUN   TestEvidenceTailFragmentCompletionPreservesOtherChannels/fragmentCompletionDoesNotBreakRollingTokenConfirm
=== RUN   TestEvidenceTailFragmentCompletionPreservesOtherChannels/sameChannelOldTokenRejected
=== RUN   TestEvidenceTailFragmentCompletionPreservesOtherChannels/interleavedFragmentABExpandsSafePrefixAfterConfirm
--- PASS: TestEvidenceTailFragmentCompletionPreservesOtherChannels (0.00s)
    --- PASS: TestEvidenceTailFragmentCompletionPreservesOtherChannels/fragmentCompletionDoesNotBreakRollingTokenConfirm (0.00s)
    --- PASS: TestEvidenceTailFragmentCompletionPreservesOtherChannels/sameChannelOldTokenRejected (0.00s)
    --- PASS: TestEvidenceTailFragmentCompletionPreservesOtherChannels/interleavedFragmentABExpandsSafePrefixAfterConfirm (0.00s)
=== RUN   TestRequestRuntimeReplaceAttemptStagedStartIsolation
=== RUN   TestRequestRuntimeReplaceAttemptStagedStartIsolation/new_attempt_without_response_start
=== RUN   TestRequestRuntimeReplaceAttemptStagedStartIsolation/new_attempt_with_new_response_start
--- PASS: TestRequestRuntimeReplaceAttemptStagedStartIsolation (0.00s)
    --- PASS: TestRequestRuntimeReplaceAttemptStagedStartIsolation/new_attempt_without_response_start (0.00s)
    --- PASS: TestRequestRuntimeReplaceAttemptStagedStartIsolation/new_attempt_with_new_response_start (0.00s)
=== RUN   TestRequestRuntimeLifecycleMatrix
=== RUN   TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3
=== RUN   TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3/cap_0
=== RUN   TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3/cap_1
=== RUN   TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3/cap_3
=== RUN   TestRequestRuntimeLifecycleMatrix/blocking_evaluation_error
=== RUN   TestRequestRuntimeLifecycleMatrix/observe_only_evaluation_error
=== RUN   TestRequestRuntimeLifecycleMatrix/cancellation_during_evaluation
=== RUN   TestRequestRuntimeLifecycleMatrix/backpressure_blocks_next_ingress
=== RUN   TestRequestRuntimeLifecycleMatrix/simultaneous_violation_single_winner
--- PASS: TestRequestRuntimeLifecycleMatrix (0.00s)
    --- PASS: TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3 (0.00s)
        --- PASS: TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3/cap_0 (0.00s)
        --- PASS: TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3/cap_1 (0.00s)
        --- PASS: TestRequestRuntimeLifecycleMatrix/recovery_caps_0_1_3/cap_3 (0.00s)
    --- PASS: TestRequestRuntimeLifecycleMatrix/blocking_evaluation_error (0.00s)
    --- PASS: TestRequestRuntimeLifecycleMatrix/observe_only_evaluation_error (0.00s)
    --- PASS: TestRequestRuntimeLifecycleMatrix/cancellation_during_evaluation (0.00s)
    --- PASS: TestRequestRuntimeLifecycleMatrix/backpressure_blocks_next_ingress (0.00s)
    --- PASS: TestRequestRuntimeLifecycleMatrix/simultaneous_violation_single_winner (0.00s)
=== RUN   TestStreamReleaserConfirmsExactlySinkProgress
=== RUN   TestStreamReleaserConfirmsExactlySinkProgress/zero_sink_progress
=== RUN   TestStreamReleaserConfirmsExactlySinkProgress/partial_sink_progress
=== RUN   TestStreamReleaserConfirmsExactlySinkProgress/partial_sink_progress_two_succeed_then_fail
=== RUN   TestStreamReleaserConfirmsExactlySinkProgress/full_sink_progress
--- PASS: TestStreamReleaserConfirmsExactlySinkProgress (0.00s)
    --- PASS: TestStreamReleaserConfirmsExactlySinkProgress/zero_sink_progress (0.00s)
    --- PASS: TestStreamReleaserConfirmsExactlySinkProgress/partial_sink_progress (0.00s)
    --- PASS: TestStreamReleaserConfirmsExactlySinkProgress/partial_sink_progress_two_succeed_then_fail (0.00s)
    --- PASS: TestStreamReleaserConfirmsExactlySinkProgress/full_sink_progress (0.00s)
PASS
ok  	iop/packages/go/streamgate	0.005s
```

### Package unit

- `go test -count=1 ./packages/go/streamgate`

_실제 출력:_

```text
ok  	iop/packages/go/streamgate	0.925s
```

### Package race

- `go test -race -count=1 ./packages/go/streamgate`

_실제 출력:_

```text
ok  	iop/packages/go/streamgate	1.956s
```

### Ignored-error/debug addition guard

- `! git diff -U0 -- packages/go/streamgate/evidence_tail.go packages/go/streamgate/evidence_tail_test.go | rg '^\+' | rg 'DEBUG|, _ := New|_ = New|desc, _ :=|cause, _ :=|causes, _ :='`

_실제 출력:_

```text
addition guard: OK
```

### Import boundary

- `! rg -n --sort path 'iop/apps/' packages/go/streamgate/evidence_tail.go`

_실제 출력:_

```text
import boundary: OK
```

### Diff

- `git diff --check`

_실제 출력:_

```text
git diff --check: OK
```

---

> **[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 |

## 코드리뷰 결과

### 종합 판정

FAIL

### 차원별 평가

| 차원 | 판정 | 근거 |
|------|------|------|
| Correctness | FAIL | 이전 pending prefix를 전부 release한 뒤 terminal이 도착하면 논리적으로 empty인 epoch가 `[0,nextSequence)`로 기록돼 replacement가 `errPreparedSnapshotMismatch`로 거부된다. |
| Completeness | FAIL | exact-width 검사는 stale non-empty range를 막지만, 계획이 요구한 일반 `[n,n)` empty trigger range를 fresh `[0,0)` 한 경우로만 보존했다. |
| Test coverage | FAIL | 새 empty-range 회귀가 release 이력이 없는 channel만 검증해, `nextSequence > 0`이고 pending이 빈 정상 terminal 경로를 놓쳤다. |
| API contract | FAIL | 이미 확정된 safe prefix 뒤의 protocol-safe terminal replacement가 실행되지 않아 epoch-bound replacement 계약을 깨뜨린다. |
| Code quality | PASS | captured width와 prefix 검사를 분리한 구조는 국소적이며 stale non-empty 거부 조건도 명확하다. |
| Implementation deviation | FAIL | 계획은 legitimate `[n,n)` range 전체를 허용하도록 요구했지만 현재 구현과 fixture는 `n == 0`만 다룬다. |
| Verification trust | PASS | 선언된 focused/contract/package unit·race와 정적 검증을 fresh 실행해 통과했고, 별도 최소 package probe로 누락 경로를 재현한 뒤 probe를 제거했다. |

### 발견된 문제

- **Required** — `packages/go/streamgate/evidence_tail.go:1658-1662`의 `firstPendingSequence()`는 pending이 비면 현재 monotonic `nextSequence`가 아니라 항상 `0`을 반환한다. 그래서 event 하나를 release해 `nextSequence == 1`, pending이 빈 상태에서 terminal을 append하면 epoch가 정상 `[1,1)` 대신 `[0,1)`로 고정되고, `packages/go/streamgate/evidence_tail.go:2023-2029`의 새 exact-width 검사가 replacement를 거부한다. 임시 package probe는 `terminal empty range = [0,1), want [n,n)`로 실패했다. pending이 비면 `firstPendingSequence()`가 `nextSequence`를 반환하도록 고치고, `TestEvidenceTailReplacementSettlement`에 이전 prefix를 전부 confirm한 뒤 terminal epoch가 `[n,n)`이며 replacement prepare/confirm이 성공하는 회귀를 추가해야 한다.

### 다음 단계

- 같은 split task에서 non-zero empty range 생성과 replacement acceptance를 보강하는 최소 후속 계획으로 이어간다.
