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

# Single-request Anthropic Ingress and Runtime Evidence

## For the Implementing Agent

Do not start until packet 03 has `complete.log`. Implement this plan exactly within the listed write boundary, run every verification command, fill all implementation-owned sections of `CODE_REVIEW-cloud-G10.md` with actual notes and stdout/stderr, keep the active pair in place, and report ready for review. Finalization belongs only to the code-review skill. If blocked, record exact blocker evidence, attempted commands/output, and the resume condition; do not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, or write `complete.log`.

## 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.

## Background

After packet 03 exposes the surface-neutral coordinator, the marked Anthropic path must admit exactly one `/v1/messages` request, bypass legacy caller continuation, drive every internal stage through that coordinator, and return one sanitized buffered result or failure. S01 requires the real HTTP boundary and a runtime Edge ingress counter as evidence.

## Analysis

### Files Read

- `AGENTS.md`
- `agent-ops/rules/project/rules.md`
- `agent-ops/rules/common/rules-roadmap.md`
- `agent-ops/rules/common/rules-agent-spec.md`
- `agent-ops/rules/project/domain/edge/rules.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_types.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/hot_path_metrics.go`
- `apps/edge/internal/openai/anthropic_surface_test.go`
- `apps/edge/internal/openai/request_identity_handler_test.go`
- `apps/edge/internal/openai/provider_test_support_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-spec/input/openai-compatible-surface.md`

### SDD Criteria

- SDD status is approved and its implementation lock is released.
- First-line Milestone task: `single-ingress`; targeted Acceptance Scenario: S01.
- S01 requires one actual `/v1/messages` POST, a runtime Edge ingress counter, immutable identity, full internal multi-stage execution behind the coordinator/API boundary, and one final/error. This packet supplies the HTTP/counter evidence on packet 03's coordinator foundation.

### Verification Context

- No separate verification handoff was supplied. Repository-native fallback is the Anthropic handler/identity suite, existing bounded metric pattern, Edge smoke profile, outer contract, input spec, and approved SDD.
- Precondition: packet 03 completion. Constraints: current checkout only; no external provider/runner; a deterministic multi-stage fake drives the coordinator.
- A real `httptest.Server` request and runtime Prometheus counter delta are the direct one-ingress oracle. Endpoint regressions, vet, and full Edge tests guard compatibility.

### State and Concurrency Findings

- Marked admission must occur after validation/authorization and before legacy pool/caller-continuation execution.
- The handler writes one sanitized terminal and acknowledges success only after that write; write failure or cancellation must notify the request-scoped execution handle.
- The ingress counter records accepted marked HTTP admission once, never per stage, retry, event, or terminal.

### Test Coverage Gaps

- Existing endpoint tests do not send one real marked POST through an HTTP server across a multi-stage fake.
- No registered runtime metric records accepted single-request ingress, and a test-local call count cannot satisfy S01.
- No endpoint test proves the marked branch avoids caller `tool_use` continuation while preserving unmarked Anthropic, Chat, and count-tokens behavior.

### Symbol References

- `runService` is implemented by `*service.Service` and multiple OpenAI test fakes; do not widen it.
- `routeDispatch` carries packet 02's immutable binding; `handleAnthropicMessages` is the marked branch point.
- Use packet 03's separate single-request service capability only for marked dispatch.

### Refine Judgment

- This is the ingress integration child produced by the one-time refinement of the corrected parent.
- Its handler, runtime counter, real-POST test, and public contract form one boundary-verification unit; further splitting would leave no independently PASS-capable HTTP claim.

### Scope Rationale

- Include marked Anthropic admission, the no-request-label runtime ingress counter, buffered result/failure translation, endpoint tests, and outer/input documentation.
- Exclude service coordinator internals, SSE projection, generic relay changes, concrete Node/workspace/provider protocol, latency/outcome metrics, and actual Claude smoke.

### Final Routing

- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh` in `pair` mode.
- Build closures are true; scores 2/2/2/1/2 = G09; base/final route `grade-boundary`; lane `cloud`; canonical filename `PLAN-cloud-G09.md`.
- Build signals: `large_indivisible_context=false`; positive loop risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `variant_product` (4); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
- Review closures are true; scores 2/2/2/2/2 = G10; route `official-review`; lane `cloud`; canonical filename `CODE_REVIEW-cloud-G10.md`.

## Dependencies and Execution Order

1. Verify exactly one packet 03 completion candidate, preferring the active path.
2. Wire a separate optional single-request capability without widening `runService`.
3. Add marked HTTP admission and the bounded runtime ingress counter before legacy continuation.
4. Prove one real POST and counter delta `+1`, then synchronize outer/input documentation and run regressions.

## Implementation Checklist

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

## Implementation Plan

### [API-1] Admit and observe one marked Anthropic request

**Problem**

- `apps/edge/internal/openai/anthropic_handler.go:101` resolves dispatch and then reaches the legacy pool/caller-continuation path at line 108 without a marked one-request branch.
- `apps/edge/internal/openai/server.go:23` defines the widely faked `runService`; widening it would break unrelated fakes and couple the capability to every endpoint.
- `apps/edge/internal/openai/hot_path_metrics.go:112` owns current Hot Path collectors but has no runtime Edge counter for accepted marked ingress, so a handler-local count cannot satisfy S01.

**Solution**

Before (`apps/edge/internal/openai/server.go:23`):

```go
type runService interface {
	SubmitRun(context.Context, edgeservice.SubmitRunRequest) (edgeservice.RunResult, error)
	SubmitProviderTunnel(context.Context, edgeservice.SubmitProviderTunnelRequest) (edgeservice.ProviderTunnelResult, error)
	SubmitProviderPool(context.Context, edgeservice.ProviderPoolDispatchRequest) (*edgeservice.ProviderPoolDispatchResult, error)
	OllamaAPI(context.Context, edgeservice.OllamaAPIRequest) (edgeservice.OllamaAPIView, error)
	CancelRun(context.Context, edgeservice.CancelRunRequest) (edgeservice.CommandResult, error)
}
```

After, without changing `runService`:

```go
type singleRequestService interface {
	StartSingleRequest(context.Context, edgeservice.SingleRequestRequest) (edgeservice.SingleRequestExecution, error)
}
```

Before (`apps/edge/internal/openai/anthropic_handler.go:101`):

```go
dispatch, err := s.resolveRouteDispatchForPrincipal(r.Context(), envelope.Model)
if err != nil || !dispatch.ProviderPool {
	s.writeAnthropicRouteError(w, err)
	return
}

needsTools := anthropicRequestNeedsTools(body)
poolReq, presetIngress, err := s.anthropicPoolRequest(r, dispatch, envelope, body, config.OperationMessages, needsTools)
```

After:

```go
dispatch, err := s.resolveRouteDispatchForPrincipal(r.Context(), envelope.Model)
// Existing authorization failure remains fail-closed.
if dispatch.SingleRequest != nil {
	capability, ok := s.service.(singleRequestService)
	if !ok {
		s.writeSingleRequestUnavailable(w)
		return
	}
	recordSingleRequestIngress()
	s.handleAnthropicSingleRequest(w, r, capability, dispatch, envelope, body)
	return
}
// Existing generic pool path remains unchanged below.
```

In `single_request_metrics.go`, declare complete imports for the already-present Prometheus dependency:

```go
import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

var singleRequestIngressTotal = promauto.NewCounter(prometheus.CounterOpts{
	Name: "iop_anthropic_single_request_ingress_total",
	Help: "Accepted marked Anthropic single-request ingress.",
})
```

For marked dispatch only, branch after validation/authorization and before pool/legacy continuation; copy request input and binding, preserve the public model, and translate one buffered sanitized final/error. Increment the counter exactly once when the marked request is accepted, not per internal stage or retry. Acknowledge success only after the dedicated response encoder reports that the terminal write succeeded; propagate write failure/cancellation to the handle. Never return caller `tool_use` or re-enter the generic branch.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/openai/server.go` — declare/wire the separate optional single-request capability without expanding `runService`.
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — branch marked admission before legacy execution and translate buffered final/error output.
- [ ] `apps/edge/internal/openai/single_request_metrics.go` — own the registered bounded Edge ingress counter without request-derived labels.
- [ ] `apps/edge/internal/openai/single_request_handler_test.go` — send one real POST through `httptest.Server`, assert counter delta `+1`, drive multi-stage/repair events, and cover acknowledgement, privacy, unavailability, failure, and cancellation.

**Test Strategy**

- `TestAnthropicSingleRequestUsesOnePost` snapshots the registered counter, sends one real HTTP POST through `httptest.Server`, drives multiple internal stages, and asserts a delta of exactly one plus one response terminal.
- Add repair success, terminal-write acknowledgement/failure, missing capability, executor failure/cancel, public-model, private-sentinel, and no-caller-`tool_use` cases.
- Rerun existing preset identity and count-tokens tests unchanged.

**Verification**

- `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
- Expected: one real marked POST increments the runtime ingress counter exactly once across multi-stage execution and returns one sanitized terminal; generic continuation/count-tokens behavior is unchanged.

### [API-2] Synchronize the marked HTTP boundary

**Problem**

- `agent-contract/outer/anthropic-compatible-api.md:24` scopes the generic Anthropic-compatible boundary but has no marked single-request exception.
- `agent-spec/input/openai-compatible-surface.md:132` describes shared Messages ingress but does not distinguish the coordinator-backed path or its runtime evidence.

**Solution**

Before (`agent-spec/input/openai-compatible-surface.md:132`):

```markdown
| 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`. |
```

After, add a separate marked-path row and matching outer-contract subsection:

```markdown
| marked single-request ingress | One authorized Messages POST freezes the coordinator binding, increments one Edge ingress counter, never returns caller `tool_use`, and commits one sanitized terminal on the same request. |
```

Document public model retention, same-request sanitized failure, terminal acknowledgement, and unchanged generic Anthropic/Chat/count-tokens behavior. Keep SSE projection and concrete workspace/provider integration explicitly deferred.

**Modified Files and Checklist**

- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define one-ingress semantics, compatibility, runtime evidence, and private/public boundaries.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize marked handler behavior, counter evidence, and explicit deferrals.

**Test Strategy**

- Skip a standalone documentation-only test because API-1's named real-POST/counter/privacy/compatibility cases are the executable contract oracle.

**Verification**

- `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`
- Expected: marked one-ingress behavior and deferrals are explicit while generic compatibility remains documented.

## Modified Files Summary

| File | Item |
|------|------|
| `apps/edge/internal/openai/server.go` | API-1 |
| `apps/edge/internal/openai/anthropic_handler.go` | API-1 |
| `apps/edge/internal/openai/single_request_metrics.go` | API-1 |
| `apps/edge/internal/openai/single_request_handler_test.go` | API-1 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-2 |
| `agent-spec/input/openai-compatible-surface.md` | API-2 |
| `agent-task/m-iop-owned-single-request-agent-execution/05+03_single_ingress/CODE_REVIEW-cloud-G10.md` | API-1, API-2 |

## Final Verification

1. `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`
2. `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
3. `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`
4. `go test ./apps/edge/internal/openai -count=1`
5. `go vet ./apps/edge/...`
6. `go test ./apps/edge/... -count=1`
7. `git diff --check`

Expected: exactly one packet 03 completion candidate exists; one real marked POST increments the registered runtime Edge ingress counter by exactly one and yields one sanitized terminal without caller continuation; compatibility and all Edge checks pass. Streaming projection, concrete workspace execution, and actual Claude smoke remain unclaimed.

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