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

# Artifact Cleanup, Terminal Intent, and Coordinator TTL

## For the Implementing Agent

Start only after predecessors 09 and 10 complete. Implement, run all commands, and fill `CODE_REVIEW-cloud-G10.md` with actual evidence. Keep active files for review. If blocked, record exact attempts/output/resume condition only; do not ask the user, create control files, classify, archive, or write `complete.log`.

## Background

A successful light request is not complete until the caller agent confirms deletion of its reserved request directory. Errors may attempt best-effort cleanup while preserving the primary terminal intent; disconnects must stop hidden work, and server TTL may reclaim only transient state while reporting possible workspace orphans without raw content.

## Dependencies and Execution Order

- Required predecessors are `09+06,08_artifact_pair` and `10+07,09_light_flow`; the directory name adds no hidden dependency.

## Analysis

### Files Read

- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/chat_handler.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/stream_gate_ingress_test.go`
- `apps/edge/internal/openai/anthropic_surface_test.go`
- `agent-spec/runtime/stream-evidence-gate.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/outer/anthropic-compatible-api.md`

### SDD Criteria

Approved/unlocked SDD; task/scenario/Evidence row S09. Evidence must cover success only after exact delete acknowledgement, primary error plus best-effort cleanup, cleanup failure precedence, caller disconnect with no hidden work, bounded TTL, and raw-free orphan request id/path observability.

### Verification Context

No handoff. Injected clock, cancellation contexts, fake tool frontiers, and observation sinks make S09 deterministic locally. Fresh/race tests required; no actual workspace deletion occurs. Confidence: high.

### Test Coverage Gaps

Existing ingress and Anthropic surface tests cover request-local dispatch and standard errors, not cross-call state TTL or agent-confirmed cleanup. Add cleanup-state tables, fake clock eviction, concurrent terminal/delete results, and redaction assertions.

### Symbol References

No rename/removal. Extend the child-05 coordinator and child-10 light terminal transition; do not change `packages/go/streamgate` public API unless compilation proves a narrowly scoped adapter is required.

### Split Judgment

This unchanged pair depends exactly on 09/10. Cleanup and TTL stay together because removal of server state, preservation of terminal intent, and orphan reporting share one exactly-once ownership invariant. This packet closes S09 but not later protocol terminal/observability/smoke tasks.

### Scope Rationale

Exclude actual server-side filesystem deletion, background cleanup after disconnect, durable orphan queues, cross-Edge resume, protocol-wide usage/id re-encoding, new partial-success status, and full route observability fields from Epic 4.

### Final Routing

`evaluation_mode=first-pass`; `finalizer=finalize-task-policy.sh` pair. Build closures true, scores `(2,2,2,1,2)` => G09 grade-boundary cloud; `large_indivisible_context=false`, risks `temporal_state,concurrent_consistency,boundary_contract,variant_product` (4), rework 0, evidence-integrity false, no gap; `PLAN-cloud-G09.md`. Review scores `(2,2,2,2,2)` => official cloud G10, `CODE_REVIEW-cloud-G10.md`, Codex `gpt-5.6-sol` xhigh.

## Implementation Checklist

- [ ] Gate light success/error completion on one exact caller-executed delete result while preserving primary terminal intent and cancellation semantics.
- [ ] Reclaim only server state by bounded TTL and emit raw-free orphan identity/path observations without hidden cleanup after disconnect.
- [ ] Run cleanup/TTL/concurrency, common race, vet, and diff verification exactly as written.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [API-1] Confirm cleanup before logical terminal

#### Problem

The child-10 flow stops at `cleanup_pending`, but current endpoint handlers can finalize as soon as provider processing ends. SDD lines 140-144 require exact delete acknowledgement before success and preservation of a primary error during best-effort cleanup.

#### Solution

Store a single pending terminal intent and emit canonical delete for `.iop/job/<request_id>/`. Validate its mapped public id/path/receipt exactly once. On success, remove coordinator state then publish the pending success/error; on cleanup failure, success becomes standard failure while an existing primary error retains its identity. Context cancellation/disconnect cancels the stage and emits no new tool/model work.

```go
// Before: cleanup_pending has no terminal owner.

// After
req.PendingTerminal = terminalIntent
req.ExpectCleanup(deleteCall)
req.CommitTerminalAfterDelete(result)
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/hot_path_cleanup.go` — terminal intent, mapped delete frontier, result/error precedence.
- [ ] `apps/edge/internal/openai/request_coordinator.go` — exactly-once terminal removal and disconnected state handling.
- [ ] `apps/edge/internal/openai/hot_path_cleanup_test.go` — success/error/delete failure/cancel/concurrent result matrix.

#### Test Strategy

Write `TestHotPathCleanupTerminalMatrix` and `TestHotPathCleanupConcurrentExactlyOnce`. Assert success is absent before receipt, duplicate results cannot complete twice, primary errors are stable, cleanup failure cannot become success, and cancelled contexts make zero subsequent calls.

#### Verification

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

Expect PASS.

### [API-2] Bound state TTL and report workspace orphan responsibility

#### Problem

An Edge-local store needs bounded abandoned-state reclamation, but deleting its entry cannot claim deletion of caller-owned workspace artifacts. Raw file content and prompts must never enter orphan telemetry.

#### Solution

Use injected monotonic time and a bounded sweep path to evict inactive/disconnected state. Emit only request id, fixed reserved relative directory, prior stage/terminal class, and reason; never execute cleanup or log tool result/body/content. Active in-flight transitions must not be evicted, and finalization/sweep must race safely.

```go
// Before: no cross-call TTL ownership.

// After
store.SweepExpired(now) // removes server state only; emits redacted orphan observation
```

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/request_coordinator_ttl.go` — bounded sweep and state-only reclamation.
- [ ] `apps/edge/internal/openai/request_coordinator_ttl_test.go` — fake-clock expiry/in-flight/finalize races and redaction.

#### Test Strategy

Write `TestLogicalRequestTTLSweep` and `TestLogicalRequestTTLObservationRedaction`. Assert inactive states expire, active locked state survives, final state is emitted once, exact reserved path is present, and secrets/raw prompt/content/tool result are absent.

#### Verification

Run `go test -race -count=1 ./apps/edge/internal/openai -run 'Test(LogicalRequestTTL|HotPathCleanup)'`; expect PASS.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/hot_path_cleanup.go` | API-1 |
| `apps/edge/internal/openai/request_coordinator.go` | API-1 |
| `apps/edge/internal/openai/hot_path_cleanup_test.go` | API-1 |
| `apps/edge/internal/openai/request_coordinator_ttl.go` | API-2 |
| `apps/edge/internal/openai/request_coordinator_ttl_test.go` | API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/CODE_REVIEW-cloud-G10.md` | API-1, API-2 |

## Final Verification

```bash
test -f agent-task/m-iop-hot-path-one-shot-execution/09+06,08_artifact_pair/complete.log
test -f agent-task/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log
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 vet ./apps/edge/internal/openai
git diff --check
```

Expected: all exit 0; terminal commit is exactly once after delete receipt; disconnect triggers no hidden work; TTL observations contain no raw content and do not claim workspace deletion. Cache is not acceptable. After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.
