<!-- task=m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core plan=1 tag=API milestone-task=terminal-control -->

# Hot Path outer-turn core sequencer

## For the Implementing Agent

구현 후 `CODE_REVIEW-cloud-G09.md`의 구현 담당 섹션에 실제 변경과 검증 출력을 채우고 active 파일을 유지한 채 review ready를 보고한다. 차단 시 정확한 명령·출력·재개 조건만 기록하며 사용자 질문, 상태 판정, archive/`complete.log` 작성은 하지 않는다.

## Background

Hot Path는 provider stage를 `normalizedStageOutput`으로 모두 수집한 뒤 응답한다. 이 child는 protocol codec과 endpoint wiring에 앞서 Stream Evidence Gate를 재사용하는 protocol-neutral outer-turn core, deterministic id/usage/cap/terminal state, decoder/codec seam을 만든다.

## Archive Evidence Snapshot

- `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log`: PASS, stage state machine과 correlation 검증 완료.
- `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/complete.log`: PASS, cleanup terminal intent와 exactly-once cleanup 검증 완료.
- 위 로그는 선행 dependency evidence이며 구현자는 archive sibling을 추가 탐색하지 않는다.

## Analysis

### Files Read

- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-hot-path-one-shot-execution.md`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `packages/go/streamgate/runtime.go`
- `packages/go/streamgate/evidence_tail.go`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`

### SDD Criteria

- 승인 SDD, `milestone-task=terminal-control`, S10.
- 이 child는 cross-stage response-start 억제, public id 재번호, usage/output-cap 합산, delta ordering, terminal/logical completion race의 protocol-neutral evidence에 기여한다.
- S10 production closure는 child 13 및 endpoint child 14/15 evidence와 합산한다.

### Verification Context

- local 규칙과 edge-smoke profile을 적용하며 fresh `-race -count=1`만 허용한다.
- 외부 runtime은 필요하지 않다. Core release/hold와 concurrent terminal fixture가 결정적 oracle이다.

### Test Coverage Gaps

- 기존 direct/light/cleanup tests는 terminal-only subscription, ordered release, id/usage/cap aggregation, terminal race를 검증하지 않는다.

### Symbol References

- 기존 public symbol rename/remove 없음. 새 type은 `apps/edge/internal/openai` 내부에서만 사용한다.

### Split Judgment

- stable contract: `streamgate.RequestRuntime` terminal/provider-error-only hold와 protocol-neutral outer-turn sequencer.
- direct/light compatibility wiring은 child 13, endpoint wire codec은 child 14/15로 분리한다.
- predecessor 10/11은 archive evidence로 충족됐다.

### Scope Rationale

- direct/light stage transition wiring, Anthropic/OpenAI wire encoding, endpoint error matrix, observability, smoke는 제외한다.
- `packages/go/streamgate` 계약은 변경하지 않는다.

### Final Routing

- evaluation_mode=isolated-reassessment, finalizer=`finalize-task-policy.sh pair`.
- build closures 모두 true, scores=2/2/1/1/2, G08, risks=`temporal_state,concurrent_consistency,boundary_contract,structured_interpretation`(4), risk-boundary → `PLAN-cloud-G08.md`.
- review closures 모두 true, scores=2/2/1/2/2, G09, official-review → `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`, recovery=0/false, capability gap 없음.

## Implementation Checklist

- [ ] [API-1] Reuse Stream Evidence Gate with terminal/provider-error-only subscriptions and introduce the normalized outer-turn core with deterministic id, usage, cap, and terminal state.
- [ ] [API-2] Add Core release/hold, ordering, aggregation, cap, and exactly-once race tests and run the child verification commands.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [API-1] Protocol-neutral outer-turn core

**Problem:** completed `normalizedStageOutput` hides content/reasoning/tool deltas until terminal completion.

**Solution:** Construct `streamgate.RequestRuntime` with blocking registrations subscribed only to terminal/provider-error events. Forward released nonterminal events through a request-scoped, mutex-protected `hotPathOuterTurn`; convert held terminal results into transition evidence. Add `hotPathStageEventDecoder` and `hotPathOuterCodec` seams, a compatibility accumulator, monotonic public ids, usage/output-cap accounting, ordered write ownership, and atomic terminal/logical completion guards.

**Modified Files and Checklist:**

- [ ] Add `apps/edge/internal/openai/hot_path_terminal_control.go` with gate assembly, event/codec interfaces, ordered sequencer, compatibility accumulator, id mapping, usage/cap accounting, and terminal guards.
- [ ] Modify `apps/edge/internal/openai/hot_path_dispatch.go` only as needed to normalize stage events into the Core runtime and expose transition decisions for child 13.

**Test Strategy:** API-2 uses recording release sink/codec and barrier-controlled goroutines.

**Verification:** `go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(TerminalOnlyCoreRelease|OuterTurnOrderingAndAggregation|OuterTurnOutputCap|OuterTurnTerminalRace)'` exits 0.

### [API-2] Core terminal-control evidence

**Problem:** no existing test proves terminal-only hold, deterministic aggregation, or exactly-once terminal ownership.

**Solution:** Cover immediate nonterminal release, terminal/provider-error hold, response-start suppression, fragmented ordering, duplicate provider ids, tool arguments, usage dedupe, cap-to-length conversion, and cancel-vs-complete/duplicate terminal attempts.

**Modified Files and Checklist:**

- [ ] Add `apps/edge/internal/openai/hot_path_terminal_control_test.go` with `TestHotPathTerminalOnlyCoreRelease`, `TestHotPathOuterTurnOrderingAndAggregation`, `TestHotPathOuterTurnOutputCap`, and `TestHotPathOuterTurnTerminalRace`.
- [ ] Record actual outputs in `agent-task/m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core/CODE_REVIEW-cloud-G09.md`.

**Test Strategy:** assert exact event order, public ids, summed usage, one terminal/logical completion, and no post-cancel write.

**Verification:** run Final Verification; every command exits 0 and race detector reports no race.

## Dependencies and Execution Order

1. Archived predecessor 10 is satisfied.
2. Archived predecessor 11 is satisfied.
3. Implement API-1, then API-2.

## Modified Files Summary

| File | Item |
|---|---|
| `apps/edge/internal/openai/hot_path_terminal_control.go` | API-1 |
| `apps/edge/internal/openai/hot_path_dispatch.go` | API-1 |
| `apps/edge/internal/openai/hot_path_terminal_control_test.go` | API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core/CODE_REVIEW-cloud-G09.md` | API-2 |

## Final Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(TerminalOnlyCoreRelease|OuterTurnOrderingAndAggregation|OuterTurnOutputCap|OuterTurnTerminalRace)'
go test -race -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
git diff --check
```

Expected: exit 0, deterministic release/hold and aggregation, one terminal winner, no race, empty diff check. Cached output is not acceptable.

After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.
