<!-- task=m-iop-hot-path-one-shot-execution/03+01,02_request_identity plan=0 tag=API milestone-task=request-identity -->

# Edge-Local Logical Request Identity Coordinator

## For the Implementing Agent

Implement only after predecessors 01 and 02 have `complete.log`. Run all verification and fill `CODE_REVIEW-cloud-G10.md` with actual evidence. Keep active files for review. On a blocker, record exact attempts/output/resume conditions only; do not ask the user, create control files, classify state, archive, or write `complete.log`.

## Background

Current request ids and Stream Evidence Gate state are request-local. Hot Path needs an Edge-local owner that correlates repeated full-history endpoint calls without trusting caller metadata, while preventing transcript mutation, tool-schema substitution, cross-principal resume, duplicate frontier consumption, and concurrent stage execution.

## Dependencies and Execution Order

- `01_preset_catalog` and `02+01_preset_model` must each produce active `complete.log`; both were missing at plan creation.

## Analysis

### Files Read

- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/chat_handler.go`
- `apps/edge/internal/openai/chat_decode.go`
- `apps/edge/internal/openai/chat_types.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_types.go`
- `apps/edge/internal/openai/dispatch_context.go`
- `apps/edge/internal/openai/principal.go`
- `apps/edge/internal/openai/stream_gate_ingress_test.go`
- `apps/edge/internal/openai/openai_auth_routes_models_test.go`
- `apps/edge/internal/openai/anthropic_surface_test.go`
- `agent-spec/runtime/stream-evidence-gate.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/outer/anthropic-compatible-api.md`

### SDD Criteria

Approved/unlocked SDD; header `request-identity`; scenario/Evidence row S05. Required evidence is full-history/frontier acceptance, immutable lineage and tool schema, public/provider tool-id mapping, cross-principal and missing-state rejection, and concurrency race safety.

### Verification Context

No handoff. The local Go/race runner is sufficient; tests use deterministic ids/time sources and endpoint fixtures, not external agents. Fresh tests are mandatory. Confidence: high on boundaries, medium on final wire correlation because protocol-gate work is intentionally a later Epic.

### Test Coverage Gaps

Ingress snapshot tests prove request-local immutability only. No existing test spans HTTP calls or detects repeated committed transcript versus the next frontier. Add unit and handler tests including same-id concurrent resumes and active-id collision injection.

### Symbol References

No rename/removal. `handleChatCompletions` and `handleAnthropicMessages` become the two ingress callers of the new coordinator; legacy/provider routes bypass it unless `routeDispatch.Preset` is present.

### Split Judgment

Child 03 depends exactly on 01/02. It owns identity, ownership, lineage, frontier, and synchronization but not mode transitions or tool semantics. Its stable PASS contract is an accepted/resumed immutable `logicalRequest` handle that later children can transition without reimplementing endpoint history parsing.

### Scope Rationale

Exclude artifact binding, direct/light stage execution, cleanup, response-envelope synthesis, durable storage, cross-Edge recovery, and new public auth tokens. A missing active state must fail, never start a new logical request.

### Final Routing

`evaluation_mode=first-pass`; `finalizer=finalize-task-policy.sh` pair. Build closures true; scores `(2,2,2,1,2)` => G09 and `grade-boundary` cloud; `large_indivisible_context=false`; risks `temporal_state,concurrent_consistency,boundary_contract,structured_interpretation,variant_product` (5), rework 0, evidence-integrity false, no capability gap; `PLAN-cloud-G09.md`. Review scores `(2,2,2,2,2)` => official cloud G10, `CODE_REVIEW-cloud-G10.md`, Codex `gpt-5.6-sol` xhigh.

## Implementation Checklist

- [ ] Implement opaque request/call/stage identity, owner affinity, immutable lineage/toolset fingerprints, and exactly-once frontier state.
- [ ] Integrate preset-backed Chat and Messages ingress without changing legacy/provider paths or trusting caller metadata as identity.
- [ ] Run deterministic concurrency, focused handler, race, vet, and diff verification exactly as written.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [API-1] Build the bounded logical-request store and lineage fence

#### Problem

`Server` has config/runtime locks but no cross-call state (`server.go:61-74`). The SDD states at lines 52-82 require one active stage, immutable prefix/transcript/toolset, a single unconsumed frontier, and terminal exactly-once behavior.

#### Solution

Add an Edge-local store keyed by a cryptographically random, path-safe 128-bit-or-stronger id. Inject id/time sources for tests. Canonicalize Chat and Messages histories into endpoint-tagged hashes, pin principal and preset generation/toolset fingerprint, map public to provider tool ids, and lock per request so only one active resume consumes the exact expected set.

```go
// Before: no cross-call owner
type Server struct { mu sync.RWMutex /* runtime config only */ }

// After
type logicalRequestStore struct { /* bounded index + per-request transition lock */ }
func (s *logicalRequestStore) Begin(...) (*logicalRequest, error)
func (s *logicalRequestStore) Resume(...) (*logicalRequest, continuationFrontier, error)
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/request_coordinator.go` — identities, state enum, bounded store, collision/replay/concurrency rules.
- [ ] `apps/edge/internal/openai/request_lineage.go` — canonical Chat/Messages transcript and toolset fingerprints.
- [ ] `apps/edge/internal/openai/request_coordinator_test.go` — unit/race matrix for owner, lineage, expected set, and exactly-once state.

#### Test Strategy

Write `TestLogicalRequestContinuationMatrix`, `TestLogicalRequestConcurrentFrontierExactlyOnce`, and `TestLogicalRequestIDCollisionRegenerates`. Assert reordered pair results may be accepted only when expected by a later child, while duplicate/unknown/missing/cross-owner/mutated history never advances stage.

#### Verification

Run `go test -race -count=1 ./apps/edge/internal/openai -run 'TestLogicalRequest'`; expect PASS and no races.

### [API-2] Join preset-backed endpoint ingress to the coordinator

#### Problem

Chat resolves and dispatches a model directly (`chat_handler.go:23-41,76-115`); Anthropic performs its own envelope/route flow. Caller metadata already carries arbitrary `request_id`-like values and must not become authoritative.

#### Solution

At each preset-backed ingress, derive authenticated principal, decode canonical history/tools, and call Begin or Resume based only on server-issued public tool ids/history correlation. Attach internal request/call/stage ids to dispatch metadata without overwriting the caller metadata namespace. Translate coordinator errors through existing endpoint-standard error writers.

```go
// Before: chat_handler.go:40-48
dispatch, err := s.resolveRouteDispatchForPrincipal(r.Context(), env.Model)
providerNativeThinking := chatRequestHasProviderNativeThinking(rawBody)

// After
dispatch, err := s.resolveRouteDispatchForPrincipal(r.Context(), env.Model)
turn, err := s.beginOrResumePresetTurn(r.Context(), dispatch, endpointChat, rawBody)
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/server.go` — own/init the coordinator and test injection points.
- [ ] `apps/edge/internal/openai/chat_handler.go` — join preset Chat ingress.
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — join preset Messages ingress.
- [ ] `apps/edge/internal/openai/request_identity_handler_test.go` — endpoint-standard begin/resume/rejection tests.

#### Test Strategy

Write `TestPresetRequestIdentityAcrossChatTurns` and `TestPresetRequestIdentityAcrossAnthropicTurns`, plus cross-principal, missing-store, caller-metadata spoof, and legacy bypass cases. Fake dispatch must remain zero on rejection.

#### Verification

Run `go test -count=1 ./apps/edge/internal/openai -run 'TestPresetRequestIdentity'`; expect PASS.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/request_coordinator.go` | API-1 |
| `apps/edge/internal/openai/request_lineage.go` | API-1 |
| `apps/edge/internal/openai/request_coordinator_test.go` | API-1 |
| `apps/edge/internal/openai/server.go` | API-2 |
| `apps/edge/internal/openai/chat_handler.go` | API-2 |
| `apps/edge/internal/openai/anthropic_handler.go` | API-2 |
| `apps/edge/internal/openai/request_identity_handler_test.go` | API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/03+01,02_request_identity/CODE_REVIEW-cloud-G10.md` | API-1, API-2 |

## Final Verification

```bash
test -f agent-task/m-iop-hot-path-one-shot-execution/01_preset_catalog/complete.log
test -f agent-task/m-iop-hot-path-one-shot-execution/02+01_preset_model/complete.log
go test -race -count=1 ./apps/edge/internal/openai -run 'Test(LogicalRequest|PresetRequestIdentity)'
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
git diff --check
```

Expected: all exit 0, exactly one concurrent continuation advances, all rejected continuations dispatch zero providers, and legacy routes are unchanged. Cache is not acceptable. After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.
