<!-- task=m-iop-owned-single-request-agent-execution/11+10_workspace_command plan=1 tag=API milestone-task=tool-executor -->

# Code Review Reference - 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.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> 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-08-06
task=m-iop-owned-single-request-agent-execution/11+10_workspace_command, plan=1, tag=API

## Archive Evidence Snapshot

- The first-pass pair is preserved at `agent-task/m-iop-owned-single-request-agent-execution/11+10_workspace_command/plan_cloud_G08_0.log` and `agent-task/m-iop-owned-single-request-agent-execution/11+10_workspace_command/code_review_cloud_G10_0.log`; it contains no implementation evidence or review verdict.
- Self-review found that assigning `cmd.Dir` to the configured path re-resolves that path at process start and can leave the admitted workspace after a rename/replacement. Plan 1 requires an internal child-launch shim to `fchdir` packet 10's opened root descriptor before executing the fixed template and fails before target start when identity cannot be preserved.

## 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-G10.md` → `code_review_cloud_G10_1.log` and `PLAN-cloud-G09.md` → `plan_cloud_G09_1.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/11+10_workspace_command/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve the first-line `milestone-task=tool-executor` metadata in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.

---

## Implementation Item Completion

| Item | Status |
|------|---------|
| API-1 Implement exact-template process execution | [x] |
| API-2 Activate typed command and cancel handling | [x] |

## Implementation Checklist

- [x] Resolve only operator-defined command ids to absolute executable/fixed args, enter the opened admitted root with an internal `fchdir`/`exec` shim, and build a minimal allowlisted environment.
- [x] Own Unix process groups with one terminal result across exit, timeout, context cancel, explicit cancel, and shared stdout/stderr truncation races.
- [x] Integrate command/cancel into the workspace runtime and Node handler without touching provider cancellation or permitting shell/PTY/arbitrary argv.
- [x] Prove success/nonzero/timeout/cancel/group-child/output/env/cross-request behavior plus root rename/replacement resistance, and synchronize command contract/spec limits.
- [x] Run dependency, focused race, package, vet, cross-build, documentation, and whitespace verification.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Review-Only Checklist

> **[REVIEW AGENT ONLY]** Implementers must not modify/check this section.

- [x] Append verdict, routing signals, dimensions, and findings.
- [x] Archive the active pair to routed suffix `1` logs.
- [x] Verify managed `.gitignore` entries.
- [ ] On PASS write `complete.log`, preserve/report Milestone metadata, move the directory, and keep the active parent while siblings remain.
- [x] On WARN/FAIL write only the required next state.

## Deviations from Plan

- No implementation or verification command deviations.
- Supplemental local Node profile checks also passed: `go test -count=1 ./apps/node/...` and `go vet ./apps/node/...`.
- The credentialed Mac/Claude full-cycle smoke was not part of this isolated packet's verification contract and was not run in the local Linux environment.

## Key Design Decisions

- The runtime copies immutable command templates and environment-name authority from the Node-private catalog. A tool request can select only an admitted command id, allowlisted environment entries, and a timeout no greater than the frozen request cap.
- The parent launches its current trusted Node/test executable as a short-lived internal shim. A bounded versioned record and a duplicate of the admitted root descriptor cross inherited pipes; the shim verifies device/inode, calls `fchdir`, closes control descriptors, and `exec`s the fixed target without `cmd.Dir`, a shell, PTY, or ambient environment.
- One owner waits for pre-exec status, process exit, timeout, context cancel, or explicit exact request/tool cancel. Cancellation kills the entire process group, and duplicate explicit cancellation remains idempotent for the open request lifecycle.
- Stdout and stderr remain separate typed fields but share one synchronized retained-byte budget. Overflow is discarded while both streams continue draining, preventing pipe backpressure deadlocks.

## Reviewer Checkpoints

- Confirm executable and args come only from the approved template; caller supplies no shell/arbitrary argv.
- Confirm the internal shim validates the opened admitted directory descriptor, calls `fchdir`, then replaces itself with only the fixed target; path rename/replacement cannot redirect it, malformed control cannot start a target, and no ambient secret is inherited.
- Confirm one wait/result owner and entire process-group termination for every cancel/timeout race.
- Confirm stdout/stderr share a cap while overflow drains, and cross-request cancel cannot kill another group.

## Verification Results

Paste actual stdout/stderr for each command; record replacements under deviations.

### 1. Dependency

`test -f agent-task/m-iop-owned-single-request-agent-execution/10+09_workspace_files/complete.log || test "$(compgen -G 'agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/10+09_workspace_files/complete.log' | wc -l)" -eq 1`

```text
(no stdout/stderr; exit 0)
```

### 2. Process race tests

`go test -race ./apps/node/internal/workspace -run 'Test(CommandExecutor|WorkspaceCommandHelperProcess)' -count=1`

```text
ok  	iop/apps/node/internal/workspace	5.505s
```

### 3. Handler race tests

`go test -race ./apps/node/internal/node -run 'TestNodeWorkspace(Command|Cancel)' -count=1`

```text
ok  	iop/apps/node/internal/node	2.258s
```

### 4. Package regression

`go test ./apps/node/internal/workspace ./apps/node/internal/node ./apps/node/internal/transport ./apps/node/cmd/node -count=1`

```text
ok  	iop/apps/node/internal/workspace	0.510s
ok  	iop/apps/node/internal/node	0.989s
ok  	iop/apps/node/internal/transport	5.584s
ok  	iop/apps/node/cmd/node	0.059s
```

### 5. Vet

`go vet ./apps/node/internal/workspace ./apps/node/internal/node ./apps/node/cmd/node`

```text
(no stdout/stderr; exit 0)
```

### 6. Darwin compile

`GOOS=darwin GOARCH=arm64 go test -c -o /tmp/iop-workspace-command-darwin.test ./apps/node/internal/workspace`

```text
(no stdout/stderr; exit 0)
```

### 7. Contract/spec search

`rg --sort path -n 'command id|fixed args|fchdir|exec|cwd|process group|environment allowlist|stdout|stderr|PTY|shell' agent-contract/inner/edge-node-runtime-wire.md agent-spec/runtime/edge-node-execution.md`

```text
agent-contract/inner/edge-node-runtime-wire.md:91:- `WorkspaceToolRequest`: permits only the closed operation enum and typed input. A structured write carries `relative_path` plus bounded `content`; legacy `write_content` remains wire-compatible but is incomplete and rejected for WRITE. COMMAND carries only an admitted `command_id`, a positive timeout no greater than the frozen request cap, and environment entries whose names are in the Node-private operator allowlist. The request contains no caller-selected Node, root, executable, argv, shell, or arbitrary environment name.
agent-contract/inner/edge-node-runtime-wire.md:92:- `Workspace*Response`: returns closed status/error-code enums and bounded content/list/stdout/stderr/exit/truncation/duration fields. Command stdout and stderr retain separate fields but consume one shared byte budget; overflow is discarded while both pipes continue draining, and `truncated=true` records any discarded byte. Transport and handler failures use stable generic errors and do not echo workspace paths, command details, content, environment values, or credentials.
agent-contract/inner/edge-node-runtime-wire.md:115:- Workspace COMMAND never accepts a shell expression, caller argv, PTY, interactive terminal, persistent process session, or caller-selected cwd. Provider run cancellation and workspace command cancellation remain separate identity spaces and handlers.
agent-contract/inner/edge-node-runtime-wire.md:126:- COMMAND resolves only an admitted command id to the immutable Node-private absolute executable and fixed args. The parent launches only its own trusted Node/test executable in an internal mode, passes a bounded versioned launch record plus a duplicate of the already-opened root descriptor, and sets a new Unix process group. The shim verifies the descriptor device/inode, calls `fchdir`, closes control descriptors, and uses `exec` to replace itself with the fixed target. It never uses `cmd.Dir`, reopens the configured root path, invokes a shell, or inherits the ambient Node environment.
agent-contract/inner/edge-node-runtime-wire.md:128:- One command owner arbitrates normal exit, non-zero exit, pre-exec failure, timeout, context cancellation, and explicit cancellation. Timeout or cancellation terminates the complete process group and waits for pipe drain/process reap before returning one terminal typed result. Explicit cancel addresses only `(request_id, tool_call_id)`; duplicate cancel remains idempotent for that request lifecycle, and a foreign request/tool identity returns typed not-found without signaling another process.
agent-spec/runtime/edge-node-execution.md:151:| workspace tool executor | A validated Darwin Node catalog owns opened root and directory handles. Go 1.24-compatible no-follow file primitives provide bounded read, bounded list, structured write, and non-recursive delete. Exact operator-owned command templates run through an inherited-root `fchdir`/`exec` shim with minimal allowlisted environment, shared stdout/stderr bounds, process-group timeout/cancel, and stable typed results. Artifact cleanup remains deferred. |
agent-spec/runtime/edge-node-execution.md:241:- Workspace admission and the private wire both fence the exact ready connection generation. The wire never exposes workspace fields through provider `RunRequest`, `NodeCommand`, or public API output. The executor exposes no caller access to `.iop`; only request-owned internal runtime code can derive `.iop/job/<request_id>`. Structured write input is required for WRITE, while legacy content-only input remains rejected. COMMAND is non-interactive and has no shell, PTY, arbitrary argv, ambient environment, path-based cwd lookup, or persistent process ownership. Request artifact cleanup remains deferred to its scheduled packet.
(additional matches from the same two documents omitted; exit 0)
```

### 8. Whitespace

`git diff --check`

```text
(no stdout/stderr; exit 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) |
| 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
- **Finding Counts:** Required 2, Suggested 0, Nit 0

### Dimension Assessment

| Dimension | Assessment | Evidence |
|-----------|------------|----------|
| Correctness | Fail | Legitimate Node command failures and successful cancel acknowledgements are rejected by the Edge response validator. |
| Completeness | Fail | The connected Edge consumer was not aligned with the newly implemented Node terminal-response shapes. |
| Test coverage | Fail | No regression exercises actual Node-produced terminal responses through Edge validation, and context cancellation is tested only before process start. |
| API contract | Fail | Node emits typed non-success status/error-code pairs that the Edge wire currently forbids. |
| Code quality | Pass | The reviewed implementation is structured, bounded, and free of review-blocking debug or dead-code residue. |
| Implementation deviation | Fail | Milestone S05 requires stable typed workspace outcomes across the Edge-Node boundary, but the packet stops at Node-local handling. |
| Verification trust | Pass | Fresh reviewer reruns matched the recorded focused results; the gap is semantic coverage, not fabricated evidence. |
| Spec conformance | Fail | Typed command failure, timeout, and cancellation outcomes do not survive the documented private wire boundary. |

### Findings

- **Required R1** — `apps/edge/internal/service/workspace_wire.go:230` accepts only `SUCCESS/UNSPECIFIED/empty-error` tool responses, while `apps/node/internal/node/workspace_handler.go:94` emits typed non-success command outcomes; `apps/edge/internal/service/workspace_wire.go:242` likewise requires `CANCELLED/UNSPECIFIED/empty-error`, while `apps/node/internal/node/workspace_handler.go:112` emits `CANCELLED/CANCELLED` with a stable message. Consequently, real non-zero, timeout, context/explicit cancellation, and successful cancel acknowledgements are rejected as malformed and their bounded typed evidence is discarded. Align the producer/consumer terminal-pair contract, continue rejecting contradictory pairs and raw Node text, and add Edge-Node boundary regressions for success, non-zero exit, timeout, cancellation, and cancel acknowledgement.
- **Required R2** — `apps/node/internal/workspace/command_executor_test.go:176` calls `cancel()` before `ExecuteCommand`, so it proves only pre-start rejection and does not verify the plan's required active-context-cancel process-group termination. Start a blocking helper and descendant, wait for the start sentinel, cancel the live context, then assert the typed `CANCELLED` result and that the entire descendant process group is gone/reaped.

### Routing Signals

- `review_rework_count=1`
- `evidence_integrity_failure=false`

### Next Step

- Prepare and execute a routed `REVIEW_API` follow-up plan that directly fixes Required R1 and R2; no user-review gate applies.
