<!-- task=m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual plan=4 tag=REVIEW_REVIEW_REVIEW_TEST milestone-task=hot-smoke -->

# Production-Compatible Cancellation and Pi Error Smoke Evidence

## For the Implementing Agent

Filling the implementation-owned sections in `CODE_REVIEW-cloud-G08.md` is mandatory. Execute this plan without changing its ownership or scope, run every verification command, paste actual output and decisions into the review artifact, keep both active files in place, and report ready for review. If blocked, record only the exact blocker, attempted command/output, and resume condition in implementation-owned evidence fields. Do not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, write `complete.log`, or update roadmap state; finalization belongs to the code-review skill.

## Background

The previous follow-up repaired production retry parsing, native Pi event projection, and empty reservation detection, but its passing self-test still encodes two runtime-incompatible assumptions. Timeout/cancel waits for an ingress-triggered 30-minute TTL orphan inside a 10-second window, and the Pi error fake exits nonzero although installed Pi JSON mode returns zero for a protocol-encoded assistant error. These direct fixes must precede the matching-runtime SDD S16 matrix.

## Archive Evidence Snapshot

- The reviewed pair is archived at `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/plan_cloud_G09_3.log` and `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/code_review_cloud_G09_3.log` with verdict `FAIL`, `review_rework_count=3`, and `evidence_integrity_failure=true`.
- Required R2: the harness requires `orphan=ttl_expired` within 10 seconds, while production uses a 30-minute default TTL and sweeps only at later preset ingress.
- Required R4: installed Pi JSON mode can emit a final assistant `stopReason=error` and return exit 0; the current derivation rejects that native combination while its fake exits 1.
- Required R3: external verification stopped at the first missing `IOP_HOT_SMOKE_BASE_URL` presence check, so no actual Claude/Pi 10-case manifest exists.
- Fresh reviewer checks passed shell syntax, the fake-only harness self-test, the exact four-package race command, and `git diff --check`; a focused Pi probe returned `pi_native_error_exit0_rejected=true` and `pi_fake_error_exit1_accepted=true`.
- Roadmap scope remains `milestone-task=hot-smoke`; no Milestone completion is claimed.

## Finding Resolution Map

| Finding | Mode | Exact fix/evidence | Changed or satisfied precondition |
|---|---|---|---|
| Required R2 | direct-fix | `scripts/e2e-hot-path-agents.sh`: close timeout/cancel observation on the production local-stage cancellation disposition, remove the synthetic immediate TTL orphan from fake traces, keep orphan classification bound to child cancellation plus the surviving workspace snapshot, and add timing-contract controls. | Replaces an impossible 10-second TTL-orphan oracle with the immediate production caller-cancel evidence that the matching runtime can emit. |
| Required R4 | direct-fix | `scripts/e2e-hot-path-agents.sh`: pass agent identity into result derivation, accept Pi's protocol error with JSON-mode exit 0 while retaining Claude/process contradiction checks, make fake Pi reproduce exit 0, and add positive/negative controls. | Replaces the fake-only nonzero Pi exit assumption with the installed Pi print-mode contract, allowing `pi:write-unavailable` to reach valid terminal evidence. |
| Required R3 | direct-fix | `scripts/e2e-hot-path-agents.sh` plus `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/CODE_REVIEW-cloud-G08.md`: after R2/R4, run the exact external preflight/matrix and record the actual manifest or the first exact remaining blocker without an S16 completion claim. | Repository-fixable false negatives are removed before external verification is repeated, so the next run is meaningful rather than an unchanged-precondition loop. |

## Analysis

### Files Read

- `scripts/e2e-hot-path-agents.sh` — complete harness, parsers, reducers, fake agents/runtime, and self-test.
- `Makefile` — isolated smoke self-test, preflight, and actual targets.
- `scripts/fixtures/hot-path-agent-smoke-manifest.schema.json` — fixed manifest contract.
- `apps/edge/internal/openai/request_coordinator.go` — coordinator defaults and detached request state.
- `apps/edge/internal/openai/request_coordinator_ttl.go` — TTL expiry and ingress-bound sweep/orphan emission.
- `apps/edge/internal/openai/request_identity_ingress.go` — the only production sweep call sites at OpenAI/Anthropic preset ingress.
- `apps/edge/internal/openai/server.go` — production coordinator construction with default options.
- `/config/.npm-global/lib/node_modules/@earendil-works/pi-coding-agent/dist/modes/print-mode.js` — installed Pi JSON output and text-only stop-reason exit handling.
- `/config/.npm-global/lib/node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts` — installed AgentSessionEvent and protocol-encoded failure contract.
- `agent-test/local/rules.md` and `agent-test/local/testing-smoke.md` — local and smoke verification rules.
- `agent-spec/runtime/stream-evidence-gate.md` and `agent-spec/input/openai-compatible-surface.md` — current runtime evidence and compatible input specifications.
- `agent-contract/outer/openai-compatible-api.md` and `agent-contract/outer/anthropic-compatible-api.md` — outer protocol boundaries.
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-hot-path-one-shot-execution.md` — active Milestone and `hot-smoke` task.
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md` — approved S16 acceptance and evidence requirements.
- `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/plan_cloud_G09_3.log` and `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/code_review_cloud_G09_3.log` — immediate predecessor plan, implementation evidence, and verdict.
- `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/code_review_cloud_G07_2.log` — prior stable finding ids and production-contract evidence.

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`, approved status (`[승인됨]`), lock released.
- Milestone metadata: `milestone-task=hot-smoke`.
- Target Acceptance Scenario: S16, actual Claude Code/Pi streaming smoke for direct, light-pass, repair, write-unavailable, and timeout/cancel.
- Evidence Map drivers: actual Claude/Pi streaming logs with visible stage/tool output; fixed terminal/error/cancellation evidence; workspace before/after and cleanup/orphan evidence; standard terminal execution against the matching runtime.
- R2 maps the cancellation row to immediate production stage evidence plus a surviving workspace, not a delayed TTL sweep. R4 maps Pi error evidence to the native final assistant event and JSON-mode process semantics. R3 preserves the actual 2x5 run as the only S16 completion oracle.

### Verification Context

- No separate `verification_context` handoff was supplied. Repository-native evidence came from the harness, Make targets, production Edge sources, installed Pi sources/types, the approved SDD, and fresh reviewer commands.
- Fresh local results: `bash -n` and `TMPDIR=/config/workspace/iop-s0 make test-hot-path-agent-smoke-self-test` exited 0; `go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service` exited 0; `git diff --check` exited 0.
- Focused Pi result: a native-shaped error stream was parsed to `terminal_error`, but derivation rejected child exit 0 and accepted the fake's exit 1.
- Production cancellation constraint: `defaultLogicalRequestTTL` is 30 minutes, `NewServer` supplies no override, and `sweepLogicalRequestTTL` is called only at preset ingress. The harness currently waits 10 seconds inside one case before any later matrix ingress.

#### External Verification Preflight

- Runner/repo: current host, `/config/workspace/iop-s0`; branch `feature/iop-hot-path-one-shot-execution`; HEAD `703f3b723202959185c04bb32c2c68383b8d04a0`; dirty worktree containing the in-scope harness plus unrelated changes.
- OS/arch: Linux `6.10.14-linuxkit`, aarch64; Go `1.26.2`.
- CLI inventory: `claude` and `pi` are installed under `/config/.npm-global/bin`; executable identity must be rebound by the harness preflight for the selected run.
- Missing selection: no matching Edge base URL, Edge binary/config/runtime-evidence file, observation file, Pi profile/provider, scenario aliases, disposable workspace parent, output path, or caller-selected secret environment names/values are available in this session. Source synchronization, runtime identity, listening port/process, and external provider host therefore cannot be proven.
- First failed command: `test -n "${IOP_HOT_SMOKE_BASE_URL:-}"`, exit 1 with no output.
- Resume/setup: select or start the matching isolated Edge runtime, export all caller-selected inputs without printing values, regenerate runtime evidence for this exact worktree and executable/config/profile identities, then run the complete presence block, Make preflight, 2x5 matrix, and final manifest assertion.
- Constraint: actual credentials and external runtime selection remain caller-controlled. If they are still absent after local fixes, record the first failure and stop without claiming S16 completion.
- Confidence: high for R2/R4 source contracts and local regression oracle; external S16 completion remains unverified.

### Test Coverage Gaps

- R2: the current self-test covers a synthetic immediate orphan and several malformed observation traces, but not the production 30-minute ingress-sweep timing boundary. Change the positive fake timeout trace to end at local `caller_cancel`, assert it is accepted, and assert an immediate TTL orphan is rejected for this case.
- R4: the current self-test parses native Pi success/error shapes but makes the error process exit 1. Change the matrix fake to exit 0, assert native Pi error/exit 0 succeeds, and retain explicit success/nonzero and missing-terminal contradiction rejection.
- R3: no local test substitutes for the actual Claude/Pi matching-runtime matrix. The schema-valid external manifest remains mandatory.
- Existing Make isolation, schema negatives, identity binding, redaction, workspace digest, and four-package race coverage remain applicable.

### Symbol References

- `reduce_observation_fragment` is called by `capture_appended_observation`; both timeout closure checks must change together.
- `capture_appended_observation` is called by `run_case` at `scripts/e2e-hot-path-agents.sh:927`.
- `parse_visible_events` is used by `run_case` and self-test probes; its Pi event projection remains unchanged.
- `derive_case_result` is called by `run_case` at line 929 and the self-test helper at line 1203; adding agent identity requires updating both call sites and their helper argument lists.
- `obs_cancel_lifecycle` feeds the generated fake-agent TERM handlers; remove only the immediate orphan record while preserving dispatch and local caller-cancel records.
- No public Go, schema, Make target, or wire-contract symbol is renamed or removed.

### Split Judgment

Keep one plan. Observation closure, process status, native terminal projection, harness-owned cancellation, and workspace orphan classification jointly decide each timeout/error row; splitting R2 and R4 from the same derivation/self-test would leave no independently PASS-capable matrix contract. The implementation boundary is one shell harness with deterministic local controls and one external manifest oracle.

### Scope Rationale

Modify only `scripts/e2e-hot-path-agents.sh` and implementation-owned evidence in `CODE_REVIEW-cloud-G08.md`. Do not change production Edge TTL behavior, coordinator configuration, Pi installation, `Makefile`, manifest schema, model aliases, credentials, runtime configuration, SDD/spec/contract/roadmap documents, or unrelated dirty-worktree files. The production and installed Pi files are source-of-truth inputs, not implementation targets.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`; `status=routed`.
- Build closures: `scope_closed=true`, `context_closed=true`, `verification_closed=true`, `evidence_trusted=true`, `ownership_closed=true`, `decision_closed=true`. Basis: exact direct-fix files, deterministic self-test controls, known external owner/preconditions, and a fixed manifest oracle; capability gap: none.
- Build scores: scope coupling 2, state/concurrency 2, blast/irreversibility 0, evidence diagnosis 2, verification complexity 2; grade G08. Base basis `local-fit`; `large_indivisible_context=false`; matched loop risks `temporal_state`, `boundary_contract`, `structured_interpretation`, `variant_product` (4); `review_rework_count=3`; `evidence_integrity_failure=true`; risk and recovery boundaries both match. Final route basis `recovery-boundary`, lane `cloud`, filename `PLAN-cloud-G08.md`.
- Review closures: all six closure fields true from the same bounded source/runtime/verification evidence; capability gap: none. Scores 2/2/0/2/2; grade G08. Route basis `official-review`, lane `cloud`, adapter `codex`, model `gpt-5.6-sol`, reasoning effort `xhigh`, filename `CODE_REVIEW-cloud-G08.md`.

## Implementation Checklist

- [ ] [REVIEW_REVIEW_REVIEW_TEST-1] Align timeout/cancel observation closure and fake traces with the production Edge caller-cancel/TTL timing contract, including positive and immediate-orphan negative controls.
- [ ] [REVIEW_REVIEW_REVIEW_TEST-2] Reconcile Pi protocol errors with JSON-mode exit 0, update every derivation call site and fake, and add native-error/process-contradiction regression controls.
- [ ] [REVIEW_REVIEW_REVIEW_TEST-3] Run local/common verification and the exact external matching-runtime preflight/matrix, recording the actual manifest or the first exact blocker without an S16 completion claim.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_REVIEW_REVIEW_TEST-1] Production Cancellation Observation Closure

#### Problem

At `scripts/e2e-hot-path-agents.sh:474-481` timeout/cancel does not close until an orphan record appears, and lines 533-546 require exactly one final `orphan=ttl_expired`. Lines 573-610 allow only 10 seconds. Production uses a 30-minute TTL and only sweeps at later ingress, so an actual child cancellation cannot satisfy the current reducer while `run_case` is blocked waiting for it.

#### Solution

Before (`scripts/e2e-hot-path-agents.sh:474-481`, `:533-546`):

```bash
if [ "$scenario" = timeout-cancel ]; then
    closure_count=$(jq '[.[] | select(.ec == "orphan")] | length' <<<"$projected")
...
and ($local[-1].value.disposition | IN("caller_cancel","timeout"))
and ($orphan | length) == 1 and $orphan[0].value.orphan == "ttl_expired"
```

After:

```bash
if [ "$scenario" = timeout-cancel ]; then
    closure_count=$(jq '[.[] | select(.ec == "stage" and .sk == "local" and (.disposition | IN("caller_cancel","timeout")))] | length' <<<"$projected")
...
and ($local[-1].value.disposition | IN("caller_cancel","timeout"))
and ($orphan | length) == 0
```

Require the cancel/timeout stage to be the last immediate observation for the harness-owned child cancellation. Keep public `cleanup=orphan` derived only when the child-only cancellation fired, the sentinel survived, and the post-run workspace snapshot still contains the reserved artifact. Remove the fake runtime's immediate TTL orphan and make a same-window orphan a negative production-timing control.

#### Modified Files and Checklist

- [ ] `scripts/e2e-hot-path-agents.sh`: change timeout closure detection and reducer ordering/count invariants.
- [ ] `scripts/e2e-hot-path-agents.sh`: remove the synthetic immediate orphan from `obs_cancel_lifecycle` and adjust observation negative fixtures.
- [ ] `scripts/e2e-hot-path-agents.sh`: add self-test assertions for production-shaped caller cancel and immediate-orphan rejection.

#### Test Strategy

Write regression coverage inside the existing shell self-test. The positive fake trace must be dispatch → local first/caller_cancel with no orphan and must still produce `timeout-cancel` cleanup `orphan` from workspace/process facts. A trace that appends an immediate `ttl_expired` orphan must be rejected as incompatible with the production timing boundary.

#### Verification

```bash
bash -n scripts/e2e-hot-path-agents.sh
TMPDIR=/config/workspace/iop-s0 make test-hot-path-agent-smoke-self-test
```

Expected: exit 0; output includes new production-shaped cancellation acceptance and immediate TTL-orphan rejection assertions.

### [REVIEW_REVIEW_REVIEW_TEST-2] Native Pi JSON Error Reconciliation

#### Problem

`scripts/e2e-hot-path-agents.sh:684-692` correctly maps a final Pi assistant `stopReason=error` to `terminal_error`, but lines 720-738 require every error terminal to have a nonzero process status. Installed `print-mode.js:81-118` prints JSON events yet computes stop-reason exit 1 only inside `mode === "text"`; the fake at lines 1538-1544 exits 1 and hides this mismatch.

#### Solution

Before (`scripts/e2e-hot-path-agents.sh:720-738`):

```bash
derive_case_result() {
    local scenario="$1" child_status="$2" triggered="$3" target="$4"
...
terminal_error)
    [ "$child_status" -ne 0 ] && [ "$triggered" = false ] && [ "$target" = none ] || return 1
```

After:

```bash
derive_case_result() {
    local agent="$1" scenario="$2" child_status="$3" triggered="$4" target="$5"
...
terminal_error)
    if [ "$agent" = pi ]; then
        [ "$child_status" -eq 0 ]
    else
        [ "$child_status" -ne 0 ]
    fi
    [ "$triggered" = false ] && [ "$target" = none ] || return 1
```

Update both production and self-test call sites for the new agent argument. Change only fake Pi `write-unavailable` to exit 0; preserve fake Claude's nonzero error. Keep success/nonzero, missing terminal, duplicate terminal, and signal-cancellation contradictions fail closed.

#### Modified Files and Checklist

- [ ] `scripts/e2e-hot-path-agents.sh`: add agent-aware error/process reconciliation and update all call sites.
- [ ] `scripts/e2e-hot-path-agents.sh`: make fake Pi JSON error exit 0 without changing its native error events.
- [ ] `scripts/e2e-hot-path-agents.sh`: add explicit Pi error/exit-0 acceptance and Pi success/nonzero rejection assertions.

#### Test Strategy

Write regression coverage inside the existing shell self-test. The 10-case fake matrix must now exercise Pi `write-unavailable` with native `agent_end` error plus child exit 0. Add a focused positive assertion for that pair and a negative control proving a success terminal with nonzero status still fails.

#### Verification

```bash
TMPDIR=/config/workspace/iop-s0 make test-hot-path-agent-smoke-self-test
```

Expected: exit 0; output proves Pi native error/exit 0 is accepted and process/terminal contradictions remain rejected.

### [REVIEW_REVIEW_REVIEW_TEST-3] Matching-Runtime S16 Evidence

#### Problem

The prior external block stopped on absent `IOP_HOT_SMOKE_BASE_URL`. SDD S16 cannot pass on fake-agent self-test evidence, and repeating the actual matrix before R2/R4 would produce false negatives.

#### Solution

After local fixes and regressions pass, run the exact caller-selected presence checks, harness preflight, 2x5 matrix, and manifest assertion. Record raw command output in `CODE_REVIEW-cloud-G08.md`. If inputs remain unavailable, stop at the first failure and record runner identity, missing input name, commands not run, and exact resume condition; do not claim S16 completion.

#### Modified Files and Checklist

- [ ] `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/CODE_REVIEW-cloud-G08.md`: record complete local output and either actual external manifest evidence or the first exact blocker.

#### Test Strategy

Do not add another fake test for R3. The required test is the actual Claude/Pi matching-runtime 10-case matrix with the fixed manifest schema and zero redaction matches.

#### Verification

Use the exact external block in Final Verification. PASS requires every command to exit 0 and the final `jq` assertion to accept the actual manifest. A first presence/preflight failure is blocker evidence only.

## Modified Files Summary

| File | Items | Purpose |
|---|---|---|
| `scripts/e2e-hot-path-agents.sh` | REVIEW_REVIEW_REVIEW_TEST-1, REVIEW_REVIEW_REVIEW_TEST-2, REVIEW_REVIEW_REVIEW_TEST-3 | Align cancellation observation and Pi process semantics, update fakes, and add regression controls before the actual run. |
| `agent-task/m-iop-hot-path-one-shot-execution/21+20_hot_smoke_actual/CODE_REVIEW-cloud-G08.md` | REVIEW_REVIEW_REVIEW_TEST-1, REVIEW_REVIEW_REVIEW_TEST-2, REVIEW_REVIEW_REVIEW_TEST-3 | Record implementation decisions, exact local results, and actual external evidence or blocker. |

## Final Verification

### Local harness and common regression

```bash
bash -n scripts/e2e-hot-path-agents.sh
TMPDIR=/config/workspace/iop-s0 make test-hot-path-agent-smoke-self-test
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
git diff --check
```

Expected: all commands exit 0. The self-test must explicitly show production-shaped timeout/cancel acceptance, immediate TTL-orphan rejection, Pi native error/exit-0 acceptance, and terminal/process contradiction rejection. Fresh Go execution is required; cached output is not acceptable.

### External matching-runtime preflight and matrix

Run presence-only checks without printing values:

```bash
test -n "${IOP_HOT_SMOKE_BASE_URL:-}"
test -n "${IOP_HOT_SMOKE_DIRECT_MODEL:-}" && test -n "${IOP_HOT_SMOKE_PASS_MODEL:-}"
test -n "${IOP_HOT_SMOKE_REPAIR_MODEL:-}" && test -n "${IOP_HOT_SMOKE_SLOW_MODEL:-}"
test -n "${IOP_HOT_SMOKE_CLAUDE_BIN:-}" && test -x "$IOP_HOT_SMOKE_CLAUDE_BIN"
test -n "${IOP_HOT_SMOKE_PI_BIN:-}" && test -x "$IOP_HOT_SMOKE_PI_BIN"
test -n "${PI_CODING_AGENT_DIR:-}" && test -d "$PI_CODING_AGENT_DIR"
test -n "${IOP_HOT_SMOKE_PI_PROVIDER:-}"
test -n "${IOP_HOT_SMOKE_EDGE_BIN:-}" && test -x "$IOP_HOT_SMOKE_EDGE_BIN"
test -n "${IOP_HOT_SMOKE_EDGE_CONFIG:-}" && test -f "$IOP_HOT_SMOKE_EDGE_CONFIG"
test -n "${IOP_HOT_SMOKE_RUNTIME_EVIDENCE:-}" && test -f "$IOP_HOT_SMOKE_RUNTIME_EVIDENCE"
test -n "${IOP_HOT_SMOKE_OBSERVATION_FILE:-}" && test -f "$IOP_HOT_SMOKE_OBSERVATION_FILE"
test -n "${IOP_HOT_SMOKE_WORKSPACE_PARENT:-}" && test -d "$IOP_HOT_SMOKE_WORKSPACE_PARENT"
test -n "${IOP_HOT_SMOKE_OUTPUT:-}"
test -n "${IOP_HOT_SMOKE_CLAUDE_SECRET_ENV:-}" && test -n "${!IOP_HOT_SMOKE_CLAUDE_SECRET_ENV:-}"
test -n "${IOP_HOT_SMOKE_PI_SECRET_ENV:-}" && test -n "${!IOP_HOT_SMOKE_PI_SECRET_ENV:-}"
make test-hot-path-agent-smoke-preflight
make test-hot-path-agent-smoke
jq -e '
  .schema_version == "1"
  and ([.cases[].id] == ["claude:direct","claude:light-pass","claude:repair","claude:write-unavailable","claude:timeout-cancel","pi:direct","pi:light-pass","pi:repair","pi:write-unavailable","pi:timeout-cancel"])
  and ([.cases[].outcome] == ["completed","completed","completed","error","cancelled","completed","completed","completed","error","cancelled"])
  and all(.cases[]; (.visible_events | length) > 0 and (.observation | length) > 0)
  and all(.cases[] | select(.scenario == "light-pass" or .scenario == "repair"); any(.visible_events[]; .kind == "tool_use"))
  and (.redaction.matches == 0)
' "$IOP_HOT_SMOKE_OUTPUT"
```

Expected: every command exits 0 against the matching isolated runtime. If blocked, paste the first exact failed command/output, runner identity, missing input name, commands not run, and resume condition; explicitly state that S16 remains incomplete.

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