<!-- task=m-iop-hot-path-one-shot-execution/14+13_anthropic_gate plan=0 tag=API milestone-task=terminal-control,anthropic-gate -->

# Anthropic Messages Hot Path stream gate

## For the Implementing Agent

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

## Background

Anthropic preset ingress는 현재 completed stage를 기존 응답 writer에 넘긴다. 선행 terminal-control의 normalized outer-turn event를 native Messages SSE 순서로 encode하고 tool continuation correlation을 보존해야 한다.

## Analysis

### Files Read

- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_stream.go`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/anthropic_bridge_test.go`
- `apps/edge/internal/openai/anthropic_native_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`

### SDD Criteria

- 승인 SDD, `milestone-task=terminal-control,anthropic-gate`, S10/S11.
- Evidence Map S11은 fragmented SSE, `tool_use`, error fixture와 handler integration을 요구한다. 체크리스트와 검증은 native event ordering, public id, continuation, error-before/after-commit을 직접 판정한다.
- 이 packet의 live codec, usage/output-cap, single-envelope evidence는 S10의 production Anthropic 절반에도 기여한다.

### Verification Context

- handoff 없음. local edge profile을 적용하고 fresh race tests를 사용한다. repo/branch/HEAD는 `/config/workspace/iop-s0`, `feature/iop-hot-path-one-shot-execution`, `6650e9f70d0104220d8077dd1d469b6a1facb9da`.
- 외부 Claude 실행은 packet 17 범위이며 이 packet은 deterministic handler fixtures로 닫힌다.

### Test Coverage Gaps

- 기존 bridge/native tests는 ordinary tunnel/bridge fragmentation을 검증하지만 preset direct/light의 multi-stage single envelope와 continuation id remap을 검증하지 않는다.

### Symbol References

- rename/remove 없음. 새 codec은 preset hot-path 분기에서만 사용한다.

### Split Judgment

- stable contract: normalized outer-turn event → Anthropic Messages native wire.
- predecessor 13 (`13+12_outer_turn_integration`)의 active `complete.log`는 현재 missing이며 구현 시작 전 반드시 생성되어야 한다.
- Chat wire는 sibling 14에서 독립 구현한다.

### Scope Rationale

- common sequencer 변경, Chat encoding, endpoint error matrix, metrics, actual Claude smoke는 제외한다.

### Final Routing

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

## Implementation Checklist

- [ ] [API-1] Encode the shared Hot Path outer turn as one native Anthropic Messages stream with correlated tool continuation and standard stop/error semantics.
- [ ] [API-2] Add fragmented direct/light/tool/error handler fixtures and run targeted plus SDD common verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [API-1] Native Messages codec integration

**Problem:** `apps/edge/internal/openai/anthropic_handler.go:29` enters preset handling, but completed stage output is written after collection; `anthropic_stream.go` only owns the ordinary bridge session.

**Solution:** Implement the predecessor `hotPathStageEventDecoder`/`hotPathOuterCodec` in `anthropic_stream.go` for both normalized RunEvent and fragmented tunnel SSE/JSON. Emit exactly one `message_start`, monotonic `content_block_start/delta/stop` for text/thinking/tool_use, one `message_delta` with outer stop reason and aggregate usage, then `message_stop`. Encode tool input fragments as `input_json_delta`, use remapped public tool ids, and close a tool-use HTTP turn while preserving `request_id` correlation. Pass `anthropicMessageRequest.MaxTokens` as the outer public output cap. Before commit use normal JSON error; after commit emit one Anthropic `error` event and no `message_stop`.

Before (`anthropic_handler.go:83`):

```go
stage, gate, collectErr := s.collectPresetSelectorResult(...)
return s.dispatchPresetTurn(..., stage, gate)
```

After:

```go
turn := newAnthropicHotPathTurn(w, flusher, publicModel, requestID)
return s.runPresetOuterTurn(r.Context(), turn, dispatch)
```

**Modified Files and Checklist:**

- [ ] Modify `apps/edge/internal/openai/anthropic_handler.go` to create the codec before preset dispatch, pass request correlation and `max_tokens`, and choose pre/post-commit error handling.
- [ ] Modify `apps/edge/internal/openai/anthropic_stream.go` with normalized/tunnel event decoding, outer-turn encoding, and exact native event ordering.

**Test Strategy:** API-2 supplies wire-level fixtures; ordinary bridge/native tests remain unchanged.

**Verification:** `go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPathAnthropic|TestAnthropicChatBridge|TestAnthropicNative'` exits 0.

### [API-2] Fragmented Anthropic evidence

**Problem:** S11 has no preset-native fixture coverage.

**Solution:** Build fragmented provider frames across JSON/SSE boundaries for direct text+thinking, light local→review, tool_use arguments, provider error before commit, provider error after visible delta, and tool_result continuation. Parse the public SSE and assert the full event-type sequence, unique indices/ids, model echo, aggregate usage, one stop or error, and stable logical request correlation.

**Modified Files and Checklist:**

- [ ] Add `apps/edge/internal/openai/hot_path_anthropic_gate_test.go` with `TestHotPathAnthropicFragmentedStream`, `TestHotPathAnthropicToolContinuation`, and `TestHotPathAnthropicErrorShape`.
- [ ] Fill `agent-task/m-iop-hot-path-one-shot-execution/14+13_anthropic_gate/CODE_REVIEW-cloud-G10.md`.

**Test Strategy:** New integration tests are mandatory and must fail if nested `message_start`, duplicate block id, raw internal ids, extra terminal, or post-error bytes appear.

**Verification:** run Final Verification; exact parsed event arrays match and all commands exit 0.

## Dependencies and Execution Order

1. `13+12_outer_turn_integration` must produce `agent-task/m-iop-hot-path-one-shot-execution/13+12_outer_turn_integration/complete.log` before implementation.
2. Implement API-1, then API-2.

## Modified Files Summary

| File | Item |
|---|---|
| `apps/edge/internal/openai/anthropic_handler.go` | API-1 |
| `apps/edge/internal/openai/anthropic_stream.go` | API-1 |
| `apps/edge/internal/openai/hot_path_anthropic_gate_test.go` | API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/14+13_anthropic_gate/CODE_REVIEW-cloud-G10.md` | API-2 |

## Final Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPathAnthropic|TestAnthropicChatBridge|TestAnthropicNative'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
git diff --check
```

Expected: exit 0, exact native ordering, no race/raw internal id/duplicate terminal, empty diff check. Cached output is not acceptable.

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