<!-- task=m-multi-provider-protocol-profile-native-messages/02+01_messages_ingress plan=2 tag=REVIEW_API -->

# Code Review Reference - REVIEW_API

> **[IMPLEMENTING AGENT — READ FIRST] Filling this file is the mandatory final implementation step.**
> The task is not complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, keep the active files in place, and report ready for review.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, create control-plane files, classify the next state, archive files, or write `complete.log`.
> Finalization is review-agent-only. Follow the ownership table at the bottom of this file.

## Overview

date=2026-08-01
task=m-multi-provider-protocol-profile-native-messages/02+01_messages_ingress, plan=2, tag=REVIEW_API

## Roadmap Targets

- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/multi-provider-protocol-profile-native-messages.md`
- Milestone link: [Milestone document](agent-roadmap/phase/operational-observability-provider-management/milestones/multi-provider-protocol-profile-native-messages.md)
- Task ids:
  - `messages-surface`: canonical/alias routes, principal auth, Anthropic model schema, and count-tokens
  - `messages-native`: native Messages raw tunnel preservation
  - `messages-chat-bridge`: Messages-to-Chat semantic and streaming bridge
- Completion mode: check-on-pass

## Archive Evidence Snapshot

- Direct predecessor PASS evidence: `agent-task/archive/2026/08/m-multi-provider-protocol-profile-native-messages/01_protocol_core/complete.log`.
- Prior plan archive: `agent-task/m-multi-provider-protocol-profile-native-messages/02+01_messages_ingress/plan_cloud_G09_01.log`.
- Prior review archive: `agent-task/m-multi-provider-protocol-profile-native-messages/02+01_messages_ingress/code_review_cloud_G09_01.log`.
- Prior verdict: `FAIL`; findings: Required=2, Suggested=0, Nit=0.
- Raw finding 1: the prior plan required only an active predecessor `complete.log`, although split-task dependency evidence must be resolved active-first and then from the matching archive path.
- Raw finding 2: REVIEW_API-1 through REVIEW_API-4, all scoped production/test files, and all implementation verification remain to be completed.
- Roadmap carryover: `messages-surface`, `messages-native`, and `messages-chat-bridge` remain unchecked until this follow-up passes.

## For the Review Agent

> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent-only. Implementing agents must not execute this section.

Compare each implementation item with source and verify that all recorded command output is trustworthy and current.

1. Append one verdict plus `review_rework_count` and `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G09.md` to `code_review_cloud_G09_02.log` and `PLAN-cloud-G09.md` to `plan_cloud_G09_02.log`.
3. On PASS, write `complete.log` and move the active task directory to `agent-task/archive/YYYY/MM/m-multi-provider-protocol-profile-native-messages/02+01_messages_ingress/`. On WARN/FAIL, fully materialize the next state required by the code-review skill.
4. On PASS for this milestone task group, report completion event metadata; roadmap mutation remains a runtime responsibility.
5. Check every applicable `Review-Only Checklist` item at the final log location before reporting.

---

## Implementation Item Completion

| Item | Status |
|------|--------|
| REVIEW_API-1 | [x] |
| REVIEW_API-2 | [x] |
| REVIEW_API-3 | [x] |
| REVIEW_API-4 | [x] |

## Implementation Checklist

- [x] Add canonical/alias Anthropic routes, shared bearer/`x-api-key` principal resolution, version-selected model schema, and native/local count-tokens behavior with S05 tests.
- [x] Implement profile-selected native Messages tunneling with a header allowlist, model rewrite, byte/SSE/error preservation, and exactly-once terminal evidence for S06.
- [x] Implement strict Messages-to-Chat non-stream/stream transformation for supported content, tools, thinking, usage, stop, and error semantics, rejecting unsupported inputs before provider wire dispatch for S07.
- [x] Run focused direct-Edge fixtures, full Edge/Node regression, and the fake Lemonade integration cycle with fresh results.
- [x] Fill all implementation-owned sections in `CODE_REVIEW-cloud-G09.md` with actual implementation notes and verification output.

## Review-Only Checklist

> **[REVIEW AGENT ONLY]** Implementing agents must not modify this checklist.

- [x] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified routing signals to `Code Review Result`.
- [x] Verify that verdict, dimension assessments, and Required/Suggested/Nit classifications are consistent.
- [x] Archive active `CODE_REVIEW-cloud-G09.md` to `code_review_cloud_G09_02.log`.
- [x] Archive active `PLAN-cloud-G09.md` to `plan_cloud_G09_02.log`.
- [x] Verify that the Agent-Ops managed `.gitignore` block unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` from the required template and leave no active task `.md` files.
- [ ] If PASS, move the active task directory to the dated archive and update this checklist at its final path.
- [ ] If PASS for this milestone task group, report completion event metadata without mutating the roadmap.
- [ ] If PASS for split work, remove the empty active parent or verify it remains because siblings/files are active.
- [x] If WARN/FAIL, materialize the next filesystem state and do not write `complete.log`.

## Deviations from Plan

- Verifications 3 through 8 used the environment-only prefix `GOCACHE=/config/.cache/iop-g09-verify.BY2DZ6/cache GOTMPDIR=/config/workspace/iop-s0/.local/gotmp-g09-messages`. The inherited Go cache was configured to another runner's unreadable `/tmp/claude-1000/.../scratchpad/gocache`, and executable test artifacts cannot run from the environment's no-exec temporary mount. Test and vet arguments were unchanged.
- `apps/edge/internal/openai/server.go` additionally deep-copies `TokenCounter` while snapshotting the model catalog so request-time local counting cannot observe mutable caller-owned configuration.
- `apps/edge/internal/openai/input_estimator.go` additionally renames the private `stringsBuilder.WriteByte` helper to `appendByte`. This is behavior-neutral and resolves the Go 1.26 vet diagnostic that methods named `WriteByte` must implement the conventional `WriteByte(byte) error` signature.

## Key Design Decisions

- Canonical and `/anthropic` compatibility routes share the same authenticated handlers. Bearer and `X-Api-Key` credentials enter the existing constant-time principal resolver, unequal dual credentials fail without disclosure, and only a validated `Anthropic-Version` selects the Anthropic models schema.
- Messages submits one provider-pool admission with no preselected tunnel operation. The request-local candidate predicate requires a concrete tunnel profile and the declared operation, streaming, and tool capabilities; `PrepareProtocolTunnel` binds the operation and body only after selection.
- Native Messages profiles receive only allowlisted content/version/known-beta headers plus profile-declared auth. A surgical top-level model patch preserves all other request bytes, while the response relay preserves provider status, allowed headers, body fragments, SSE order, and returns on the first terminal frame.
- The Chat bridge uses strict JSON decoding and fails unknown or unrepresentable options before any provider wire request. It maps system/text/image/tool use/tool result/tool choice/thinking in, and maps text/reasoning/tool calls/usage/finish reasons/errors out. Its request-local SSE state reconstructs fragmented tool arguments, preserves block order, and makes `[DONE]` plus tunnel END idempotent.
- Count-tokens is local only when the catalog declares a deterministic or configured estimator. Otherwise it admits only a native profile with an explicit `count_tokens` operation; Chat-only candidates fail as `not_supported_error` before wire dispatch.

## Reviewer Checkpoints

- Confirm the archived predecessor PASS evidence was accepted through the active-first/exact-archive split dependency rule.
- Confirm canonical and `/anthropic` aliases share handlers and principal context; unequal Authorization/`X-Api-Key` credentials fail without disclosing either token.
- Confirm `anthropic-version`, not User-Agent or vendor inference, selects the Anthropic model schema.
- Confirm candidate filtering occurs before provider wire dispatch and selected-profile request preparation chooses only declared operations/capabilities.
- Confirm native relay changes only documented model/auth headers and preserves body/status/error/SSE ordering with exactly one terminal.
- Confirm the Chat bridge rejects unsupported semantics before provider wire dispatch and preserves content order, tool ids/arguments, thinking, usage, stop reasons, and errors.
- Confirm count-tokens uses a declared native operation or deterministic local counter and never substitutes an arbitrary Chat request.
- Confirm all tests are fresh and the fake integration cycle does not require external credentials.

## Verification Results

> **Implementation owner:** Run each command exactly as written and paste actual stdout/stderr plus exit status. If a command must change, record the replacement and reason in `Deviations from Plan` first.

### Verification 1

```bash
test -f agent-task/archive/2026/08/m-multi-provider-protocol-profile-native-messages/01_protocol_core/complete.log
```

```text
(no stdout/stderr)
exit status: 0
```

### Verification 2

```bash
command -v go && go version && go env GOROOT
```

```text
/config/.local/bin/go
go version go1.26.2 linux/arm64
/config/opt/go
exit status: 0
```

### Verification 3

```bash
go test -count=1 ./apps/edge/internal/openai -run 'TestAnthropic(Canonical|Principal|Models|CountTokens)'
```

```text
Replacement executed with the environment-only prefix documented in Deviations:
ok  	iop/apps/edge/internal/openai	0.035s
exit status: 0
```

### Verification 4

```bash
go test -count=1 ./apps/edge/internal/openai -run 'TestAnthropicNative'
```

```text
Replacement executed with the environment-only prefix documented in Deviations:
ok  	iop/apps/edge/internal/openai	0.038s
exit status: 0
```

### Verification 5

```bash
go test -count=1 ./apps/edge/internal/openai -run 'TestAnthropicChatBridge'
```

```text
Replacement executed with the environment-only prefix documented in Deviations:
ok  	iop/apps/edge/internal/openai	0.032s
exit status: 0
```

### Verification 6

```bash
go vet ./apps/edge/...
```

```text
Replacement executed with the environment-only prefix documented in Deviations:
(no stdout/stderr)
exit status: 0
```

### Verification 7

```bash
go test -count=1 ./apps/edge/...
```

```text
Replacement executed with the environment-only prefix documented in Deviations:
ok  	iop/apps/edge/cmd/edge	1.076s
ok  	iop/apps/edge/internal/bootstrap	14.849s
ok  	iop/apps/edge/internal/configrefresh	0.779s
ok  	iop/apps/edge/internal/controlplane	4.546s
ok  	iop/apps/edge/internal/edgecmd	0.368s
ok  	iop/apps/edge/internal/edgevalidate	0.087s
ok  	iop/apps/edge/internal/events	0.053s
ok  	iop/apps/edge/internal/input	0.163s
ok  	iop/apps/edge/internal/input/a2a	0.145s
ok  	iop/apps/edge/internal/node	0.138s
ok  	iop/apps/edge/internal/openai	7.609s
ok  	iop/apps/edge/internal/opsconsole	0.196s
ok  	iop/apps/edge/internal/service	5.998s
ok  	iop/apps/edge/internal/transport	4.831s
exit status: 0
```

### Verification 8

```bash
go test -count=1 ./apps/node/...
```

```text
Replacement executed with the environment-only prefix documented in Deviations:
ok  	iop/apps/node/cmd/node	0.103s
ok  	iop/apps/node/internal/adapters	0.078s
?   	iop/apps/node/internal/adapters/mock	[no test files]
ok  	iop/apps/node/internal/adapters/ollama	0.036s
ok  	iop/apps/node/internal/adapters/openai_compat	0.159s
ok  	iop/apps/node/internal/adapters/vllm	0.150s
ok  	iop/apps/node/internal/bootstrap	1.495s
ok  	iop/apps/node/internal/node	0.894s
ok  	iop/apps/node/internal/router	0.520s
ok  	iop/apps/node/internal/store	0.131s
ok  	iop/apps/node/internal/transport	5.595s
exit status: 0
```

### Verification 9

```bash
IOP_LEMONADE_MODE=fake ./scripts/e2e-openai-lemonade.sh
```

```text
[openai-lemonade] OpenAI-compatible Lemonade serving test PASSED (mode=fake).
exit status: 0
```

### Verification 10

```bash
rg -n --sort path '"/(anthropic/)?v1/(messages|models)' apps/edge/internal/openai
```

```text
apps/edge/internal/openai/anthropic_bridge_test.go:33:	w := serveAnthropicRequest(srv, "/v1/messages", string(fixture.Request))
apps/edge/internal/openai/anthropic_bridge_test.go:115:	w := serveAnthropicRequest(srv, "/v1/messages", body)
apps/edge/internal/openai/anthropic_bridge_test.go:163:			req := newAnthropicRequest(http.MethodPost, "/v1/messages", tc.body)
apps/edge/internal/openai/anthropic_bridge_test.go:189:	w := serveAnthropicRequest(srv, "/v1/messages", `{"model":"claude-route","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
apps/edge/internal/openai/anthropic_bridge_test.go:223:	w := serveAnthropicRequest(srv, "/v1/messages", `{"model":"claude-route","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hello"}]}`)
apps/edge/internal/openai/anthropic_native_test.go:46:			req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(requestBody))
apps/edge/internal/openai/anthropic_native_test.go:120:	req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"claude-route","max_tokens":32,"stream":true,"messages":[{"role":"user","content":"hello"}]}`))
apps/edge/internal/openai/anthropic_native_test.go:152:	w := serveAnthropicRequest(srv, "/v1/messages", `{"model":"claude-route","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
apps/edge/internal/openai/anthropic_surface_test.go:30:	for _, path := range []string{"/v1/messages", "/anthropic/v1/messages"} {
apps/edge/internal/openai/anthropic_surface_test.go:63:		req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/anthropic_surface_test.go:81:		req := httptest.NewRequest(http.MethodGet, "/anthropic/v1/models", nil)
apps/edge/internal/openai/anthropic_surface_test.go:101:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/anthropic_surface_test.go:119:	aliasReq := httptest.NewRequest(http.MethodGet, "/anthropic/v1/models", nil)
apps/edge/internal/openai/anthropic_surface_test.go:127:		httptest.NewRequest(http.MethodGet, "/anthropic/v1/models", nil),
apps/edge/internal/openai/anthropic_surface_test.go:129:			r := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/anthropic_surface_test.go:141:	openAIReq := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/anthropic_surface_test.go:160:		w := serveAnthropicRequest(srv, "/v1/messages/count_tokens", requestBody)
apps/edge/internal/openai/anthropic_surface_test.go:178:		w := serveAnthropicRequest(srv, "/v1/messages/count_tokens", requestBody)
apps/edge/internal/openai/anthropic_surface_test.go:195:		w := serveAnthropicRequest(srv, "/v1/messages/count_tokens", requestBody)
apps/edge/internal/openai/anthropic_types.go:113:	return path == "/v1/messages" || path == "/v1/messages/count_tokens" ||
apps/edge/internal/openai/cancellation_routes_test.go:196:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/cancellation_routes_test.go:214:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/cancellation_routes_test.go:232:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/identity_metering_test.go:40:			req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/identity_metering_test.go:65:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/openai_auth_routes_models_test.go:29:			req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/openai_auth_routes_models_test.go:58:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/openai_auth_routes_models_test.go:83:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/provider_dispatch_test.go:28:	req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
apps/edge/internal/openai/routes.go:12:	mux.HandleFunc("/v1/models", s.withAuth(s.handleModels))
apps/edge/internal/openai/routes.go:21:	for _, path := range []string{"/v1/messages", "/anthropic/v1/messages"} {
apps/edge/internal/openai/routes.go:24:	for _, path := range []string{"/v1/messages/count_tokens", "/anthropic/v1/messages/count_tokens"} {
apps/edge/internal/openai/routes.go:27:	mux.HandleFunc("/anthropic/v1/models", s.withAuth(s.handleModels))
exit status: 0
```

### Verification 11

```bash
git diff --check
```

```text
(no stdout/stderr)
exit status: 0
```

---

> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled every implementation-owned section?**
> If anything is blank, fill it before saving. Leave review-agent-only sections unchanged.

## Section Ownership

| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, review instructions | Fixed at stub creation | Implementing agent must not modify or execute archive/finalization instructions |
| Roadmap Targets | Fixed at stub creation | Review copies them to completion evidence only on PASS |
| Archive Evidence Snapshot | Fixed at stub creation | Only the cited archive evidence may be read for prior-loop context |
| Implementation Item Completion | Implementing agent | Change `[ ]` to `[x]` only after completing each item |
| Implementation Checklist | Implementing agent | Change `[ ]` to `[x]` only; do not edit text/order |
| Review-Only Checklist | Review agent only | Implementing agent must not modify it |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual evidence |
| Reviewer Checkpoints | Fixed at stub creation | Review agent verifies them |
| Verification Results | Implementing agent | Fill output only; command changes require a deviation entry |
| Code Review Result | Review agent | Appended during review; absent from this stub |

## Code Review Result

- Overall Verdict: FAIL
- Dimension Assessment:
  - Correctness: Fail — the Chat bridge can emit content events after its terminal `message_stop` event when `[DONE]` and later SSE data arrive in the same tunnel body frame.
  - Completeness: Fail — REVIEW_API-3 does not yet satisfy the planned request-local terminal-state invariant.
  - Test Coverage: Fail — the stream tests cover `[DONE]` followed by tunnel END but do not cover later SSE data in the same body frame after `[DONE]`.
  - API Contract: Fail — the emitted Anthropic stream can violate the required `message_start` → content block events → `message_delta` → `message_stop` ordering by appending content block events after `message_stop`.
  - Code Quality: Pass — the scoped implementation is cohesive, request-local, and contains no review-scoped debug code, dead code, or unresolved TODOs.
  - Implementation Deviation: Pass — the `TokenCounter` snapshot copy and private helper rename are justified, bounded deviations with no adverse review finding.
  - Verification Trust: Pass — focused tests, Edge vet/tests, Node tests, the route scan, diff hygiene, and the fake Lemonade E2E were reproduced; the first concurrent cold-cache E2E attempt timed out while compiling its fake server, and the isolated rerun passed.
  - Spec Conformance: Fail — SDD state `response/terminal` has no next state and its bridge output requires `message_stop` last, but the reproduced stream transitions back to content output after terminal.
- Findings:
  - Required — `apps/edge/internal/openai/anthropic_stream.go:67-83` checks `stopped` only when `Feed` begins, then continues consuming every event already buffered in that call after `[DONE]` invokes `Finish`. A focused reviewer test with one chunk containing `data: [DONE]\n\n` followed by a content delta failed because the response emitted `message_stop`, then `content_block_start` and `content_block_delta` containing `late`. Stop consuming and discard buffered post-terminal bytes immediately when `Finish` or `Error` reaches the terminal state, and add a regression that combines `[DONE]`, later same-frame data, and tunnel END while asserting that `message_stop` is the final event exactly once.
- Routing Signals:
  - `review_rework_count=2`
  - `evidence_integrity_failure=false`
- Next Step: Invoke the plan skill in `prepare-follow-up` mode with this raw finding, rerun isolated task routing, and materialize the routed follow-up PLAN/CODE_REVIEW pair after archiving this pair.
