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

# Anthropic Messages caller codec integration

## For the Implementing Agent

구현 후 `CODE_REVIEW-cloud-G10.md`의 구현 담당 섹션에 실제 변경·검증 출력을 채우고 active 파일을 유지한다. 차단 시 정확한 blocker와 재개 조건만 기록하며 archive/`complete.log` 작성이나 상태 판정은 하지 않는다.

## Background

Provider stage protocol은 caller endpoint protocol과 독립적이다. 이 child는 child 13의 normalized outer-turn events만 Anthropic Messages wire로 encode한다. 선택된 provider가 OpenAI여도 Anthropic caller codec은 동일해야 하며, provider decoding을 `anthropic_stream.go`에서 다시 구현하지 않는다.

## Archive Evidence Snapshot

- 이전 active plan/review pair는 구현 전에 source reanalysis로 대체됐다. 구현 evidence와 verdict는 없다.

## Analysis

### Files Read

- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `agent-contract/outer/anthropic-compatible-api.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/anthropic_bridge_test.go`
- `apps/edge/internal/openai/anthropic_native_test.go`
- `agent-test/local/rules.md`

### SDD Criteria

- 승인 SDD S10/S11: one native Messages envelope, fragmented text/thinking/tool deltas, correlated `tool_use`, aggregate usage, caller-native stop/error semantics.
- streaming 성공은 `message_start` → blocks → one `message_delta` → `message_stop`; committed error는 one `error` event 뒤 `message_stop`을 쓰지 않는다.

### Verification Context

- deterministic handler/wire fixtures와 fresh race tests로 닫는다. 실제 Claude smoke는 child 21이다.

### Test Coverage Gaps

- preset branch가 initial dispatch를 재사용하면서 full request `max_tokens`를 보존하고, normalized events를 Messages stream/non-stream response로 쓰는 evidence가 없다.

### Symbol References

- public rename/remove 없음. Child 12/13 provider stage decoder를 caller codec이 재사용하지도 대체하지도 않는다.

### Split Judgment

- stable contract: normalized outer events → Anthropic caller wire. Chat caller wire는 sibling 15, complete error matrix는 child 17이다.

### Scope Rationale

- provider protocol decoding, common sequencer, cross-endpoint error matrix, observation, smoke는 제외한다.

### Final Routing

- evaluation_mode=isolated-reassessment, finalizer=`finalize-task-policy.sh pair`.
- build scores=2/2/2/1/2, risks=`temporal_state,boundary_contract,structured_interpretation,variant_product`(4), grade-boundary → `PLAN-cloud-G09.md`.
- review → `CODE_REVIEW-cloud-G10.md`; `large_indivisible_context=false`, recovery=0/false.

## Implementation Checklist

- [ ] [API-1] Add a caller-facing Anthropic Messages outer codec and pass the already-dispatched preset result, request identity, stream mode, and `max_tokens` into the shared turn.
- [ ] [API-2] Add native streaming/non-streaming, mixed-provider, fragmentation, tool, cap, and baseline error handler fixtures.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

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

**Problem:** `anthropic_handler.go` currently collects selector output and only then dispatches/writes it; its envelope decode also does not retain the caller output cap.

**Solution:** Decode/retain the full Messages request fields needed by Hot Path, including required `max_tokens`. On the preset branch, create the Anthropic outer codec before consuming the already-dispatched initial result and pass that result to the shared runner without redispatch. Encode normalized text/thinking/tool events with monotonic public block/tool ids and `input_json_delta`; render aggregate normalized usage at the outer terminal. Support streaming SSE plus the existing non-stream JSON compatibility path. Keep precommit JSON errors and postcommit native error hooks for child 17.

**Modified Files and Checklist:**

- [ ] Modify `apps/edge/internal/openai/anthropic_handler.go` to retain `max_tokens`, create the caller codec, and pass the initial dispatch result/correlation into the shared turn.
- [ ] Modify `apps/edge/internal/openai/anthropic_stream.go` only for normalized outer-event encoding and stream/non-stream terminal rendering.

**Test Strategy:** invoke the preset handler with OpenAI- and Anthropic-backed fake stages; assert identical caller-native structure.

**Verification:** targeted API-2 command exits 0.

### [API-2] Anthropic wire evidence

**Problem:** ordinary bridge/native tests do not cover a multi-stage Hot Path outer turn.

**Solution:** Add fragmented direct/light/tool fixtures, mixed provider protocols, response-start suppression, stable public ids, input JSON assembly, usage sum, max-token length stop, non-stream regression, and representative pre/post-commit error cases. Leave the exhaustive terminal matrix to child 17.

**Modified Files and Checklist:**

- [ ] Add `apps/edge/internal/openai/hot_path_anthropic_gate_test.go` with handler-level native wire fixtures.
- [ ] Record actual output in `agent-task/m-iop-hot-path-one-shot-execution/14+13_anthropic_gate/CODE_REVIEW-cloud-G10.md`.

**Test Strategy:** parse emitted SSE/JSON and compare exact event order/fields rather than substring-only checks.

**Verification:** run Final Verification; all commands exit 0 without race.

## Dependencies and Execution Order

1. Directory dependency `13` must produce `agent-task/m-iop-hot-path-one-shot-execution/13+12_outer_turn_integration/complete.log`.
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|TestAnthropic(ChatBridge|Native)'
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, provider-independent native Messages output, one envelope/terminal, correct cap/usage/tool correlation, non-stream regression preserved.

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