<!-- task=m-iop-hot-path-one-shot-execution/11+09,10_cleanup plan=1 tag=REVIEW_API milestone-task=cleanup -->

# Review Follow-up: Cleanup Terminal Commit and State TTL

## For the Implementing Agent

This is the mandatory FAIL follow-up for the archived API plan. Both predecessor gates are satisfied by the exact archived `complete.log` files listed below. Implement every item, run every verification command with fresh results, and fill `CODE_REVIEW-cloud-G10.md`. Stop with the active pair ready for review; do not archive, write `complete.log`, mutate roadmap state, or create `USER_REVIEW.md`.

## Background

The light hot path currently returns its provider review output immediately after changing the record to `cleanup_pending`; it never issues or verifies the canonical caller-executed delete for `.iop/job/<request_id>/`. Coordinator expiry also silently drops every expired record without distinguishing active work or recording raw-free orphan responsibility. SDD scenario S09 requires one terminal owner across the caller delete frontier, error precedence and disconnect behavior, bounded server-state reclamation, and deterministic evidence.

## Dependencies and Execution Order

- `09+06,08_artifact_pair` is complete at `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/09+06,08_artifact_pair/complete.log`.
- `10+07,09_light_flow` is complete at `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log`.
- Check those archive paths exactly. Do not repeat the obsolete active-path-only preflight.

## Archive Evidence Snapshot

- Archived plan: `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/plan_cloud_G09_0.log`
- Archived review: `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/code_review_cloud_G10_0.log`
- Verdict: FAIL
- Finding counts: Required 3, Suggested 0, Nit 0.
- Required source gaps: `hot_path_review.go` returns a logical terminal before an exact delete receipt; `request_coordinator.go` retains terminal state and silently deletes expired state without active-state protection or raw-free orphan observations.
- Required evidence gap: both implementation items and their focused/common race and vet outputs were left incomplete because the implementer checked only obsolete active predecessor paths.
- Predecessor correction: both exact archived predecessor `complete.log` files above report PASS.
- Roadmap carryover: milestone task `cleanup`, approved/unlocked SDD scenario and Evidence Map row S09 only.

## Analysis

### Files Read

- `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/PLAN-cloud-G09.md`
- `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/CODE_REVIEW-cloud-G10.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/milestone/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `agent-spec/runtime/stream-evidence-gate.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/request_coordinator.go`
- `apps/edge/internal/openai/request_coordinator_test.go`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `apps/edge/internal/openai/hot_path_light.go`
- `apps/edge/internal/openai/hot_path_light_test.go`
- `apps/edge/internal/openai/hot_path_review.go`
- `apps/edge/internal/openai/hot_path_review_test.go`
- `apps/edge/internal/openai/artifact_pair.go`
- `apps/edge/internal/openai/artifact_pair_test.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/workspace_tool_binding.go`
- `apps/edge/internal/openai/workspace_tool_codec.go`

### SDD Criteria

The SDD is approved and unlocked. This task implements only S09 and its Evidence Map row: success is not externally terminal before an exact canonical delete acknowledgement; a primary endpoint error survives best-effort cleanup failure; delete failure cannot become success; disconnect performs no hidden model/tool cleanup; TTL reclaims bounded inactive server state only; and orphan observations contain fixed request/path/stage/reason metadata without prompt, result, content, credentials, or other raw bodies.

### Verification Context

There is no handoff. Use the current local checkout with Go 1.26.2 linux/arm64, injected clocks, cancellation contexts, deterministic fake frontiers, and a capturable observation sink. No external service, credential, provider call, or real workspace deletion is required. Fresh reviewer evidence showed that both archived predecessor gates pass, the existing selected race baseline passes, `git diff --check` passes, and no `TestHotPathCleanup*` or `TestLogicalRequestTTL*` test is registered. Do not use cached verification.

### Test Coverage Gaps

Current tests assert that review completion becomes a final response while the light record remains `cleanup_pending`. They do not cover the delete issue/result frontier, exact receipt matching, duplicate or concurrent cleanup results, primary-error precedence, disconnect suppression, active-state TTL protection, finalization/sweep races, bounded reclamation, or raw-free orphan observations. Replace the obsolete terminal assertions and add deterministic table/race coverage for both Chat Completions and Anthropic ingress behavior.

### Symbol References

No public symbol is renamed or removed. Extend the internal light disposition/store and coordinator with cleanup ownership and sweep helpers. Reuse the pinned `workspaceBinding`, canonical delete operation, reserved `.iop/job/<request_id>/` path, encoded payload correlation, and `matchResultReceipt`; do not add a second mapping or receipt dialect. Keep `packages/go/streamgate` public API unchanged.

### Split Judgment

Keep the two items in one pair. Cleanup finalization, coordinator removal, TTL sweep races, and orphan reporting share one exactly-once ownership invariant and the same request identity. The only predecessors are 09 and 10, and their exact archived PASS logs satisfy the dependency. Splitting would duplicate terminal-state semantics across packets.

### Scope Rationale

Exclude actual Edge-side filesystem deletion, background cleanup or model calls after disconnect, a durable orphan queue, cross-Edge resume, protocol-wide terminal/usage/id redesign, S10/S11/S12/S15/S16 evidence, and live full-cycle smoke. S16 owns live smoke; this packet supplies deterministic S09 behavior and evidence only.

### Final Routing

`evaluation_mode=review-follow-up`; finalizer `finalize-task-policy.sh pair`. Build closures all true with scores `(2,2,2,2,2)` and risks `temporal_state,concurrent_consistency,boundary_contract,variant_product` (4), `large_indivisible_context=false`, `review_rework_count=1`, `evidence_integrity_failure=false`, no recovery gap: grade-boundary cloud build `PLAN-cloud-G10.md`. Official review closures all true with scores `(2,2,2,2,2)`: cloud `CODE_REVIEW-cloud-G10.md`, Codex `gpt-5.6-sol` xhigh.

## Implementation Checklist

- [ ] Hold one success or primary-error terminal intent behind a canonical exact delete receipt and make cleanup/finalization exactly once across duplicates and races.
- [ ] Preserve primary error identity, convert successful work plus cleanup failure to the standard endpoint error, and stop without hidden model/tool cleanup after cancellation or disconnect.
- [ ] Reclaim only bounded inactive server state by TTL, protect active work, remove matching hot-path records safely, and emit fixed raw-free orphan responsibility observations.
- [ ] Add deterministic cleanup, TTL, redaction, cancellation, and concurrency tests for both compatible endpoint flows.
- [ ] Run every focused and final verification command exactly as written and fill all implementation-owned sections in `CODE_REVIEW-cloud-G10.md` with actual output.

### [REVIEW_API-1] Commit terminal intent only after exact cleanup acknowledgement

#### Problem

`advanceHotPathReview` currently calls `markCleanupPending` and immediately returns the final provider output. There is no cleanup call/result frontier, persisted terminal intent, exact receipt admission, or exactly-once completion owner. Artifact-pair failures and endpoint cancellation can therefore either orphan the reserved directory silently or tempt hidden post-disconnect work.

#### Solution

Introduce a cleanup transaction owned by the light request record. Persist either the successful output or the original endpoint error before issuing one canonical mapped delete for `.iop/job/<request_id>/` through the request's pinned workspace binding. Admit only the exact public/provider call id, correlation digest, path, operation, and configured result matcher. A matched successful receipt removes matching artifact/light/coordinator state before releasing the stored terminal response. A failed or mismatched receipt turns a pending success into the standard endpoint cleanup failure, while an existing primary endpoint error retains its identity/status/message. Duplicate and concurrent results must have one terminal winner. Cancellation or disconnect must issue no subsequent cleanup/model call; leave only bounded server state for the TTL observer.

Route exact correlated artifact generation failures into the same primary-error cleanup transaction. Malformed, unknown, or untrusted continuations remain fail-closed and are never grounds for a blind delete. Let ingress recognize cleanup-ready dispositions and write the stored terminal result without another provider dispatch.

```go
// One owner persists terminal intent before issuing cleanup.
record.beginCleanup(intent, canonicalDelete)
receipt := matchResultReceipt(record.binding, record.cleanupPayload, result)
terminal := record.commitCleanup(receipt) // exactly once
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/hot_path_cleanup.go` — add terminal-intent storage, canonical delete issue/result frontier, exact receipt admission, and error precedence.
- [ ] `apps/edge/internal/openai/hot_path_light.go` — extend the light record/disposition to hold cleanup state and prevent early terminal output.
- [ ] `apps/edge/internal/openai/hot_path_review.go` — transition review success into cleanup instead of returning final output.
- [ ] `apps/edge/internal/openai/artifact_pair.go` — route exact correlated artifact failure through primary-error cleanup without weakening malformed-result rejection.
- [ ] `apps/edge/internal/openai/request_identity_ingress.go` — consume cleanup dispositions and publish a stored terminal only after cleanup commit.
- [ ] `apps/edge/internal/openai/request_coordinator.go` — add exact owned-record removal/state transitions needed by cleanup and sweep races.
- [ ] `apps/edge/internal/openai/hot_path_cleanup_test.go` — cover success, primary error, delete failure, mismatch, cancellation, duplicate, and concurrent-result matrices on both endpoint surfaces.
- [ ] `apps/edge/internal/openai/hot_path_light_test.go` — replace obsolete immediate-terminal expectations with cleanup-pending/delete-frontier assertions.
- [ ] `apps/edge/internal/openai/hot_path_review_test.go` — assert review completion cannot escape before delete acknowledgement.
- [ ] `apps/edge/internal/openai/artifact_pair_test.go` — cover exact artifact failure cleanup and malformed continuation fail-closed behavior.

#### Test Strategy

Add `TestHotPathCleanupTerminalMatrix`, `TestHotPathCleanupConcurrentExactlyOnce`, and endpoint variants under the `TestHotPathCleanup` prefix. Assert no final response before the exact delete receipt, exactly one canonical reserved-path call, no second terminal on duplicates/races, stable primary errors, standard failure for success-plus-delete-failure, no cleanup/model work after cancellation, and identical logical semantics for Chat Completions and Anthropic responses.

#### Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run '^TestHotPathCleanup'
```

Expected: exit 0 with every registered cleanup test passing freshly.

### [REVIEW_API-2] Bound inactive state TTL and emit raw-free orphan responsibility

#### Problem

Coordinator terminal records remain resident, and current expiry opportunistically deletes all old records silently. It neither protects active in-flight transitions nor coordinates matching light/artifact store removal, bounded work, or the S09 orphan observation contract.

#### Solution

Add a bounded coordinator sweep driven by the injected clock. Select only inactive, disconnected, cleanup-pending, or terminal records that exceed TTL; never evict an active in-flight transition. Return immutable raw-free snapshots under the coordinator lock, then remove the matching light/artifact records and emit observations after releasing locks. Each observation may contain only request id, canonical reserved relative directory, prior state/stage or terminal class, and a fixed reason. It must not contain prompt text, artifact bytes, tool arguments/results, credentials, provider bodies, or claims that the caller-owned directory was deleted. Invoke the sweep at deterministic server ingress boundaries, with finalization-versus-sweep races producing one owner and no deadlock.

```go
expired := coordinator.sweepExpired(now, maxSweep)
for _, item := range expired {
    server.dropMatchingHotPathState(item)
    server.observePossibleWorkspaceOrphan(item.redacted())
}
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/request_coordinator_ttl.go` — implement bounded state-only sweep selection, active-state protection, and redacted snapshots.
- [ ] `apps/edge/internal/openai/request_coordinator_ttl_test.go` — test fake-clock expiry, bounds, active survival, finalize/sweep races, and observation redaction.
- [ ] `apps/edge/internal/openai/request_identity_ingress.go` — trigger deterministic ingress sweeps without filesystem or provider work.
- [ ] `apps/edge/internal/openai/request_coordinator.go` — expose the minimum internal state/removal hooks shared by cleanup and TTL.

#### Test Strategy

Add `TestLogicalRequestTTLSweep`, `TestLogicalRequestTTLActiveSurvives`, `TestLogicalRequestTTLFinalizeRace`, and `TestLogicalRequestTTLObservationRedaction`. Assert the configured sweep bound, inactive expiry, active survival, exact once-only ownership under races, matching store removal, canonical `.iop/job/<request_id>/` observation, and absence of injected sentinel prompt/content/result/credential values.

#### Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run '^Test(LogicalRequestTTL|HotPathCleanup)'
```

Expected: exit 0 with fresh cleanup and TTL race coverage.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/hot_path_cleanup.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_cleanup_test.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_light.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_light_test.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_review.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_review_test.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/artifact_pair.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/artifact_pair_test.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/request_identity_ingress.go` | REVIEW_API-1, REVIEW_API-2 |
| `apps/edge/internal/openai/request_coordinator.go` | REVIEW_API-1, REVIEW_API-2 |
| `apps/edge/internal/openai/request_coordinator_ttl.go` | REVIEW_API-2 |
| `apps/edge/internal/openai/request_coordinator_ttl_test.go` | REVIEW_API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/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/09+06,08_artifact_pair/complete.log
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log
go test ./apps/edge/internal/openai -list 'Test(LogicalRequestTTL|HotPathCleanup)' | rg '^Test(HotPathCleanup|LogicalRequestTTL)'
go test -race -count=1 ./apps/edge/internal/openai -run '^Test(LogicalRequestTTL|HotPathCleanup)'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
go test -count=1 ./apps/edge/...
go vet ./apps/edge/...
gofmt -d apps/edge/internal/openai/hot_path_cleanup.go apps/edge/internal/openai/hot_path_cleanup_test.go apps/edge/internal/openai/hot_path_light.go apps/edge/internal/openai/hot_path_light_test.go apps/edge/internal/openai/hot_path_review.go apps/edge/internal/openai/hot_path_review_test.go apps/edge/internal/openai/artifact_pair.go apps/edge/internal/openai/artifact_pair_test.go apps/edge/internal/openai/request_identity_ingress.go apps/edge/internal/openai/request_coordinator.go apps/edge/internal/openai/request_coordinator_ttl.go apps/edge/internal/openai/request_coordinator_ttl_test.go
git diff --check
```

Expected: every command exits 0; the registration command prints both required test families; `gofmt -d` and `git diff --check` print nothing. All test commands must be fresh (`-count=1` where supported). Live provider/full-cycle smoke is intentionally excluded because S16 owns that evidence; no external credential or caller workspace is needed. After all code and test work, fill every implementation-owned section in `CODE_REVIEW-cloud-G10.md` with actual stdout/stderr.
