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

# One-POST Single-request Coordinator

## For the Implementing Agent

Do not start until predecessor 02 has `complete.log`. Implement only this packet, run every command, and fill all implementation-owned sections of `CODE_REVIEW-cloud-G10.md` with actual notes and stdout/stderr before reporting ready for review. Keep active files in place; finalization is code-review-only. If blocked, record the exact blocker, attempts/output, and resume condition in the 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

The current Anthropic preset path joins caller `tool_result` continuations across multiple HTTP requests and binds one codec per HTTP turn. SDD S01 instead requires one actual `POST /v1/messages` whose immutable request and preset snapshot remain owned by Edge until all internal stage events converge to one result.

## Analysis

### Files Read

- `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/anthropic_handler.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/request_coordinator.go`
- `apps/edge/internal/openai/request_coordinator_test.go`
- `apps/edge/internal/openai/request_identity_handler_test.go`
- `apps/edge/internal/openai/anthropic_surface_test.go`
- `apps/edge/internal/openai/anthropic_stream.go`
- `apps/edge/internal/openai/hot_path_light.go`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `apps/edge/internal/openai/hot_path_terminal_control.go`
- `apps/edge/internal/openai/hot_path_terminal_control_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-test/local/edge-smoke.md`

### SDD Criteria

- SDD approved; Milestone task `single-ingress`; Acceptance Scenario S01.
- Evidence Map requires a Claude-invocation-style integration test whose Edge-observed `/v1/messages` POST count is exactly one and whose final response needs no caller ingress.
- This packet implements the Edge state machine, executor boundary, and Anthropic handler ownership needed for S01. It does not claim the actual Claude smoke in S12 or the concrete workspace tool loop in S06.

### Verification Context

- No separate handoff was supplied. Repository-native evidence is the current two-turn Anthropic request-identity test, handler call graph, terminal race tests, and local edge profile.
- Baseline related package tests passed at starting HEAD.
- Precondition: `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log`.
- External preflight is not applicable: exact ingress count is deterministically measured at the in-process Edge handler. Real Claude/provider/Node execution is intentionally excluded and belongs to `claude-smoke`.
- Confidence: high for Edge ownership and HTTP-count evidence; concrete provider/tool behavior is represented by a deterministic executor fake and remains owned by other Milestone tasks.

### Test Coverage Gaps

- `TestPresetRequestIdentityAcrossAnthropicTurns` proves the old generic preset continuation behavior with two requests; it must remain for unmarked presets.
- No test measures actual Edge POST count for a marked fixed preset while multiple internal plan/work/tool/review events occur.
- No test covers the approved state set, immutable admission clone, one-active-stage rule, duplicate/stale event rejection, caller cancellation, or exactly-once final selection. Add coordinator and handler tests, including `-race`.

### Symbol References

- No symbol is renamed or removed.
- `handleAnthropicMessages` is the sole Messages handler for canonical and alias paths.
- `joinPresetAnthropicIngress` remains referenced by Chat and generic preset paths; this packet must bypass it only when `dispatch.SingleRequest != nil`.
- `Server` construction is centralized in `NewServer`; add coordinator/runtime ownership without changing `runService` or protobuf.

### Split Judgment

- This packet's indivisible invariant is one Edge-owned state machine and one HTTP handler lifetime. Splitting state transition selection from handler cancellation/terminal ownership would leave no independently meaningful ingress proof.
- Predecessor index 02 resolves to active sibling `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/`; at planning time its `complete.log` is missing, so implementation is pending that exact evidence and is not ambiguous.
- Successor `04+03_stream_terminal` consumes the closed public progress/result event boundary defined here.

### Scope Rationale

- Do not implement Node workspace RPC, tool execution, tool-loop continuation, plan prompts, work behavior, review repair, budget policy, cleanup metrics, or real Claude smoke.
- Do not modify generic Chat or generic preset continuation behavior.
- The runtime executor port is real coordination architecture, not a fake production success path: absence/unavailability fails on the same request without fallback or a second caller request.

### Final Routing

- evaluation_mode `first-pass`; finalizer `finalize-task-policy.sh` pair.
- Build closures all true. Scores 2/2/2/1/2 = G09; base/final route `grade-boundary`; lane `cloud`; filename `PLAN-cloud-G09.md`.
- Build signals: `large_indivisible_context=false`; risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`, `variant_product` (5); risk boundary matched but grade basis retained; rework 0; evidence integrity false; no capability gap.
- Review closures all true. Scores 2/2/2/2/2 = G10; `official-review` on cloud Codex `gpt-5.6-sol` xhigh; filename `CODE_REVIEW-cloud-G10.md`.

## Dependencies and Execution Order

1. Require predecessor 02 `complete.log` at its active path or matching same-group archive path.
2. Implement coordinator kernel before wiring the handler inside this packet.
3. Leave the typed public progress/result boundary stable for successor 04; do not implement its SSE projector here.

## Implementation Checklist

- [ ] Implement the request-local single-request state machine and executor event boundary with immutable admission, one active stage, fail-closed transitions, cancellation, and exactly-once terminal tests.
- [ ] Route marked Anthropic Messages requests through that coordinator before legacy preset ingress, keep one HTTP lifetime, return one sanitized final/error, and prove actual Edge ingress POST count 1 with a multi-stage fake.
- [ ] Preserve unmarked preset/Chat/count-tokens behavior and synchronize the Anthropic contract plus current implementation specs.
- [ ] Run targeted, race, full Edge regression, 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] Add the request-local coordinator kernel

**Problem**

- `apps/edge/internal/openai/request_coordinator.go` models `agent_tool_wait` and caller `resumed` states for cross-request continuations, not the SDD single-request stage lifecycle.
- `apps/edge/internal/openai/server.go:58`-`77` owns only the legacy logical coordinator, artifact frontier, and light-flow store.

**Solution**

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

    executionPresets   []config.ExecutionPreset
    requestCoordinator *logicalRequestCoordinator
    artifactFrontiers  *artifactFrontierStore
    lightFlows         *hotPathLightStore

After:

    executionPresets        []config.ExecutionPreset
    requestCoordinator      *logicalRequestCoordinator
    singleRequestCoordinator *singleRequestCoordinator
    singleRequestExecutor   SingleRequestExecutor
    artifactFrontiers       *artifactFrontierStore
    lightFlows              *hotPathLightStore

- Add `single_request_coordinator.go` with approved states `accepted`, `planning`, `working`, `internal_tool`, `reviewing`, `finalizing`, `completed`, `failed`, and `cancelled`.
- Define a narrow typed executor boundary that accepts an immutable copy of request bytes, request/public model/preset identity, compiled stage routes, workspace ref, and limits, then emits a closed event vocabulary. It must not accept caller-selected Node/path/model overrides.
- Enforce one active stage generation, legal ordered transitions, stale/duplicate event rejection, mutually exclusive terminal states, and exactly one final result. Copy maps/slices/raw bytes at admission.
- Expose only closed phase progress plus sanitized final/error to the outer handler. Raw provider reasoning, tool calls/results, route credentials, and internal terminal data never cross the public-event boundary.
- Propagate request context cancellation once to the active executor and converge to `cancelled` without inventing a success terminal. An unavailable executor returns a same-request fail-closed error.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/openai/single_request_coordinator.go` — implement state, immutable admission, executor/events, transition and terminal ownership.
- [ ] `apps/edge/internal/openai/single_request_coordinator_test.go` — add table, stale/duplicate, immutability, cancel/complete race, and terminal-count tests.
- [ ] `apps/edge/internal/openai/server.go` — install coordinator and executor ownership without changing `runService`.

**Test Strategy**

- Write `TestSingleRequestCoordinatorStateMachine` for plan → work → internal tool → work → review → finalizing → completed.
- Write `TestSingleRequestCoordinatorRejectsStaleOrDuplicateEvents` and `TestSingleRequestCoordinatorAdmissionIsImmutable`.
- Write `TestSingleRequestCoordinatorCancelCompleteRaceHasOneTerminal` with repeated race iterations under `go test -race`.
- Use an in-memory deterministic executor only; no Node/proto or external provider fixture.

**Verification**

- `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestCoordinator' -count=1`
- Expected: all transitions and race iterations have one winner and no race report.

### [API-2] Give marked Messages requests one HTTP lifetime

**Problem**

- `apps/edge/internal/openai/anthropic_handler.go:101`-`163` builds legacy preset ingress before dispatch and may return a caller tool terminal.
- `apps/edge/internal/openai/request_identity_ingress.go:168`-`266` explicitly consumes Anthropic continuation structure from a later request.

**Solution**

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

    dispatch, err := s.resolveRouteDispatchForPrincipal(...)
    ...
    poolReq, presetIngress, err := s.anthropicPoolRequest(...)

After:

    dispatch, err := s.resolveRouteDispatchForPrincipal(...)
    ...
    if dispatch.SingleRequest != nil {
        s.handleAnthropicSingleRequest(w, r, dispatch, envelope, body, *tokenLimit.MaxTokens)
        return
    }
    poolReq, presetIngress, err := s.anthropicPoolRequest(...)

- Branch only marked fixed presets before `anthropicPoolRequest`/`joinPresetAnthropicIngress`. The one handler invocation owns the coordinator until result, error, or caller disconnect.
- Use the existing Anthropic codec for a buffered final response in both JSON and stream modes at this stage; emit only validated final text with the requested public model and never `tool_use`, private reasoning, or internal stage terminals.
- Accept a public-event observer callback but keep progress emission nil/buffered until successor 04. This creates a stable projector boundary without changing the current endpoint framing yet.
- On handler cancellation, stop writing and cancel the coordinator/executor. On executor unavailable/error, return one standard sanitized Anthropic error in the same request.
- Keep count-tokens, unmarked presets, native routes, Chat bridge, and canonical/alias endpoint registration unchanged.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/openai/anthropic_handler.go` — add the marked branch and single-lifetime response handling.
- [ ] `apps/edge/internal/openai/single_request_handler_test.go` — add exact ingress counter and compatibility tests.

**Test Strategy**

- Write `TestAnthropicSingleRequestIngressCountIsOne` around `srv.routes()` with an HTTP counting wrapper. Send one client POST; have the executor fake emit plan/work/internal-tool/review/final; assert counter 1, executor starts once, public model echo, final text, no `tool_use`, and no follow-up request.
- Write `TestAnthropicSingleRequestIngressSnapshotIsImmutable` by mutating original config/body after admission and comparing the executor snapshot.
- Write `TestAnthropicSingleRequestFailureDoesNotRequestContinuation` and `TestAnthropicSingleRequestCountTokensBypassesCoordinator`.
- Rerun `TestPresetRequestIdentityAcrossAnthropicTurns` unchanged to prove the legacy unmarked path remains compatible.

**Verification**

- `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
- Expected: marked path observes exactly one POST and generic continuation/count-tokens tests remain unchanged.

### [API-3] Synchronize the boundary documentation

**Problem**

- The outer Anthropic contract currently describes the virtual-preset Hot Path as per-turn structural classification and documents caller replay for Chat bridge tools.
- Current specs do not distinguish the new marked fixed path from that generic compatibility behavior.

**Solution**

- Document the fixed marker exception: one `/v1/messages` POST, immutable request binding, internal event consumption, no caller `tool_use` continuation, requested public model retention, same-request failure, and unchanged generic/Chat/count-tokens paths.
- Record the executor port as an Edge-owned request coordinator boundary; concrete workspace wire/tool loop remains outside this task and must not be represented as complete.

**Modified Files and Checklist**

- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define one-POST semantics and compatibility boundary.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize handler behavior and test evidence.
- [ ] `agent-spec/runtime/edge-node-execution.md` — describe the Edge coordinator port without claiming Node workspace implementation.

**Test Strategy**

- No separate doc test. API-2 integration assertions are the contract oracle; review must compare prose to the named tests.

**Verification**

- `rg --sort path -n 'single-request|one POST|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
- Expected: the fixed path and exclusions are explicit, with no private endpoint, credential, or raw path.

## Modified Files Summary

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

## Final Verification

1. `test -f agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log' -print | sort | grep -q .`
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestCoordinator' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
4. `rg --sort path -n 'single-request|one POST|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
5. `go test ./apps/edge/internal/openai -count=1`
6. `go test ./apps/edge/... -count=1`
7. `git diff --check`

Expected: dependency evidence exists; state/race tests pass; one client call produces one Edge POST and one final/error without caller continuation; all generic regressions pass. Fresh Go execution is mandatory via `-count=1`. Actual Claude S12 remains explicitly unclaimed.

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