<!-- task=m-stream-evidence-gate-core/19+18_core_runtime_loop plan=13 tag=REVIEW_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_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=13, tag=REVIEW_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_G03_12.log`
- 이전 Review: `agent-task/m-stream-evidence-gate-core/19+18_core_runtime_loop/code_review_cloud_G03_12.log`
- 판정: `FAIL`
- 문제 수: Required 1, Suggested 0, Nit 0
- 문제 요약: `firstPendingSequence()`가 빈 pending에서 `nextSequence`가 아닌 `0`을 반환해, 이전 prefix를 전부 release한 뒤 terminal이 오면 정상 empty epoch가 `[0,n)`으로 기록되고 exact-width 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 실행에서 통과했다.
  - prefix event 하나를 full confirm한 뒤 terminal을 append한 임시 package probe는 `terminal empty range = [0,1), want [n,n)`로 실패했다. 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_13.log`, `PLAN-local-G03.md` → `plan_local_G03_13.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_REVIEW_CORE_RUNTIME_LOOP-1 - Preserve non-zero empty epoch boundary | [x] |

## 구현 체크리스트

- [x] pending이 비었을 때 ready epoch 시작점이 `nextSequence`를 사용해 release 이력이 있는 terminal/provider-error trigger도 exact `[n,n)` range를 갖게 한다.
- [x] `TestEvidenceTailReplacementSettlement`에 fully released prefix 뒤 non-zero empty terminal replacement prepare/confirm 성공과 state 보존 회귀를 추가한다.
- [x] fresh focused/package unit·race, format, guard, import boundary와 diff 검증을 통과시킨다.
- [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_G03_13.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_local_G03_13.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/m-stream-evidence-gate-core/19+18_core_runtime_loop/`를 `agent-task/archive/2026/07/m-stream-evidence-gate-core/19+18_core_runtime_loop/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
- [x] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-stream-evidence-gate-core/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
- [ ] WARN/FAIL이면 code-review skill의 판정에 맞는 다음 filesystem state를 작성하고 `complete.log`를 작성하지 않는다.

## 계획 대비 변경 사항

- 테스트에서 원본 텍스트를 하나만 append하는 대신 rolling threshold(12 rune)를 넘기기 위해 두 개의 text event를 append하도록 변경했다. 계획의 `rolling event 하나를 prepare/full confirm` 서술은 nextSequence > 0 조건을 만들기 위한 것이었으며, 실제 rolling threshold를 만족하는 충분한 text length가 필요하다.
- 기존 `empty_range_terminal_trigger_accepts_replacement` 테스트의 unrelated channel "b" pending 검증을 신규 회귀 테스트에서 제거했다. 신규 테스트는 buildReplacementTail의 기본 구조를 사용하지만 "b" 채널 이벤트를 사전에 생성하지 않으므로 해당 assertion은 관련이 없다.

## 주요 설계 결정

- `firstPendingSequence()`의 empty fallback을 `0`에서 `cs.nextSequence`로 변경했다. 이는 threshold/fragment completion call site가 pending non-empty 경로를 통해 호출되므로 변경 영향이 terminal/provider-error trigger epoch 생성 한 곳으로 국한된다.
- 신규 회귀 테스트는 rolling prefix를 full confirm한 뒤 terminal trigger가 `[n,n)` empty epoch를 생성하고, replacement prepare/confirm이 성공하며, committed cursor와 nextSequence가 안정적으로 유지되는지를 검증한다.

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

- empty pending에서 `firstPendingSequence()`가 현재 `nextSequence`를 반환하는가.
- prefix full confirm 뒤 terminal/provider-error epoch가 `[n,n)`으로 고정되는가.
- non-zero empty replacement prepare/confirm이 성공하면서 이미 release된 prefix를 다시 소비하지 않는가.
- stale consumed non-empty range rejection과 fresh `[0,0)` empty acceptance가 모두 유지되는가.
- 변경이 EvidenceTail package-private source/test에만 머물고 public/transport/runtime 계약을 넓히지 않는가.

## 검증 결과

### 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
```

### 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
=== RUN   TestEvidenceTailReplacementSettlement/empty_range_after_fully_released_prefix_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)
    --- PASS: TestEvidenceTailReplacementSettlement/empty_range_after_fully_released_prefix_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.004s
```

### Focused race

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

_실제 출력:_

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

### Existing contract regression

- `go test -count=1 -v ./packages/go/streamgate -run '^(TestEvidenceTailTerminalGateConfiguredTrigger|TestEvidenceTailFragmentCompletionPreservesOtherChannels|TestStreamReleaserConfirmsExactlySinkProgress|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   TestEvidenceTailTerminalGateConfiguredTrigger
=== RUN   TestEvidenceTailTerminalGateConfiguredTrigger/configuredTerminalTriggerExcludesControlEvent
=== RUN   TestEvidenceTailTerminalGateConfiguredTrigger/configuredProviderErrorTriggerExcludesControlEvent
=== RUN   TestEvidenceTailTerminalGateConfiguredTrigger/terminalTriggerWithNoPendingData
=== RUN   TestEvidenceTailTerminalGateConfiguredTrigger/subsequentAppendAfterTerminal
--- PASS: TestEvidenceTailTerminalGateConfiguredTrigger (0.00s)
    --- PASS: TestEvidenceTailTerminalGateConfiguredTrigger/configuredTerminalTriggerExcludesControlEvent (0.00s)
    --- PASS: TestEvidenceTailTerminalGateConfiguredTrigger/configuredProviderErrorTriggerExcludesControlEvent (0.00s)
    --- PASS: TestEvidenceTailTerminalGateConfiguredTrigger/terminalTriggerWithNoPendingData (0.00s)
    --- PASS: TestEvidenceTailTerminalGateConfiguredTrigger/subsequentAppendAfterTerminal (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.004s
```

### Package unit

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

_실제 출력:_

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

### Package race

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

_실제 출력:_

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

### 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
(no output)
```

### Import boundary

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

_실제 출력:_

```text
(no output)
```

### Diff

- `git diff --check`

_실제 출력:_

```text
(no 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

### 차원별 평가

| 차원 | 판정 | 근거 |
|------|------|------|
| Correctness | PASS | 빈 pending의 시작 sequence가 `nextSequence`로 고정되어, fully released prefix 뒤 terminal trigger가 정확한 `[n,n)` epoch를 만든다. |
| Completeness | PASS | 계획의 non-zero empty terminal replacement prepare/confirm 및 상태 보존 회귀를 구현·검증했다. |
| Test coverage | PASS | fresh `[0,0)`, stale non-empty 거부, non-zero `[2,2)` empty range, sink progress 및 runtime 경로 회귀를 함께 실행했다. |
| API contract | PASS | transport-agnostic `EvidenceTail` 내부 상태만 변경했으며 공개/transport 계약을 넓히지 않았다. |
| Code quality | PASS | empty fallback은 단일 helper에 국한되고, 테스트 주석의 실제 sequence 값도 `[2,2)` 기대와 일치시켰다. |
| Implementation deviation | PASS | rolling threshold를 만족시키기 위한 두 text event 사용은 계획의 `nextSequence > 0` 조건과 일치한다. |
| Verification trust | PASS | host Go identity, proto/build, focused·contract·package unit/race, format, static guard와 diff 검증을 현재 checkout에서 재실행했다. |

### 발견된 문제

없음

### 다음 단계

- PASS: `complete.log`을 작성하고 task artifact를 archive한 뒤 런타임 완료 이벤트 메타데이터를 보고한다.

