<!-- task=m-iop-owned-single-request-agent-execution/20+19_review_stage plan=1 tag=API milestone-task=review-stage -->

# Review, repair, and composite activation

## For the Implementing Agent

Filling the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.

## Background

The artifact, Plan, and Work packets establish service-owned lifecycle and private provider/tool primitives without installing a production executor. This final Epic slice implements Gemini Review and bounded repair, composes all stages behind existing executor/continuation contracts, installs the composite at Edge startup, and synchronizes the current contract/spec. Actual Claude/provider qualification remains S12 `claude-smoke`.

## Archive Evidence Snapshot

- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/plan_cloud_G09_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/code_review_cloud_G09_0.log`.
- The archived pair contains no implementation evidence and no official verdict. It was preserved because explicit self-review found material dependency and state-machine defects.
- Its active-only predecessor check could not survive task-19 archival. Its expected `repairing -> reviewing` edge is rejected by the existing service transition table and by the SDD, which requires re-review dispatch while the lifecycle remains `repairing`.
- It also omitted the direct reviewer inspection path `reviewing -> internal_tool(saved reviewing) -> reviewing`. This revision covers inspection and repair as separate deterministic fixtures.
- No production code, test, contract, spec, or roadmap completion is claimed by the archived pair.

## Analysis

### Files Read

- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_tool_types.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `apps/edge/internal/service/service.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/input/manager.go`
- `apps/edge/internal/input/manager_test.go`

### SDD Criteria

- SDD is approved and unlocked; this packet contributes `review-stage`.
- S10 requires Gemini high-reasoning Review, strict pass, permitted reviewer inspection, one IOP-owned repair call at a time, `repairing -> internal_tool(saved repairing) -> repairing`, re-review after repair, REVIEW persistence, and only then finalization.
- The lifecycle table permits `reviewing -> internal_tool|repairing|finalizing` and `repairing -> internal_tool|finalizing`; it does not permit `repairing -> reviewing`.
- Provider-stage data stays private. The public result is only the reviewer-approved output after REVIEW is durable.

### Verification Context

- No verification handoff was supplied. Existing controller state-machine, cleanup, input composition, handler, and stream tests are the repository-native oracle.
- Checkout preflight: branch `feature/iop-owned-single-request-agent-execution`, starting HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`; only active Epic task artifacts differ, with no direct production code/test/document delta from that base.
- Deterministic provider and workspace-tool fixtures can prove S10 and production composition without remote credentials or an external runner.
- Actual Claude/Mac full-cycle qualification remains the separate S12 `claude-smoke` task.

### Test Coverage Gaps

- Existing service tests cover the generic transition table and saved-stage restoration, but no provider runner proves direct reviewer inspection or repair/re-review semantics.
- No test proves that a re-review provider dispatch occurs while controller state remains `repairing`, or explicitly rejects the obsolete `repairing -> reviewing` expectation.
- No production composite currently proves final-output provenance, request-isolated continuation, installation, cancellation, or terminal cleanup across all stages.

### Symbol References

- `isValidTransition` in `apps/edge/internal/service/single_request.go` is the existing lifecycle oracle; do not add `repairing -> reviewing` or include that file in the planned modification set.
- `SingleRequestExecutor`, `SingleRequestToolContinuation`, `Service.SetSingleRequestExecutor`, and the predecessor's bridge are the composition boundaries to implement/reuse.
- `apps/edge/internal/input/manager.go` is the production installation point. No public Anthropic request or event type is renamed or extended.

### Split Judgment

- Predecessor 19 owns Work results and request-safe tool continuation. Resolve exactly one task-19 evidence file, read it, and inspect the completed source contract before implementation.
- Review, repair, final-output provenance, composite ownership, installation, and current-document synchronization form one ordered activation boundary: installation is unsafe without all earlier items.
- External Claude/provider qualification stays split as S12 because it requires a separate environment and evidence class.

### Scope Rationale

Include only Review/inspection/repair, composite wiring, production installation, deterministic lifecycle evidence, and current contract/spec synchronization. Exclude new service state edges, caller-visible schemas, caller tools/credentials, config examples, generic error/cancel quality tasks, and any claim that local fixtures satisfy S12.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures are all true. Scores `2/2/2/1/2` => G09, base/route `grade-boundary`, `worker/cloud/G09`, `PLAN-cloud-G09.md`.
- Review closures are all true. Scores `2/2/2/1/2` => G09, `official-review`, `review/cloud/G09`, `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`; risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`; `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.

## Dependencies and Execution Order

1. Before implementation or review, run the exact dependency command in Final Verification. It must print exactly one task-19 completion path from active or archive storage and exit zero; missing or ambiguous evidence is a blocker.
2. Read only that resolved `complete.log`, then inspect the completed Plan artifact, provider-stage, Work result, and continuation bridge APIs in source. Record a blocker instead of recreating or replacing an incompatible predecessor boundary.
3. Implement and prove Review pass, direct inspection, and repair/re-review before composing all stages.
4. Prove deterministic composite lifecycle and tool behavior before installing it in `apps/edge/internal/input/manager.go`.
5. Update current contract/spec last and leave S12 external evidence explicitly deferred.

## Implementation Checklist

- [ ] Implement Gemini high-reasoning Review with strict pass, direct non-mutating inspection, REVIEW persistence before finalization, and fail-closed bounded results.
- [ ] Implement one-tool-at-a-time repair with `repairing -> internal_tool(saved repairing) -> repairing`, re-review dispatch while state remains repairing, and no invalid `repairing -> reviewing` transition.
- [ ] Add a concurrent request-safe composite executor that drives Plan → Work → Review through one controller, reuses the predecessor continuation bridge, and returns only reviewer-approved output.
- [ ] Install the composite at Edge input startup and add S10, inspection, repair, full lifecycle, concurrent isolation, cancellation, cleanup, and installation fixtures without changing the public Anthropic schema.
- [ ] Update the current outer contract and implementation spec, then run dependency, focused race, installation, regression, vet, deterministic document/search, and diff checks while leaving S12 external evidence deferred.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [API-1] Implement strict Review, inspection, and persisted pass evidence

**Problem**

Work returns only a private completion candidate and verification evidence. Returning it directly would skip independent Review. A reviewer may also need to inspect workspace state before deciding, but the prior plan omitted the SDD's `reviewing -> internal_tool(saved reviewing) -> reviewing` path.

**Solution**

Add `single_request_review_stage.go`. Read PLAN, accept the bounded Work candidate/evidence, submit `reviewing`, and dispatch a fixed Gemini high request containing only immutable task, PLAN, candidate, and verification evidence. Decode a closed union:

- strict pass with non-empty bounded final output and review summary;
- exactly one admitted non-mutating inspection call while reviewing; or
- exactly one admitted repair call that enters repairing.

For inspection, register the predecessor bridge, submit `internal_tool` with saved `reviewing`, wait for the exact result, restore `reviewing`, append a bounded sanitized exchange, and redispatch Review. On pass, write `SingleRequestArtifactReview` before submitting `finalizing`, then return a clone of only the approved output. Reject free-form/mixed/multiple/oversized outcomes and sanitize provider/tool failures.

**Modified Files and Checklist**

- [ ] Add prompt, high-option dispatch, closed result decoding, inspection loop, write-before-finalize ordering, and bounded DTOs in `apps/edge/internal/openai/single_request_review_stage.go`.
- [ ] Add pass, direct inspection, exact request body, malformed/mixed/multiple/provider error, artifact failure, bounds, and cancellation tests in `apps/edge/internal/openai/single_request_review_stage_test.go`.

**Test Strategy**

Use deterministic provider/tool fakes and a recording controller. Assert `reviewing -> internal_tool(saved reviewing) -> reviewing -> finalizing` for an inspection-before-pass fixture, high reasoning on every review request, REVIEW before finalizing, exact correlation, and no private candidate/error leakage.

**Verification**

Run the focused ReviewStage race test in Final Verification.

### [API-2] Drive bounded repair and re-review without a false state edge

**Problem**

S10 assigns mutation to Review-owned repair. The existing state machine restores `repairing` after every tool result and permits finalizing from repairing; it deliberately rejects `repairing -> reviewing`. The archived plan's expected sequence would therefore fail and tempt an out-of-scope service transition change.

**Solution**

On a first mutating defect call, submit `repairing`, then execute one admitted tool through `internal_tool` with saved `repairing`. Restore `repairing`, append the bounded sanitized tool exchange, and redispatch Gemini Review while controller state stays `repairing`. Any subsequent admitted inspection or repair call repeats `repairing -> internal_tool(saved repairing) -> repairing`. Only a later strict pass may persist REVIEW and submit `finalizing`. Enforce coordinator/local bounds, exact identities, and no pre-repair candidate release. Do not modify the service transition table.

**Modified Files and Checklist**

- [ ] Add repair/re-review behavior to `apps/edge/internal/openai/single_request_review_stage.go` using the predecessor bridge and controller API.
- [ ] Add `reviewing -> repairing -> internal_tool(saved repairing) -> repairing -> finalizing` pass-after-repair, repeated bounded tool, correlation, failure, stale/duplicate result, cancellation, and waiter-cleanup fixtures in `apps/edge/internal/openai/single_request_review_stage_test.go`.
- [ ] Assert the re-review provider call happens while recorded lifecycle state is `repairing` and that no test or code attempts `repairing -> reviewing`.

**Test Strategy**

Record states separately from provider dispatches. The key fixture must prove the second Gemini review request occurs between restored `repairing` and finalizing, uses high reasoning, and reaches finalizing only after strict pass plus durable REVIEW.

**Verification**

Run focused Review race tests and deterministic state-order search; `apps/edge/internal/service/single_request.go` must remain unchanged by this packet.

### [API-3] Compose the three private stages

**Problem**

Installing stage runners independently would split lifecycle ownership, let a Work candidate become terminal, and leave continuation without a stable concurrent executor instance.

**Solution**

Add `single_request_executor.go` implementing existing service executor and continuation interfaces. Per request, run Plan, Work, and Review against one controller and immutable binding. Delegate results to the request-safe bridge, preserve cancellation and generic errors, and return only the Review-approved output. Shared executor state is limited to keyed bridge entries, all removed on every terminal path.

**Modified Files and Checklist**

- [ ] Add the composite and exported production constructor in `apps/edge/internal/openai/single_request_executor.go`.
- [ ] Add pass, inspection, repair, concurrent isolation, cancellation, stage failure, final-output provenance, and waiter-cleanup tests in `apps/edge/internal/openai/single_request_executor_test.go`.

**Test Strategy**

Drive a deterministic full lifecycle through the real service controller with one Work tool and Review inspection/repair variants. Assert legal monotonic envelopes, artifact order, reviewer-only terminal output, concurrent identity isolation under `-race`, and cleanup after injected failures.

**Verification**

Run focused executor/review race tests and unchanged service cleanup/tool-loop tests.

### [API-4] Install and synchronize the active contract

**Problem**

A complete composite remains unreachable until Edge startup installs it. Once installed, current docs must stop claiming managed single-request execution is unavailable while distinguishing deterministic local evidence from S12 qualification.

**Solution**

Construct and install the executor in `apps/edge/internal/input/manager.go` after its dependencies exist. Add an input fixture proving production construction no longer leaves the executor unset; do not add a public getter or change Anthropic request/event schemas. Update the outer contract and current spec with stage order, private provider outcomes, generic failure behavior, local evidence, and explicit S12 deferral.

**Modified Files and Checklist**

- [ ] Install `openai.NewSingleRequestExecutor(...)` through the existing setter in `apps/edge/internal/input/manager.go`.
- [ ] Add installation/unavailable-regression coverage in `apps/edge/internal/input/manager_test.go`.
- [ ] Update `agent-contract/outer/anthropic-compatible-api.md` and `agent-spec/runtime/edge-node-execution.md` without claiming external qualification.

**Test Strategy**

Use the existing input construction seam and deterministic dependencies. Prove installation, then run unchanged public handler/stream regressions.

**Verification**

Run input installation, changed-package regression/vet, constructor/state searches, and current-document searches in Final Verification.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/single_request_review_stage.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_review_stage_test.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_executor.go` | API-3 |
| `apps/edge/internal/openai/single_request_executor_test.go` | API-3 |
| `apps/edge/internal/input/manager.go` | API-4 |
| `apps/edge/internal/input/manager_test.go` | API-4 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-4 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/CODE_REVIEW-cloud-G09.md` | API-1, API-2, API-3, API-4 |

## Final Verification

Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.

1. `bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/19_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/19+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/19_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/19+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'` — prints exactly one predecessor completion path and exits zero before implementation or review.
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequest(ReviewStage|Executor)' -count=1` — pass, direct inspection, repair/re-review, composite, concurrency, cancellation, and failure fixtures pass without races.
3. `go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup|EnvelopeOrdering)' -count=1` — unchanged coordinator tool-loop, cleanup, and envelope-ordering invariants pass freshly.
4. `go test ./apps/edge/internal/input -run 'TestManager.*SingleRequestExecutor' -count=1` — production construction installs the executor.
5. `go test ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input -count=1` — changed-path regressions pass freshly.
6. `go vet ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input && go test ./apps/edge/... -count=1` — changed packages vet cleanly and broader Edge regression passes.
7. `rg --sort path -n 'NewSingleRequestExecutor|SetSingleRequestExecutor|reasoning_effort|SingleRequestArtifactReview|finalizing|repairing' apps/edge/internal/openai apps/edge/internal/input --glob '*.go'` — installation, high Review option, repair, REVIEW persistence, and finalization ordering are explicit and test-covered; no `repairing -> reviewing` implementation is introduced.
8. `git diff --exit-code HEAD -- apps/edge/internal/service/single_request.go` — this packet leaves the predecessor-completed canonical service transition table unchanged in its implementation worktree and index.
9. `rg --sort path -n 'Plan|Work|Review|repair|active|claude-smoke|S12|deferred' agent-contract/outer/anthropic-compatible-api.md agent-spec/runtime/edge-node-execution.md` — docs describe active local behavior and leave external qualification deferred.
10. `git diff --check` — no whitespace errors.

Actual provider/Claude full-cycle evidence remains owned by S12 `claude-smoke`.

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