<!-- task=m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix plan=1 tag=API milestone-task=error-cancel -->

# Anthropic/Chat endpoint terminal and error matrix

## For the Implementing Agent

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

## Background

Child 16의 공통 disposition을 caller protocol별 wire/status/commit policy로 완전히 닫는다. 이번 SDD의 Hot Path endpoint는 Anthropic Messages와 OpenAI Chat Completions이며 `/v1/responses`는 이 matrix 범위가 아니다.

## 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`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/inner/edge-node-runtime-wire.md`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_stream.go`
- `apps/edge/internal/openai/chat_handler.go`
- `apps/edge/internal/openai/normalized_sse.go`
- `apps/edge/internal/openai/cancellation_routes_test.go`
- `apps/edge/internal/openai/chat_stream_session_test.go`
- `agent-test/local/rules.md`

### SDD Criteria

- 승인 SDD S13: endpoint × commit state × disposition source × active stage matrix, native output-limit stop, silent caller cancel, one terminal and no post-terminal write.
- Chat committed ordinary error는 protocol-compatible error chunk와 `[DONE]`; Anthropic committed error는 standard `error` event이며 `message_stop`을 뒤따르지 않는다.

### Verification Context

- handler-level recorder, disconnecting writer, barrier fixture, fresh race tests로 닫는다.

### Test Coverage Gaps

- preset Hot Path에 대해 precommit/committed provider error, validation, timeout, caller cancel, cap, tool/success terminal을 두 endpoint 모두 교차하는 table test가 없다.

### Symbol References

- public rename/remove 없음. Child 16 disposition만 endpoint policy 입력으로 사용한다.

### Split Judgment

- stable contract: common disposition → caller-native terminal/error behavior. Common lifecycle 변경은 child 16에서 완료되어야 한다.

### Scope Rationale

- `/v1/responses`, provider-stage decode, observation schema, actual CLI smoke는 제외한다. Ordinary non-Hot-Path regressions는 영향 확인용으로만 실행한다.

### Final Routing

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

## Implementation Checklist

- [ ] [API-1] Map every common disposition to exact precommit/committed Anthropic Messages and Chat behavior, including native output-cap and silent caller cancel.
- [ ] [API-2] Add a complete two-endpoint terminal/error/cancel race matrix and ordinary endpoint regressions.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [API-1] Endpoint policy closure

**Problem:** baseline endpoint codecs do not by themselves prove correct behavior for every terminal source before and after response commit.

**Solution:** Define explicit endpoint mapping tables over disposition and commit state. Before commit, use the endpoint's normal JSON error/status contract. After commit, emit exactly one native stream error/terminal sequence: Anthropic `error` without `message_stop`; Chat error chunk then `[DONE]` where the existing contract requires it. Map public-cap exhaustion to native length stop, close tool turns normally, suppress all wire output for caller cancellation, and reject later callbacks/writes.

**Modified Files and Checklist:**

- [ ] Modify `apps/edge/internal/openai/anthropic_handler.go` for Anthropic precommit disposition/status mapping.
- [ ] Modify `apps/edge/internal/openai/anthropic_stream.go` for committed Anthropic terminal/error mapping.
- [ ] Modify `apps/edge/internal/openai/chat_handler.go` for Chat precommit disposition/status mapping.
- [ ] Modify `apps/edge/internal/openai/normalized_sse.go` for committed Chat terminal/error mapping.

**Test Strategy:** table-driven endpoint × commit × disposition × stage fixtures assert status, bytes, flush count, terminal count, and post-terminal rejection.

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

### [API-2] Matrix evidence

**Problem:** existing cancellation/stream-session tests cover ordinary endpoint sessions but not preset multi-stage ownership.

**Solution:** Extend it with direct/local/review/repair active-stage rows for success, tool_turn, length, provider_error, validation_error, timeout, and caller_cancel. Include cancel-vs-complete and disconnect-during-write races, exact active `CancelRun` count, Anthropic no-`message_stop` after error, Chat `[DONE]` policy, and no post-terminal bytes.

**Modified Files and Checklist:**

- [ ] Modify `apps/edge/internal/openai/cancellation_routes_test.go` with the Hot Path endpoint matrix and race fixtures.
- [ ] Record actual output in `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/CODE_REVIEW-cloud-G10.md`.

**Test Strategy:** structural decode of emitted JSON/SSE plus exact status/flush/cancel trace.

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

## Dependencies and Execution Order

1. Directory dependency `14` must produce `agent-task/m-iop-hot-path-one-shot-execution/14+13_anthropic_gate/complete.log`.
2. Directory dependency `15` must produce `agent-task/m-iop-hot-path-one-shot-execution/15+13_chat_gate/complete.log`.
3. Directory dependency `16` must produce `agent-task/m-iop-hot-path-one-shot-execution/16+14,15_terminal_disposition/complete.log`.
4. 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/chat_handler.go` | API-1 |
| `apps/edge/internal/openai/normalized_sse.go` | API-1 |
| `apps/edge/internal/openai/cancellation_routes_test.go` | API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/CODE_REVIEW-cloud-G10.md` | API-2 |

## Final Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(EndpointTerminalMatrix|CancelCompleteRace)|Test(ChatStreamSession|AnthropicNative|StreamChatCompletion)'
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 terminal/error behavior for both scoped endpoints, silent caller cancel, one active cancellation/terminal, no post-terminal bytes or race.

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