<!-- task=m-iop-hot-path-one-shot-execution/13+12_outer_turn_integration plan=2 tag=REVIEW_API milestone-task=terminal-control -->

# Close outer-turn cap and compatibility integration gaps

## For the Implementing Agent

Implement only the two review findings below. After implementation, fill every implementation-owned section in `CODE_REVIEW-cloud-G09.md`, keep the active pair in place, and stop. Do not archive the pair, write `complete.log`, or classify the next state.

## Background

The first integration pass attached the collected selector and light stages to an HTTP-turn sequencer, but production turns still use an unlimited sequencer cap, exhausted budgets still dispatch one more provider stage, normalized requests do not receive the remaining cap, and endpoint rendering does not use the capped accumulator for content/reasoning/tools. The passing targeted regex also did not contain the handler-level compatibility and transition tests claimed by API-2.

## Archive Evidence Snapshot

- `code_review_cloud_G09_1.log` records the first review verdict: FAIL with two Required findings. The implementation must close both findings; it must not rely on the prior passing regex as evidence because the required handler test was absent.
- `plan_cloud_G08_1.log` is the superseded integration plan whose API-1/API-2 claims are narrowed here to the unclosed cap, compatibility, and evidence obligations.

## Analysis

### Files Read

- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/artifact_pair.go`
- `apps/edge/internal/openai/hot_path_light.go`
- `apps/edge/internal/openai/hot_path_review.go`
- `apps/edge/internal/openai/hot_path_terminal_control.go`
- `apps/edge/internal/openai/hot_path_direct_test.go`
- `apps/edge/internal/openai/hot_path_light_test.go`
- `apps/edge/internal/openai/hot_path_terminal_control_test.go`
- `agent-test/local/rules.md`

### SDD Criteria

- Approved SDD S10 requires one outer envelope across same-HTTP internal stages, nested response-start and stage-terminal suppression, public block/tool identity remapping, ordered normalized deltas, summed usage, caller output-cap enforcement, and one public terminal.
- A direct/tool/error/cap outcome terminates the HTTP turn. A local completion may advance to review/repair only while the same request-local outer turn remains nonterminal and has output budget.

### Verification Context

- The relevant behavior is deterministic inside Edge. Scripted provider-pool fixtures can prove Chat and Messages handler behavior without a live node or external provider.
- The prior targeted and package race commands passed, but the regex silently matched no `TestHotPathOuterTurnCompatibility` function. Fresh evidence must name real handler tests and verify their assertions.
- Supplemental `go test -count=1 ./apps/edge/...` remains unsuitable as a completion gate in this environment because the unrelated actual-node bootstrap test cannot execute its temporary binary; the repository-native race and vet commands below are authoritative for this follow-up.

### Test Coverage Gaps

- No handler fixture proves that the already-dispatched selector result is consumed without redispatch.
- No handler table covers direct, tool, local-pass, local-review, repair, cap-exhausted, and post-terminal stop rows for both caller protocols with exact provider submission counts.
- No test inspects the normalized `Run.Input` options and selected tunnel body together to prove that the same decreasing remaining cap is authoritative.
- No caller-visible assertion proves that capped content/reasoning/tool output, aggregate usage, and endpoint-native terminal reason all come from the same outer result.

### Symbol References

- No public symbol is renamed or removed. The change remains within the Edge OpenAI-compatible package and its existing internal fixtures.

### Split Judgment

- Keep one implementation packet. Budget state, dispatch admission, frontier registration, compatibility rendering, and endpoint assertions form one atomic outer-turn invariant; splitting them would permit a provider dispatch or caller response to observe a partially integrated state.

### Scope Rationale

- Include only production paths necessary to make the caller cap authoritative and the deterministic handler tests necessary to prove the two Required findings.
- Exclude endpoint-native streaming codec replacement, live-node/provider smoke, telemetry, cleanup redesign, and later S14-S16 protocol/observation work.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`, `finalizer_mode=pair`.
- Build closure scores: scope=2, state/concurrency=2, blast/irreversibility=1, evidence/diagnosis=2, verification=2; grade G09, base/route basis `grade-boundary`, lane `cloud`.
- Positive loop-risk signatures: `temporal_state`, `concurrent_consistency`, `boundary_contract`, `variant_product` (4); `large_indivisible_context=false`.
- Recovery signals: `review_rework_count=1`, `evidence_integrity_failure=true`; risk and recovery boundaries match but do not replace the G09 grade-boundary basis.
- Review closure scores: scope=2, state/concurrency=2, blast/irreversibility=1, evidence/diagnosis=2, verification=2; `official-review`, `cloud`, G09, adapter `codex`, model `gpt-5.6-sol`, reasoning effort `xhigh`.
- Canonical active files: `PLAN-cloud-G09.md` and `CODE_REVIEW-cloud-G09.md`.

## Implementation Checklist

- [ ] [REVIEW_API-1] Make the caller cap and outer accumulator authoritative for dispatch, frontier registration, compatibility rendering, and terminal cleanup.
- [ ] [REVIEW_API-2] Add real Chat/Messages handler evidence for every required transition and compatibility row with exact dispatch counts.
- [ ] Fill all implementation-owned sections in `CODE_REVIEW-cloud-G09.md` with actual changes and fresh command output.

### [REVIEW_API-1] Authoritative cap, response, and terminal flow

**Problem:** `dispatchPresetTurn` and `runHotPathLightStage` construct unlimited outer turns; `hotPathRemainingOutputTokens` maps exhaustion to `1`; normalized `Run.Input` omits the remaining cap; and direct/artifact/light terminal paths can write the pre-accumulator output. These seams allow post-cap provider work and make the sequencer observational rather than authoritative.

**Solution:** Construct each request-local outer turn with the parsed caller cap. Represent unlimited, positive remaining, and exhausted budget without overloading zero; check the budget before acquiring or dispatching another light stage, and on exhaustion commit one endpoint-native length terminal and release logical/frontier state without provider work. Apply the remaining value to normalized request options and both protocol tunnel bodies as a reserved value that stage options cannot override. Before registering tool frontiers or writing any direct/artifact/light response, derive one compatibility output from the committed outer accumulator so capped content/reasoning, public tool identities, summed usage, and terminal reason agree; preserve endpoint-required provider metadata and existing artifact/coordinator correlations while making the frontier and wire response use the same public tool IDs. Errors and cancellation must retain the existing single-terminal cleanup owner.

**Modified Files and Checklist:**

- [ ] Modify `apps/edge/internal/openai/hot_path_terminal_control.go` to expose unambiguous remaining/exhausted state and a complete compatibility accumulator projection.
- [ ] Modify `apps/edge/internal/openai/hot_path_dispatch.go` to initialize the selector turn from trusted caller-cap metadata and reserve the remaining cap in normalized and tunnel stage requests without redispatching the collected selector result.
- [ ] Modify `apps/edge/internal/openai/hot_path_direct.go` so direct and ordinary-tool frontier registration and endpoint output use the same committed outer compatibility result.
- [ ] Modify `apps/edge/internal/openai/artifact_pair.go` so mapped artifact tool identities and the caller response remain aligned with the committed outer result.
- [ ] Modify `apps/edge/internal/openai/hot_path_light.go` to stop before post-cap local/review dispatch, commit before terminal writes, render every terminal branch through the compatibility result, and clean up the logical request exactly once.

**Test Strategy:** Exercise unlimited, positive, and exhausted budgets; assert normalized/tunnel cap equality and stage-option non-override; assert a cap reached by one stage prevents the next stage submission; and compare caller output with the accumulator for text, reasoning, tools, usage, and terminal reason.

**Verification:** Both named handler tests and the race regression commands in Final Verification exit 0.

### [REVIEW_API-2] Handler-level transition and compatibility evidence

**Problem:** the prior test named as integration only called a usage helper and body builders, while the regex contained a nonexistent compatibility alternative. It did not prove handler dispatch ownership or caller-visible behavior.

**Solution:** Add actual `TestHotPathOuterTurnIntegration` and `TestHotPathOuterTurnCompatibility` handler fixtures for Chat and Messages. Cover direct completion, ordinary tool completion, local pass into review, review tool/resolution, repair continuation, caller-cap exhaustion, and terminal/cancel stop. For every row, record exact provider-pool submissions per inbound HTTP request and assert no selector redispatch, no provider submission after cap/terminal/cancel, one caller response start/terminal, stable endpoint shape, ordered combined content/reasoning/tools, aggregate usage, and decreasing or exhausted remaining cap in both normalized input and the selected tunnel body. Reuse existing scripted fixtures and keep live transports out of scope.

**Modified Files and Checklist:**

- [ ] Extend `apps/edge/internal/openai/hot_path_terminal_control_test.go` with budget-state, compatibility projection, one-terminal, and post-terminal unit or race assertions supporting the handler matrix.
- [ ] Extend `apps/edge/internal/openai/hot_path_direct_test.go` with real Chat/Messages direct/tool handler rows and exact initial dispatch counts.
- [ ] Extend `apps/edge/internal/openai/hot_path_light_test.go` with real Chat/Messages local-review/repair/cap rows, captured normalized/tunnel budgets, and exact same-request dispatch counts.
- [ ] Record actual implementation notes and verification output in `agent-task/m-iop-hot-path-one-shot-execution/13+12_outer_turn_integration/CODE_REVIEW-cloud-G09.md`.

**Test Strategy:** Ensure the two required test functions exist, fail when an extra submission is injected, and inspect both protocol variants rather than relying on a regex alternative with no matching function.

**Verification:** Run the exact targeted regex, confirm both named functions execute, then run the full package race set, vet, and diff checks.

## Dependencies and Execution Order

1. Preserve the completed child-12 outer-turn core contract and existing working-tree changes.
2. Implement REVIEW_API-1 before changing handler expectations.
3. Implement REVIEW_API-2 against the authoritative production path, then run Final Verification.

## Modified Files Summary

| File | Item |
|---|---|
| `apps/edge/internal/openai/hot_path_terminal_control.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_dispatch.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_direct.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/artifact_pair.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_light.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_terminal_control_test.go` | REVIEW_API-2 |
| `apps/edge/internal/openai/hot_path_direct_test.go` | REVIEW_API-2 |
| `apps/edge/internal/openai/hot_path_light_test.go` | REVIEW_API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/13+12_outer_turn_integration/CODE_REVIEW-cloud-G09.md` | REVIEW_API-2 |

## Final Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(OuterTurnIntegration|OuterTurnCompatibility|Direct|Light|Cleanup)'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
go vet ./apps/edge/...
git diff --check
```

Expected: every command exits 0; the targeted output includes real `TestHotPathOuterTurnIntegration` and `TestHotPathOuterTurnCompatibility` executions; each inbound request has the exact expected provider submission count; exhausted or terminal turns submit no later stage; caller-visible content/reasoning/tools, usage, and terminal match the authoritative outer result; no race is reported.

After completing all code changes, fill every implementation-owned section in `CODE_REVIEW-cloud-G09.md` and leave the active pair in place.
