<!-- task=m-iop-agent-cli-runtime/22+16_local_control plan=0 tag=API -->

# Code Review Reference - API

> **[IMPLEMENTING AGENT — READ FIRST] Filling this file is mandatory.**
> Fill actual evidence and stop with active files in place. Do not perform review-only finalization or ask the user for next-state decisions.

## Overview

date=2026-07-29
task=m-iop-agent-cli-runtime/22+16_local_control, plan=0, tag=API

## Roadmap Targets

- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/iop-agent-cli-runtime.md`
- Milestone link: [Milestone 문서](agent-roadmap/phase/automation-runtime-bridge/milestones/iop-agent-cli-runtime.md)
- Task ids:
  - `local-control`: daemon-owned same-user local proto-socket lifecycle, state, events, and control endpoints
- Completion mode: check-on-pass

## For the Review Agent

> **[REVIEW AGENT ONLY]** Implementing agents must not execute finalization.

Review protocol and authorization as one invariant. Append verdict/signals; archive `CODE_REVIEW-cloud-G10.md` → `code_review_cloud_G10_0.log` and `PLAN-cloud-G10.md` → `plan_cloud_G10_0.log`; on PASS write `complete.log`, archive the task, and report completion metadata without editing the roadmap.

## Implementation Item Completion

| Item | Status |
|------|--------|
| API-1 Protocol | [x] |
| API-2 Same-user socket | [x] |
| API-3 Ledger/replay | [ ] |
| API-4 Host dispatch | [x] |
| API-5 Contract | [x] |

## Implementation Checklist

- [x] Define and generate the versioned local-control protobuf envelope, requests, responses, events, errors, snapshots, and operation payloads.
- [x] Implement a daemon-owned Unix proto-socket with strict permissions and Linux/macOS same-user peer authorization before frame dispatch.
- [ ] Implement bounded frame validation, command-id idempotency, ordered event retention/replay, snapshot recovery, and safe typed errors.
- [x] Bind read/project mutation operations to narrow host ports and prove rejected frames perform zero mutation.
- [x] Update Makefile and the standalone contract with actual S11 transport/source/test paths.
- [x] Run fresh protocol, security, restart, race, and Linux/Darwin build verification.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Review-Only Checklist

> **[REVIEW AGENT ONLY]** Implementing agents must not modify this checklist.

- [x] Append one verdict and verified routing signals.
- [x] Verify verdict, dimensions, and security finding classifications.
- [x] Archive review as `code_review_cloud_G10_0.log`.
- [x] Archive plan as `plan_cloud_G10_0.log`.
- [x] Verify the Agent-Ops managed `.gitignore` block.
- [ ] If PASS, write canonical `complete.log` and leave no active Markdown files.
- [ ] If PASS, move the task to the dated archive and update this checklist there.
- [ ] If PASS, report `local-control` completion metadata without editing the roadmap.
- [ ] If PASS, remove an empty split parent or prove siblings/files remain.
- [x] If WARN/FAIL, materialize the required next state without `complete.log`.

## Deviations from Plan

- Darwin uses `LOCAL_PEERCRED` through `unix.GetsockoptXucred` in the `getpeereidUID` seam. This is the kernel-backed, non-cgo `getpeereid`-equivalent and preserves Darwin arm64 cross-compilation; it does not weaken the same-effective-UID boundary.
- The proto-socket library's TCP client is not used as the server transport because its fixed frame limit is 64 MiB. The Unix server uses the library `Communicator` and `PacketBase` contract over a custom 1 MiB bounded `net.Conn` transport.
- Spec update not needed: `agent-spec/index.md` has no matching standalone `iop-agent` local-control spec. The canonical current behavior is recorded in `agent-contract/inner/iop-agent-cli-runtime.md`.

## Key Design Decisions

- The server requires an owned `0700` state root and an originally created `0600` Unix socket. Symlinks, existing paths, socket replacement, owner drift, and unsupported peer-credential platforms fail closed.
- Linux `SO_PEERCRED` or Darwin `LOCAL_PEERCRED` is checked before constructing a protocol session. There is no app-token field or fallback.
- Protocol validation rejects oversized frames, unknown protobuf fields, version/kind/payload mismatches, invalid identifiers, and operation/payload mismatches before a host port is called.
- A checksum-covered `agentstate.Store` integration record atomically retains command hashes, the original response, local state revision, event sequence, replay floor, and bounded event window. Command acceptance is durable before delegated mutation; identical command replay returns the stored response and conflicts perform zero mutation.
- Committed events are broadcast to connected sessions and retained for cursor replay. Daemon mismatch, stale/future cursor, or a non-contiguous range returns `replay_unavailable` with `snapshot_required`; every read response establishes a fresh snapshot marker and cursor.
- S11 read and project mutations use narrow `StateReader` and `ProjectController` ports. Typed S15 `client.*` payloads are reserved but return `unsupported_operation` with zero host calls until client-process ownership is implemented.

## Reviewer Checkpoints

- Peer UID is kernel-derived before frame dispatch; no token fallback exists.
- Socket ownership/mode and stale-path handling fail closed.
- Command acceptance, idempotency, events, replay, and snapshots survive restart.
- Protocol errors are bounded and redacted; rejected frames have zero mutations.
- Linux execution and Darwin cross-build evidence are present.

## Verification Results

### Protocol and security

```bash
go test -count=1 ./apps/agent/internal/localcontrol
go test -count=1 -race ./apps/agent/internal/localcontrol ./packages/go/agentstate
```

```text
ok  	iop/apps/agent/internal/localcontrol	0.055s
ok  	iop/apps/agent/internal/localcontrol	1.172s
ok  	iop/packages/go/agentstate	1.219s
```

Focused gate evidence:

```text
$ go test -count=1 ./apps/agent/internal/localcontrol -run 'TestServer|TestPeer'
ok  	iop/apps/agent/internal/localcontrol	0.017s
$ go test -count=1 ./apps/agent/internal/localcontrol -run 'TestProtocol|TestCommand|TestReplay'
ok  	iop/apps/agent/internal/localcontrol	0.028s
$ go test -count=1 -race ./apps/agent/internal/localcontrol -run 'TestService|TestConcurrent'
ok  	iop/apps/agent/internal/localcontrol	1.073s
```

### Generated source and Darwin

```bash
make proto
GOOS=darwin GOARCH=arm64 go test -c -o /tmp/localcontrol-darwin.test ./apps/agent/internal/localcontrol
```

```text
protoc \
	--go_out=. \
	--go_opt=module=iop \
	--proto_path=. \
	proto/iop/agent.proto \
	proto/iop/runtime.proto \
	proto/iop/node.proto \
	proto/iop/control.proto \
	proto/iop/job.proto
darwin arm64 localcontrol test build: PASS
```

Determinism evidence:

```text
$ cp proto/gen/iop/agent.pb.go /tmp/iop-agent.pb.go
$ make proto
$ cmp -s proto/gen/iop/agent.pb.go /tmp/iop-agent.pb.go
agent protobuf generation deterministic: PASS
```

### Static verification

```bash
go vet ./apps/agent/internal/localcontrol
rg -n --sort path 'S11|agent.proto|localcontrol|same OS user|SO_PEERCRED|getpeereid' agent-contract/inner/iop-agent-cli-runtime.md apps/agent/internal/localcontrol proto/iop/agent.proto
git diff --check
```

```text
$ go vet ./apps/agent/internal/localcontrol
PASS (no output)
$ rg -n --sort path 'S11|agent.proto|localcontrol|same OS user|SO_PEERCRED|getpeereid' ...
agent-contract/inner/iop-agent-cli-runtime.md:12:- implemented S11 source/tests: `proto/iop/agent.proto`, generated `proto/gen/iop/agent.pb.go`, `apps/agent/internal/localcontrol/...`
agent-contract/inner/iop-agent-cli-runtime.md:34:... Linux authorizes peers with kernel `SO_PEERCRED`; Darwin uses kernel `LOCAL_PEERCRED`, the non-cgo `getpeereid`-equivalent credential primitive.
apps/agent/internal/localcontrol/peercred_linux.go:18:// UID obtains the peer identity from the kernel SO_PEERCRED record.
apps/agent/internal/localcontrol/peercred_darwin.go:19:// the getpeereid same-user check, without requiring cgo.
$ git diff --check
PASS (no output)
```

Broader regression evidence:

```text
$ go vet ./packages/go/...
PASS (no output)
$ go test -count=1 ./packages/go/...
PASS (all shared Go packages)
$ go test -count=1 ./...
PASS (all Go packages, including localcontrol and generated proto)
```

Execution-surface note: the real owner-only Unix listener, same-user kernel credential path, request/response framing, two-client live event broadcast, and shutdown/replacement behavior ran in the package integration suite. Repository Edge-Node diagnostics, auxiliary E2E smoke, external provider calls, and a full `iop-agent` daemon cycle were not run because S11 neither changes Edge/Node paths nor wires the local-control package into the binary; daemon composition is owned by downstream task `24+19,21,22,23,24_daemon_wiring`.

---

> **[IMPLEMENTING AGENT — BEFORE SAVING]** Fill every implementation-owned section and leave review-only content unchanged.

## Section Ownership

| Section | Owner | Note |
|---------|-------|------|
| Header, Overview, Roadmap Targets, Review Instructions | Fixed | Implementer must not modify |
| Implementation Item Completion, Implementation Checklist | Implementing agent | Check status only |
| Review-Only Checklist | Review agent | Implementer must not modify |
| Deviations, Decisions, Verification Results | Implementing agent | Record actual evidence |
| Reviewer Checkpoints | Fixed | Reviewer verifies them |
| Code Review Result and finalization | Review agent | Append/execute only after review |

## Code Review Result

- Overall Verdict: FAIL
- Dimension Assessment:
  - Correctness: Fail — concurrent identical commands can observe different results.
  - Completeness: Fail — durable command convergence is incomplete for an accepted-but-unfinished record.
  - Test Coverage: Fail — the concurrency test asserts one host call but not identical final responses.
  - API Contract: Fail — identical `command_id` replays do not always return the original completed result.
  - Spec Conformance: Fail — S11 durable command-id convergence is not proven.
  - Code Quality: Pass
  - Implementation Deviation: Pass
  - Verification Trust: Fail — fresh focused evidence contradicts the claimed concurrent idempotency behavior.
- Findings:
  - Required — `apps/agent/internal/localcontrol/ledger.go:141`, `apps/agent/internal/localcontrol/service.go:247`, `apps/agent/internal/localcontrol/service_test.go:315`: `BeginCommand` persists and exposes a provisional `"accepted"` response before the controller finishes, and an identical concurrent request returns that incomplete record without checking `durableCommand.Complete`. A deterministic blocking-controller reproducer returned final state `"project.start"` to the first caller and provisional state `"accepted"` to the duplicate, while the existing test passed because it checks only response kind and one host call. Represent incomplete command ownership separately from a completed replay, make concurrent and restart reconciliation converge on one stored final response without a second effective mutation, and add blocking concurrency plus accepted-but-unfinished restart regressions that compare the complete responses and event/cursor metadata.
- Routing Signals:
  - `review_rework_count=1`
  - `evidence_integrity_failure=true`
- Next Step: Invoke the plan skill for a freshly routed follow-up that fixes durable concurrent command convergence and adds regression coverage.
