<!-- task=m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core plan=2 tag=API milestone-task=terminal-control -->

# Code Review Reference - API

> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> Fill all implementation-owned sections, leave active files in place, and report ready for review. On blocker, record exact command/output/resume condition only. Final verdict, log rename, `complete.log`, archive moves, and review-only checklist are review-agent-only.

## Overview

date=2026-08-03
task=m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core, plan=2, tag=API

## Archive Evidence Snapshot

- Predecessor 10/11 archived `complete.log` files are PASS evidence cited by the plan.
- Plan/review 1 was superseded before implementation; it contains no implementation verdict/evidence.

## For the Review Agent

Compare every item with source and fresh output. Append verdict/routing signals, archive this file to `code_review_cloud_G09_2.log` and the plan to `plan_cloud_G08_2.log`, then follow the code-review skill for PASS/WARN/FAIL. Preserve `milestone-task=terminal-control` on PASS.

## Implementation Item Completion

| Item | Status |
|---|---|
| API-1 Stage gate and HTTP-turn ownership | [x] |
| API-2 Core evidence | [x] |

## Implementation Checklist

- [x] [API-1] Add the stage-scoped gate/source contract and one HTTP-turn sequencer with normalized events, public identity, usage, output-cap, and terminal ownership.
- [x] [API-2] Prove progressive release, terminal hold, provider protocol fragmentation, aggregation, cap, and exactly-once races with deterministic tests.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Review-Only Checklist

- [x] Append exactly one PASS/WARN/FAIL verdict with `review_rework_count` and `evidence_integrity_failure`.
- [x] Verify findings and dimension assessment match the verdict.
- [x] Archive active review/plan to suffix `2` logs without overwriting prior logs.
- [x] Verify the Agent-Ops managed `.gitignore` block.
- [ ] On PASS write standard `complete.log`, preserve milestone metadata, move this child to the dated archive, and remove the active parent only if empty.
- [x] On WARN/FAIL write the directed next state and no `complete.log`.

## Deviations from Plan

none

## Key Design Decisions

- Each provider stage creates and closes its own `streamgate.RequestRuntime`; its release sink forwards nonterminal normalized deltas to `hotPathOuterTurn` and retains only typed terminal evidence.
- `hotPathOuterTurn` is mutex-owned and protocol-neutral. It suppresses nested starts, remaps tool IDs per stage, deduplicates reported usage by provider response ID, applies a turn-wide rune cap, and permits exactly one public terminal.
- OpenAI Chat and Anthropic Messages tunnel bytes are decoded incrementally by common stage sources selected from committed provider dispatch metadata, never from the caller endpoint.

## Reviewer Checkpoints

- Confirm each provider stage owns a separate `streamgate.RequestRuntime`; only the HTTP-turn sequencer spans internal stages.
- Confirm OpenAI adapters are reused, Anthropic provider decoding is common-stage input, and caller endpoint policy is absent.
- Confirm nonterminal deltas release progressively and exactly one outer terminal wins with bounded id/usage/cap state.

## Verification Results

### Targeted

Command: `go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(StageRuntime|StageProtocolFragments|OuterTurnOrderingAndAggregation|OuterTurnOutputCap|OuterTurnTerminalRace)'`

```text
ok  \tiop/apps/edge/internal/openai\t1.123s
exit status 0
```

### Common regression

Command: `go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service`

```text
ok  \tiop/packages/go/streamgate\t2.107s
ok  \tiop/packages/go/config\t1.660s
ok  \tiop/apps/edge/internal/openai\t11.582s
ok  \tiop/apps/edge/internal/service\t7.645s
exit status 0
```

### Diff

Command: `git diff --check`

```text
exit status 0
```

## Section Ownership

Implementation completion/checklist status, deviations, decisions, and verification output belong to the implementing agent. Header, item text/order, checkpoints, and commands are fixed. Review-only checklist and final `Code Review Result` belong only to the review agent.

## Code Review Result

- Overall Verdict: FAIL
- Dimension Assessment:
  - Correctness: Fail — the stage transport can be reported as successful after malformed/incomplete tunnel framing, transport ownership is not released, and non-text public output bypasses the turn cap.
  - Completeness: Fail — the core omits required close/cancel ownership and boundary handling needed for a safely reusable stage runtime.
  - Test Coverage: Fail — the deterministic suite does not cover missing `RESPONSE_START`, channel close before `END`, close/cancel exactly-once, or cap enforcement for reasoning/tool fragments.
  - API Contract: Fail — the virtual-preset contract requires malformed tunnel ordering to fail closed and the SDD applies the caller cap to the full public outer response.
  - Code Quality: Fail — the no-op attempt controller makes the runtime's resource-cleanup API ineffective for real stage transports.
  - Implementation Deviation: Fail — the implemented core cannot satisfy the plan's stage-owned lifecycle and full public output-cap boundary without changing its current source/controller contracts.
  - Verification Trust: Pass — the reviewer reran every recorded command successfully; the failure is in uncovered contract boundaries, not fabricated command evidence.
- Findings:
  - Required — `apps/edge/internal/openai/hot_path_terminal_control.go:453`: `hotPathStageController.AbortAttempt` is a no-op and does not implement graceful close, while `runHotPathStage` relies on `CloseRequestResources` to release the current attempt. A real `RunResult` or `ProviderTunnelResult` will therefore retain transport/admission ownership on success, error, and cancellation. Pass an idempotent transport-owning controller into the stage runtime, implement both cancel/abort and graceful close semantics, and add success/cancel/error tests proving release exactly once.
  - Required — `apps/edge/internal/openai/hot_path_stage_stream.go:157`: channel close synthesizes a successful terminal, and `apps/edge/internal/openai/hot_path_stage_stream.go:225` / `apps/edge/internal/openai/hot_path_stage_stream.go:273` synthesize a 200 response start for `BODY` or `END` before `RESPONSE_START`. The virtual-preset contracts require malformed ordering to fail closed, and the existing collector rejects close-before-completion. Emit a sanitized provider-error terminal for all three malformed variants and add table-driven fragmented-frame tests.
  - Required — `apps/edge/internal/openai/hot_path_terminal_control.go:171`: only text deltas consume `outputCapRunes`; reasoning at line 182 and tool arguments at line 192 bypass the turn-wide public output budget. Apply one bounded accounting policy to every caller-visible delta (with a deterministic no-partial-tool policy where truncating JSON would be invalid) and extend the output-cap test across stage changes, reasoning, and tool fragments.
- Routing Signals:
  - review_rework_count=1
  - evidence_integrity_failure=false
- Next Step: Invoke the plan skill in `prepare-follow-up` mode with these raw findings and freshly route the smallest corrective pair.
