<!-- task=m-iop-hot-path-one-shot-execution/07+02,04,06_route_selector_direct plan=1 tag=REVIEW_API milestone-task=route-selector,direct-flow -->

# Production Preset Direct-Path Closure

## For the Implementing Agent

Implement every checklist item, run the exact verification commands, and fill the implementation-owned sections in `CODE_REVIEW-*-G??.md` with actual notes and stdout/stderr. Keep the active pair in place and report ready for official review. If blocked, record only the exact blocker, attempted commands/output, and resume condition in implementation-owned 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 first implementation created isolated selector/direct helpers, but preset-backed Chat and Messages handlers still return through the ordinary provider-pool paths. The production path therefore activates logical-request state without invoking structural selection, direct continuation, or direct terminal handling. This follow-up closes the S03/S07 production boundary and removes synthetic response metadata.

## Archive Evidence Snapshot

- Prior plan: `agent-task/m-iop-hot-path-one-shot-execution/07+02,04,06_route_selector_direct/plan_local_G07_0.log`.
- Prior review: `agent-task/m-iop-hot-path-one-shot-execution/07+02,04,06_route_selector_direct/code_review_cloud_G08_0.log`.
- Verdict: FAIL with 3 Required, 0 Suggested, and 0 Nit findings.
- Required closure: connect real Chat/Messages preset output to the selector/direct runner; use pinned capability/health evidence and exact canonical control shapes; preserve actual provider response identity/usage instead of synthetic values.
- Affected files: the preset Chat/Messages handler branches, hot-path selector/dispatch/direct implementation, and their focused tests.
- Verification evidence: static reference search found `dispatchPresetTurn` called only by its direct unit test; fresh focused test/race/vet commands were additionally blocked by an out-of-scope concurrent compile error in `apps/edge/internal/openai/workspace_tool_codec.go` and must be rerun after the shared package compiles.
- Roadmap carryover: `route-selector,direct-flow`; SDD S03 requires deterministic no-prose structural routing and S07 requires real direct text/high-thinking/tool completion with no reserved artifact path.

## Dependencies and Execution Order

- `02+01_preset_generation` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/02+01_preset_generation/complete.log`.
- `04+02,03_preset_model_authorization` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/04+02,03_preset_model_authorization/complete.log`.
- `06+04,05_request_identity_ingress` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/06+04,05_request_identity_ingress/complete.log`.

## Analysis

### Files Read

- `apps/edge/internal/openai/chat_handler.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/hot_path_selector.go`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/request_coordinator.go`
- `apps/edge/internal/openai/run_result.go`
- `apps/edge/internal/openai/stream_gate_tunnel_codec.go`
- `apps/edge/internal/openai/hot_path_selector_test.go`
- `apps/edge/internal/openai/hot_path_direct_test.go`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/outer/anthropic-compatible-api.md`

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`; status `[승인됨]`, lock released.
- First-line tasks: `route-selector,direct-flow`.
- S03/Evidence Map: real output-shape, allowlist, and hard-gate table evidence with no natural-language parsing.
- S07/Evidence Map: handler-integrated text/high-thinking/tool direct completion with `.iop/job/<request_id>` absence.
- These rows require production handler integration, exact canonical shape rejection, state frontier/terminal assertions, and actual endpoint response evidence in the checklist and final commands.

### Verification Context

- No verification handoff was supplied; repository-native evidence came from the active pair, Edge/testing domain rules, local Edge smoke profile, API contracts, source, and focused tests.
- Host preflight: `/config/.local/bin/go`, Go `1.26.2`, `GOROOT=/config/opt/go`; repository root `/config/workspace/iop-s0`; current dirty worktree is the intended shared basis.
- Required commands are fresh focused tests, race suites, full Edge package tests, vet, formatting, deterministic symbol search, and diff checking. Cached output is not acceptable.
- Current gap: fresh package commands stop on a concurrently added out-of-scope `workspace_tool_codec.go` compile error. Do not modify that unrelated file in this packet; rerun all commands once the shared package compiles and record any remaining blocker exactly.
- External live-provider smoke is not part of this S03/S07 packet; S16 `hot-smoke` owns credentialed Claude/Pi qualification. Confidence: high for the production-path and contract defects.

### Test Coverage Gaps

- Existing selector tables exercise only the helper and inject `healthy=false` directly; they do not prove a production-derived gate or reject conflicting path sources/arbitrary control tool names.
- `TestHotPathDispatchPresetTurn` calls the helper directly; no handler test proves that a real preset request reaches it.
- Direct tests construct normalized output and do not assert actual provider response ID/usage preservation or handler-owned coordinator transitions.

### Symbol References

- No rename or removal is planned.
- `dispatchPresetTurn` references are currently its definition and `TestHotPathDispatchPresetTurn`; production Chat and Anthropic handlers have no call site.
- `normalizedStageOutput` is currently created only inside hot-path files/tests and is not populated from a production provider result.

### Split Judgment

Keep one plan. Structural classification, response metadata, and coordinator frontier/terminal must be committed as one direct-turn invariant; splitting handler wiring from response/state correctness would leave a production path that cannot independently PASS S03/S07.

### Scope Rationale

Include only direct selection/execution for preset-backed Chat and Messages plus required tests. Exclude light workspace binding/pair handling, local/review/repair, cleanup, cross-stage envelope composition, observability, config/schema, credentialed smoke, and concurrent `workspace_tool_*` work because later Milestone children own those boundaries.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`, mode `pair`.
- All build/review closures are true: scope, context, verification, evidence, ownership, and decisions are fixed; capability gap: none.
- Build scores `(2,2,2,2,2)` => G10, base/final basis `grade-boundary`, cloud, `PLAN-cloud-G10.md`.
- Review scores `(2,2,2,2,2)` => G10, `official-review`, cloud, `CODE_REVIEW-cloud-G10.md` using Codex `gpt-5.6-sol` xhigh.
- `large_indivisible_context=true`; risks `temporal_state,concurrent_consistency,boundary_contract,structured_interpretation,variant_product` (5); `review_rework_count=1`; `evidence_integrity_failure=true`; risk and recovery boundaries matched without replacing the grade-boundary basis.

## Implementation Checklist

- [ ] Connect real preset Chat/Messages provider results to structural selection using pinned capability/health evidence and exact canonical control shapes.
- [ ] Complete direct text/reasoning/tool continuation and terminal responses with actual response identity/usage, stable public model identity, and no reserved artifact path.
- [ ] Add handler-level regressions and run fresh focused, race, full Edge, vet, formatting, deterministic reference, and diff verification after the shared package compiles.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_API-1] Wire production structural selection

#### Problem

`chat_handler.go:125-130` and `anthropic_handler.go:61-83` dispatch preset selectors but write through ordinary provider-pool paths; `hot_path_dispatch.go:8-60` is unreachable from production. `hot_path_selector.go:70-74` also replaces the required production health/capability decision with a constant `true`, and `extractPathFromToolCall` accepts a first matching path without canonical operation validation.

#### Solution

Create one production stage-output collection boundary in the existing hot-path dispatch code for both normalized RunEvent and supported tunnel responses. In the preset branches, collect the selector attempt into canonical content/reasoning/tool operations plus response metadata, build a pinned gate from the selected dispatch/capability result and immutable preset bindings, then call structural classification before choosing direct/light. Treat canonical prepare/write roles and their exact issued paths as controls; reject wrong tool names, conflicting path fields, duplicate/mixed calls, and any unvalidated reserved-path occurrence.

```go
// Before: join coordinator, then relay the ordinary provider-pool result.
s.handleChatCompletionsProviderPool(w, dc)

// After: preset results cross one normalized selector boundary.
stage, gate, err := s.collectPresetSelectorResult(r.Context(), dc, result)
decision, err := classifyHotPathOutput(dispatch.Preset, issued, stage, gate)
return s.dispatchPresetDecision(w, r, dispatch, runMeta, stage, decision)
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/chat_handler.go` — route preset pool results through the production selector boundary.
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — route native/bridge preset Messages results through the same decision contract.
- [ ] `apps/edge/internal/openai/hot_path_dispatch.go` — collect real selector results and dispatch the validated decision.
- [ ] `apps/edge/internal/openai/hot_path_selector.go` — replace the boolean shortcut/path heuristic with pinned gate and canonical exact-shape validation.
- [ ] `apps/edge/internal/openai/hot_path_selector_test.go` — add production-gate, arbitrary-role, conflicting-path, mixed, partial, and disabled/unhealthy cases.
- [ ] `apps/edge/internal/openai/hot_path_direct_test.go` — add handler-driven Chat/Messages selector tests with a fake provider result.

#### Test Strategy

Extend `TestHotPathSelectorDecisionMatrix` with masked reserved paths, wrong canonical roles, conflicting path sources, and a pinned failed gate. Replace the helper-only dispatch assertion with `TestHotPathPresetHandlersDirect`, exercising real Chat and Messages handlers and asserting selector rejection occurs before direct output/state transition.

#### Verification

```bash
go test -count=1 ./apps/edge/internal/openai -run 'TestHotPath(SelectorDecisionMatrix|PresetHandlersDirect)'
```

Expected: PASS with production handler call sites and every malformed/gate case rejected deterministically.

### [REVIEW_API-2] Preserve direct wire metadata and coordinator state

#### Problem

`hot_path_direct.go:29-63` updates a coordinator only when the helper is called, while `hot_path_direct.go:196-330` hand-builds Anthropic output with fabricated token usage and no actual provider response identity. The normalized direct value cannot currently carry the response metadata needed by the OpenAI/Anthropic contracts.

#### Solution

Extend the canonical stage output with the actual selector response identity, terminal reason, and protocol usage collected from the selected attempt. Reuse established endpoint response structures/codec behavior when emitting direct output, rewrite only the public virtual model identity, never invent usage, and establish the public/provider tool-ID mapping plus issued-call hash before the tool terminal is committed. On text completion, terminal the logical request exactly once; on tool output, leave exactly one waiting frontier. Any response-write/collection failure must close through the endpoint-standard error path without reporting success.

```go
// Before: synthetic ids/usage are generated by the direct encoder.
Usage: anthropicUsage{InputTokens: 10, OutputTokens: 10}

// After: metadata is propagated from the selector attempt.
response := directResponseFromStage(stage, turn.PublicModelID)
// Omit usage only when the provider did not report it; never synthesize it.
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/hot_path_dispatch.go` — propagate collected identity, terminal, usage, and tool mappings.
- [ ] `apps/edge/internal/openai/hot_path_direct.go` — emit contract-preserving direct responses and exact coordinator transitions without synthetic values.
- [ ] `apps/edge/internal/openai/hot_path_direct_test.go` — assert Chat/Anthropic stream and non-stream metadata, model echo, tool frontier, terminal exactly-once, and reserved-path absence through handlers.

#### Test Strategy

Expand `TestHotPathPresetHandlersDirect` with Chat and Anthropic text/reasoning/tool variants. Use distinct provider response IDs and non-default usage counts so the test fails on fabricated/default values; inspect coordinator snapshots after tool and final responses and assert no emitted call/path contains `.iop/job/`.

#### Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(Selector|PresetHandlers|Direct)'
```

Expected: PASS with actual response metadata, one waiting frontier for tools, and one logical terminal for final text.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/chat_handler.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/anthropic_handler.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_dispatch.go` | REVIEW_API-1, REVIEW_API-2 |
| `apps/edge/internal/openai/hot_path_selector.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_direct.go` | REVIEW_API-2 |
| `apps/edge/internal/openai/hot_path_selector_test.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_direct_test.go` | REVIEW_API-1, REVIEW_API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/07+02,04,06_route_selector_direct/CODE_REVIEW-cloud-G10.md` | REVIEW_API-1, REVIEW_API-2 |

## Final Verification

```bash
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/02+01_preset_generation/complete.log
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/04+02,03_preset_model_authorization/complete.log
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/06+04,05_request_identity_ingress/complete.log
rg --sort path -n 'dispatchPresetTurn|collectPresetSelectorResult|classifyHotPathOutput' apps/edge/internal/openai --glob '*.go'
go test -count=1 ./apps/edge/internal/openai -run 'TestHotPath(SelectorDecisionMatrix|PresetHandlersDirect|Direct)'
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(Selector|PresetHandlers|Direct)'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
route_selector_tmp_dir="$(mktemp -d /config/.tmp-iop-route-selector.XXXXXX)"
TMPDIR="$route_selector_tmp_dir" go test -count=1 ./apps/edge/...
rm -rf "$route_selector_tmp_dir"
go vet ./apps/edge/...
gofmt -d apps/edge/internal/openai/chat_handler.go apps/edge/internal/openai/anthropic_handler.go apps/edge/internal/openai/hot_path_dispatch.go apps/edge/internal/openai/hot_path_selector.go apps/edge/internal/openai/hot_path_direct.go apps/edge/internal/openai/hot_path_selector_test.go apps/edge/internal/openai/hot_path_direct_test.go
git diff --check
```

Expected: all commands exit 0; deterministic search shows production handler integration; direct mode never depends on prose, preserves actual endpoint metadata and virtual model identity, owns exactly one tool frontier or logical terminal, and emits no reserved artifact path. Cached test output is not acceptable.

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