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

# Code Review Reference - REVIEW_API

> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.

## Overview

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

## Archive Evidence Snapshot

- The current pair will archive as `plan_cloud_G08_2.log` and `code_review_cloud_G09_2.log`; the review verdict is FAIL with 3 Required, 0 Suggested, and 0 Nit findings.
- Required findings: inject idempotent abort/graceful-close ownership instead of the no-op stage controller; reject tunnel `BODY`/`END` before `RESPONSE_START` and channel close before explicit completion; apply the one turn-wide cap to text, reasoning, and tool arguments with deterministic crossing-fragment behavior.
- Reviewer verification passed: targeted race test `ok iop/apps/edge/internal/openai 1.384s`; common race packages passed (`streamgate 2.171s`, `config 1.944s`, `openai 11.271s`, `service 7.183s`); `git diff --check` exited 0. These commands did not cover the required boundary variants.
- Split predecessors remain satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log` and `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/complete.log`.

## For the Review Agent

> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.

Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:

1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G08.md` → `code_review_cloud_G08_3.log` and `PLAN-cloud-G07.md` → `plan_cloud_G07_3.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=terminal-control` in `complete.log` and report it for runtime aggregation. Roadmap evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.

---

## Implementation Item Completion

| Item | Status |
|------|---------|
| REVIEW_API-1 Stage transport ownership and strict tunnel framing | [x] |
| REVIEW_API-2 Full public-output cap | [x] |

## Implementation Checklist

- [x] [REVIEW_API-1] Make stage attempt ownership idempotently abort/close real transports and fail closed on incomplete or out-of-order tunnel framing, with deterministic lifecycle regressions.
- [x] [REVIEW_API-2] Enforce the one outer-turn output cap across text, reasoning, and tool arguments and prove cap/terminal behavior across fragments and stages.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Review-Only Checklist

> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.

- [x] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [x] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [x] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G08_3.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_cloud_G07_3.log`.
- [x] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [x] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [x] If PASS, move active task directory `agent-task/m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core/` to `agent-task/archive/YYYY/MM/m-iop-hot-path-one-shot-execution/12+10,11_outer_turn_core/` and update this checklist at the final archive path.
- [x] If PASS, preserve and report `milestone-task=terminal-control` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [x] If PASS, remove empty active parent `agent-task/m-iop-hot-path-one-shot-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.

## Deviations from Plan

None. The corrective packet remained limited to the three planned OpenAI core files and this implementation evidence.

## Key Design Decisions

- The stage runtime now requires an injected `hotPathStageAttemptController`. Its internal owner wraps abort and graceful close with independent `sync.Once` guards, so repeated Core error cleanup and final resource cleanup reach the real transport at most once.
- Tunnel framing requires an explicit `RESPONSE_START` before `BODY` or `END`, and an explicit terminal frame before channel close. Violations produce one sanitized provider-error normalized event and never synthesize a successful stage terminal.
- One rune budget is consumed by text, reasoning, and tool arguments across all stages. Text and reasoning may release a Unicode-safe prefix; a tool-argument fragment that crosses the boundary is withheld atomically, exhausts the turn, and prevents all later releases.

## Reviewer Checkpoints

- Confirm the stage binding receives a real idempotent controller: success calls graceful close once, error/cancel calls abort once, and repeated cleanup does nothing.
- Confirm `BODY`/`END` before `RESPONSE_START` and channel close before explicit completion produce one sanitized provider-error terminal with no public success.
- Confirm text, reasoning, and tool arguments all consume the same turn budget across stage changes, with deterministic crossing-fragment handling and one `length` terminal.
- Confirm valid fragmented OpenAI/Anthropic decoding remains intact and direct/light integration or endpoint codecs were not pulled into this corrective child.

## Verification Results

Paste actual stdout/stderr and exit status for every command. Fresh `-count=1` output is required; summaries or cached results are not accepted.

### Focused lifecycle and cap race

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

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

### Common race 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.135s
ok  \tiop/packages/go/config\t1.670s
ok  \tiop/apps/edge/internal/openai\t11.634s
ok  \tiop/apps/edge/internal/service\t7.110s
exit status: 0
```

### Vet

Command: `go vet ./apps/edge/internal/openai`

```text
stdout/stderr: (empty)
exit status: 0
```

### Formatting

Command: `gofmt -d apps/edge/internal/openai/hot_path_stage_stream.go apps/edge/internal/openai/hot_path_terminal_control.go apps/edge/internal/openai/hot_path_terminal_control_test.go`

```text
stdout/stderr: (empty; all listed files are gofmt-clean)
exit status: 0
```

### Diff

Command: `git diff --check`

```text
stdout/stderr: (empty)
exit status: 0
```

---

> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.

## Section Ownership

| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Archive Evidence Snapshot | Fixed at stub creation from plan | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

## Code Review Result

- Overall Verdict: PASS
- Dimension Assessment:
  - Correctness: Pass — the injected stage controller now closes successful attempts gracefully and aborts error/cancel outcomes idempotently; malformed tunnel framing fails closed; one turn-wide rune budget covers text, reasoning, and tool arguments.
  - Completeness: Pass — both corrective checklist items and their integrated lifecycle, framing, cap, terminal, formatting, vet, and regression evidence are complete.
  - Test Coverage: Pass — deterministic race tests cover successful/error/cancel transport ownership, BODY/END before RESPONSE_START, close before END, fragmented OpenAI/Anthropic decoding, cross-stage cap behavior, and the terminal race.
  - API Contract: Pass — malformed virtual-preset tunnel ordering yields a sanitized provider-error terminal with no public success, and output-cap exhaustion resolves to the endpoint-native `length` reason.
  - Code Quality: Pass — ownership and framing state are explicit, concurrency-sensitive state is guarded, and fresh vet/gofmt/diff checks are clean.
  - Implementation Deviation: Pass — the corrective implementation stays within the planned stage core, terminal controller, tests, and evidence artifact; direct/light handler wiring and endpoint codecs remain excluded.
  - Verification Trust: Pass — the reviewer reran every planned command from the current checkout; focused race, common race, vet, gofmt, and diff checks all exited 0.
  - Spec Conformance: Pass — the implementation contributes the SDD S10 terminal-control evidence for strict stage boundaries, one outer-turn aggregation boundary, and exactly-once terminal ownership without claiming the Milestone Task complete.
- Findings: None
- Routing Signals:
  - review_rework_count=1
  - evidence_integrity_failure=false
- Next Step: PASS — archive the active pair, write `complete.log`, and emit Milestone completion metadata for runtime aggregation.
