<!-- task=m-iop-agent-cli-runtime/15+13_host_lifecycle plan=1 tag=REVIEW_API -->

# 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-07-30
task=m-iop-agent-cli-runtime/15+13_host_lifecycle, plan=1, tag=REVIEW_API

## Archive Evidence Snapshot

- Prior plan: `agent-task/m-iop-agent-cli-runtime/15+13_host_lifecycle/plan_local_G06_0.log`
- Prior review: `agent-task/m-iop-agent-cli-runtime/15+13_host_lifecycle/code_review_cloud_G06_0.log`
- Verdict: FAIL
- Findings: Required 1, Suggested 0, Nit 0. `Start` holds `lifecycleMu` while components start, and `Stop` waits for that mutex before calling the stored cancel function, so a context-blocked component cannot be stopped.
- Affected files: `apps/agent/internal/host/host.go`, `apps/agent/internal/host/host_test.go`
- Verification evidence: fresh package, race, vet, formatting, and diff checks passed; a focused reviewer regression failed after 250 ms with `Stop() could not cancel an in-progress component Start`.
- Roadmap carryover: this is a compatibility prerequisite for the active IOP Agent CLI Runtime Milestone and does not complete a Roadmap Task id.

## 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-G04.md` → `code_review_cloud_G04_1.log` and `PLAN-local-G04.md` → `plan_local_G04_1.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-agent-cli-runtime/15+13_host_lifecycle/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS and task group is `m-<milestone-slug>`, report completion event metadata. Roadmap state check and `update-roadmap` calls are runtime responsibilities.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.

---

## Implementation Item Completion

| Item | Status |
|------|---------|
| REVIEW_API-1 Concurrent Stop cancellation | [x] |

## Implementation Checklist

- [x] Publish a concurrent stop request before lifecycle teardown waits, and add a deterministic regression proving prompt cancellation, started-prefix rollback, and safe repeated Stop.
- [x] Run fresh focused, full-package, race, vet, formatting, and diff verification.
- [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_G04_1.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_local_G04_1.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`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-agent-cli-runtime/15+13_host_lifecycle/` to `agent-task/archive/YYYY/MM/m-iop-agent-cli-runtime/15+13_host_lifecycle/` and update this checklist at the final archive path.
- [ ] If PASS and task group is `m-<milestone-slug>`, report completion event metadata for runtime, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-agent-cli-runtime/` or verify it was kept due to remaining siblings/files.
- [x] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.

## Deviations from Plan

The plan's test strategy described the blocking component returning an error matching `context.Canceled`. The actual implementation has the blocking fake component return `ctx.Err()` after `<-ctx.Done()`, which yields `context.Canceled`. This is the idiomatic Go pattern for a cancellable blocker and produces the same error identity the plan requires.

The plan's `Start` pseudocode showed `h.mu.Unlock()` after the `stopRequested` check without also checking `h.status.LaunchErr` or `len(h.started) > 0`. The implementation preserves those pre-existing guards in the same lock window for correctness with the existing `Start` semantics.

## Key Design Decisions

1. **`stopRequested` flag under `mu`**: A separate bool protected by the same `mu` that guards `cancel` and `status` avoids introducing a second mutex. The flag is set before `cancel()` is called so that a concurrent `Start` observing the flag after it acquires `lifecycleMu` cannot proceed past the guard.

2. **Cancel before `lifecycleMu`**: `Stop` publishes the cancel function snapshot and invokes it while only holding `mu`. Only after the cancel signal is in flight does it acquire `lifecycleMu` for the teardown phase. This is the core fix: a component blocked in `Start` on `ctx.Done()` is unblocked immediately, without waiting for `Stop` to acquire `lifecycleMu`.

3. **No premature `Status.Stopped`**: `Stop` sets `h.status.Stopped = true` only after the reverse teardown loop completes. This preserves the invariant that callers can observe a stopped host only after all resources have been released.

4. **Lock ordering preserved**: `mu` is always acquired before `lifecycleMu` in `Stop` (cancel path), and `lifecycleMu` is held across the entire `Start` body including the `mu` snapshot. No lock-order inversion is introduced because `Stop` releases `mu` before acquiring `lifecycleMu`, and `Start` never acquires `mu` while holding `lifecycleMu` in a way that conflicts with `Stop`'s release-then-acquire sequence.

5. **Test uses `startDone` channel**: The blocking fake component signals readiness via `close(startDone)` so the test can deterministically race `Stop` against a component that is guaranteed to be blocked in `Start`.

## Reviewer Checkpoints

- A concurrent `Stop` cancels a component whose `Start` is waiting on the host run context without first waiting for `lifecycleMu`.
- A stop request cannot be lost between `Start` acquiring the lifecycle mutex and publishing its cancel function.
- Startup cancellation rolls back only the successfully started prefix in reverse order; the failing component is not stopped.
- `Status.Stopped` is not published before cleanup finishes, error identities remain inspectable, and repeated `Stop` remains safe.
- The host package does not duplicate shared `agenttask` lifecycle algorithms or expand the application port surface.

## Verification Results

Paste actual stdout/stderr for every command below. If a command changes, record the replacement and reason in `Deviations from Plan`.

### REVIEW_API-1 Focused Verification

```bash
gofmt -w apps/agent/internal/host/*.go
go test -count=1 -run 'TestHost(StartStopOrdering|StartRollback|StopIsIdempotent|StopCancelsInProgressStart)$' ./apps/agent/internal/host
```

```
gofmt: clean

ok  	iop/apps/agent/internal/host	0.002s
```

### Final Verification

```bash
gofmt -w apps/agent/internal/host/*.go
go test -count=1 -run 'TestHost(StartStopOrdering|StartRollback|StopIsIdempotent|StopCancelsInProgressStart)$' ./apps/agent/internal/host
go test -count=1 ./apps/agent/internal/host
go test -count=1 -race ./apps/agent/internal/host
go vet ./apps/agent/internal/host
git diff --check
```

```
gofmt: clean

ok  	iop/apps/agent/internal/host	0.002s

ok  	iop/apps/agent/internal/host	0.002s

ok  	iop/apps/agent/internal/host	1.006s

vet: clean

diff check: clean
```

---

> **[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) |
| Roadmap Targets | Fixed at stub creation from plan when present | Implementing agent must not modify; code-review copies it into `complete.log` as `Roadmap Completion` only on PASS |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | 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: FAIL
- Dimension Assessment:
  - Correctness: Pass
  - Completeness: Fail
  - Test coverage: Fail
  - API contract: Pass
  - Code quality: Pass
  - Implementation deviation: Fail
  - Verification trust: Pass
- Findings:
  - Required — `apps/agent/internal/host/host_test.go:191`: `TestHostStopCancelsInProgressStart` waits for both lifecycle goroutines to finish before reading `Status().Stopped` at line 227, so it does not prove the planned invariant that terminal status stays unpublished while started-prefix cleanup is still running. Add deterministic stop-entered and stop-release gates to the ready component, assert `Status().Stopped == false` while that cleanup is blocked, release cleanup, and retain the existing terminal, error-identity, trace, idempotency, and race assertions.
- Routing Signals:
  - `review_rework_count=2`
  - `evidence_integrity_failure=false`
- Next Step: Invoke the plan skill with the raw finding and fresh verification evidence, rerun isolated routing, and materialize the smallest follow-up pair.
