<!-- task=m-iop-hot-path-one-shot-execution/04+02,03_preset_model_authorization plan=2 tag=REVIEW_API milestone-task=preset-model -->

# Preserve Virtual Preset Identity in Native Anthropic Responses and Contracts

## For the Implementing Agent

Implement every checklist item, run every verification command, and fill the implementation-owned sections of `CODE_REVIEW-cloud-G08.md` with actual notes and stdout/stderr. Keep the active PLAN/review files in place and report ready for review; finalization is code-review-skill only. If blocked, record only the exact blocker, attempted commands/output, and resume condition in implementation-owned evidence fields. Do not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, or write `complete.log`.

## Background

Managed preset authorization and projected credential identity now follow the catalog binding, and the Chat bridge preserves the requested virtual model. The native Anthropic Messages relay still copies provider BODY frames byte-for-byte, however, so successful virtual-preset responses expose the provider's internal served model. The active OpenAI- and Anthropic-compatible contracts also still limit managed discovery and public identity to projected route ids or aliases, contradicting the approved SDD and the implemented virtual-preset admission behavior.

## Archive Evidence Snapshot

- Current review evidence will be archived as `agent-task/m-iop-hot-path-one-shot-execution/04+02,03_preset_model_authorization/plan_cloud_G07_1.log` and `agent-task/m-iop-hot-path-one-shot-execution/04+02,03_preset_model_authorization/code_review_cloud_G07_1.log`.
- Verdict: FAIL. Findings: 2 Required, 0 Suggested, 0 Nit.
- Required behavior: preserve the external virtual model identity in successful native Anthropic Messages JSON and fragmented SSE responses without changing ordinary non-preset responses, provider error bytes/status, event ordering, or terminal behavior.
- Required contract repair: update both active outer API contracts for virtual-preset discovery/admission, unique selector/all-stage authorization, projected-route credential identity, and external virtual response model identity while retaining ordinary managed-route fail-closed behavior.
- Fresh review evidence: predecessor checks, the focused virtual-preset suite, race suite, vet, gofmt diff, and `git diff --check` passed. A temporary reviewer regression against the native Anthropic driver failed with `response model="served-selector-model", want public virtual model "virtual-public-model"` and was removed after capture.
- Roadmap carryover: milestone task `preset-model`, approved SDD scenario S01. Predecessors remain satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/02+01_preset_generation/complete.log` and `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/03+01_preset_model_config/complete.log`.

## Dependencies and Execution Order

- `02+01_preset_generation` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/02+01_preset_generation/complete.log`.
- `03+01_preset_model_config` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/03+01_preset_model_config/complete.log`.
- Complete `REVIEW_API-1` before contract and end-to-end evidence work in `REVIEW_API-2`.

## Analysis

### Files Read

- `agent-roadmap/current.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/milestones/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `agent-spec/index.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/provider-pool-config-refresh.md`
- `agent-contract/index.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/edge-config-runtime-refresh.md`
- `agent-ops/rules/project/domain/edge/rules.md`
- `agent-ops/rules/project/domain/platform-common/rules.md`
- `agent-ops/rules/project/domain/testing/rules.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`
- `agent-test/local/platform-common-smoke.md`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_native.go`
- `apps/edge/internal/openai/anthropic_native_test.go`
- `apps/edge/internal/openai/provider_model_rewrite.go`
- `apps/edge/internal/openai/principal_routes.go`
- `apps/edge/internal/openai/principal_routes_test.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/routes.go`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/chat_handler.go`
- `apps/edge/internal/openai/provider_test_support_test.go`

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`, status approved and unlocked.
- Milestone task metadata: `preset-model`.
- Target: Acceptance Scenario S01.
- Evidence Map: S01 requires deterministic managed zero/one/multiple selector and stage bindings, virtual model listing/admission, and response identity that remains the requested virtual model rather than an internal stage target. The prior repair closes the binding and credential half; the native Anthropic codec and active outer contracts leave the response/API half incomplete.

### Verification Context

- Handoff supplied: current FAIL verdict, raw findings, and fresh reviewer output in the active review.
- Sources read: local test rules and the Edge/platform smoke references listed above.
- Commands/criteria: fresh native virtual-preset tests, fresh race tests for streamgate/config/OpenAI/service, OpenAI vet, gofmt diff for touched Go files, deterministic contract text inspection, and `git diff --check`; cached output is not acceptable.
- Preconditions: Go is available at `/config/.local/bin/go`, version `go1.26.2`, with `GOROOT=/config/opt/go`; both archived predecessor `complete.log` files exist.
- Constraints: local deterministic tests only. No external credentials, services, hosts, ports, or runtime processes are required, so external verification preflight is not applicable.
- Confidence: high. The reviewer reproducer isolates the native relay and the existing native tunnel fixtures cover byte preservation and frame fragmentation.

### Test Coverage Gaps

- Native Anthropic non-stream virtual preset response identity: missing; assert a provider top-level `model` is replaced with the requested virtual id.
- Native Anthropic fragmented SSE virtual preset response identity: missing; assert nested `message_start.message.model` is rewritten across fragmented frames while event order and one terminal event remain stable.
- Non-preset and provider-error preservation after the new rewrite path: protect the existing raw byte/status behavior explicitly.
- Public contract evidence: both active outer contracts still describe route-id-only managed discovery/admission and omit the virtual preset credential/public identity split.

### Symbol References

- `writeAnthropicNativeTunnelResponse` is called by native Messages and Count Tokens in `apps/edge/internal/openai/anthropic_handler.go`. Any signature change must update both call sites; Count Tokens must pass no public-model rewrite identity.
- No exported symbol is renamed or removed.

### Split Judgment

Do not split. Native codec rewriting, its regression fixtures, and the two public contracts describe one indivisible external identity invariant. The change is compact and all predecessor work is already complete.

### Scope Rationale

Limit source changes to the native Anthropic response relay and its two handler call sites, with regressions in the existing native tunnel test file and contract synchronization in the two active outer contracts. Exclude principal-route binding, preset config schemas, service/lease behavior, OpenAI Chat response rewriting, Anthropic Chat bridge behavior, other execution stages, agent-spec documents, and roadmap state because those areas are either already corrected or outside the failing boundary.

### Final Routing

- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh pair`.
- Build target: closures true; scores `(2,1,2,2,1)` = G08; base `local-fit`, recovery boundary matched, route cloud; canonical `PLAN-cloud-G08.md`.
- Review target: closures true; scores `(2,1,2,2,1)` = G08; official review route cloud; canonical `CODE_REVIEW-cloud-G08.md`.
- `large_indivisible_context=false`.
- Positive loop risks: `boundary_contract`, `structured_interpretation`, `variant_product`; count 3.
- Recovery signals: `review_rework_count=2`, `evidence_integrity_failure=true`.
- Capability-gap evidence: none.

## Implementation Checklist

- [ ] Preserve the virtual public model identity in successful native Anthropic Messages JSON and fragmented SSE responses without changing ordinary or error relay semantics.
- [ ] Add deterministic native non-stream/stream regressions and synchronize both outer API contracts with the approved virtual-preset behavior.
- [ ] Run the focused, race, vet, format, contract-inspection, and diff verification exactly as written.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_API-1] Preserve virtual identity in the native Anthropic relay

#### Problem

`apps/edge/internal/openai/anthropic_handler.go:70` sends native Messages responses to `writeAnthropicNativeTunnelResponse`, and `apps/edge/internal/openai/anthropic_native.go:66-80` writes every BODY frame unchanged. The existing virtual-preset Anthropic assertion exercises the OpenAI Chat bridge, not the native `anthropic_messages` driver. As a result, a successful native request admitted as `virtual-public-model` exposes the provider's internal `served-selector-model`.

#### Solution

Pass the dispatch's preset-only public identity into the native Messages relay; pass an empty identity from Count Tokens. Activate rewriting only when that identity is non-empty and the provider response is successful. For non-stream JSON, buffer the complete fragmented body and replace only the top-level `model` before the response is finalized. For Anthropic SSE, line-buffer arbitrary BODY fragmentation and replace only `message_start` payloads at nested `message.model`; preserve event names, every unrelated data field/line, ordering, line endings, and exactly-once terminal behavior. Remove or recompute `Content-Length` when bytes change. Preserve the current byte-for-byte path for ordinary non-preset responses and provider error status/bodies.

The helper shape is implementation-owned. Reuse the existing line-fragment and JSON patching conventions where useful, but do not apply the OpenAI top-level SSE model rewriter to Anthropic's nested event schema.

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/anthropic_handler.go` — pass virtual-preset response identity only for native Messages and no identity for Count Tokens.
- [ ] `apps/edge/internal/openai/anthropic_native.go` — rewrite successful preset JSON/SSE identity while retaining raw ordinary/error relay behavior.
- [ ] `apps/edge/internal/openai/anthropic_native_test.go` — cover non-stream, fragmented stream, and preservation boundaries.

#### Test Strategy

Add `TestAnthropicNativeVirtualPresetPreservesPublicModelIdentity` in `apps/edge/internal/openai/anthropic_native_test.go` with non-stream and streaming subtests. Drive the managed virtual preset through the native provider profile, use an internal served model distinct from the requested public id, and assert the captured selector credential route remains projected. Fragment the SSE `message_start` across BODY frames, then assert the nested public model, unchanged event order/other fields, and one terminal event. Keep the existing raw response and provider-error tests passing.

#### Verification

Run `go test -count=1 ./apps/edge/internal/openai -run 'Test(AnthropicNativeVirtualPresetPreservesPublicModelIdentity|AnthropicNative|VirtualPresetModelHandlersPreservePublicIdentity)'`; expect PASS with fresh execution.

### [REVIEW_API-2] Synchronize public contracts and close S01 evidence

#### Problem

`agent-contract/outer/openai-compatible-api.md:54-58` and `agent-contract/outer/anthropic-compatible-api.md:51-55` say managed discovery contains only projected route ids and that the public request model must be a route id or alias. Production now also lists and admits catalog virtual preset ids whose selector and stages are authorized by distinct canonical bindings, while credentials retain the selector's projected route identity and responses must retain the virtual id.

#### Solution

Update both managed authorization/routing sections to distinguish ordinary projected-route admission from virtual execution-preset admission. Specify that a virtual preset is discoverable/admissible only when the selector and every stage reference resolve to exactly one principal route through its canonical catalog binding, ambiguous or missing references fail closed, the selected route's real projected id/revisions remain the credential authority, and the virtual id remains the external response model across compatible protocols. Retain the existing rules for ordinary managed routes, legacy mode, auth failures, and data-plane trust boundaries.

#### Modified Files and Checklist

- [ ] `agent-contract/outer/openai-compatible-api.md` — document virtual preset discovery, admission, credential binding, and response identity.
- [ ] `agent-contract/outer/anthropic-compatible-api.md` — mirror the same managed virtual-preset contract for Anthropic surfaces.
- [ ] `apps/edge/internal/openai/anthropic_native_test.go` — provide the native protocol evidence referenced by the synchronized contracts.

#### Test Strategy

Use the `REVIEW_API-1` native regressions together with the existing virtual-preset authorization matrix and Chat/Anthropic bridge coverage. Inspect both contract files deterministically to confirm they name virtual preset admission, unique stage binding, projected credential identity, and public response model identity.

#### Verification

Run the focused test and deterministic contract `rg` commands from Final Verification; expect all tests to pass and both active contracts to contain the synchronized managed-preset rules.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/anthropic_handler.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/anthropic_native.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/anthropic_native_test.go` | REVIEW_API-1, REVIEW_API-2 |
| `agent-contract/outer/openai-compatible-api.md` | REVIEW_API-2 |
| `agent-contract/outer/anthropic-compatible-api.md` | REVIEW_API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/04+02,03_preset_model_authorization/CODE_REVIEW-cloud-G08.md` | REVIEW_API-1, REVIEW_API-2 |

## Final Verification

```bash
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/02+01_preset_generation/complete.log
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/03+01_preset_model_config/complete.log
go test -count=1 ./apps/edge/internal/openai -run 'Test(AnthropicNativeVirtualPresetPreservesPublicModelIdentity|AnthropicNative|VirtualPresetModelHandlersPreservePublicIdentity|VirtualPresetModelAuthorizationMatrix)'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
go vet ./apps/edge/internal/openai
gofmt -d apps/edge/internal/openai/anthropic_handler.go apps/edge/internal/openai/anthropic_native.go apps/edge/internal/openai/anthropic_native_test.go
rg --sort path -n 'virtual preset|execution preset|projected route|credential|response model' agent-contract/outer/openai-compatible-api.md agent-contract/outer/anthropic-compatible-api.md
git diff --check
```

Expected: every command exits 0 with fresh tests; native Anthropic JSON and SSE responses expose the requested virtual id, ordinary/error relay semantics remain unchanged, and both active outer contracts match SDD S01.

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