<!-- task=m-iop-agent-cli-runtime/10+06_state_recovery plan=2 tag=REVIEW_REVIEW_API -->

# Code Review Reference - REVIEW_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-29
task=m-iop-agent-cli-runtime/10+06_state_recovery, plan=2, tag=REVIEW_REVIEW_API

## Roadmap Targets

- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/iop-agent-cli-runtime.md`
- Milestone link: [Milestone document](agent-roadmap/phase/automation-runtime-bridge/milestones/iop-agent-cli-runtime.md)
- Task ids:
  - `state-recovery`: singleton/workspace lease, checkpoint, restart reconciliation
- Completion mode: check-on-pass

## Archive Evidence Snapshot

- Prior plan: `agent-task/m-iop-agent-cli-runtime/10+06_state_recovery/plan_local_G06_1.log`
- Prior review: `agent-task/m-iop-agent-cli-runtime/10+06_state_recovery/code_review_cloud_G07_1.log`
- Verdict: `FAIL`
- Findings: Required=1, Suggested=0, Nit=0.
- Required finding: active claims are validated by separate loads instead of inside the guarded durable mutation; integration is not renewed; cleanup releases reloaded successor tokens and omits device release.
- Affected files: `packages/go/agenttask/manager.go`, `packages/go/agenttask/intent.go`, `packages/go/agenttask/reconcile.go`, `packages/go/agenttask/dispatch.go`, `packages/go/agenttask/review.go`, `packages/go/agenttask/integration_queue.go`, and the lease test harness/tests.
- Fresh reviewer evidence: the implementation's named focused tests, twenty-repeat run, race run, shared-package run, vet, formatting, proto generation, and `git diff --check` passed.
- Focused failure evidence: `go test -count=1 -run '^TestReviewerReproducerRejectsReviewResultAndPreservesSuccessorLeases$' -v ./packages/go/agenttask` failed because the late review reached `completed` and both successor leases were absent after reconciliation.
- Roadmap carryover: SDD S09 and Milestone task `state-recovery` remain incomplete until every durable result commit is atomically fenced and cleanup cannot delete successor ownership.

## 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-G08.md` → `code_review_cloud_G08_2.log` and `PLAN-cloud-G07.md` → `plan_cloud_G07_2.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-agent-cli-runtime/10+06_state_recovery/`. 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_REVIEW_API-1 — Make the lease set an atomic durable-write fence | [x] |
| REVIEW_REVIEW_API-2 — Close the renewal and cleanup lifecycle with deterministic evidence | [x] |

## Implementation Checklist

- [x] Atomically validate the exact active lease claims inside every guarded durable mutation and reject late provider, reviewer, and integrator results even when ownership changes before the next renewal tick.
- [x] Enroll integration claims in the reconciliation renewal lifetime and cancel guarded work when any tracked renewal loses ownership.
- [x] Stop the renewal supervisor before cleanup, release only originally captured exact device/project/workspace/integration claims, and preserve all successor tokens.
- [x] Replace the misleading lease tests with deterministic renewal, takeover-denial, immediate-loss, cancellation, no-stale-commit, device-release, and successor-retention coverage.
- [x] Run every focused, repeated, race, shared-package, vet, formatting, proto, contract, and diff verification command and fill all implementation-owned sections in `CODE_REVIEW-cloud-G08.md`.

## 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_G08_2.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_cloud_G07_2.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/10+06_state_recovery/` to `agent-task/archive/YYYY/MM/m-iop-agent-cli-runtime/10+06_state_recovery/` 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

No contract text changed: both applicable inner contracts already require the
atomic fence, renewal cancellation, and exact-token release semantics.

The CAS-retry fence test was added to the deterministic manager matrix in
addition to the four plan-named tests. It proves that a successor written by a
forced `ErrRevisionConflict` is reloaded and rejected before retrying the
durable result mutation.

The worktree contained unrelated in-progress changes before this task. They
were preserved; this implementation changed only the active `agenttask` lease
path, its package-private test seam, regression tests, and this evidence.

## Key Design Decisions

- Guarded reconciliation contexts carry their `leaseSet`. `mutateDecision`
  snapshots the exact scope/owner/token/subject claims and validates them
  against the same state snapshot used for the following CAS attempt. A CAS
  conflict reloads and validates again.
- Lease acquisition, renewal, and cleanup use an explicit unfenced internal
  context. Cleanup first joins the renewal supervisor, then releases only
  captured immutable claim handles; exact-token release cannot delete a
  successor.
- Integration claims are added before `Integrator.Integrate`, removed under
  the renewal-set lock before release, and therefore participate in both
  renewal and atomic durable-write fencing for their full external lifetime.
- The renewal ticker override is package-private and test-only. Production
  continues to use the bounded `time.Ticker` supervisor and the persisted
  `LeaseRecord` shape is unchanged.

## Reviewer Checkpoints

- Confirm the exact active scope/subject/token claims are validated against the same `ManagerState` snapshot and revision used by each guarded CAS, including every retry after `ErrRevisionConflict`.
- Confirm provider, reviewer, and integrator result paths cannot persist result, blocker, rework, locator, or terminal-state changes after any required claim is replaced.
- Confirm integration claims join the live renewal set before `Integrator.Integrate` and are removed/released without racing renewal.
- Confirm reconciliation stops and joins the renewal supervisor before cleanup, releases the captured device claim, and never reloads a token to choose what to release.
- Confirm exact-token cleanup removes claims still owned by this manager and preserves successor device/project/workspace/integration claims.
- Confirm the renewal tests observe real supervisor-driven expiry extension and prove a second manager cannot take over; manual store expiry extension is not acceptable renewal evidence.
- Confirm immediate-loss tests release each external result before the next renewal tick and still reject every stale commit, then separately prove the renewal loop cancels blocked work.
- Confirm test-only clock/ticker control remains package-internal and the persisted `LeaseRecord` format and public API remain compatible.
- Confirm both inner contracts still match the implemented atomic-fence, renewal, cancellation/rejection, and exact-token-release semantics.

## Verification Results

### Environment identity

```bash
command -v go && readlink -f "$(command -v go)" && go version && go env GOROOT
```

```text
/config/.local/bin/go
/config/opt/go/bin/go
go version go1.26.2 linux/arm64
/config/opt/go
exit status 0
```

### Proto generation

```bash
make proto
```

```text
protoc --go_out=. --go_opt=module=iop --proto_path=. proto/iop/runtime.proto proto/iop/node.proto proto/iop/control.proto proto/iop/job.proto
exit status 0
```

### Focused lease lifecycle matrix

```bash
go test -count=1 -run '^(TestLeaseSupervisorRenewsAllTrackedScopesAndDeniesTakeover|TestLeaseLossImmediatelyFencesProviderAndReviewResults|TestLeaseLossImmediatelyFencesIntegrationResult|TestLeaseCleanupReleasesOwnedClaimsAndPreservesSuccessors)$' -v ./packages/go/agenttask
```

```text
PASS
ok  iop/packages/go/agenttask  0.022s
The named matrix passed renewal of device/project/workspace/integration,
duplicate-owner denial, immediate provider/reviewer/integrator fencing, and
exact-token cleanup/successor retention.
exit status 0
```

### Repeated deterministic lease matrix

```bash
go test -count=20 -run '^(TestLeaseSupervisorRenewsAllTrackedScopesAndDeniesTakeover|TestLeaseLossImmediatelyFencesProviderAndReviewResults|TestLeaseLossImmediatelyFencesIntegrationResult|TestLeaseCleanupReleasesOwnedClaimsAndPreservesSuccessors)$' ./packages/go/agenttask
```

```text
ok  iop/packages/go/agenttask  0.662s
exit status 0
```

### Race verification

```bash
go test -count=1 -race ./packages/go/agentstate ./packages/go/agenttask
```

```text
ok  iop/packages/go/agentstate  1.172s
ok  iop/packages/go/agenttask   1.562s
exit status 0
```

### Shared package regression

```bash
go test -count=1 ./packages/go/...
```

```text
ok  iop/packages/go/agentconfig          0.072s
ok  iop/packages/go/agentguard           0.035s
ok  iop/packages/go/agentpolicy          0.034s
ok  iop/packages/go/agentprovider/catalog 0.132s
ok  iop/packages/go/agentprovider/cli         40.185s
ok  iop/packages/go/agentprovider/cli/status  44.385s
ok  iop/packages/go/agentruntime               1.121s
ok  iop/packages/go/agentstate                 0.294s
ok  iop/packages/go/agenttask                  0.331s
ok  iop/packages/go/agentworkspace             9.568s
ok  iop/packages/go/audit                      0.030s
ok  iop/packages/go/config                     0.190s
ok  iop/packages/go/hostsetup                  0.063s
ok  iop/packages/go/observability              0.027s
ok  iop/packages/go/streamgate                 1.073s
exit status 0
```

### Vet

```bash
go vet ./packages/go/agentstate ./packages/go/agenttask
```

```text
No output.
exit status 0
```

### Formatting

```bash
gofmt -d packages/go/agenttask/ports.go packages/go/agenttask/intent.go packages/go/agenttask/manager.go packages/go/agenttask/reconcile.go packages/go/agenttask/dispatch.go packages/go/agenttask/review.go packages/go/agenttask/integration_queue.go packages/go/agenttask/test_support_test.go packages/go/agenttask/manager_test.go packages/go/agenttask/integration_queue_test.go
```

```text
No output; all listed files are gofmt-clean.
exit status 0
```

### Contract conformance

```bash
rg --sort path -n 'Every external result|only exact tokens|atomic fence' agent-contract/inner/agent-runtime.md agent-contract/inner/iop-agent-cli-runtime.md
```

```text
agent-contract/inner/agent-runtime.md:57: Every external result ... atomic fence ... only exact tokens ...
agent-contract/inner/iop-agent-cli-runtime.md:63: Every external result ... atomic fence ... only exact tokens ...
exit status 0
```

### Diff check

```bash
git diff --check
```

```text
No output.
exit status 0
```

---

> **[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 |
| Agent UI Completion | Mixed | Present only for plan-required agent-ui code work; implementing agent fills actual evidence, review agent applies `implemented` status/evidence update on PASS and copies the section into `complete.log` |
| 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

| Dimension | Assessment | Evidence |
|---|---|---|
| Correctness | Fail | Reconciliation releases a project claim after a foreign workspace conflict but leaves that released claim in the live `leaseSet`; the next independent project is rejected with `ErrLeaseLost`. |
| Completeness | Fail | The exact-claim lifecycle is incomplete for early project release paths, so tracked durable claims and the supervisor's live claim set can diverge. |
| Test coverage | Fail | The focused matrix covers renewal, immediate external-result fencing, CAS retry, cleanup, and successor retention, but it does not cover a project-local workspace conflict followed by an independent project in the same reconciliation. |
| API contract | Fail | `iop.agent-runtime` requires project-local blockers not to stop another project, while the reproduced stale tracked claim aborts reconciliation before the independent project runs. |
| Code quality | Pass | The atomic CAS fence, immutable claim handles, renewal supervisor, and exact-token release helpers are readable and otherwise aligned with the intended design. |
| Implementation deviation | Fail | The plan requires dynamic claims to be removed before exact release; the early project release at `reconcile.go:76` releases durable state without removing the same handle from `leaseSet`. |
| Verification trust | Pass | Fresh reviewer runs reproduced all claimed focused, repeated, race, shared-package, vet, formatting, proto, contract-search, and diff-check results. The failure is an uncovered behavior rather than contradicted evidence. |
| Spec conformance | Fail | SDD S09 requires singular ownership without duplicate execution and exact retained state; a project-local ownership conflict currently prevents an unrelated project from continuing. |

### Findings

- Required — `packages/go/agenttask/reconcile.go:58` and `packages/go/agenttask/reconcile.go:76`: after adding `projectClaim` to `leaseSet`, the foreign-workspace branch releases that claim in durable state but never removes it from the tracked set. On the next project iteration, `leases.Validate` observes the intentionally released token as lost and returns a reconciliation-wide `ErrLeaseLost`, violating `agent-contract/inner/agent-runtime.md:70`. A focused reviewer reproducer started `a-blocked` and `b-independent`, installed a foreign lease only for `workspace-a`, and failed with `agenttask lease ownership lost during operation: project lease a-blocked no longer matches`; `b-independent` never ran. Remove the captured claim from `leaseSet` before every early exact release, use the unfenced exact-token release helper, and add a deterministic two-project regression proving the blocked project remains local while the independent project completes.

### Routing Signals

- `review_rework_count=3`
- `evidence_integrity_failure=false`

### Next Step

- Invoke the plan skill in `prepare-follow-up` mode with this Required finding and fresh reviewer evidence, then archive the current pair and materialize the freshly routed follow-up pair.
