<!-- task=m-iop-owned-single-request-agent-execution/05+03_single_ingress plan=0 tag=API milestone-task=single-ingress -->

# Code Review Reference - API

> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> 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, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> 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, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.

## Overview

date=2026-08-06
task=m-iop-owned-single-request-agent-execution/05+03_single_ingress, plan=0, tag=API

## Archive Evidence Snapshot

- Refined parent evidence is retained in packet 03 as `plan_cloud_G09_2.log` and `code_review_cloud_G10_2.log`; earlier intent remains in its sibling logs `0` and `1`.
- The parent pair contained no implementation evidence or review verdict; implementation has not started.
- Fresh-context correction preserved here: S01 requires a runtime Edge ingress counter plus a real HTTP POST counter-delta assertion, not only a test-local handler count.
- Split allocation: packet 03 owns the surface-neutral coordinator/state machine and runtime spec. This child owns marked HTTP admission, bounded ingress observation, endpoint integration tests, and outer/input documentation.

## For the Review Agent

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

Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:

1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G10.md` → `code_review_cloud_G10_0.log` and `PLAN-cloud-G09.md` → `plan_cloud_G09_0.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/05+03_single_ingress/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=single-ingress` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.

---

## Implementation Item Completion

| Item | Status |
|------|--------|
| API-1 Admit and observe one marked Anthropic request | [x] |
| API-2 Synchronize the marked HTTP boundary | [x] |

## Implementation Checklist

- [x] Route marked Anthropic Messages requests through packet 03's separate service capability before legacy admission, while preserving immutable binding and public model echo.
- [x] Record exactly one accepted marked ingress in a registered bounded Edge counter with no request-derived labels and never increment per internal stage.
- [x] Prove one real HTTP POST, runtime counter delta `+1`, one sanitized terminal, acknowledgement behavior, privacy, and unmarked/count-tokens compatibility.
- [x] Synchronize the outer contract and input spec without claiming streaming projection, concrete workspace/provider execution, or actual Claude smoke.
- [x] Run exact dependency, focused endpoint, documentation, package, vet, full Edge, and `git diff --check` verification.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Review-Only Checklist

> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.

- [x] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [x] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [x] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G10_0.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_0.log`.
- [x] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [x] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [x] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/05+03_single_ingress/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/05+03_single_ingress/` and update this checklist at the final archive path.
- [x] If PASS, preserve and report `milestone-task=single-ingress` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [x] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.

## Deviations from Plan

None. The implementation stayed within the listed files and left finalization, archive movement, `complete.log`, and roadmap state untouched. A supplemental race run was performed in addition to the required commands.

## Key Design Decisions

- Kept `runService` unchanged and introduced the narrow optional `singleRequestService` capability only at marked Messages admission.
- Performed full Anthropic body validation after authenticated route resolution, rejected missing coordinator capability without generic fallback, and incremented the unlabeled runtime counter exactly once at accepted marked admission.
- Passed defensive copies of the immutable binding and request input to the service coordinator. Only the finalizing result is projected; internal progress, errors, tools, routes, credentials, and workspace identity remain private.
- Encoded one buffered Anthropic JSON terminal with the requested public model and acknowledged success only after a complete body write. Short/failed writes receive negative acknowledgement, and request cancellation cancels the execution.
- Preserved ordinary Anthropic/Chat and count-tokens paths. Streaming progress/ping projection, concrete workspace/provider execution, and actual Claude smoke remain explicitly deferred.

## Reviewer Checkpoints

- Packet 03 completion evidence existed before implementation.
- Marked admission occurs after validation/authorization and before legacy pool/caller continuation.
- `runService` is unchanged; only marked dispatch requires the narrow optional capability.
- Exactly one real HTTP POST increments the registered runtime Edge ingress counter by exactly one across all internal stages.
- The counter has no request-derived labels and is not incremented per stage, retry, event, or terminal.
- Public model echo is preserved; output has no reasoning, tool wire, provider/route/credential/workspace values, or caller `tool_use` continuation.
- Success acknowledgement follows the terminal write; failure and cancellation notify the execution handle.
- Unmarked Anthropic, Chat, and count-tokens compatibility remains unchanged.

## Verification Results

### Dependency

Command: `test -f agent-task/m-iop-owned-single-request-agent-execution/03+02_single_request_coordinator/complete.log || test "$(compgen -G 'agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/03+02_single_request_coordinator/complete.log' | wc -l)" -eq 1`

_Actual output/status:_

Exit status: `0` (no stdout/stderr). Exactly one dependency candidate existed at `agent-task/archive/2026/08/m-iop-owned-single-request-agent-execution/03+02_single_request_coordinator/complete.log`.

### One runtime-counted ingress and compatibility

Command: `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`

_Actual output:_

```text
ok  	iop/apps/edge/internal/openai	0.052s
```

### Documentation

Command: `rg --sort path -n 'single-request|one POST|ingress|tool_use|count_tokens|defer' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md`

_Actual output:_

```text
agent-contract/outer/anthropic-compatible-api.md:47:`credential_plane.enabled=true` selects managed mode at startup. The Control Plane supplies the initial secret-free projection in the authenticated mTLS hello and pushes newer generations after durable credential mutations. Edge shares one bounded immutable cache across OpenAI and Anthropic-compatible ingress and fails closed when a managed hello or refresh is missing, stale, invalid, or expired.
agent-contract/outer/anthropic-compatible-api.md:75:### Marked preset: single-request admission
agent-contract/outer/anthropic-compatible-api.md:77:An authorized fixed single-request preset compiles one service-owned admission value
agent-contract/outer/anthropic-compatible-api.md:90:### Marked preset: one-ingress runtime boundary
agent-contract/outer/anthropic-compatible-api.md:100:`iop_anthropic_single_request_ingress_total` exactly once. The counter has no labels and
agent-contract/outer/anthropic-compatible-api.md:110:`stop_reason="end_turn"`, and no caller-facing `tool_use` continuation. The endpoint
agent-contract/outer/anthropic-compatible-api.md:116:progress/ping and streaming terminal projection are deferred. Concrete Node workspace
agent-contract/outer/anthropic-compatible-api.md:129:- Managed mode sources provider authentication only from the credential slot and Node-targeted lease. Config validation rejects `openai.provider_auth` and static provider credential sources, while ingress rejects caller-supplied legacy provider credential headers with `400 invalid_request_error`.
agent-contract/outer/anthropic-compatible-api.md:160:### `POST /v1/messages/count_tokens` 및 `POST /anthropic/v1/messages/count_tokens`
agent-contract/outer/anthropic-compatible-api.md:162:Anthropic count_tokens 호환 요청.
agent-contract/outer/anthropic-compatible-api.md:216:- `stream`: `true`이면 ordinary provider routes relay raw provider SSE. `false` 또는 생략이면 non-streaming JSON 응답을 반환한다. An admitted virtual-preset Hot Path is the narrow exception described in routing: it emits the caller-requested endpoint-native shape after structural classification. The marked single-request coordinator boundary currently emits only the buffered JSON terminal described above; its SSE projection is deferred.
agent-contract/outer/anthropic-compatible-api.md:240:    { "type": "tool_use", "id": "toolu_xxx", "name": "search", "input": { "query": "..." } }
agent-contract/outer/anthropic-compatible-api.md:258:- `content`: text, thinking, tool_use block array.
agent-contract/outer/anthropic-compatible-api.md:259:- `stop_reason`: `end_turn`, `max_tokens`, `tool_use`, `stop_sequence` 중 하나.
agent-contract/outer/anthropic-compatible-api.md:315:- `invalid_request_error`: 요청 validation 실패 (missing field, bad value, unsupported header), request body가 ingress 상한 초과 (413)
agent-contract/outer/anthropic-compatible-api.md:349:Chat bridge는 Gemini OpenAI-compatible tool call의 `extra_content.google.thought_signature`를 opaque Anthropic `tool_use.id`에 담아 caller에게 전달한다. Caller는 해당 id를 tool result까지 변경 없이 replay해야 하며, 다음 요청에서 Edge는 원래 tool call id와 signature를 복원한다. Signature가 없는 provider의 tool id는 변경하지 않는다.
agent-contract/outer/anthropic-compatible-api.md:377:- `count_tokens` capability + `count_tokens` operation (count_tokens native fallback 요청인 경우; TokenCounter local count path는 provider selection 및 capability check가 필요 없다)
agent-contract/outer/anthropic-compatible-api.md:388:Anthropic handlers do not record the OpenAI canonical usage metric series. Native `USAGE` tunnel frames are ignored by the Anthropic relay; provider-reported usage remains in the native response body or is converted by the Chat bridge response path. The marked coordinator exception records only the unlabeled admission counter `iop_anthropic_single_request_ingress_total`; it does not infer provider usage or expose request-derived dimensions.
agent-contract/outer/anthropic-compatible-api.md:406:- `iop.openai-compatible-api`: `agent-contract/outer/openai-compatible-api.md` (공유 auth, metadata, ingress, usage metric, model catalog)
agent-spec/input/openai-compatible-surface.md:28:    path: apps/edge/internal/openai/stream_gate_ingress.go
agent-spec/input/openai-compatible-surface.md:29:    notes: body 첫 read 전 ingress 상한과 request-local snapshot
agent-spec/input/openai-compatible-surface.md:53:    notes: Unlabeled runtime counter for accepted marked Anthropic single-request ingress
agent-spec/input/openai-compatible-surface.md:126:| marked preset single-request admission | An authorized fixed single-request preset compiles one service-owned admission value at request start: requested public model, canonical plan/work/review bindings resolved through managed authorization, opaque workspace capability, and absolute resource caps. Later refresh cannot mutate the admitted shape. No private binding is echoed to the caller. Compiled only after every canonical reference is verified through its catalog binding for the authenticated principal; missing, duplicate, unauthorized, dynamically selected, or option-inconsistent inputs are rejected without fallback. |
agent-spec/input/openai-compatible-surface.md:127:| marked single-request ingress | One validated and authorized Messages POST enters the separate service coordinator capability before legacy provider/caller continuation, increments `iop_anthropic_single_request_ingress_total` once, and returns one buffered sanitized Anthropic terminal. Internal stage/tool progress never becomes caller `tool_use`; terminal success is acknowledged only after the response body write succeeds. |
agent-spec/input/openai-compatible-surface.md:140:| Anthropic ingress | `POST /v1/messages` and `POST /anthropic/v1/messages` share one handler; the corresponding count-tokens paths share another. `/anthropic/v1/models`, and `/v1/models` with `anthropic-version`, return the Anthropic model-list shape. Wrong methods return `405 invalid_request_error`. |
agent-spec/input/openai-compatible-surface.md:141:| Anthropic caller auth | Anthropic ingress accepts `Authorization: Bearer <token>` or `X-Api-Key: <token>`. If both are present they must match; shared principal-token and legacy bearer fallback apply after this validation. |
agent-spec/input/openai-compatible-surface.md:144:| bounded ingress와 Stream Evidence Gate | Chat/Responses body를 첫 read 전에 최대 16 MiB로 제한한다. `openai.stream_evidence_gate.enabled=true`인 지원 경로는 response-start staging, filter arbitration, bounded recovery와 단일 terminal을 `runtime/stream-evidence-gate`에 위임한다. |
agent-spec/input/openai-compatible-surface.md:147:| model-driven response path | request `model`이 가리키는 provider capability가 provider raw tunnel 또는 normalized RunEvent path를 결정한다. caller metadata는 route나 response shape를 선택하지 않는다. OpenAI와 Anthropic ingress는 같은 model catalog와 provider-pool dispatch를 공유한다. |
agent-spec/input/openai-compatible-surface.md:162:- 포함: OpenAI-compatible HTTP auth, bounded ingress, request validation, route resolution, bounded metadata 처리, chat/responses 변환, provider-pool dispatch handoff, tool/reasoning/strict output 처리.
agent-spec/input/openai-compatible-surface.md:201:- `credential_plane.enabled` is the startup-only managed/legacy switch. Managed mode requires TLS on OpenAI ingress, CP-Edge, and Edge-Node hops; config validation rejects legacy principal/provider-auth and static provider credential sources.
agent-spec/input/openai-compatible-surface.md:203:- `openai.stream_evidence_gate`는 기본 비활성이고, recovery cap 0..3과 16 MiB 이하 ingress snapshot 상한을 설정한다. 변경은 현재 restart-required다.
agent-spec/input/openai-compatible-surface.md:211:- A marked single-request Messages dispatch requires the narrow service coordinator capability and never falls back to the generic provider pool. The handler copies the immutable binding and request input, counts the accepted HTTP admission once with no labels, exposes only the service's final sanitized output with the requested public model, and cancels the execution on caller disconnect. Missing capability and runtime failures use sanitized same-request errors. Count-tokens does not enter or increment this path.
agent-spec/input/openai-compatible-surface.md:212:- Claude Code Messages requests may use adaptive thinking, `output_config.effort`, structured output, cache-control annotations, and supported beta headers. The Chat bridge consumes those headers, maps supported fields, and requires callers to replay opaque `tool_use.id` values unchanged so Gemini thought signatures can be restored on tool-result turns.
agent-spec/input/openai-compatible-surface.md:221:- OpenAI handlers emit `iop_openai_requests_total`, `iop_openai_usage_tokens_total`, `iop_openai_reasoning_observed_total`, `iop_openai_reasoning_chars_total`, and `iop_openai_reasoning_estimated_tokens_total`. Anthropic handlers do not emit these series. The marked single-request boundary emits only the unlabeled `iop_anthropic_single_request_ingress_total` admission counter.
agent-spec/input/openai-compatible-surface.md:264:- Marked single-request output is currently buffered JSON. Anthropic SSE progress/ping projection, concrete Node workspace/provider execution, and actual Claude qualification remain deferred and are not implied by the ingress counter or deterministic fake-coordinator test.
agent-spec/input/openai-compatible-surface.md:282:- 2026-07-28: bounded ingress와 Stream Evidence Gate 활성 경로·한계·검증 포인터를 현재 구현 기준으로 반영.
agent-spec/input/openai-compatible-surface.md:286:- 2026-08-01: Synchronized Anthropic ingress, provider-pool admission, usage boundaries, and Responses capability admission with the current handlers.
agent-spec/input/openai-compatible-surface.md:290:- 2026-08-06: Added marked single-request Messages admission through the separate service coordinator capability, one unlabeled runtime ingress counter, buffered sanitized terminal acknowledgement, and deterministic real-POST compatibility evidence.
```

### Final regression

Commands:

- `go test ./apps/edge/internal/openai -count=1`
- `go vet ./apps/edge/...`
- `go test ./apps/edge/... -count=1`
- `git diff --check`

_Actual output:_

- `go test ./apps/edge/internal/openai -count=1`

  ```text
  ok  	iop/apps/edge/internal/openai	7.961s
  ```

- `go vet ./apps/edge/...`

  Exit status: `0` (no stdout/stderr).

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

  ```text
  ok  	iop/apps/edge/cmd/edge	0.135s
  ok  	iop/apps/edge/internal/authprojection	0.038s
  ok  	iop/apps/edge/internal/bootstrap	0.435s
  ok  	iop/apps/edge/internal/configrefresh	0.110s
  ok  	iop/apps/edge/internal/controlplane	6.604s
  ok  	iop/apps/edge/internal/edgecmd	0.085s
  ok  	iop/apps/edge/internal/edgevalidate	0.065s
  ok  	iop/apps/edge/internal/events	0.045s
  ok  	iop/apps/edge/internal/input	0.078s
  ok  	iop/apps/edge/internal/input/a2a	0.059s
  ok  	iop/apps/edge/internal/node	0.048s
  ok  	iop/apps/edge/internal/openai	8.005s
  ok  	iop/apps/edge/internal/opsconsole	0.041s
  ok  	iop/apps/edge/internal/service	5.958s
  ok  	iop/apps/edge/internal/transport	4.775s
  ```

- `git diff --check`

  Exit status: `0` (no stdout/stderr).

---

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

## Section Ownership

| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

## Code Review Result

### Overall Verdict

PASS

### Dimension Assessment

| Dimension | Assessment | Evidence |
|-----------|------------|----------|
| Correctness | Pass | Marked Messages admission branches before the legacy pool, copies the immutable binding/input, emits only the finalizing result, and propagates write acknowledgement and caller cancellation. |
| Completeness | Pass | API-1 and API-2 implementation, documentation, and implementation-owned review evidence are complete within the packet's buffered-JSON scope. |
| Test coverage | Pass | A real HTTP POST proves counter delta `+1`, a single sanitized terminal, acknowledgement behavior, privacy, unavailable/failure/cancel paths, and count-tokens compatibility; focused, package, race, and full Edge suites pass. |
| API contract | Pass | The outer contract and input spec match the implemented one-ingress boundary, public model echo, sanitized failures, unlabeled metric, and explicit SSE/workspace/provider/Claude deferrals. |
| Code quality | Pass | The narrow optional interface preserves `runService`; no debug code, dead code, stale references, formatting drift, or unrelated packet-owned source changes were found. |
| Implementation deviation | Pass | The implementation stayed within the planned write boundary; the supplemental race run strengthened verification without changing scope. |
| Verification trust | Pass | Reviewer fresh runs reproduced the focused test, OpenAI package, race, vet, full Edge, documentation, formatting, and diff results. |
| Spec conformance | Pass | `milestone-task=single-ingress` exists in the active Milestone, and the implementation evidence satisfies SDD scenario S01 and its Evidence Map for this packet. |

### Findings

None.

### Routing Signals

- `review_rework_count=0`
- `evidence_integrity_failure=false`

### Next Step

PASS: archive the active plan/review pair, write `complete.log`, and move this split task to the 2026/08 task archive while preserving `milestone-task=single-ingress` for runtime aggregation.
