feat(epic): plan-work-review 작업을 준비한다

This commit is contained in:
toki 2026-08-07 08:17:18 +09:00
parent 3bb4a24ad7
commit f4dad6ba88
14 changed files with 2906 additions and 0 deletions

View file

@ -0,0 +1,187 @@
<!-- task=m-iop-owned-single-request-agent-execution/17_internal_artifact_wire plan=0 tag=API milestone-task=plan-stage,work-stage,review-stage -->
# 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-07
task=m-iop-owned-single-request-agent-execution/17_internal_artifact_wire, plan=0, tag=API
## 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-G09.md``code_review_cloud_G09_0.log` and `PLAN-cloud-G09.md``plan_cloud_G09_0.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/17_internal_artifact_wire/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=plan-stage,work-stage,review-stage` 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 Define the closed artifact protocol and canonical terminals | [ ] |
| API-2 Implement Node-owned artifact access | [ ] |
| API-3 Make artifacts part of coordinator lifecycle ownership | [ ] |
| API-4 Synchronize the implemented contract and spec | [ ] |
## Implementation Checklist
- [ ] Add and regenerate the closed request-owned PLAN/REVIEW artifact protobuf family, including Go and Dart generated bindings.
- [ ] Implement bounded Node internal artifact read/write handling and typed transport dispatch without exposing `.iop` to model workspace tools.
- [ ] Integrate artifact access into the Edge wire and `SingleRequestController`, preserving one workspace open, exact admitted Node generation, terminal cleanup, cancellation, bounds, and raw-error redaction.
- [ ] Update the inner runtime contract and current implementation spec, then run focused, race, broader Edge/Node/shared, generation, client, vet, and diff checks.
- [ ] 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.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G09_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_0.log`.
- [ ] 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-owned-single-request-agent-execution/17_internal_artifact_wire/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/17_internal_artifact_wire/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=plan-stage,work-stage,review-stage` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Confirm the wire accepts only enum-selected `PLAN`/`REVIEW` artifacts and never extends public `WorkspaceToolRequest` path authority.
- Confirm Node reads compare the inventoried device/inode/type through descriptor-relative no-follow operations and both directions enforce size caps.
- Confirm artifact-first, tool-after-artifact, cancel, terminal, stale-generation, and malformed-response paths preserve one open and one cleanup without raw error/path leakage.
- Confirm protobuf bindings are generator output and contract/spec text does not claim Plan/Work/Review provider drivers or actual Claude qualification.
## Verification Results
Paste actual stdout/stderr for every command. If a command changes, record the replacement and reason in `Deviations from Plan` before pasting its output.
### 1. Protobuf generation
`make proto && make proto-dart`
Expected: both generators exit zero and tracked Go/Dart bindings reflect the source schema.
```text
_Paste actual output here._
```
### 2. Focused cross-boundary tests
`go test ./packages/go/workspaceprotocol ./apps/node/internal/workspace ./apps/node/internal/node ./apps/node/internal/transport ./apps/edge/internal/transport ./apps/edge/internal/service -count=1`
Expected: all focused packages pass freshly.
```text
_Paste actual output here._
```
### 3. Race verification
`go test -race ./apps/edge/internal/service ./apps/node/internal/transport -run 'Test.*(WorkspaceArtifact|SingleRequestArtifact)' -count=1`
Expected: artifact lifecycle/correlation tests pass with no race report.
```text
_Paste actual output here._
```
### 4. Vet
`go vet ./packages/go/... && go vet ./apps/node/... && go vet ./apps/edge/internal/service`
Expected: relevant shared, Node, and Edge packages vet cleanly.
```text
_Paste actual output here._
```
### 5. Broader regressions
`go test ./packages/go/... ./apps/node/... ./apps/edge/... -count=1`
Expected: all shared and consumer packages pass freshly.
```text
_Paste actual output here._
```
### 6. Client generated-binding check
`make client-test`
Expected: generated Dart bindings compile and all Flutter tests pass.
```text
_Paste actual output here._
```
### 7. Boundary search
`rg --sort path -n 'WorkspaceArtifact|plan\.md|review\.md' proto/iop/runtime.proto apps/edge apps/node packages/go/workspaceprotocol agent-contract/inner/edge-node-runtime-wire.md agent-spec/runtime/edge-node-execution.md`
Expected: results are confined to the private artifact/runtime boundary and its tests/docs.
```text
_Paste actual output here._
```
### 8. Diff hygiene
`git diff --check`
Expected: exit zero with no output.
```text
_Paste actual output here._
```
External note: actual Claude/Mac full-cycle evidence is intentionally owned by SDD S12 and Milestone task `claude-smoke`, not this packet.
---
> **[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 |

View file

@ -0,0 +1,309 @@
<!-- task=m-iop-owned-single-request-agent-execution/17_internal_artifact_wire plan=0 tag=API milestone-task=plan-stage,work-stage,review-stage -->
# Request-owned internal artifact wire
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
The coordinator can create request-owned Node workspace state only as a side effect of a model tool call, while SDD S08 requires the planner to persist `plan.md` before Work begins. The existing `WriteInternalArtifact` helper is Node-local and has no read path or typed Edge-Node contract. This packet adds a closed plan/review artifact family and integrates it with coordinator workspace-open and cleanup ownership without allowing model tools to name `.iop`.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-ops/rules/project/rules.md`
- `agent-ops/rules/common/rules-roadmap.md`
- `agent-ops/rules/common/rules-agent-spec.md`
- `agent-ops/rules/project/domain/client/rules.md`
- `agent-ops/rules/project/domain/edge/rules.md`
- `agent-ops/rules/project/domain/node/rules.md`
- `agent-ops/rules/project/domain/platform-common/rules.md`
- `agent-ops/rules/project/domain/testing/rules.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/inner/edge-node-runtime-wire.md`
- `proto/iop/runtime.proto`
- `proto/gen/iop/runtime.pb.go`
- `apps/client/lib/gen/proto/iop/runtime.pb.dart`
- `apps/client/lib/gen/proto/iop/runtime.pbenum.dart`
- `apps/client/lib/gen/proto/iop/runtime.pbjson.dart`
- `apps/node/internal/workspace/runtime.go`
- `apps/node/internal/workspace/cleanup.go`
- `apps/node/internal/workspace/cleanup_path_unix.go`
- `apps/node/internal/workspace/cleanup_path_other.go`
- `apps/node/internal/node/workspace_handler.go`
- `apps/node/internal/transport/parser.go`
- `apps/node/internal/transport/session.go`
- `apps/edge/internal/transport/server.go`
- `apps/edge/internal/service/workspace_wire.go`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `packages/go/workspaceprotocol/terminal.go`
- `packages/go/workspaceprotocol/terminal_test.go`
- `apps/node/internal/workspace/cleanup_test.go`
- `apps/node/internal/node/workspace_handler_test.go`
- `apps/node/internal/transport/parser_test.go`
- `apps/node/internal/transport/session_test.go`
- `apps/edge/internal/transport/server_test.go`
- `apps/edge/internal/service/workspace_wire_test.go`
- `apps/edge/internal/service/single_request_test.go`
- `apps/edge/internal/service/single_request_cleanup_test.go`
- `apps/edge/internal/service/single_request_tool_loop_test.go`
### SDD Criteria
- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`, `[승인됨]`, `SDD 잠금: 해제`.
- First-line contribution ids: `plan-stage,work-stage,review-stage`.
- Targeted scenarios: S08 needs an empty request job and internal `plan.md` write; S09 needs Work to read the plan; S10 needs durable review evidence before finalization.
- Evidence Map drivers: the S08 plan artifact fixture, S09 plan-read/work fixture, and S10 review pass/repair artifact fixture. They require a reserved artifact kind, bounded read/write, identity echo validation, and cleanup evidence in this foundation packet; stage-specific provider assertions remain in dependent packets.
### Verification Context
- No verification handoff was supplied. Repository-native sources were `agent-test/local/rules.md`, `client-smoke.md`, `edge-smoke.md`, `node-smoke.md`, and `platform-common-smoke.md` plus the Makefile `proto`/`proto-dart` targets.
- Preflight: branch `feature/iop-owned-single-request-agent-execution`, HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`, clean worktree; Go `1.26.2 linux/arm64`, protoc `29.3`, `protoc-gen-go`, `protoc-gen-dart`, and Flutter `3.41.5` are available.
- Baseline command passed: `go test ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input ./apps/edge/internal/transport ./apps/node/internal/workspace ./apps/node/internal/node ./apps/node/internal/transport ./packages/go/workspaceprotocol -count=1`.
- Constraints: local deterministic tests use ephemeral connections and temporary directories; no provider endpoint or credential is required. Actual Claude/Mac qualification is owned by SDD S12 `claude-smoke` and is not completion evidence for this packet.
- Confidence: high. Current source already owns secure artifact creation and exact cleanup inventory; the missing pieces are a bounded read primitive, a closed wire family, and coordinator lifecycle integration.
### Test Coverage Gaps
- Existing cleanup tests cover write inventory, exact-tree cleanup, identity replacement, sibling isolation, and cancellation, but do not cover internal reads.
- Existing Node handler and transport tests cover open/tool/cancel/cleanup families, but no reserved artifact request/response.
- Existing Edge wire tests cover stale-generation fencing, canonical response triples, timeout, and raw-error redaction, but no artifact kind/content bounds.
- Existing coordinator cleanup tests cover tool-triggered open only; they do not prove artifact-triggered open, one cleanup, or cancellation races. All four gaps receive deterministic tests in this packet.
### Symbol References
No symbol is renamed or removed. `SingleRequestController` at `apps/edge/internal/service/single_request.go:69` gains methods; its only production implementation is `singleRequestHandle`, and repository search found no test fake that directly implements the interface.
### Split Judgment
- `17_internal_artifact_wire`: stable contract is a closed `PLAN`/`REVIEW` artifact read/write wire plus coordinator-owned open/cleanup; PASS is proto regeneration and cross-Edge/Node lifecycle tests. No new sibling predecessor is required.
- `18+17_plan_stage`: consumes this contract to write the plan artifact.
- `19+18_work_stage`: consumes the completed plan runner and artifact read.
- `20+19_review_stage`: consumes Work to persist review evidence and activate the composite executor.
- Indices 01-16 are occupied by archived siblings under the same task group; only directory basenames were inspected for collision-free allocation, not archive contents.
### Scope Rationale
This packet does not implement provider prompts, provider response decoding, Work tool policy, Review repair, production executor installation, the `error-cancel` task, or actual Claude qualification. It does not expose arbitrary internal paths: the wire carries an enum for `PLAN` or `REVIEW`, and Node alone maps that enum to `plan.md` or `review.md`. Public workspace tools continue to reject `.iop` paths.
### Final Routing
- `evaluation_mode=first-pass`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures: scope/context/verification/evidence/ownership/decision all true. Scores `2/2/2/1/2` => G09, base/route `grade-boundary`, `worker/cloud/G09`, `PLAN-cloud-G09.md`.
- Review closures: all true. Scores `2/2/2/1/2` => G09, `official-review`, `review/cloud/G09`, `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`; positive loop risks: `temporal_state`, `concurrent_consistency`, `boundary_contract` (3); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Implementation Checklist
- [ ] Add and regenerate the closed request-owned PLAN/REVIEW artifact protobuf family, including Go and Dart generated bindings.
- [ ] Implement bounded Node internal artifact read/write handling and typed transport dispatch without exposing `.iop` to model workspace tools.
- [ ] Integrate artifact access into the Edge wire and `SingleRequestController`, preserving one workspace open, exact admitted Node generation, terminal cleanup, cancellation, bounds, and raw-error redaction.
- [ ] Update the inner runtime contract and current implementation spec, then run focused, race, broader Edge/Node/shared, generation, client, vet, and diff checks.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Define the closed artifact protocol and canonical terminals
**Problem**
`proto/iop/runtime.proto:383-471` defines open/tool/cancel/cleanup, but it has no coordinator-only artifact family. Reusing `WorkspaceToolRequest.relative_path` would make `.iop` naming part of the model tool surface and violate SDD D08.
**Solution**
Add `WorkspaceArtifactKind` (`PLAN`, `REVIEW`) and `WorkspaceArtifactOperation` (`READ`, `WRITE`) plus request/response messages. The request contains only `request_id`, kind, operation, and bounded write content; the response echoes identity/operation and carries the canonical status triple and bounded read content. Add `ArtifactTerminal` to the shared terminal authority, then regenerate bindings only through the Makefile.
Before (`proto/iop/runtime.proto:460`):
```proto
message WorkspaceCleanupRequest {
string request_id = 1;
}
```
After:
```proto
enum WorkspaceArtifactKind { /* UNSPECIFIED, PLAN, REVIEW */ }
enum WorkspaceArtifactOperation { /* UNSPECIFIED, READ, WRITE */ }
message WorkspaceArtifactRequest { /* request_id, kind, operation, content */ }
message WorkspaceArtifactResponse { /* echoed identity, terminal triple, content */ }
```
**Modified Files and Checklist**
- [ ] Update `proto/iop/runtime.proto` without renumbering existing fields or extending `WorkspaceOperation`.
- [ ] Regenerate `proto/gen/iop/runtime.pb.go` with `make proto`.
- [ ] Regenerate `apps/client/lib/gen/proto/iop/runtime.pb.dart`, `apps/client/lib/gen/proto/iop/runtime.pbenum.dart`, and `apps/client/lib/gen/proto/iop/runtime.pbjson.dart` with `make proto-dart`; never hand-edit them.
- [ ] Add canonical artifact terminal pairs in `packages/go/workspaceprotocol/terminal.go` and table coverage in `packages/go/workspaceprotocol/terminal_test.go`.
**Test Strategy**
Write normal and boundary tests: parser round trips must retain enum numbers and bytes; canonical success/not-ready/not-found/invalid/internal outcomes must be accepted and contradictory pairs rejected.
**Verification**
Run `make proto && make proto-dart && go test ./packages/go/workspaceprotocol -count=1`; generation and tests must exit zero.
### [API-2] Implement Node-owned artifact access
**Problem**
`apps/node/internal/workspace/cleanup.go:19` can create an inventoried artifact, but there is no identity-checked read primitive. `apps/node/internal/node/workspace_handler.go:15-166` and `apps/node/internal/transport/session.go:31-237` dispatch only the four existing workspace families.
**Solution**
Add `ReadInternalArtifact` with the same request lock, cleaning fence, descriptor-relative no-follow checks, inventory identity comparison, and fixed size bound as write. Node maps the two enum kinds to fixed filenames, rejects every malformed kind/operation/content combination before filesystem effects, emits canonical generic terminals, and registers the typed request concurrently with the other workspace messages.
Before (`apps/node/internal/workspace/cleanup.go:19`):
```go
func (r *Runtime) WriteInternalArtifact(requestID, relativePath string, content []byte) error
```
After:
```go
func (r *Runtime) ReadInternalArtifact(requestID, relativePath string) ([]byte, error)
func (r *Runtime) WriteInternalArtifact(requestID, relativePath string, content []byte) error
```
**Modified Files and Checklist**
- [ ] Add the runtime read and Unix descriptor helper in `apps/node/internal/workspace/cleanup.go` and `apps/node/internal/workspace/cleanup_path_unix.go`, with the unsupported-platform stub in `apps/node/internal/workspace/cleanup_path_other.go`.
- [ ] Add `OnWorkspaceArtifact` mapping and generic canonical failures in `apps/node/internal/node/workspace_handler.go`.
- [ ] Register parser and concurrent request listener support in `apps/node/internal/transport/parser.go` and `apps/node/internal/transport/session.go`.
- [ ] Extend `apps/node/internal/workspace/cleanup_test.go`, `apps/node/internal/node/workspace_handler_test.go`, `apps/node/internal/transport/parser_test.go`, and `apps/node/internal/transport/session_test.go` with read/write, malformed, not-found, identity replacement, unsupported-handler, and disconnect/cleanup cases.
**Test Strategy**
Write `TestWorkspaceInternalArtifactReadWriteIsolation`, `TestNodeWorkspaceArtifactMapping`, `TestNodeParserMapWorkspaceArtifact`, and `TestSessionWorkspaceArtifactRequest`. Fixtures use `t.TempDir`/`net.Pipe`, assert plan/review only, prove sibling request isolation and no raw path/error leakage, and keep the public `.iop` denial assertion.
**Verification**
Run `go test ./apps/node/internal/workspace ./apps/node/internal/node ./apps/node/internal/transport -run 'Test.*(InternalArtifact|WorkspaceArtifact)' -count=1`; all focused assertions must pass freshly.
### [API-3] Make artifacts part of coordinator lifecycle ownership
**Problem**
`apps/edge/internal/service/workspace_wire.go:28-210` cannot send artifacts, and `SingleRequestController` at `apps/edge/internal/service/single_request.go:69` cannot request them. Cleanup at `single_request.go:522` only knows whether a model tool opened the workspace, so an artifact-only request could leak its `.iop/job/<request_id>` tree or race terminal cleanup.
**Solution**
Add an artifact wire method that freezes the admitted Node generation, validates every response echo and canonical terminal, and enforces `binding.Limits.MaxOutputBytes` on writes and reads. Extend the controller with typed plan/review read/write methods implemented in a cohesive `single_request_artifact.go`: it shares the existing lazy open, work accounting, wait group, request/stage deadlines, and `toolLoop.opened` cleanup gate so one request opens once and every terminal path waits for the artifact operation before one cleanup.
Before (`apps/edge/internal/service/single_request.go:69`):
```go
type SingleRequestController interface {
RequestID() string
Binding() *SingleRequestBinding
Context() context.Context
State() SingleRequestState
SubmitEnvelope(env SingleRequestEnvelope) error
}
```
After:
```go
type SingleRequestController interface {
// existing methods
ReadInternalArtifact(context.Context, SingleRequestArtifactKind) ([]byte, error)
WriteInternalArtifact(context.Context, SingleRequestArtifactKind, []byte) error
}
```
**Modified Files and Checklist**
- [ ] Add Edge response parsing in `apps/edge/internal/transport/server.go` and round-trip coverage in `apps/edge/internal/transport/server_test.go`.
- [ ] Add the fenced sender/validator in `apps/edge/internal/service/workspace_wire.go` and fixtures in `apps/edge/internal/service/workspace_wire_test.go`.
- [ ] Add the typed controller contract in `apps/edge/internal/service/single_request.go` and coordinator implementation in new `apps/edge/internal/service/single_request_artifact.go`.
- [ ] Add lifecycle/race tests in new `apps/edge/internal/service/single_request_artifact_test.go`, including artifact-first open, tool-after-artifact no second open, terminal/cancel wait, exactly-one cleanup, size rejection before send, and stale/malformed response failure.
**Test Strategy**
Write `TestWorkspaceArtifactWire` and `TestSingleRequestArtifactLifecycle` families over `net.Pipe`. Use blocked artifact responders to prove cleanup waits and cancellation terminates without duplicate open/cleanup; run the coordinator package under `-race`.
**Verification**
Run `go test -race ./apps/edge/internal/service -run 'Test(WorkspaceArtifactWire|SingleRequestArtifact)' -count=1`; it must pass with no race report.
### [API-4] Synchronize the implemented contract and spec
**Problem**
`agent-contract/inner/edge-node-runtime-wire.md:71-99` documents internal artifact inventory and cleanup but no artifact read/write wire. `agent-spec/runtime/edge-node-execution.md:175,286` likewise cannot describe how Plan, Work, and Review share request artifacts.
**Solution**
Document the closed enum surface, identity/generation fences, bounds, no-follow inventory reads, lazy-open sharing, cleanup ordering, and continued public `.iop` denial. Keep provider stage drivers and actual Claude qualification explicitly deferred to the dependent stage packets.
**Modified Files and Checklist**
- [ ] Update `agent-contract/inner/edge-node-runtime-wire.md` with request/response fields and failure/privacy semantics.
- [ ] Update `agent-spec/runtime/edge-node-execution.md` with the implemented artifact lifecycle and remaining stage-driver limitation.
**Test Strategy**
No document-only test is added; the contract claims are backed by API-1 through API-3 tests and deterministic searches in final verification.
**Verification**
Run `rg --sort path -n 'WorkspaceArtifact|plan\.md|review\.md|public workspace' agent-contract/inner/edge-node-runtime-wire.md agent-spec/runtime/edge-node-execution.md`; output must show the closed artifact family and public-path exclusion.
## Modified Files Summary
| File | Items |
|------|-------|
| `proto/iop/runtime.proto` | API-1 |
| `proto/gen/iop/runtime.pb.go` | API-1 |
| `apps/client/lib/gen/proto/iop/runtime.pb.dart` | API-1 |
| `apps/client/lib/gen/proto/iop/runtime.pbenum.dart` | API-1 |
| `apps/client/lib/gen/proto/iop/runtime.pbjson.dart` | API-1 |
| `packages/go/workspaceprotocol/terminal.go` | API-1 |
| `packages/go/workspaceprotocol/terminal_test.go` | API-1 |
| `apps/node/internal/workspace/cleanup.go` | API-2 |
| `apps/node/internal/workspace/cleanup_path_unix.go` | API-2 |
| `apps/node/internal/workspace/cleanup_path_other.go` | API-2 |
| `apps/node/internal/workspace/cleanup_test.go` | API-2 |
| `apps/node/internal/node/workspace_handler.go` | API-2 |
| `apps/node/internal/node/workspace_handler_test.go` | API-2 |
| `apps/node/internal/transport/parser.go` | API-2 |
| `apps/node/internal/transport/parser_test.go` | API-2 |
| `apps/node/internal/transport/session.go` | API-2 |
| `apps/node/internal/transport/session_test.go` | API-2 |
| `apps/edge/internal/transport/server.go` | API-3 |
| `apps/edge/internal/transport/server_test.go` | API-3 |
| `apps/edge/internal/service/workspace_wire.go` | API-3 |
| `apps/edge/internal/service/workspace_wire_test.go` | API-3 |
| `apps/edge/internal/service/single_request.go` | API-3 |
| `apps/edge/internal/service/single_request_artifact.go` | API-3 |
| `apps/edge/internal/service/single_request_artifact_test.go` | API-3 |
| `agent-contract/inner/edge-node-runtime-wire.md` | API-4 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/17_internal_artifact_wire/CODE_REVIEW-cloud-G09.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached results are not acceptable.
1. `make proto && make proto-dart` — both generators exit zero and tracked Go/Dart bindings reflect the source schema.
2. `go test ./packages/go/workspaceprotocol ./apps/node/internal/workspace ./apps/node/internal/node ./apps/node/internal/transport ./apps/edge/internal/transport ./apps/edge/internal/service -count=1` — focused cross-boundary packages pass.
3. `go test -race ./apps/edge/internal/service ./apps/node/internal/transport -run 'Test.*(WorkspaceArtifact|SingleRequestArtifact)' -count=1` — artifact lifecycle/correlation tests pass without races.
4. `go vet ./packages/go/... && go vet ./apps/node/... && go vet ./apps/edge/internal/service` — relevant shared, Node, and Edge packages vet cleanly.
5. `go test ./packages/go/... ./apps/node/... ./apps/edge/... -count=1` — broader shared/consumer regression passes.
6. `make client-test` — generated Dart bindings compile in the client test suite and all tests pass.
7. `rg --sort path -n 'WorkspaceArtifact|plan\.md|review\.md' proto/iop/runtime.proto apps/edge apps/node packages/go/workspaceprotocol agent-contract/inner/edge-node-runtime-wire.md agent-spec/runtime/edge-node-execution.md` — results are confined to the private artifact/runtime boundary and its tests/docs.
8. `git diff --check` — no whitespace errors.
Actual Claude/Mac full-cycle evidence is intentionally not run here; SDD S12 and Milestone task `claude-smoke` own that separate external verification.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.

View file

@ -0,0 +1,147 @@
<!-- task=m-iop-owned-single-request-agent-execution/18+17_plan_stage plan=1 tag=API milestone-task=plan-stage -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> Complete the fixed checklists and evidence fields, leave both active files in place, and report ready for review. Only the official review agent may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the blocker, attempted commands/output, and resume condition here; do not change owner or scope.
## Overview
date=2026-08-07
task=m-iop-owned-single-request-agent-execution/18+17_plan_stage, plan=1, tag=API
## For the Review Agent
Compare every implementation item with source and freshly rerun the recorded verification. Then append the official verdict and routing signals. On PASS, archive this file as `code_review_cloud_G06_1.log`, archive the plan as `plan_local_G06_1.log`, write `complete.log` preserving `milestone-task=plan-stage`, and move the task directory to the dated archive. On WARN/FAIL, write only the next filesystem state prescribed by the code-review skill. The implementing agent must not perform these steps.
## Archive Evidence Snapshot
- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/plan_local_G06_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/code_review_cloud_G06_0.log`.
- The archived pair contains no implementation evidence and no official verdict; it was preserved only because this explicit self-review found a semantic dependency-proof defect.
- The prior active-only `complete.log` check was invalid after a predecessor PASS moves the predecessor directory under `agent-task/archive/YYYY/MM/`. This revision requires exactly one matching active-or-archive predecessor evidence file before implementation or review.
- No production code, test, contract, spec, or roadmap completion is claimed by the archived pair.
## Implementation Item Completion
| Item | Status |
|------|---------|
| API-1 Preserve authorized managed route facts in stage admission | [ ] |
| API-2 Add the private managed provider-stage codec | [ ] |
| API-3 Implement S08 Plan and persist `plan.md` | [ ] |
| API-4 Record the partial implementation state | [ ] |
## Implementation Checklist
- [ ] Extend immutable stage admission with the exact managed provider-pool, candidate, and credential facts required for stage dispatch, with validation and defensive clone coverage.
- [ ] Add a bounded non-streaming single-request provider-stage request/response codec that reuses provider-pool admission and rejects normalized, mismatched, malformed, oversized, or provider-error outcomes.
- [ ] Implement the Gemini Plan runner: emit planning, send the immutable task with `reasoning_effort=high`, require a small plan plus verification criteria, and persist PLAN through the controller artifact API.
- [ ] Update the current implementation spec and run dependency, focused, broader Edge, vet, deterministic search, and diff checks without production activation.
- [ ] 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 section.
- [ ] Append one `PASS`, `WARN`, or `FAIL` verdict with verified `review_rework_count` and `evidence_integrity_failure`.
- [ ] Verify verdict, dimension assessment, and Required/Suggested/Nit classifications agree.
- [ ] Archive this file to `code_review_cloud_G06_1.log` and the plan to `plan_local_G06_1.log`.
- [ ] Verify `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] On PASS, write template-compliant `complete.log`, preserve/report `milestone-task=plan-stage`, move the task directory to the dated archive, and remove the active parent only if empty.
- [ ] On WARN/FAIL, write the exact next filesystem state and do not write `complete.log`.
## Deviations from Plan
_Record deviations and rationale here._
## Key Design Decisions
_Record implementation decisions here._
## Reviewer Checkpoints
- Verify every Plan dispatch uses the frozen model group, route/profile/credential revisions, exact candidate predicate, and lease binding without refresh re-resolution or fallback.
- Verify reserved body fields override option maps, high reasoning reaches Gemini Plan, and caller models/tools/credentials never become internal authority.
- Verify frame order/status/size/result schema and artifact failures fail generically, close the handle, and expose no provider reasoning or raw error.
- Verify the runner remains inactive in production and the spec leaves Work, Review/repair, composite activation, and S12 qualification deferred.
## Verification Results
Paste actual stdout/stderr for every command. Any replacement requires a matching `Deviations from Plan` entry.
### 1. Dependency evidence
`bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/17_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/17+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/17_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/17+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'`
Expected: exactly one path and exit zero before implementation or review.
```text
_Paste actual output here._
```
### 2. Focused admission/Plan tests
`go test ./apps/edge/internal/service ./apps/edge/internal/openai -run 'TestSingleRequest(Binding|PresetBinding|ProviderStage|PlanStage)' -count=1`
```text
_Paste actual output here._
```
### 3. Vet
`go vet ./apps/edge/internal/service ./apps/edge/internal/openai`
```text
_Paste actual output here._
```
### 4. Edge regression
`go test ./apps/edge/... -count=1`
```text
_Paste actual output here._
```
### 5. No incomplete production activation
`rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'`
```text
_Paste actual output here._
```
### 6. Spec synchronization
`rg --sort path -n 'Plan stage|plan\.md|not installed|deferred' agent-spec/runtime/edge-node-execution.md`
```text
_Paste actual output here._
```
### 7. Diff hygiene
`git diff --check`
```text
_Paste actual output here._
```
External qualification remains S12 `claude-smoke` after composite activation.
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not change finalization metadata |
| Archive Evidence Snapshot | Fixed at stub creation | Read only cited prior evidence when needed |
| Implementation Item Completion and Checklist text/order | Fixed at stub creation | Implementing agent changes only `[ ]` to `[x]` |
| Review-Only Checklist | Review agent | Implementing agent must not modify it |
| Deviations, Key Design Decisions | Implementing agent | Replace placeholders with actual evidence |
| Reviewer Checkpoints and verification commands | Fixed at stub creation | Implementing agent fills output only; command changes require a deviation |
| Code Review Result | Review agent appends | Not present in this stub |

View file

@ -0,0 +1,217 @@
<!-- task=m-iop-owned-single-request-agent-execution/18+17_plan_stage plan=1 tag=API milestone-task=plan-stage -->
# Authorized Plan provider stage
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G06.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
Marked single-request admission freezes canonical Plan/Work/Review model names and options, but it does not preserve the managed route facts needed to dispatch a provider stage. No provider-specific runner currently converts the immutable Anthropic task into a bounded Gemini Plan request or persists its result. This packet adds a reusable non-streaming managed-stage codec and the S08 Plan runner, while leaving production executor installation to the Review packet.
## Archive Evidence Snapshot
- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/plan_local_G06_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/code_review_cloud_G06_0.log`.
- The archived pair contains no implementation evidence and no official verdict; it was preserved only because this explicit self-review found a semantic dependency-proof defect.
- The prior active-only `complete.log` check was invalid after a predecessor PASS moves the predecessor directory under `agent-task/archive/YYYY/MM/`. This revision requires exactly one matching active-or-archive predecessor evidence file before implementation or review.
- No production code, test, contract, spec, or roadmap completion is claimed by the archived pair.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/edge-config-runtime-refresh.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/provider_pool.go`
- `apps/edge/internal/service/provider_tunnel.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/principal_routes.go`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/anthropic_handler.go`
### SDD Criteria
- SDD is approved and unlocked; this packet contributes `plan-stage`.
- S08 requires immutable user task input, Gemini 3.6 Flash, `reasoning_effort=high`, a small plan plus verification criteria, and an internal `plan.md` write.
- Evidence must inspect the effective provider request/options, authorized candidate and credential fence, bounded result codec, planning envelope, and exact PLAN artifact write.
### Verification Context
- No verification handoff was supplied. The local test rule and existing service/OpenAI tests are the repository-native oracle.
- Checkout preflight: branch `feature/iop-owned-single-request-agent-execution`, HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`; only active Epic task artifacts differ, with no direct production code/test/document delta from that base.
- Deterministic provider frames and candidate selection are sufficient for this packet; no remote provider, credential, or runner is required.
- Actual Claude/Mac qualification remains S12 `claude-smoke` after composite activation.
### Test Coverage Gaps
- Binding tests cover stage model/options and refresh isolation, but not frozen dispatch/credential facts.
- Provider-pool tests cover general dispatch, but not a private single-request body/result codec.
- Existing handler tests use fake executors and do not prove the S08 Gemini request/options/artifact sequence.
### Symbol References
- `SingleRequestStageBinding` is built by `resolveStageBinding`; update all repository composite literals or keep a zero-value dispatch only in helpers that never dispatch.
- `routeDispatch`, `managedRouteCandidatePredicate`, `CredentialBinding`, `ProviderPoolDispatchRequest`, and `PrepareProtocolTunnel` are the existing boundaries to reuse. No symbol is renamed or removed.
### Split Judgment
- Predecessor 17 owns controller PLAN/REVIEW artifact access and workspace lifecycle cleanup. Resolve exactly one predecessor `complete.log`, read that exact evidence, then inspect the completed source contract before coding.
- This packet owns the immutable managed dispatch snapshot, private provider-stage codec, and directly testable Plan runner without production activation.
- Work and Review remain separate because their continuation and repair state machines require independent evidence.
### Scope Rationale
Exclude Work tool calls, Review verdict/repair, composite installation, public response changes, generic error/cancel quality work, config examples, and external provider execution. Do not introduce fallback, dynamic model selection, caller credentials/tools, or a new public API.
### Final Routing
- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures are all true. Scores `2/1/1/1/1` => G06, base/route `local-fit`, `worker/local/G06`, `PLAN-local-G06.md`.
- Review closures are all true. Scores `2/1/1/1/1` => G06, `official-review`, `review/cloud/G06`, `CODE_REVIEW-cloud-G06.md`.
- `large_indivisible_context=false`; risks `boundary_contract`, `structured_interpretation`; `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Dependencies and Execution Order
1. Before implementation or review, run the exact dependency command in Final Verification. It must print exactly one predecessor evidence path from active or archive storage and exit zero; missing or ambiguous evidence is a blocker.
2. Read only that resolved `complete.log`, then inspect predecessor 17's completed artifact API in source. If it contradicts this plan, record the blocker instead of recreating or replacing its boundary.
3. Implement this packet without installing it through `SetSingleRequestExecutor`; task 20 owns production composition after all stages exist.
## Implementation Checklist
- [ ] Extend immutable stage admission with the exact managed provider-pool, candidate, and credential facts required for stage dispatch, with validation and defensive clone coverage.
- [ ] Add a bounded non-streaming single-request provider-stage request/response codec that reuses provider-pool admission and rejects normalized, mismatched, malformed, oversized, or provider-error outcomes.
- [ ] Implement the Gemini Plan runner: emit planning, send the immutable task with `reasoning_effort=high`, require a small plan plus verification criteria, and persist PLAN through the controller artifact API.
- [ ] Update the current implementation spec and run dependency, focused, broader Edge, vet, deterministic search, and diff checks without production activation.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Preserve authorized managed route facts in stage admission
**Problem**
`resolveStageBinding` currently returns only model and options even though `routeDispatch` holds the principal, credential slot, route/profile revisions, model group, provider, upstream model, timeouts, and candidate predicate. Re-resolving those facts later would cross the immutable admission boundary.
**Solution**
Add a service-owned `SingleRequestStageDispatchBinding` to every stage. Copy only secret-free managed route facts during admission, validate required identity/revision fields, deep-clone mutable values, and expose reconstruction of the request-local candidate predicate plus `CredentialBinding`. Do not retain projection maps, closures over refreshable state, secrets, endpoints, or Node selection.
**Modified Files and Checklist**
- [ ] Update `apps/edge/internal/service/single_request_types.go` and its tests for the validated DTO and clone behavior.
- [ ] Update `apps/edge/internal/openai/single_request_preset_binding.go` and its tests for exact route facts, rejection, and refresh isolation across all three stages.
**Test Strategy**
Cover exact values, each missing/mismatched identity or revision, defensive cloning, and mutation after refresh.
**Verification**
Run the focused binding/preset tests in Final Verification.
### [API-2] Add the private managed provider-stage codec
**Problem**
The provider pool supports one-shot dispatch, but no single-request component builds the server-owned Chat request or consumes a bounded non-streaming tunnel terminal. Caller-facing codecs would forward caller authority and public error semantics.
**Solution**
Add `single_request_provider_stage.go` with a narrow `SubmitProviderPool` dependency. Build a non-streaming `chat_completions` operation after candidate selection supplies the final target, attach only frozen predicate/credential facts, collect ordered response frames under deadline/output bounds, require HTTP 2xx and the frozen Chat profile, and decode exactly one assistant result. Reserved model/messages/tools/stream/credential fields must not be overridden by option maps.
**Modified Files and Checklist**
- [ ] Add the codec in `apps/edge/internal/openai/single_request_provider_stage.go`.
- [ ] Add deterministic normal and fail-closed fixtures in `apps/edge/internal/openai/single_request_plan_stage_test.go`.
**Test Strategy**
Cover content, wrong candidate/profile/path, normalized results, non-2xx, frame order, duplicate terminal, body limit, malformed JSON, missing choice, unexpected tool call, close behavior, and generic errors.
**Verification**
Run the focused ProviderStage test in Final Verification.
### [API-3] Implement S08 Plan and persist `plan.md`
**Problem**
The admitted immutable body reaches a service executor, but no runner emits `planning`, constructs the fixed Gemini request, or writes the PLAN artifact.
**Solution**
Add `single_request_plan_stage.go`. Embed the immutable task in a fixed prompt, merge only frozen Plan options, force `reasoning_effort=high`, decode strict bounded JSON with non-empty plan and verification fields, render Markdown, and write `SingleRequestArtifactPlan`. Submit only the planning envelope and do not install the incomplete executor.
**Modified Files and Checklist**
- [ ] Add fixed prompt/result schema and runner in `apps/edge/internal/openai/single_request_plan_stage.go`.
- [ ] Add S08 success and fail-closed fixtures in `apps/edge/internal/openai/single_request_plan_stage_test.go`.
**Test Strategy**
Inspect the effective provider JSON, immutable task inclusion, high option, lack of caller authority, exact artifact kind/content, malformed output, bounds, and artifact-write failure.
**Verification**
Run the focused ProviderStage/PlanStage tests in Final Verification.
### [API-4] Record the partial implementation state
**Problem**
The current spec says no provider-specific stage driver exists. After this packet Plan exists as a tested component, but Work, Review, composite activation, and external qualification remain deferred.
**Solution**
Update the current spec with the frozen route snapshot and tested Plan runner while keeping the endpoint's composite activation and S12 qualification explicitly deferred. Do not update the public contract as if the full executor were active.
**Modified Files and Checklist**
- [ ] Update `agent-spec/runtime/edge-node-execution.md` implementation, verification, limitation, and history sections.
**Test Strategy**
The executable fixtures support the document statement; deterministic search verifies the partial-state wording.
**Verification**
Run the spec search in Final Verification.
## Modified Files Summary
| File | Items |
|------|-------|
| `apps/edge/internal/service/single_request_types.go` | API-1 |
| `apps/edge/internal/service/single_request_types_test.go` | API-1 |
| `apps/edge/internal/openai/single_request_preset_binding.go` | API-1 |
| `apps/edge/internal/openai/single_request_preset_binding_test.go` | API-1 |
| `apps/edge/internal/openai/single_request_provider_stage.go` | API-2 |
| `apps/edge/internal/openai/single_request_plan_stage.go` | API-3 |
| `apps/edge/internal/openai/single_request_plan_stage_test.go` | API-2, API-3 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/CODE_REVIEW-cloud-G06.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.
1. `bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/17_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/17+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/17_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/17+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'` — prints exactly one predecessor completion path and exits zero before implementation or review.
2. `go test ./apps/edge/internal/service ./apps/edge/internal/openai -run 'TestSingleRequest(Binding|PresetBinding|ProviderStage|PlanStage)' -count=1` — admission, codec, and S08 fixtures pass freshly.
3. `go vet ./apps/edge/internal/service ./apps/edge/internal/openai` — changed packages vet cleanly.
4. `go test ./apps/edge/... -count=1` — broader Edge regression passes.
5. `rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'` — no incomplete composite is production-installed.
6. `rg --sort path -n 'Plan stage|plan\.md|not installed|deferred' agent-spec/runtime/edge-node-execution.md` — spec distinguishes implemented Plan from deferred stages/activation.
7. `git diff --check` — no whitespace errors.
Actual provider/Claude full-cycle evidence remains owned by S12 `claude-smoke` after composite activation.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.

View file

@ -0,0 +1,177 @@
<!-- task=m-iop-owned-single-request-agent-execution/18+17_plan_stage plan=0 tag=API milestone-task=plan-stage -->
# 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-07
task=m-iop-owned-single-request-agent-execution/18+17_plan_stage, plan=0, tag=API
## 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-G06.md` → `code_review_cloud_G06_0.log` and `PLAN-local-G06.md` → `plan_local_G06_0.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/18+17_plan_stage/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=plan-stage` 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 Preserve authorized managed route facts in stage admission | [ ] |
| API-2 Add the private managed provider-stage codec | [ ] |
| API-3 Implement S08 Plan and persist `plan.md` | [ ] |
| API-4 Record the partial implementation state | [ ] |
## Implementation Checklist
- [ ] Extend immutable stage admission with the exact managed provider-pool, candidate, and credential facts required for stage dispatch, with validation and defensive clone coverage.
- [ ] Add a bounded non-streaming single-request provider-stage request/response codec that reuses provider-pool admission and rejects normalized, mismatched, malformed, oversized, or provider-error outcomes.
- [ ] Implement the Gemini Plan runner: emit planning, send the immutable task with `reasoning_effort=high`, require a small plan plus verification criteria, and persist PLAN through the controller artifact API.
- [ ] Update the current implementation spec and run dependency, focused, broader Edge, vet, deterministic search, and diff checks without production activation.
- [ ] 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.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G06_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_local_G06_0.log`.
- [ ] 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-owned-single-request-agent-execution/18+17_plan_stage/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/18+17_plan_stage/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=plan-stage` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Verify every Plan dispatch uses the frozen managed model group, route/profile/credential revisions, exact candidate predicate, and lease binding without refresh re-resolution or fallback.
- Verify reserved body fields override operator option maps, `reasoning_effort=high` reaches Gemini Plan, and caller models/tools/credentials never become internal authority.
- Verify tunnel frame order/status/size/result schema and artifact write failures all fail generically, close the handle, and emit no private reasoning or raw provider error.
- Verify the runner is not installed in production and the spec clearly leaves Work, Review/repair, composite activation, and S12 qualification deferred.
## Verification Results
Paste actual stdout/stderr for every command. If a command changes, record the replacement and reason in `Deviations from Plan` before pasting its output.
### 1. Dependency evidence
`test -f agent-task/m-iop-owned-single-request-agent-execution/17_internal_artifact_wire/complete.log`
Expected: exit zero before implementation or review.
```text
_Paste actual output here._
```
### 2. Focused admission/Plan tests
`go test ./apps/edge/internal/service ./apps/edge/internal/openai -run 'TestSingleRequest(Binding|PresetBinding|ProviderStage|PlanStage)' -count=1`
Expected: admission, codec, and S08 fixtures pass freshly.
```text
_Paste actual output here._
```
### 3. Vet
`go vet ./apps/edge/internal/service ./apps/edge/internal/openai`
Expected: both changed Edge packages vet cleanly.
```text
_Paste actual output here._
```
### 4. Edge regression
`go test ./apps/edge/... -count=1`
Expected: all Edge packages pass freshly.
```text
_Paste actual output here._
```
### 5. No incomplete production activation
`rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'`
Expected: no production installation of an incomplete composite exists; only the existing setter/tests or explicitly deferred references appear.
```text
_Paste actual output here._
```
### 6. Spec synchronization
`rg --sort path -n 'Plan stage|plan\.md|not installed|deferred' agent-spec/runtime/edge-node-execution.md`
Expected: Plan is implemented while Work, Review/repair, activation, and external qualification remain deferred.
```text
_Paste actual output here._
```
### 7. Diff hygiene
`git diff --check`
Expected: exit zero with no output.
```text
_Paste actual output here._
```
External note: actual provider/Claude full-cycle evidence remains owned by SDD S12 `claude-smoke` after the composite runner is complete.
---
> **[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 |

View file

@ -0,0 +1,268 @@
<!-- task=m-iop-owned-single-request-agent-execution/18+17_plan_stage plan=0 tag=API milestone-task=plan-stage -->
# Authorized Plan provider stage
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G06.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
Marked single-request admission freezes canonical Plan/Work/Review model names and options, but it discards the authorized managed route facts required to dispatch a provider stage. No provider-specific runner currently converts the immutable Anthropic task into a bounded Gemini Plan request or persists its result. This packet adds a reusable non-streaming managed stage codec and the S08 Plan runner, but deliberately leaves production executor installation to the final Review packet.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/edge-config-runtime-refresh.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_types_test.go`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/provider_pool.go`
- `apps/edge/internal/service/provider_tunnel.go`
- `apps/edge/internal/service/run_types.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/openai/single_request_preset_binding_test.go`
- `apps/edge/internal/openai/principal_routes.go`
- `apps/edge/internal/openai/principal_routes_test.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/chat_types.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_types.go`
### SDD Criteria
- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`, `[승인됨]`, `SDD 잠금: 해제`.
- First-line contribution id: `plan-stage`.
- Targeted scenario: S08 — immutable user task plus empty request job produces a small plan and verification criteria using Gemini 3.6 Flash with `reasoning_effort=high`, then writes internal `plan.md`.
- Evidence Map driver: “Gemini plan request/options/artifact fixture.” The checklist therefore verifies the exact authorized candidate/credential fence, request options/body, bounded provider response, planning envelope, and PLAN artifact write rather than merely checking a mocked state transition.
### Verification Context
- No verification handoff was supplied. Repository-native sources were `agent-test/local/rules.md`, `edge-smoke.md`, and the related service/OpenAI tests.
- Current checkout preflight: branch `feature/iop-owned-single-request-agent-execution`, HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`, clean worktree; Go `1.26.2 linux/arm64` is available.
- Baseline relevant packages passed with `-count=1`; no external provider, credential, or remote runner is needed because provider frames and candidate selection are deterministic fixtures.
- Constraint: the Plan runner must not be installed as the service executor while Work/Review are absent. Actual Claude/Mac qualification remains SDD S12 `claude-smoke`.
- Confidence: high after predecessor completion. The current provider-pool surface already supports request-local candidate predicates, protocol-operation filtering, credential leases, final-target body building, and bounded tunnel handles.
### Test Coverage Gaps
- Binding tests cover stage model/options and refresh isolation, but not dispatch/credential route facts.
- Provider-pool tests cover candidate filtering and tunnel dispatch generally, but no single-request stage request body or private result codec.
- Existing single-request handler tests use injected fake executors; they do not establish S08 Gemini request/options/artifact behavior. This packet adds focused normal and failure fixtures.
### Symbol References
No symbol is renamed or removed. `SingleRequestStageBinding` construction occurs in `resolveStageBinding` and service tests; all composite literals found by repository search must be updated or remain valid through a zero-value route only in test helpers that never dispatch.
### Split Judgment
- Predecessor 17 contract: controller-owned PLAN/REVIEW artifact read/write with exact workspace lifecycle cleanup; PASS evidence is `agent-task/m-iop-owned-single-request-agent-execution/17_internal_artifact_wire/complete.log`.
- At plan creation the predecessor `complete.log` is missing, so implementation must wait. The directory name `18+17_plan_stage` is the runtime source of truth.
- This packet's stable contract is an immutable managed stage dispatch snapshot plus a directly testable Plan runner that is not production-installed. PASS evidence is the S08 provider request/options/artifact fixture.
- Work and Review stay separate because their tool continuation and repair state machines have independent invariants and deterministic PASS tests.
### Scope Rationale
This packet excludes Work tool calls, provider continuation, Review verdict/repair, manager installation, public response changes, generic error/cancel quality work, config examples, and actual provider execution. It consumes the frozen model references already approved by the preset and does not introduce fallback, dynamic model selection, caller credentials, caller tools, or a new public API.
### Final Routing
- `evaluation_mode=first-pass`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures: scope/context/verification/evidence/ownership/decision all true. Scores `2/1/1/1/1` => G06, base/route `local-fit`, `worker/local/G06`, `PLAN-local-G06.md`.
- Review closures: all true. Scores `2/1/1/1/1` => G06, `official-review`, `review/cloud/G06`, `CODE_REVIEW-cloud-G06.md`.
- `large_indivisible_context=false`; positive loop risks: `boundary_contract`, `structured_interpretation` (2); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Dependencies and Execution Order
1. Do not implement until `agent-task/m-iop-owned-single-request-agent-execution/17_internal_artifact_wire/complete.log` exists. No archive candidate exists yet at plan creation.
2. Implement this packet only after that evidence is present; do not add dependencies absent from `18+17_plan_stage`.
3. Do not install the resulting runner into `Service.SetSingleRequestExecutor`; `20+19_review_stage` owns production activation after all stages exist.
## Implementation Checklist
- [ ] Extend immutable stage admission with the exact managed provider-pool, candidate, and credential facts required for stage dispatch, with validation and defensive clone coverage.
- [ ] Add a bounded non-streaming single-request provider-stage request/response codec that reuses provider-pool admission and rejects normalized, mismatched, malformed, oversized, or provider-error outcomes.
- [ ] Implement the Gemini Plan runner: emit planning, send the immutable task with `reasoning_effort=high`, require a small plan plus verification criteria, and persist PLAN through the controller artifact API.
- [ ] Update the current implementation spec and run dependency, focused, broader Edge, vet, deterministic search, and diff checks without production activation.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Preserve authorized managed route facts in stage admission
**Problem**
`apps/edge/internal/openai/single_request_preset_binding.go:163` returns only `Model` and `Options`, even though its source `routeDispatch` contains the principal, credential slot, route/profile revisions, model group, provider, upstream model, timeouts, and candidate predicate. A runner using only the canonical model would have to re-resolve mutable config or bypass the lease fence.
**Solution**
Add a service-owned `SingleRequestStageDispatchBinding` to each stage. Copy the exact frozen managed route facts at compilation, validate required identity/revision fields in `NewSingleRequestBinding`, clone all mutable values, and expose a method that reconstructs only the request-local candidate predicate and `CredentialBinding` needed by provider-pool dispatch. Do not retain a refreshable map, closure over mutable projection state, secret, endpoint, or Node selection.
Before (`apps/edge/internal/service/single_request_types.go:94`):
```go
type SingleRequestStageBinding struct {
Model string
Options map[string]any
}
```
After:
```go
type SingleRequestStageBinding struct {
Model string
Options map[string]any
Dispatch SingleRequestStageDispatchBinding
}
```
**Modified Files and Checklist**
- [ ] Add validated dispatch DTOs and deep-clone behavior in `apps/edge/internal/service/single_request_types.go`.
- [ ] Extend normal, missing-field, clone, refresh-isolation, and malformed-route tests in `apps/edge/internal/service/single_request_types_test.go`.
- [ ] Copy route facts in `apps/edge/internal/openai/single_request_preset_binding.go` without changing public model echo or workspace admission.
- [ ] Expand `apps/edge/internal/openai/single_request_preset_binding_test.go` to assert exact route/credential facts, candidate rejection, and post-refresh isolation for all three stages.
**Test Strategy**
Write tests for exact managed values, wrong/missing principal/slot/route/profile/revision/model-group rejection, clone isolation, and refresh mutation. Existing model/options/shape tests remain unchanged and must continue to pass.
**Verification**
Run `go test ./apps/edge/internal/service ./apps/edge/internal/openai -run 'TestSingleRequest(Binding|PresetBinding)' -count=1`; all admission tests must pass freshly.
### [API-2] Add the private managed provider-stage codec
**Problem**
`apps/edge/internal/service/provider_pool.go:107-203` accepts a one-shot pool dispatch, but no single-request component builds its managed Chat request or consumes a non-streaming tunnel terminal. Caller-facing codecs cannot be reused because they forward caller tool/schema choices and public error semantics.
**Solution**
Create `single_request_provider_stage.go` with a narrow `SubmitProviderPool` dependency. Build a non-streaming `chat_completions` operation from server-owned messages/options after candidate selection supplies the final target; attach only the frozen credential binding and predicate. Collect ordered response-start/body/end frames under the stage deadline and max-output bound, require HTTP 2xx and the frozen OpenAI Chat profile, decode exactly one assistant message, and return typed content/tool-call data without reasoning or raw provider errors.
Before (`apps/edge/internal/openai/server.go:23`):
```go
type runService interface {
SubmitProviderPool(context.Context, edgeservice.ProviderPoolDispatchRequest) (*edgeservice.ProviderPoolDispatchResult, error)
}
```
After:
```go
type singleRequestProviderStageService interface {
SubmitProviderPool(context.Context, edgeservice.ProviderPoolDispatchRequest) (*edgeservice.ProviderPoolDispatchResult, error)
}
```
**Modified Files and Checklist**
- [ ] Add `apps/edge/internal/openai/single_request_provider_stage.go` with request assembly, frozen candidate predicate, tunnel collection, typed decode, bounds, cancellation, and generic errors.
- [ ] Keep stage options server-owned: reserved `model`, `messages`, `tools`, `stream`, and credential fields cannot be overridden by option maps.
- [ ] Cover normal content, wrong candidate/profile/path, normalized result, non-2xx, bad frame order, duplicate terminal, oversized body, malformed JSON, missing choice, and unexpected Plan tool call in `apps/edge/internal/openai/single_request_plan_stage_test.go`.
**Test Strategy**
Write a narrow fake that implements only `SubmitProviderPool`, invokes `PrepareProtocolTunnel` with a selected candidate, captures the final body, and returns deterministic frame sequences. Assertions must inspect the effective target, immutable route predicate, credential binding, option precedence, close call, and generic error behavior.
**Verification**
Run `go test ./apps/edge/internal/openai -run 'TestSingleRequestProviderStage' -count=1`; all codec fixtures must pass.
### [API-3] Implement S08 Plan and persist `plan.md`
**Problem**
`apps/edge/internal/openai/anthropic_handler.go:223-227` passes the immutable admitted body to a service executor, but no runner emits `planning`, creates the required small plan/verification criteria, or writes the PLAN artifact.
**Solution**
Create `single_request_plan_stage.go`. Treat the admitted Anthropic JSON as immutable task data inside a fixed system/user prompt, explicitly ignore caller-selected models/tools as execution authority, merge only the frozen Plan options, and require `reasoning_effort=high`. Decode a strict server-owned JSON result containing non-empty `plan` and `verification` fields, render bounded Markdown, write `SingleRequestArtifactPlan` through the controller, and return the artifact bytes to the later Work runner. Submit only the `planning` envelope; do not install an incomplete outer executor.
Before (`apps/edge/internal/openai/anthropic_handler.go:223`):
```go
Prompt: string(append([]byte(nil), body...)),
```
After (new private runner contract):
```go
plan, err := runner.Run(ctx, req.Prompt, req.Binding.Plan, ctrl)
// writes the exact bounded rendering through SingleRequestArtifactPlan
```
**Modified Files and Checklist**
- [ ] Add fixed prompt/result schema and Plan stage runner in `apps/edge/internal/openai/single_request_plan_stage.go`.
- [ ] Add S08 fixtures in `apps/edge/internal/openai/single_request_plan_stage_test.go` for high option, immutable task inclusion, no caller-tool authority, small plan/verification rendering, artifact kind/content, malformed output, and write failure.
**Test Strategy**
Write `TestSingleRequestPlanStageWritesArtifact` and table-driven fail-closed cases. The success fixture must inspect the final provider JSON and controller write, and verify no public stream/output receives provider reasoning or stage terminal data.
**Verification**
Run `go test ./apps/edge/internal/openai -run 'TestSingleRequest(ProviderStage|PlanStage)' -count=1`; the S08 fixture and all boundaries must pass.
### [API-4] Record the partial implementation state
**Problem**
`agent-spec/runtime/edge-node-execution.md:286` says no provider-specific Plan/Work/Review driver exists. After this packet, Plan exists as a tested component but the composite execution remains intentionally inactive.
**Solution**
Update the current spec to describe the authorized route snapshot and tested Plan artifact runner, while stating that Work, Review/repair, composite installation, and actual Claude qualification are still deferred. Do not update the public Anthropic contract as though the endpoint were active.
**Modified Files and Checklist**
- [ ] Update `agent-spec/runtime/edge-node-execution.md` implementation/limitation/history sections with the partial state and S08 tests.
**Test Strategy**
No document-only test; deterministic searches and the executable fixtures validate the statement.
**Verification**
Run `rg --sort path -n 'Plan stage|plan\.md|Work|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md`; the spec must distinguish implemented Plan from inactive composite stages.
## Modified Files Summary
| File | Items |
|------|-------|
| `apps/edge/internal/service/single_request_types.go` | API-1 |
| `apps/edge/internal/service/single_request_types_test.go` | API-1 |
| `apps/edge/internal/openai/single_request_preset_binding.go` | API-1 |
| `apps/edge/internal/openai/single_request_preset_binding_test.go` | API-1 |
| `apps/edge/internal/openai/single_request_provider_stage.go` | API-2 |
| `apps/edge/internal/openai/single_request_plan_stage.go` | API-3 |
| `apps/edge/internal/openai/single_request_plan_stage_test.go` | API-2, API-3 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/CODE_REVIEW-cloud-G06.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/17_internal_artifact_wire/complete.log` — predecessor completion evidence exists before implementation or review.
2. `go test ./apps/edge/internal/service ./apps/edge/internal/openai -run 'TestSingleRequest(Binding|PresetBinding|ProviderStage|PlanStage)' -count=1` — admission, codec, and S08 fixtures pass.
3. `go vet ./apps/edge/internal/service ./apps/edge/internal/openai` — changed Edge packages vet cleanly.
4. `go test ./apps/edge/... -count=1` — broader Edge regression passes.
5. `rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'` — no production installation of an incomplete composite exists; only the existing setter/tests or explicitly deferred references appear.
6. `rg --sort path -n 'Plan stage|plan\.md|not installed|deferred' agent-spec/runtime/edge-node-execution.md` — spec records Plan as implemented and later stages/activation as deferred.
7. `git diff --check` — no whitespace errors.
Actual provider/Claude full-cycle evidence is intentionally excluded and remains owned by SDD S12 `claude-smoke` after the composite runner is implemented.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.

View file

@ -0,0 +1,155 @@
<!-- task=m-iop-owned-single-request-agent-execution/19+18_work_stage plan=1 tag=API milestone-task=work-stage -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> Complete the fixed checklists and evidence fields, leave both active files in place, and report ready for review. Only the official review agent may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the blocker, attempted commands/output, and resume condition here; do not change owner or scope.
## Overview
date=2026-08-07
task=m-iop-owned-single-request-agent-execution/19+18_work_stage, plan=1, tag=API
## For the Review Agent
Compare every item with source and freshly rerun the recorded verification. Then append the official verdict and routing signals. On PASS, archive this file as `code_review_cloud_G08_1.log`, archive the plan as `plan_cloud_G08_1.log`, write `complete.log` preserving `milestone-task=work-stage`, and move the task directory to the dated archive. On WARN/FAIL, write only the next state prescribed by the code-review skill. The implementing agent must not perform these steps.
## Archive Evidence Snapshot
- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/plan_cloud_G08_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/code_review_cloud_G08_0.log`.
- The archived pair has no implementation evidence and no official verdict; self-review preserved it before correcting its semantic dependency proof.
- The prior active-only path would fail after a predecessor PASS archives task 18. This revision resolves exactly one active-or-archive `complete.log` and then consumes the predecessor's actual completed source contract.
- No production code, test, spec, or roadmap completion is claimed by the archived pair.
## Implementation Item Completion
| Item | Status |
|------|---------|
| API-1 Correlate provider tool continuations per request | [ ] |
| API-2 Drive the S09 Work provider/tool loop | [ ] |
| API-3 Keep the service coordinator contract intact | [ ] |
| API-4 Record Work as implemented but inactive | [ ] |
## Implementation Checklist
- [ ] Add a concurrent request-safe internal tool continuation bridge that correlates one provider call to one coordinator result and unregisters on every success, failure, timeout, and cancel path.
- [ ] Implement the ornith-fast Work runner to read PLAN, expose only admitted IOP workspace tools, drive ordered provider/tool continuations, and return bounded completion and verification evidence.
- [ ] Add S09 fixtures for write+verify completion, every Work request's high-option absence, identity/correlation isolation, malformed/multiple tool calls, limits, cancellation, and provider/tool failures under `-race`.
- [ ] Update the current implementation spec and run dependency, focused race, service compatibility, broader Edge, vet, deterministic option search, and diff checks without production activation.
- [ ] 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 section.
- [ ] Append one `PASS`, `WARN`, or `FAIL` verdict with verified `review_rework_count` and `evidence_integrity_failure`.
- [ ] Verify verdict, dimension assessment, and Required/Suggested/Nit classifications agree.
- [ ] Archive this file to `code_review_cloud_G08_1.log` and the plan to `plan_cloud_G08_1.log`.
- [ ] Verify `.gitignore` unignores task Markdown/log files and ignores `agent-roadmap/current.md`.
- [ ] On PASS, write template-compliant `complete.log`, preserve/report `milestone-task=work-stage`, move the task directory to the dated archive, and remove the active parent only if empty.
- [ ] On WARN/FAIL, write the exact next filesystem state and do not write `complete.log`.
## Deviations from Plan
_Record deviations and rationale here._
## Key Design Decisions
_Record implementation decisions here._
## Reviewer Checkpoints
- Verify the bridge correlates exact request/stage/tool identities, delivers outside its lock, and removes waiters on every terminal path.
- Verify every initial and resumed Work request uses the frozen ornith-fast route and contains no effective high-reasoning option.
- Verify only admitted workspace schemas reach the provider; tool results flow through the coordinator and preserve budgets, saved state, cancellation, and generic errors.
- Verify completion requires bounded verification evidence, remains private, and the runner is not production-installed before Review exists.
## Verification Results
Paste actual stdout/stderr for every command. Any replacement requires a matching `Deviations from Plan` entry.
### 1. Dependency evidence
`bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/18_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/18+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/18_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/18+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'`
Expected: exactly one path and exit zero before implementation or review.
```text
_Paste actual output here._
```
### 2. Focused Work race tests
`go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1`
```text
_Paste actual output here._
```
### 3. Service compatibility
`go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup)' -count=1`
```text
_Paste actual output here._
```
### 4. Vet and Edge regression
`go vet ./apps/edge/internal/openai && go test ./apps/edge/... -count=1`
```text
_Paste actual output here._
```
### 5. Work reasoning isolation
`rg --sort path -n 'reasoning_effort' apps/edge/internal/openai/single_request_work_stage.go apps/edge/internal/openai/single_request_work_stage_test.go`
```text
_Paste actual output here._
```
### 6. No incomplete production activation
`rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'`
```text
_Paste actual output here._
```
### 7. Spec synchronization
`rg --sort path -n 'ornith-fast|Work stage|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md`
```text
_Paste actual output here._
```
### 8. Diff hygiene
`git diff --check`
```text
_Paste actual output here._
```
External qualification remains S12 `claude-smoke`.
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not change finalization metadata |
| Archive Evidence Snapshot | Fixed at stub creation | Read only cited prior evidence when needed |
| Implementation Item Completion and Checklist text/order | Fixed at stub creation | Implementing agent changes only `[ ]` to `[x]` |
| Review-Only Checklist | Review agent | Implementing agent must not modify it |
| Deviations, Key Design Decisions | Implementing agent | Replace placeholders with actual evidence |
| Reviewer Checkpoints and verification commands | Fixed at stub creation | Implementing agent fills output only; command changes require a deviation |
| Code Review Result | Review agent appends | Not present in this stub |

View file

@ -0,0 +1,215 @@
<!-- task=m-iop-owned-single-request-agent-execution/19+18_work_stage plan=1 tag=API milestone-task=work-stage -->
# Work stage tool continuation
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G08.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
The Plan packet yields private `plan.md` content and a managed provider-stage codec, but the fixed Work stage remains absent. The coordinator already owns one closed internal workspace call/result continuation at a time. This packet adds a concurrent request-safe ornith-fast runner that reads the plan, translates only server-approved workspace tools, resumes the provider with the correlated result, and returns bounded completion and verification evidence without inheriting high reasoning.
## Archive Evidence Snapshot
- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/plan_cloud_G08_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/code_review_cloud_G08_0.log`.
- The archived pair has no implementation evidence and no official verdict; self-review preserved it before correcting its semantic dependency proof.
- The prior active-only path would fail after a predecessor PASS archives task 18. This revision resolves exactly one active-or-archive `complete.log` and then consumes the predecessor's actual completed source contract.
- No production code, test, spec, or roadmap completion is claimed by the archived pair.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_tool_types.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `apps/edge/internal/service/single_request_test.go`
- `apps/edge/internal/service/single_request_tool_loop_test.go`
- `apps/edge/internal/service/single_request_cleanup_test.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/server.go`
### SDD Criteria
- SDD is approved and unlocked; this packet contributes `work-stage`.
- S09 requires canonical `ornith-fast` to read PLAN, receive no `reasoning_effort=high`, make actual workspace changes and verification through IOP-owned tools, and produce a completion candidate.
- Evidence must cover ordered provider/tool/result flow, exact identity correlation, PLAN read, completion and verification evidence, and absence of high reasoning from every Work provider request.
### Verification Context
- No verification handoff was supplied. Existing service/OpenAI tool-loop tests plus local test rules are the oracle.
- Checkout preflight: branch `feature/iop-owned-single-request-agent-execution`, starting HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`; only active Epic artifacts differ, with no direct production code/test/document delta from that base.
- Deterministic provider frames and existing typed Node-wire doubles require no external provider, endpoint, or credential.
- Actual Claude/Mac full-cycle evidence remains S12 `claude-smoke` after Review activation.
### Test Coverage Gaps
- Service tests prove generic internal calls and continuation, but not provider Chat tool-call decoding or multi-turn Work messages.
- Preset tests prove Work options omit high, but not every effective initial/resumed provider body.
- No production-capable bridge test currently proves cross-request correlation, cleanup, and S09 write-plus-verify completion under `-race`.
### Symbol References
- `SingleRequestToolContinuation` is currently implemented only by test executors; the new bridge becomes the first production-capable implementation but remains uninstalled until task 20.
- Existing `SingleRequestController` and tool-loop envelopes are the state and budget authority. No existing state transition or public symbol is renamed.
### Split Judgment
- Predecessor 18 owns the authorized provider-stage codec and Plan artifact writer. Resolve one exact predecessor evidence file, read it, then inspect the completed source APIs before implementation.
- This packet owns a directly testable Work runner and request-safe continuation bridge without production activation.
- Review/repair remains separate because its independent pass/defect state machine and final-output provenance need their own evidence.
### Scope Rationale
Exclude Review verdict/repair, final user response, composite installation, public error mapping, generic no-progress/error-cancel policy, config changes, and external provider smoke. Never forward caller tools, arbitrary environment, credentials, private paths, or Plan/Review reasoning options to Work.
### Final Routing
- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures are all true. Scores `2/2/1/1/2` => G08, base `local-fit`, route `risk-boundary`, `worker/cloud/G08`, `PLAN-cloud-G08.md`.
- Review closures are all true. Scores `2/2/1/1/2` => G08, `official-review`, `review/cloud/G08`, `CODE_REVIEW-cloud-G08.md`.
- `large_indivisible_context=false`; risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`; `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Dependencies and Execution Order
1. Before implementation or review, run the exact dependency command in Final Verification. It must print exactly one task-18 completion path from active or archive storage and exit zero; missing or ambiguous evidence is a blocker.
2. Read only that resolved `complete.log`, then inspect the completed provider-stage and artifact APIs in source. If they contradict this plan, record a blocker instead of recreating their types or reopening ownership.
3. Implement Work only after the proof succeeds; keep the runner uninstalled because task 20 owns final composition.
## Implementation Checklist
- [ ] Add a concurrent request-safe internal tool continuation bridge that correlates one provider call to one coordinator result and unregisters on every success, failure, timeout, and cancel path.
- [ ] Implement the ornith-fast Work runner to read PLAN, expose only admitted IOP workspace tools, drive ordered provider/tool continuations, and return bounded completion and verification evidence.
- [ ] Add S09 fixtures for write+verify completion, every Work request's high-option absence, identity/correlation isolation, malformed/multiple tool calls, limits, cancellation, and provider/tool failures under `-race`.
- [ ] Update the current implementation spec and run dependency, focused race, service compatibility, broader Edge, vet, deterministic option search, and diff checks without production activation.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Correlate provider tool continuations per request
**Problem**
`SingleRequestToolContinuation` delivers results at executor scope while the Node response arrives asynchronously. A shared production executor needs exact request/stage/tool correlation without a global channel, lock-held blocking, duplicate delivery, or retained waiter after cancellation.
**Solution**
Add a private bridge in `single_request_work_stage.go`, keyed by immutable `(request_id, stage_id, tool_call_id)`. Register before submitting the internal-tool envelope, reject duplicate keys, wait under the stage/request context, consume one cloned result, and unregister by `defer`. Validate identities and deliver outside the map lock using a bounded/non-blocking path.
**Modified Files and Checklist**
- [ ] Add bridge lifecycle and `ContinueInternalTool` implementation in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Store no prompt, arguments, paths, credentials, or provider payloads in the bridge map.
- [ ] Add concurrent correlation, duplicate, stale, cancellation, and cleanup tests in `apps/edge/internal/openai/single_request_work_stage_test.go`.
**Test Strategy**
Reorder results across multiple request identities, assert exact delivery and zero pending entries, and run under the race detector.
**Verification**
Run the focused WorkToolBridge race test in Final Verification.
### [API-2] Drive the S09 Work provider/tool loop
**Problem**
No runner reads PLAN, projects admitted workspace capabilities into provider tool schemas, or resumes ornith-fast after a correlated internal result. Reusing a caller-facing path could forward caller tools or terminate the outer request.
**Solution**
Implement `singleRequestWorkStage.Run`: read `SingleRequestArtifactPlan`, submit `working`, build fixed task/plan messages and only admitted operation/command/environment tools. For exactly one provider tool call, register the bridge, submit `internal_tool` with saved `working`, wait for the exact result, return to `working`, append a bounded sanitized assistant/tool exchange, and redispatch. On content, require strict non-empty completion and verification evidence. Reject mixed/multiple/unknown calls, malformed arguments, identity mismatch, missing evidence, or any effective `reasoning_effort` field.
**Modified Files and Checklist**
- [ ] Add Work prompt, schema projection, multi-turn assembly, strict completion decode, and result DTO in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Reuse task 18's provider codec and controller artifact API; do not bypass coordinator budgets or send workspace wire directly.
- [ ] Add deterministic initial/tool-result/resumed body and completion assertions in `apps/edge/internal/openai/single_request_work_stage_test.go`.
**Test Strategy**
Have fake ornith-fast request a workspace write, then an admitted verification command, then return completion/verification JSON. Assert PLAN inclusion, frozen route use, exact identities, no reasoning-effort field on any request, bounds, and generic failures.
**Verification**
Run the focused WorkStage/ToolBridge race test in Final Verification.
### [API-3] Keep the service coordinator contract intact
**Problem**
A fake-only loop could pass while violating the real coordinator's saved-stage transitions, iteration/output limits, cancellation, or cleanup ordering.
**Solution**
Drive the Work runner through the existing controller and continuation surfaces. Require `working -> internal_tool(saved working) -> working`, exact identity, existing budget failures, cancellation, and cleanup behavior. Do not alter service state transitions; any proven incompatibility is a recorded blocker/deviation, not silent scope expansion.
**Modified Files and Checklist**
- [ ] Add coordinator-compatible controller/envelope assertions in `apps/edge/internal/openai/single_request_work_stage_test.go`.
- [ ] Re-run existing service tool-loop and cleanup tests unchanged as compatibility oracles.
**Test Strategy**
Use the OpenAI fixture to prove interface compatibility, then rely on unchanged service fixtures for state/budget/cleanup invariants.
**Verification**
Run the focused service tests in Final Verification.
### [API-4] Record Work as implemented but inactive
**Problem**
After this packet the current spec must distinguish implemented Plan/Work pieces from still-missing Review/repair and production activation.
**Solution**
Document PLAN read, Work option isolation, private continuation, completion/verification schema, and deterministic S09 evidence. Preserve explicit deferral of Review/repair, composite installation, and S12 external evidence.
**Modified Files and Checklist**
- [ ] Update `agent-spec/runtime/edge-node-execution.md` implementation, verification, limitation, and history text.
**Test Strategy**
Executable fixtures back the behavior; deterministic search checks the partial-state language.
**Verification**
Run the spec search in Final Verification.
## Modified Files Summary
| File | Items |
|------|-------|
| `apps/edge/internal/openai/single_request_work_stage.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_work_stage_test.go` | API-1, API-2, API-3 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/CODE_REVIEW-cloud-G08.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.
1. `bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/18_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/18+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/18_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/18+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'` — prints exactly one predecessor completion path and exits zero before implementation or review.
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1` — S09 and failure/correlation fixtures pass without races.
3. `go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup)' -count=1` — coordinator/tool/cleanup invariants pass freshly.
4. `go vet ./apps/edge/internal/openai && go test ./apps/edge/... -count=1` — OpenAI vets cleanly and broader Edge regression passes.
5. `rg --sort path -n 'reasoning_effort' apps/edge/internal/openai/single_request_work_stage.go apps/edge/internal/openai/single_request_work_stage_test.go` — code shows rejection/omission logic and tests prove no effective Work request field.
6. `rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'` — no production composite is installed yet.
7. `rg --sort path -n 'ornith-fast|Work stage|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md` — spec records Work and the remaining deferrals accurately.
8. `git diff --check` — no whitespace errors.
Actual provider/Claude full-cycle evidence remains owned by S12 `claude-smoke`.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.

View file

@ -0,0 +1,187 @@
<!-- task=m-iop-owned-single-request-agent-execution/19+18_work_stage plan=0 tag=API milestone-task=work-stage -->
# 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-07
task=m-iop-owned-single-request-agent-execution/19+18_work_stage, plan=0, tag=API
## 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_0.log` and `PLAN-cloud-G08.md` → `plan_cloud_G08_0.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/19+18_work_stage/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=work-stage` 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 Correlate provider tool continuations per request | [ ] |
| API-2 Drive the S09 Work provider/tool loop | [ ] |
| API-3 Keep the service coordinator contract intact | [ ] |
| API-4 Record Work as implemented but inactive | [ ] |
## Implementation Checklist
- [ ] Add a concurrent request-safe internal tool continuation bridge that correlates one provider call to one coordinator result and unregisters on every success, failure, timeout, and cancel path.
- [ ] Implement the ornith-fast Work runner to read PLAN, expose only admitted IOP workspace tools, drive ordered provider/tool continuations, and return bounded completion and verification evidence.
- [ ] Add S09 fixtures for write+verify completion, every Work request's high-option absence, identity/correlation isolation, malformed/multiple tool calls, limits, cancellation, and provider/tool failures under `-race`.
- [ ] Update the current implementation spec and run dependency, focused race, service compatibility, broader Edge, vet, deterministic option search, and diff checks without production activation.
- [ ] 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.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G08_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G08_0.log`.
- [ ] 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-owned-single-request-agent-execution/19+18_work_stage/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/19+18_work_stage/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=work-stage` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Verify the bridge keys every waiter by immutable request/stage/tool identities, never blocks while holding its map lock, consumes one result, and unregisters on all exits.
- Verify every Work dispatch stays on frozen ornith-fast admission, omits effective `reasoning_effort`, exposes only the admitted IOP operations, and rejects caller tools or credentials as authority.
- Verify provider tool calls and coordinator results retain exact correlation across reordering, duplicate/stale results, cancellation, budget failure, and concurrent requests.
- Verify completion and verification evidence are strict and bounded, production activation remains absent, and the spec leaves Review/repair, activation, and S12 qualification deferred.
## Verification Results
Paste actual stdout/stderr for every command. If a command changes, record the replacement and reason in `Deviations from Plan` before pasting its output.
### 1. Dependency evidence
`test -f agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/complete.log`
Expected: exit zero before implementation or review.
```text
_Paste actual output here._
```
### 2. Focused Work race tests
`go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1`
Expected: S09, continuation correlation, cancellation, and failure fixtures pass without races.
```text
_Paste actual output here._
```
### 3. Service compatibility
`go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup)' -count=1`
Expected: existing coordinator/tool/cleanup invariants pass freshly.
```text
_Paste actual output here._
```
### 4. Vet and Edge regression
`go vet ./apps/edge/internal/openai && go test ./apps/edge/... -count=1`
Expected: OpenAI vets cleanly and broader Edge regression passes.
```text
_Paste actual output here._
```
### 5. Work option isolation
`rg --sort path -n 'reasoning_effort' apps/edge/internal/openai/single_request_work_stage.go apps/edge/internal/openai/single_request_work_stage_test.go`
Expected: production code contains only explicit rejection/omission logic and tests prove no effective Work request field.
```text
_Paste actual output here._
```
### 6. No incomplete production activation
`rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'`
Expected: no production composite installation exists yet.
```text
_Paste actual output here._
```
### 7. Spec synchronization
`rg --sort path -n 'ornith-fast|Work stage|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md`
Expected: Work is implemented while Review/repair, activation, and external qualification remain deferred.
```text
_Paste actual output here._
```
### 8. Diff hygiene
`git diff --check`
Expected: exit zero with no output.
```text
_Paste actual output here._
```
External note: actual provider/Claude full-cycle evidence remains owned by SDD S12 `claude-smoke` after the composite runner is complete.
---
> **[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 |

View file

@ -0,0 +1,242 @@
<!-- task=m-iop-owned-single-request-agent-execution/19+18_work_stage plan=0 tag=API milestone-task=work-stage -->
# Work stage tool continuation
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G08.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
The preceding Plan packet yields a private `plan.md` and a managed provider-stage codec, but the fixed Work stage still has no implementation. The coordinator already owns one closed internal workspace call/result continuation at a time; the missing layer is a concurrent request-safe ornith-fast runner that reads the plan, translates only server-approved workspace tools, resumes the provider with the correlated result, and produces bounded completion/verification evidence without inheriting high reasoning.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_tool_types.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `apps/edge/internal/service/single_request_test.go`
- `apps/edge/internal/service/single_request_tool_types_test.go`
- `apps/edge/internal/service/single_request_tool_loop_test.go`
- `apps/edge/internal/service/single_request_cleanup_test.go`
- `apps/edge/internal/openai/chat_types.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/server.go`
### SDD Criteria
- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`, `[승인됨]`, `SDD 잠금: 해제`.
- First-line contribution id: `work-stage`.
- Targeted scenario: S09 — with a plan and writable workspace, canonical `ornith-fast` reads the plan, receives no `reasoning_effort=high`, performs actual changes and verification through IOP-owned tools, and produces a completion candidate.
- Evidence Map driver: “ornith-fast tool work fixture and high-option absence test.” The checklist requires an ordered write/command/result fixture, plan artifact read, exact identity correlation, completion candidate, verification evidence, and negative high-option assertions on every Work provider request.
### Verification Context
- No verification handoff was supplied. Repository-native sources were `agent-test/local/rules.md`, `edge-smoke.md`, and the service/OpenAI tool-loop tests.
- Checkout preflight remains branch `feature/iop-owned-single-request-agent-execution`, starting HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`; Go `1.26.2 linux/arm64` is available.
- Baseline relevant packages passed with fresh tests. The Work fixture uses deterministic provider frames and the existing typed Node-wire test doubles; it needs no endpoint, provider credential, or external runner.
- Constraint: package tests prove S09 stage behavior but are not actual Claude/Mac full-cycle evidence. That evidence belongs to S12 `claude-smoke` after Review activation.
- Confidence: high after predecessor completion. The service coordinator already enforces identity, single pending call, max iterations/output, stage deadline, capability allowlists, cancel propagation, and cleanup.
### Test Coverage Gaps
- Existing service tests prove generic internal calls and continuation, but not provider Chat tool-call decoding or multi-turn Work messages.
- Existing preset tests prove Work options omit high, but not the effective provider body on initial and resumed attempts.
- There is no cross-request pending-result correlation test for a production executor bridge and no S09 write+verify completion fixture. This packet adds both, including `-race` execution.
### Symbol References
No symbol is renamed or removed. `SingleRequestToolContinuation` at `apps/edge/internal/service/single_request_tool_types.go:88` is currently implemented only by test executors; the new request-safe bridge becomes the first production-capable implementation but is not installed until the successor packet.
### Split Judgment
- Predecessor 18 contract: authorized provider-stage codec and Plan artifact writer; PASS evidence is `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/complete.log`.
- At plan creation that `complete.log` is missing, so implementation must wait. The directory name `19+18_work_stage` declares the only new sibling dependency.
- This packet's stable contract is a directly testable Work runner plus concurrent continuation bridge; it does not activate an incomplete public execution path.
- Review/repair remains separate because its pass/defect branch and `reviewing -> repairing -> finalizing` invariant require independent evidence.
### Scope Rationale
This packet excludes Review verdicts/repairs, final user response, production executor installation, public error mapping, generic no-progress/error-cancel policy, config changes, and external provider smoke. It does not forward caller tools, arbitrary environment, provider credentials, private paths, or Plan/Review reasoning options to Work.
### Final Routing
- `evaluation_mode=first-pass`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures: scope/context/verification/evidence/ownership/decision all true. Scores `2/2/1/1/2` => G08, base `local-fit`, route `risk-boundary`, `worker/cloud/G08`, `PLAN-cloud-G08.md`.
- Review closures: all true. Scores `2/2/1/1/2` => G08, `official-review`, `review/cloud/G08`, `CODE_REVIEW-cloud-G08.md`.
- `large_indivisible_context=false`; positive loop risks: `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation` (4), so risk boundary matched; `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Dependencies and Execution Order
1. Do not implement until `agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/complete.log` exists. No archive candidate exists yet at plan creation.
2. Implement the Work stage using the predecessor's exact provider-stage and artifact contracts; do not re-open or replace those boundaries.
3. Do not install the runner through `SetSingleRequestExecutor`; `20+19_review_stage` owns final composition and activation.
## Implementation Checklist
- [ ] Add a concurrent request-safe internal tool continuation bridge that correlates one provider call to one coordinator result and unregisters on every success, failure, timeout, and cancel path.
- [ ] Implement the ornith-fast Work runner to read PLAN, expose only admitted IOP workspace tools, drive ordered provider/tool continuations, and return bounded completion and verification evidence.
- [ ] Add S09 fixtures for write+verify completion, every Work request's high-option absence, identity/correlation isolation, malformed/multiple tool calls, limits, cancellation, and provider/tool failures under `-race`.
- [ ] Update the current implementation spec and run dependency, focused race, service compatibility, broader Edge, vet, deterministic option search, and diff checks without production activation.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Correlate provider tool continuations per request
**Problem**
`SingleRequestToolContinuation` at `apps/edge/internal/service/single_request_tool_types.go:88` delivers results to an executor-level method, while `single_request_tool_loop.go:224` calls it asynchronously after the Node response. A production executor shared by concurrent requests needs exact request/stage/tool correlation without a global channel, lock-held blocking, duplicate delivery, or retained waiter after cancellation.
**Solution**
Create a private bridge in `single_request_work_stage.go` keyed by immutable `(request_id, stage_id, tool_call_id)`. Register before submitting the internal-tool envelope, reject duplicates, wait with the stage/request context, consume exactly one cloned result, and unregister in `defer` on every path. `ContinueInternalTool` validates all identities, performs one non-blocking/bounded delivery outside the map lock, and rejects missing or duplicate waiters generically.
Before (`apps/edge/internal/service/single_request_tool_types.go:88`):
```go
type SingleRequestToolContinuation interface {
ContinueInternalTool(context.Context, InternalWorkspaceToolResult) error
}
```
After (new implementation shape):
```go
type singleRequestToolBridge struct {
mu sync.Mutex
pending map[singleRequestToolKey]chan edgeservice.InternalWorkspaceToolResult
}
```
**Modified Files and Checklist**
- [ ] Add bridge/key/waiter lifecycle and `ContinueInternalTool` implementation in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Ensure stored values contain no prompt, tool arguments, workspace paths, credentials, or provider payloads.
- [ ] Add concurrent correlation, duplicate, stale, cancellation, and waiter cleanup tests in `apps/edge/internal/openai/single_request_work_stage_test.go`.
**Test Strategy**
Write `TestSingleRequestWorkToolBridgeConcurrentCorrelation` with multiple request identities and deliberately reordered results. Add duplicate/stale/cancel table cases and assert the pending map returns to zero; run under `go test -race`.
**Verification**
Run `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWorkToolBridge' -count=1`; every correlation case passes without race reports.
### [API-2] Drive the S09 Work provider/tool loop
**Problem**
The coordinator understands internal envelopes, but no runner reads PLAN, projects the admitted workspace capability into provider tool schemas, or resumes ornith-fast after `ContinueInternalTool`. A generic caller-facing Chat tool path would incorrectly forward caller tools and could terminate the outer Anthropic request.
**Solution**
Implement `singleRequestWorkStage.Run`. Read `SingleRequestArtifactPlan`, submit `working`, build fixed Work messages with the immutable task and plan, and derive tool definitions only from the admitted operation/command/environment names. On exactly one provider tool call, decode it into `InternalWorkspaceToolCall`, register the bridge, submit `internal_tool` with saved `working`, wait for the result, submit the saved-stage return envelope, append a bounded sanitized assistant/tool exchange, and redispatch. On content, require a strict completion schema containing non-empty completion candidate and verification evidence. Reject zero/multiple mixed tool calls, unknown names, malformed arguments, identity mismatch, missing evidence, or any effective `reasoning_effort` field.
Before (`apps/edge/internal/service/single_request.go:824`):
```go
case SingleRequestStateWorking:
return to == SingleRequestStateInternalTool || to == SingleRequestStateReviewing || ...
```
After (new runner behavior):
```go
plan := ctrl.ReadInternalArtifact(ctx, edgeservice.SingleRequestArtifactPlan)
// working -> internal_tool -> working repeats until a bounded completion candidate
```
**Modified Files and Checklist**
- [ ] Add Work prompt, tool-schema projection, multi-turn message assembly, strict completion decode, and result DTO in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Reuse the predecessor's provider codec and controller artifact API; do not bypass coordinator budgets or send workspace wire directly.
- [ ] Add deterministic initial/tool-result/resumed body assertions and completion parsing in `apps/edge/internal/openai/single_request_work_stage_test.go`.
**Test Strategy**
Write `TestSingleRequestWorkStageWritesAndVerifies`: fake ornith-fast first requests `workspace_write`, then an approved verification command, then returns completion/verification JSON. Assert PLAN bytes are included, each provider request targets the frozen Work route, no request contains `reasoning_effort`, tool results retain exact identities, and the completion DTO is bounded. Add table-driven malformed/multiple/unknown/tool-failure/provider-error/cancel cases.
**Verification**
Run `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1`; S09 and all failure/correlation fixtures pass.
### [API-3] Keep the service coordinator contract intact
**Problem**
The new runner depends on the service-owned tool state machine and cleanup gates. A locally passing fake-controller loop could still violate saved-stage transitions, max-iteration/output enforcement, cancel propagation, or cleanup ordering when used with the real coordinator.
**Solution**
Add an interoperability fixture that drives the Work runner through the existing controller contract and typed continuation surface. It must observe `working -> internal_tool -> working`, exact call/result identity, existing budget failures, caller cancellation, and no terminal cleanup regression. Do not modify service state transitions unless a compile mismatch proves a narrowly required adapter change; any such change is outside this plan and must be recorded as a deviation/blocker rather than silently expanded.
**Modified Files and Checklist**
- [ ] Add coordinator-compatible fake controller/envelope assertions to `apps/edge/internal/openai/single_request_work_stage_test.go`.
- [ ] Re-run existing `apps/edge/internal/service` tool-loop and cleanup packages unchanged as the service compatibility oracle.
**Test Strategy**
No new service test file is planned because the state-machine behavior is already covered exhaustively. The new OpenAI fixture proves the runner speaks that interface, and existing service tests are required final verification.
**Verification**
Run `go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup)' -count=1`; existing coordinator invariants remain green.
### [API-4] Record Work as implemented but inactive
**Problem**
After this packet the implementation spec must no longer say all provider stage drivers are absent, but Review/repair and production activation are still missing.
**Solution**
Update the spec with the implemented PLAN-read, ornith-fast option isolation, private tool continuation, completion/verification schema, and deterministic S09 fixture. Preserve the explicit deferral for Review/repair, composite installation, and S12 external evidence.
**Modified Files and Checklist**
- [ ] Update `agent-spec/runtime/edge-node-execution.md` implementation, verification, limitation, and history text.
**Test Strategy**
No document-only test; behavior is backed by API-1 through API-3.
**Verification**
Run `rg --sort path -n 'ornith-fast|Work stage|reasoning_effort|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md`; statements must match the partial implementation state.
## Modified Files Summary
| File | Items |
|------|-------|
| `apps/edge/internal/openai/single_request_work_stage.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_work_stage_test.go` | API-1, API-2, API-3 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/CODE_REVIEW-cloud-G08.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/18+17_plan_stage/complete.log` — predecessor completion evidence exists before implementation or review.
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1` — S09, continuation correlation, cancellation, and failure fixtures pass without races.
3. `go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup)' -count=1` — existing coordinator/tool/cleanup invariants pass freshly.
4. `go vet ./apps/edge/internal/openai && go test ./apps/edge/... -count=1` — OpenAI vets cleanly and broader Edge regression passes.
5. `rg --sort path -n 'reasoning_effort' apps/edge/internal/openai/single_request_work_stage.go apps/edge/internal/openai/single_request_work_stage_test.go` — production code contains only explicit rejection/omission logic and tests prove no effective Work request field.
6. `rg --sort path -n 'SetSingleRequestExecutor|NewSingleRequestExecutor' apps/edge --glob '*.go'` — no production composite installation exists yet.
7. `rg --sort path -n 'ornith-fast|Work stage|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md` — spec records Work as implemented and later activation/review/external evidence as deferred.
8. `git diff --check` — no whitespace errors.
Actual provider/Claude full-cycle evidence remains intentionally outside this packet and belongs to SDD S12 `claude-smoke`.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.

View file

@ -0,0 +1,178 @@
<!-- task=m-iop-owned-single-request-agent-execution/20+19_review_stage plan=1 tag=API milestone-task=review-stage -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> Complete the fixed checklists and evidence fields, leave both active files in place, and report ready for review. Only the official review agent may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the blocker, attempted commands/output, and resume condition here; do not change owner or scope.
## Overview
date=2026-08-07
task=m-iop-owned-single-request-agent-execution/20+19_review_stage, plan=1, tag=API
## For the Review Agent
Compare every item with source and freshly rerun recorded verification. Then append the official verdict and routing signals. On PASS, archive this file as `code_review_cloud_G09_1.log`, archive the plan as `plan_cloud_G09_1.log`, write `complete.log` preserving `milestone-task=review-stage`, and move the task directory to the dated archive. On WARN/FAIL, write only the next state prescribed by the code-review skill. The implementing agent must not perform these steps.
## Archive Evidence Snapshot
- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/plan_cloud_G09_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/code_review_cloud_G09_0.log`.
- The archived pair contains no implementation evidence and no official verdict. It was preserved because explicit self-review found material dependency and state-machine defects.
- Its active-only predecessor check could not survive task-19 archival. Its expected `repairing -> reviewing` edge is rejected by the existing service transition table and by the SDD, which requires re-review dispatch while the lifecycle remains `repairing`.
- It also omitted the direct reviewer inspection path `reviewing -> internal_tool(saved reviewing) -> reviewing`. This revision covers inspection and repair as separate deterministic fixtures.
- No production code, test, contract, spec, or roadmap completion is claimed by the archived pair.
## Implementation Item Completion
| Item | Status |
|------|---------|
| API-1 Implement strict Review, inspection, and persisted pass evidence | [ ] |
| API-2 Drive bounded repair and re-review without a false state edge | [ ] |
| API-3 Compose the three private stages | [ ] |
| API-4 Install and synchronize the active contract | [ ] |
## Implementation Checklist
- [ ] Implement Gemini high-reasoning Review with strict pass, direct non-mutating inspection, REVIEW persistence before finalization, and fail-closed bounded results.
- [ ] Implement one-tool-at-a-time repair with `repairing -> internal_tool(saved repairing) -> repairing`, re-review dispatch while state remains repairing, and no invalid `repairing -> reviewing` transition.
- [ ] Add a concurrent request-safe composite executor that drives Plan → Work → Review through one controller, reuses the predecessor continuation bridge, and returns only reviewer-approved output.
- [ ] Install the composite at Edge input startup and add S10, inspection, repair, full lifecycle, concurrent isolation, cancellation, cleanup, and installation fixtures without changing the public Anthropic schema.
- [ ] Update the current outer contract and implementation spec, then run dependency, focused race, installation, regression, vet, deterministic document/search, and diff checks while leaving S12 external evidence deferred.
- [ ] 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 section.
- [ ] Append one `PASS`, `WARN`, or `FAIL` verdict with verified `review_rework_count` and `evidence_integrity_failure`.
- [ ] Verify verdict, dimension assessment, and Required/Suggested/Nit classifications agree.
- [ ] Archive this file to `code_review_cloud_G09_1.log` and the plan to `plan_cloud_G09_1.log`.
- [ ] Verify `.gitignore` unignores task Markdown/log files and ignores `agent-roadmap/current.md`.
- [ ] On PASS, write template-compliant `complete.log`, preserve/report `milestone-task=review-stage`, move the task directory to the dated archive, and remove the active parent only if empty.
- [ ] On WARN/FAIL, write the exact next filesystem state and do not write `complete.log`.
## Deviations from Plan
_Record deviations and rationale here._
## Key Design Decisions
_Record implementation decisions here._
## Reviewer Checkpoints
- Verify direct inspection records `reviewing -> internal_tool(saved reviewing) -> reviewing`; mutation records `reviewing -> repairing -> internal_tool(saved repairing) -> repairing`.
- Verify re-review provider dispatch occurs while state remains `repairing`; no implementation/test expects or enables `repairing -> reviewing`.
- Verify every Review/re-review request uses the frozen Gemini route and effective high reasoning, and every tool is admitted, correlated, bounded, and serialized one at a time.
- Verify REVIEW is durable before finalizing, only reviewer-approved bytes become terminal, shared state is request-isolated, and all waiters clean up.
- Verify production installation uses existing boundaries, public schemas remain unchanged, docs claim only local deterministic evidence, and S12 remains deferred.
## Verification Results
Paste actual stdout/stderr for every command. Any replacement requires a matching `Deviations from Plan` entry.
### 1. Dependency evidence
`bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/19_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/19+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/19_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/19+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'`
Expected: exactly one path and exit zero before implementation or review.
```text
_Paste actual output here._
```
### 2. Focused Review/composite race tests
`go test -race ./apps/edge/internal/openai -run 'TestSingleRequest(ReviewStage|Executor)' -count=1`
```text
_Paste actual output here._
```
### 3. Service state and cleanup compatibility
`go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup|EnvelopeOrdering)' -count=1`
```text
_Paste actual output here._
```
### 4. Production installation
`go test ./apps/edge/internal/input -run 'TestManager.*SingleRequestExecutor' -count=1`
```text
_Paste actual output here._
```
### 5. Changed-path regression
`go test ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input -count=1`
```text
_Paste actual output here._
```
### 6. Vet and Edge regression
`go vet ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input && go test ./apps/edge/... -count=1`
```text
_Paste actual output here._
```
### 7. Installation and state-order evidence
`rg --sort path -n 'NewSingleRequestExecutor|SetSingleRequestExecutor|reasoning_effort|SingleRequestArtifactReview|finalizing|repairing' apps/edge/internal/openai apps/edge/internal/input --glob '*.go'`
Expected: installation and tests make high Review, legal repair, REVIEW persistence, and finalization ordering explicit; no `repairing -> reviewing` behavior is introduced.
```text
_Paste actual output here._
```
### 8. Canonical service transition table remains unchanged
`git diff --exit-code HEAD -- apps/edge/internal/service/single_request.go`
Expected: no task-20 worktree delta against the predecessor-completed transition table.
```text
_Paste actual output here._
```
### 9. Contract/spec synchronization
`rg --sort path -n 'Plan|Work|Review|repair|active|claude-smoke|S12|deferred' agent-contract/outer/anthropic-compatible-api.md agent-spec/runtime/edge-node-execution.md`
```text
_Paste actual output here._
```
### 10. Diff hygiene
`git diff --check`
```text
_Paste actual output here._
```
External qualification remains S12 `claude-smoke`.
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not change finalization metadata |
| Archive Evidence Snapshot | Fixed at stub creation | Read only cited prior evidence when needed |
| Implementation Item Completion and Checklist text/order | Fixed at stub creation | Implementing agent changes only `[ ]` to `[x]` |
| Review-Only Checklist | Review agent | Implementing agent must not modify it |
| Deviations, Key Design Decisions | Implementing agent | Replace placeholders with actual evidence |
| Reviewer Checkpoints and verification commands | Fixed at stub creation | Implementing agent fills output only; command changes require a deviation |
| Code Review Result | Review agent appends | Not present in this stub |

View file

@ -0,0 +1,236 @@
<!-- task=m-iop-owned-single-request-agent-execution/20+19_review_stage plan=1 tag=API milestone-task=review-stage -->
# Review, repair, and composite activation
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
The artifact, Plan, and Work packets establish service-owned lifecycle and private provider/tool primitives without installing a production executor. This final Epic slice implements Gemini Review and bounded repair, composes all stages behind existing executor/continuation contracts, installs the composite at Edge startup, and synchronizes the current contract/spec. Actual Claude/provider qualification remains S12 `claude-smoke`.
## Archive Evidence Snapshot
- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/plan_cloud_G09_0.log`.
- Prior review stub: `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/code_review_cloud_G09_0.log`.
- The archived pair contains no implementation evidence and no official verdict. It was preserved because explicit self-review found material dependency and state-machine defects.
- Its active-only predecessor check could not survive task-19 archival. Its expected `repairing -> reviewing` edge is rejected by the existing service transition table and by the SDD, which requires re-review dispatch while the lifecycle remains `repairing`.
- It also omitted the direct reviewer inspection path `reviewing -> internal_tool(saved reviewing) -> reviewing`. This revision covers inspection and repair as separate deterministic fixtures.
- No production code, test, contract, spec, or roadmap completion is claimed by the archived pair.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_tool_types.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `apps/edge/internal/service/service.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/input/manager.go`
- `apps/edge/internal/input/manager_test.go`
### SDD Criteria
- SDD is approved and unlocked; this packet contributes `review-stage`.
- S10 requires Gemini high-reasoning Review, strict pass, permitted reviewer inspection, one IOP-owned repair call at a time, `repairing -> internal_tool(saved repairing) -> repairing`, re-review after repair, REVIEW persistence, and only then finalization.
- The lifecycle table permits `reviewing -> internal_tool|repairing|finalizing` and `repairing -> internal_tool|finalizing`; it does not permit `repairing -> reviewing`.
- Provider-stage data stays private. The public result is only the reviewer-approved output after REVIEW is durable.
### Verification Context
- No verification handoff was supplied. Existing controller state-machine, cleanup, input composition, handler, and stream tests are the repository-native oracle.
- Checkout preflight: branch `feature/iop-owned-single-request-agent-execution`, starting HEAD `3bb4a24ad750a9ce5b7754a70db24545554ba238`; only active Epic task artifacts differ, with no direct production code/test/document delta from that base.
- Deterministic provider and workspace-tool fixtures can prove S10 and production composition without remote credentials or an external runner.
- Actual Claude/Mac full-cycle qualification remains the separate S12 `claude-smoke` task.
### Test Coverage Gaps
- Existing service tests cover the generic transition table and saved-stage restoration, but no provider runner proves direct reviewer inspection or repair/re-review semantics.
- No test proves that a re-review provider dispatch occurs while controller state remains `repairing`, or explicitly rejects the obsolete `repairing -> reviewing` expectation.
- No production composite currently proves final-output provenance, request-isolated continuation, installation, cancellation, or terminal cleanup across all stages.
### Symbol References
- `isValidTransition` in `apps/edge/internal/service/single_request.go` is the existing lifecycle oracle; do not add `repairing -> reviewing` or include that file in the planned modification set.
- `SingleRequestExecutor`, `SingleRequestToolContinuation`, `Service.SetSingleRequestExecutor`, and the predecessor's bridge are the composition boundaries to implement/reuse.
- `apps/edge/internal/input/manager.go` is the production installation point. No public Anthropic request or event type is renamed or extended.
### Split Judgment
- Predecessor 19 owns Work results and request-safe tool continuation. Resolve exactly one task-19 evidence file, read it, and inspect the completed source contract before implementation.
- Review, repair, final-output provenance, composite ownership, installation, and current-document synchronization form one ordered activation boundary: installation is unsafe without all earlier items.
- External Claude/provider qualification stays split as S12 because it requires a separate environment and evidence class.
### Scope Rationale
Include only Review/inspection/repair, composite wiring, production installation, deterministic lifecycle evidence, and current contract/spec synchronization. Exclude new service state edges, caller-visible schemas, caller tools/credentials, config examples, generic error/cancel quality tasks, and any claim that local fixtures satisfy S12.
### Final Routing
- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures are all true. Scores `2/2/2/1/2` => G09, base/route `grade-boundary`, `worker/cloud/G09`, `PLAN-cloud-G09.md`.
- Review closures are all true. Scores `2/2/2/1/2` => G09, `official-review`, `review/cloud/G09`, `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`; risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`; `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Dependencies and Execution Order
1. Before implementation or review, run the exact dependency command in Final Verification. It must print exactly one task-19 completion path from active or archive storage and exit zero; missing or ambiguous evidence is a blocker.
2. Read only that resolved `complete.log`, then inspect the completed Plan artifact, provider-stage, Work result, and continuation bridge APIs in source. Record a blocker instead of recreating or replacing an incompatible predecessor boundary.
3. Implement and prove Review pass, direct inspection, and repair/re-review before composing all stages.
4. Prove deterministic composite lifecycle and tool behavior before installing it in `apps/edge/internal/input/manager.go`.
5. Update current contract/spec last and leave S12 external evidence explicitly deferred.
## Implementation Checklist
- [ ] Implement Gemini high-reasoning Review with strict pass, direct non-mutating inspection, REVIEW persistence before finalization, and fail-closed bounded results.
- [ ] Implement one-tool-at-a-time repair with `repairing -> internal_tool(saved repairing) -> repairing`, re-review dispatch while state remains repairing, and no invalid `repairing -> reviewing` transition.
- [ ] Add a concurrent request-safe composite executor that drives Plan → Work → Review through one controller, reuses the predecessor continuation bridge, and returns only reviewer-approved output.
- [ ] Install the composite at Edge input startup and add S10, inspection, repair, full lifecycle, concurrent isolation, cancellation, cleanup, and installation fixtures without changing the public Anthropic schema.
- [ ] Update the current outer contract and implementation spec, then run dependency, focused race, installation, regression, vet, deterministic document/search, and diff checks while leaving S12 external evidence deferred.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Implement strict Review, inspection, and persisted pass evidence
**Problem**
Work returns only a private completion candidate and verification evidence. Returning it directly would skip independent Review. A reviewer may also need to inspect workspace state before deciding, but the prior plan omitted the SDD's `reviewing -> internal_tool(saved reviewing) -> reviewing` path.
**Solution**
Add `single_request_review_stage.go`. Read PLAN, accept the bounded Work candidate/evidence, submit `reviewing`, and dispatch a fixed Gemini high request containing only immutable task, PLAN, candidate, and verification evidence. Decode a closed union:
- strict pass with non-empty bounded final output and review summary;
- exactly one admitted non-mutating inspection call while reviewing; or
- exactly one admitted repair call that enters repairing.
For inspection, register the predecessor bridge, submit `internal_tool` with saved `reviewing`, wait for the exact result, restore `reviewing`, append a bounded sanitized exchange, and redispatch Review. On pass, write `SingleRequestArtifactReview` before submitting `finalizing`, then return a clone of only the approved output. Reject free-form/mixed/multiple/oversized outcomes and sanitize provider/tool failures.
**Modified Files and Checklist**
- [ ] Add prompt, high-option dispatch, closed result decoding, inspection loop, write-before-finalize ordering, and bounded DTOs in `apps/edge/internal/openai/single_request_review_stage.go`.
- [ ] Add pass, direct inspection, exact request body, malformed/mixed/multiple/provider error, artifact failure, bounds, and cancellation tests in `apps/edge/internal/openai/single_request_review_stage_test.go`.
**Test Strategy**
Use deterministic provider/tool fakes and a recording controller. Assert `reviewing -> internal_tool(saved reviewing) -> reviewing -> finalizing` for an inspection-before-pass fixture, high reasoning on every review request, REVIEW before finalizing, exact correlation, and no private candidate/error leakage.
**Verification**
Run the focused ReviewStage race test in Final Verification.
### [API-2] Drive bounded repair and re-review without a false state edge
**Problem**
S10 assigns mutation to Review-owned repair. The existing state machine restores `repairing` after every tool result and permits finalizing from repairing; it deliberately rejects `repairing -> reviewing`. The archived plan's expected sequence would therefore fail and tempt an out-of-scope service transition change.
**Solution**
On a first mutating defect call, submit `repairing`, then execute one admitted tool through `internal_tool` with saved `repairing`. Restore `repairing`, append the bounded sanitized tool exchange, and redispatch Gemini Review while controller state stays `repairing`. Any subsequent admitted inspection or repair call repeats `repairing -> internal_tool(saved repairing) -> repairing`. Only a later strict pass may persist REVIEW and submit `finalizing`. Enforce coordinator/local bounds, exact identities, and no pre-repair candidate release. Do not modify the service transition table.
**Modified Files and Checklist**
- [ ] Add repair/re-review behavior to `apps/edge/internal/openai/single_request_review_stage.go` using the predecessor bridge and controller API.
- [ ] Add `reviewing -> repairing -> internal_tool(saved repairing) -> repairing -> finalizing` pass-after-repair, repeated bounded tool, correlation, failure, stale/duplicate result, cancellation, and waiter-cleanup fixtures in `apps/edge/internal/openai/single_request_review_stage_test.go`.
- [ ] Assert the re-review provider call happens while recorded lifecycle state is `repairing` and that no test or code attempts `repairing -> reviewing`.
**Test Strategy**
Record states separately from provider dispatches. The key fixture must prove the second Gemini review request occurs between restored `repairing` and finalizing, uses high reasoning, and reaches finalizing only after strict pass plus durable REVIEW.
**Verification**
Run focused Review race tests and deterministic state-order search; `apps/edge/internal/service/single_request.go` must remain unchanged by this packet.
### [API-3] Compose the three private stages
**Problem**
Installing stage runners independently would split lifecycle ownership, let a Work candidate become terminal, and leave continuation without a stable concurrent executor instance.
**Solution**
Add `single_request_executor.go` implementing existing service executor and continuation interfaces. Per request, run Plan, Work, and Review against one controller and immutable binding. Delegate results to the request-safe bridge, preserve cancellation and generic errors, and return only the Review-approved output. Shared executor state is limited to keyed bridge entries, all removed on every terminal path.
**Modified Files and Checklist**
- [ ] Add the composite and exported production constructor in `apps/edge/internal/openai/single_request_executor.go`.
- [ ] Add pass, inspection, repair, concurrent isolation, cancellation, stage failure, final-output provenance, and waiter-cleanup tests in `apps/edge/internal/openai/single_request_executor_test.go`.
**Test Strategy**
Drive a deterministic full lifecycle through the real service controller with one Work tool and Review inspection/repair variants. Assert legal monotonic envelopes, artifact order, reviewer-only terminal output, concurrent identity isolation under `-race`, and cleanup after injected failures.
**Verification**
Run focused executor/review race tests and unchanged service cleanup/tool-loop tests.
### [API-4] Install and synchronize the active contract
**Problem**
A complete composite remains unreachable until Edge startup installs it. Once installed, current docs must stop claiming managed single-request execution is unavailable while distinguishing deterministic local evidence from S12 qualification.
**Solution**
Construct and install the executor in `apps/edge/internal/input/manager.go` after its dependencies exist. Add an input fixture proving production construction no longer leaves the executor unset; do not add a public getter or change Anthropic request/event schemas. Update the outer contract and current spec with stage order, private provider outcomes, generic failure behavior, local evidence, and explicit S12 deferral.
**Modified Files and Checklist**
- [ ] Install `openai.NewSingleRequestExecutor(...)` through the existing setter in `apps/edge/internal/input/manager.go`.
- [ ] Add installation/unavailable-regression coverage in `apps/edge/internal/input/manager_test.go`.
- [ ] Update `agent-contract/outer/anthropic-compatible-api.md` and `agent-spec/runtime/edge-node-execution.md` without claiming external qualification.
**Test Strategy**
Use the existing input construction seam and deterministic dependencies. Prove installation, then run unchanged public handler/stream regressions.
**Verification**
Run input installation, changed-package regression/vet, constructor/state searches, and current-document searches in Final Verification.
## Modified Files Summary
| File | Items |
|------|-------|
| `apps/edge/internal/openai/single_request_review_stage.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_review_stage_test.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_executor.go` | API-3 |
| `apps/edge/internal/openai/single_request_executor_test.go` | API-3 |
| `apps/edge/internal/input/manager.go` | API-4 |
| `apps/edge/internal/input/manager_test.go` | API-4 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-4 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/CODE_REVIEW-cloud-G09.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.
1. `bash -c 'set -euo pipefail; shopt -s nullglob; candidates=(agent-task/m-iop-owned-single-request-agent-execution/19_*/complete.log agent-task/m-iop-owned-single-request-agent-execution/19+*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/19_*/complete.log agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/19+*/complete.log); printf "%s\n" "${candidates[@]}"; ((${#candidates[@]} == 1))'` — prints exactly one predecessor completion path and exits zero before implementation or review.
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequest(ReviewStage|Executor)' -count=1` — pass, direct inspection, repair/re-review, composite, concurrency, cancellation, and failure fixtures pass without races.
3. `go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup|EnvelopeOrdering)' -count=1` — unchanged coordinator tool-loop, cleanup, and envelope-ordering invariants pass freshly.
4. `go test ./apps/edge/internal/input -run 'TestManager.*SingleRequestExecutor' -count=1` — production construction installs the executor.
5. `go test ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input -count=1` — changed-path regressions pass freshly.
6. `go vet ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input && go test ./apps/edge/... -count=1` — changed packages vet cleanly and broader Edge regression passes.
7. `rg --sort path -n 'NewSingleRequestExecutor|SetSingleRequestExecutor|reasoning_effort|SingleRequestArtifactReview|finalizing|repairing' apps/edge/internal/openai apps/edge/internal/input --glob '*.go'` — installation, high Review option, repair, REVIEW persistence, and finalization ordering are explicit and test-covered; no `repairing -> reviewing` implementation is introduced.
8. `git diff --exit-code HEAD -- apps/edge/internal/service/single_request.go` — this packet leaves the predecessor-completed canonical service transition table unchanged in its implementation worktree and index.
9. `rg --sort path -n 'Plan|Work|Review|repair|active|claude-smoke|S12|deferred' agent-contract/outer/anthropic-compatible-api.md agent-spec/runtime/edge-node-execution.md` — docs describe active local behavior and leave external qualification deferred.
10. `git diff --check` — no whitespace errors.
Actual provider/Claude full-cycle evidence remains owned by S12 `claude-smoke`.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.

View file

@ -0,0 +1,189 @@
<!-- task=m-iop-owned-single-request-agent-execution/20+19_review_stage plan=0 tag=API milestone-task=review-stage -->
# 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-07
task=m-iop-owned-single-request-agent-execution/20+19_review_stage, plan=0, tag=API
## 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-G09.md` → `code_review_cloud_G09_0.log` and `PLAN-cloud-G09.md` → `plan_cloud_G09_0.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/20+19_review_stage/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=review-stage` 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 strict Review and persisted pass evidence | [ ] |
| API-2 Drive bounded repair and mandatory re-review | [ ] |
| API-3 Compose the three private stages | [ ] |
| API-4 Install and synchronize the active contract | [ ] |
## Implementation Checklist
- [ ] Implement the Gemini high-reasoning Review runner that reads PLAN and Work evidence, accepts only strict pass output, persists REVIEW before finalization, and fails closed on malformed or provider-error outcomes.
- [ ] Implement the one-tool-at-a-time repair path with `repairing -> internal_tool(saved repairing) -> repairing`, exact continuation correlation, bounded re-review, and no release of an unreviewed Work candidate.
- [ ] Add the concurrent request-safe composite executor that drives Plan → Work → Review through one controller, exposes the predecessor's continuation bridge, and returns only reviewer-approved final output.
- [ ] Install the composite executor at Edge input startup and add deterministic S10, full lifecycle, concurrent isolation, cancellation, cleanup, and installation fixtures without altering the public Anthropic schema.
- [ ] Update the current outer contract and implementation spec, then run dependency, focused race, installation, regression, vet, deterministic contract/spec, and diff checks while leaving S12 external evidence deferred.
- [ ] 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.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G09_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_0.log`.
- [ ] 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-owned-single-request-agent-execution/20+19_review_stage/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/20+19_review_stage/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=review-stage` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Verify every Review dispatch uses frozen Gemini admission with effective high reasoning and only the immutable task, PLAN, bounded Work candidate, and verification evidence.
- Verify defect handling permits exactly one admitted IOP repair call at a time and observes `reviewing -> repairing -> internal_tool(saved repairing) -> repairing -> reviewing` before any pass.
- Verify REVIEW persistence precedes finalizing, only reviewer-approved bytes reach the caller, and malformed/provider/tool/artifact/cancel paths expose no candidate or provider detail.
- Verify the composite stores no unkeyed per-request mutable state, correlates concurrent continuations exactly, and cleans waiters plus service resources on every exit.
- Verify production startup installs the composite through the existing setter without changing the public Anthropic schema, and contract/spec text leaves S12 external qualification deferred.
## Verification Results
Paste actual stdout/stderr for every command. If a command changes, record the replacement and reason in `Deviations from Plan` before pasting its output.
### 1. Dependency evidence
`test -f agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/complete.log`
Expected: exit zero before implementation or review.
```text
_Paste actual output here._
```
### 2. Focused Review/composite race tests
`go test -race ./apps/edge/internal/openai -run 'TestSingleRequest(ReviewStage|Executor)' -count=1`
Expected: S10, repair, composite, concurrency, cancellation, and failure fixtures pass without races.
```text
_Paste actual output here._
```
### 3. Production installation
`go test ./apps/edge/internal/input -run 'TestManager.*SingleRequestExecutor' -count=1`
Expected: production construction installs the executor and does not regress to unavailable.
```text
_Paste actual output here._
```
### 4. Changed-package regression
`go test ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input -count=1`
Expected: coordinator, public handler/stream, OpenAI, and input regressions pass freshly.
```text
_Paste actual output here._
```
### 5. Vet and Edge regression
`go vet ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input && go test ./apps/edge/... -count=1`
Expected: changed packages vet cleanly and broader Edge regression passes.
```text
_Paste actual output here._
```
### 6. Lifecycle and installation evidence
`rg --sort path -n 'NewSingleRequestExecutor|SetSingleRequestExecutor|reasoning_effort|SingleRequestArtifactReview|finalizing|repairing' apps/edge/internal/openai apps/edge/internal/input --glob '*.go'`
Expected: installation, high Review option, repair, REVIEW persistence, and finalization ordering are explicit and test-covered.
```text
_Paste actual output here._
```
### 7. Contract and spec synchronization
`rg --sort path -n 'Plan|Work|Review|repair|active|claude-smoke|S12|deferred' agent-contract/outer/anthropic-compatible-api.md agent-spec/runtime/edge-node-execution.md`
Expected: documents describe active local behavior and leave external qualification deferred.
```text
_Paste actual output here._
```
### 8. Diff hygiene
`git diff --check`
Expected: exit zero with no output.
```text
_Paste actual output here._
```
External note: actual provider/Claude full-cycle evidence remains owned by SDD S12 `claude-smoke`.
---
> **[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 |

View file

@ -0,0 +1,199 @@
<!-- task=m-iop-owned-single-request-agent-execution/20+19_review_stage plan=0 tag=API milestone-task=review-stage -->
# Review, repair, and composite activation
## For the Implementing Agent
Filling the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` is the mandatory last implementation step. Run every verification command, paste actual output, keep both active files in place, and report ready for review; only the official code-review skill may append a verdict, archive files, write `complete.log`, or classify the next state. If blocked, record the exact blocker, attempted commands/output, and resume condition only in the review evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, or change the owner or scope.
## Background
The artifact, Plan, and Work packets establish the service-owned lifecycle and private provider/tool primitives without installing a production executor. This final Epic slice implements the fixed Gemini Review/repair loop, composes all three stages behind the existing service executor/continuation contracts, installs that composite at Edge startup, and updates the current contract/spec. Actual Claude/provider qualification remains the separate S12 `claude-smoke` work item.
## Analysis
### Files Read
- `AGENTS.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-owned-single-request-agent-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_tool_types.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `apps/edge/internal/service/single_request_test.go`
- `apps/edge/internal/service/single_request_cleanup_test.go`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/single_request_preset_binding.go`
- `apps/edge/internal/input/manager.go`
- `apps/edge/internal/input/manager_test.go`
### SDD Criteria
- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`, `[승인됨]`, `SDD 잠금: 해제`.
- S10 requires Gemini Review with high reasoning, strict pass output, exactly one IOP repair tool call for a defect, `repairing -> internal_tool(saved repairing) -> repairing`, re-review after repair, Review artifact persistence, and only then finalization.
- The production executor must keep all provider stage outcomes private, return only the reviewer-approved final output, and preserve the service coordinator's monotonic lifecycle and cleanup ownership.
- First-line contribution id: `review-stage`.
### Current Behavior and Root Cause
- `apps/edge/internal/service/single_request.go` already invokes a `SingleRequestExecutor`, but no production constructor is installed through `SetSingleRequestExecutor`.
- The preceding packets intentionally stop after a private Work completion candidate. Without Review, repair, and composite ownership, accepting that candidate would bypass S10 and expose an internal stage result as caller output.
- `apps/edge/internal/input/manager.go` creates the OpenAI service and installs its dependencies, making it the narrow production composition point. The existing service lifecycle and public Anthropic handler remain the external boundary and must not be duplicated.
- The outer contract and implementation spec currently defer production execution. They must be updated only after installation and deterministic end-to-end fixtures exist.
### Direct-Small Classification
No slice is direct-small. Review/repair changes provider dispatch and internal-tool temporal behavior; composite execution introduces shared continuation/concurrency ownership; installation changes a runtime responsibility boundary; and contract/spec synchronization depends on those behaviors. They are one ordered large slice with explicit verification.
### Routing Decision
- Plan finalizer input: mode `build`, task key `m-iop-owned-single-request-agent-execution/20+19_review_stage`, plan index `0`, tag `API`, milestone contribution `review-stage`, candidate `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/PLAN.md`.
- Build closures: scope/context/verification/evidence/ownership/decision all true. Scores `2/2/2/1/2` => G09, base and route `grade-boundary`, `worker/cloud/G09`, `PLAN-cloud-G09.md`.
- Review closures: all true. Scores `2/2/2/1/2` => G09, `official-review`, `review/cloud/G09`, `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`; positive loop risks: `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation` (4); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
## Dependencies and Execution Order
1. Do not implement until `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/complete.log` exists. No archive candidate exists yet at plan creation.
2. Implement Review/repair against the predecessor's exact artifact, provider-stage, Work result, and tool-continuation contracts; do not reopen their ownership or wire shapes.
3. Compose Plan → Work → Review and prove deterministic lifecycle/tool behavior before installing the constructor in `apps/edge/internal/input/manager.go`.
4. Update the outer contract and current implementation spec last. Do not mark S12 external provider/Claude qualification complete.
## Implementation Checklist
- [ ] Implement the Gemini high-reasoning Review runner that reads PLAN and Work evidence, accepts only strict pass output, persists REVIEW before finalization, and fails closed on malformed or provider-error outcomes.
- [ ] Implement the one-tool-at-a-time repair path with `repairing -> internal_tool(saved repairing) -> repairing`, exact continuation correlation, bounded re-review, and no release of an unreviewed Work candidate.
- [ ] Add the concurrent request-safe composite executor that drives Plan → Work → Review through one controller, exposes the predecessor's continuation bridge, and returns only reviewer-approved final output.
- [ ] Install the composite executor at Edge input startup and add deterministic S10, full lifecycle, concurrent isolation, cancellation, cleanup, and installation fixtures without altering the public Anthropic schema.
- [ ] Update the current outer contract and implementation spec, then run dependency, focused race, installation, regression, vet, deterministic contract/spec, and diff checks while leaving S12 external evidence deferred.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
### [API-1] Implement strict Review and persisted pass evidence
**Problem**
Work produces only an internal completion candidate and verification evidence. Returning it directly would skip the independently routed Gemini reviewer and omit the required durable REVIEW artifact.
**Solution**
Create `single_request_review_stage.go` with a runner that reads the private PLAN artifact, receives the bounded Work result, submits `reviewing`, and sends a fixed high-reasoning Gemini request containing the immutable task, plan, candidate, and verification evidence. Decode a closed result union: pass requires non-empty bounded final output and review summary; defect requires a single repair instruction represented by exactly one admitted IOP workspace tool call. On pass, write `SingleRequestArtifactReview`, then submit `finalizing`, and only then return cloned final bytes. Reject free-form/mixed/multiple/oversized results and sanitize provider failures.
**Modified Files and Checklist**
- [ ] Add the Review prompt, high-option dispatch, closed pass/defect decode, REVIEW write-before-finalize ordering, and bounded result DTO in `apps/edge/internal/openai/single_request_review_stage.go`.
- [ ] Add pass ordering, exact request-body, malformed/mixed/multiple/provider-error, artifact-failure, and cancellation tests in `apps/edge/internal/openai/single_request_review_stage_test.go`.
**Test Strategy**
Use a deterministic provider fake and recording controller. Assert every Review request targets the frozen Gemini route with effective `reasoning_effort=high`; pass writes REVIEW before `finalizing`; no raw provider payload or candidate escapes any failure.
**Verification**
Run `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestReviewStage' -count=1`; pass and fail-closed cases must succeed without races.
### [API-2] Drive bounded repair and mandatory re-review
**Problem**
A defect cannot be finalized or handed back to Work. S10 assigns repair to the Review runner and requires the coordinator's saved-stage internal-tool round trip followed by another independent Review decision.
**Solution**
For a defect response, require exactly one known tool and admitted operation. Submit `repairing`, register the predecessor's correlation bridge, submit `internal_tool` with saved `repairing`, wait for the exact result, submit the saved-stage return, append a bounded sanitized tool exchange, and redispatch Review. Enforce coordinator and local review bounds, reject recursive/multiple/unknown calls, and never expose the pre-repair candidate. Only a later strict pass may persist REVIEW and finalize.
**Modified Files and Checklist**
- [ ] Add the repair/re-review loop to `apps/edge/internal/openai/single_request_review_stage.go` using the predecessor bridge and controller API.
- [ ] Add defect→repair→re-review→pass, correlation, tool/provider failure, bound, duplicate/stale result, and cancel fixtures to `apps/edge/internal/openai/single_request_review_stage_test.go`.
**Test Strategy**
Record exact states and envelopes for a defect fixture. Require `reviewing -> repairing -> internal_tool(saved repairing) -> repairing -> reviewing -> finalizing`, exact tool identity, high reasoning on both Review dispatches, and zero retained waiters.
**Verification**
Run the focused Review race test and inspect its state-order assertion; no defect fixture may reach finalizing before a re-review pass.
### [API-3] Compose the three private stages
**Problem**
Installing stage runners independently would split lifecycle ownership, allow a Work candidate to become terminal, and leave `ContinueInternalTool` without a stable executor instance for concurrent requests.
**Solution**
Create `single_request_executor.go` implementing the existing service executor and tool-continuation interfaces. For each request, run Plan, Work, and Review in order against the same controller and immutable binding. Delegate tool results to the request-safe bridge, preserve cancellation and generic errors, and return only the reviewer-approved final output. The shared executor must contain no per-request mutable state outside keyed bridge entries and must clean every entry on all terminal paths.
**Modified Files and Checklist**
- [ ] Add the composite implementation and exported production constructor in `apps/edge/internal/openai/single_request_executor.go`.
- [ ] Add full pass, repair, concurrent request isolation, cancellation, stage failure, final-output provenance, and waiter cleanup tests in `apps/edge/internal/openai/single_request_executor_test.go`.
**Test Strategy**
Drive a deterministic full lifecycle through the real service controller, including one Work tool and one Review repair tool. Assert the monotonic envelope sequence, artifact order, only the reviewer output at terminal, concurrent identity isolation under `-race`, and cleanup after every injected failure.
**Verification**
Run `go test -race ./apps/edge/internal/openai -run 'TestSingleRequest(ReviewStage|Executor)' -count=1` and the existing service cleanup/tool-loop tests.
### [API-4] Install and synchronize the active contract
**Problem**
Even a complete composite remains unreachable until Edge startup installs it. Once installed, the outer contract/spec must stop claiming that managed single-request execution is unavailable, while still distinguishing deterministic local coverage from S12 external qualification.
**Solution**
Construct and install the executor in `apps/edge/internal/input/manager.go` after the OpenAI service and required runtime dependencies exist. Add an input-layer fixture that exercises the existing single-request path far enough to prove the executor is installed rather than receiving the current unavailable error; do not add a public getter or change the Anthropic request/stream schema. Update the outer contract and current spec with the active ownership, stage ordering, generic failure behavior, local evidence, and explicit S12 deferral.
**Modified Files and Checklist**
- [ ] Install `openai.NewSingleRequestExecutor(...)` through the existing service setter in `apps/edge/internal/input/manager.go`.
- [ ] Add installation and unavailable-regression coverage in `apps/edge/internal/input/manager_test.go`.
- [ ] Update `agent-contract/outer/anthropic-compatible-api.md` and `agent-spec/runtime/edge-node-execution.md` without changing request/event schemas or claiming external qualification.
**Test Strategy**
Use the existing input construction seam and deterministic dependencies. Prove the production manager no longer leaves the executor unset, then run public handler/stream regressions unchanged.
**Verification**
Run the input installation test, broader Edge tests, and deterministic searches for constructor installation, stage order, REVIEW-before-finalize, active contract wording, and deferred S12 evidence.
## Modified Files Summary
| File | Items |
|------|-------|
| `apps/edge/internal/openai/single_request_review_stage.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_review_stage_test.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_executor.go` | API-3 |
| `apps/edge/internal/openai/single_request_executor_test.go` | API-3 |
| `apps/edge/internal/input/manager.go` | API-4 |
| `apps/edge/internal/input/manager_test.go` | API-4 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-4 |
| `agent-spec/runtime/edge-node-execution.md` | API-4 |
| `agent-task/m-iop-owned-single-request-agent-execution/20+19_review_stage/CODE_REVIEW-cloud-G09.md` | API-1, API-2, API-3, API-4 |
## Final Verification
Fresh output is required; Go tests use `-count=1` and cached output is not acceptable.
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/complete.log` — predecessor completion evidence exists before implementation or review.
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequest(ReviewStage|Executor)' -count=1` — S10, repair, composite, concurrency, cancellation, and failure fixtures pass without races.
3. `go test ./apps/edge/internal/input -run 'TestManager.*SingleRequestExecutor' -count=1` — production construction installs the executor and does not regress to unavailable.
4. `go test ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input -count=1` — coordinator, public handler/stream, OpenAI, and input regressions pass freshly.
5. `go vet ./apps/edge/internal/service ./apps/edge/internal/openai ./apps/edge/internal/input && go test ./apps/edge/... -count=1` — changed packages vet cleanly and broader Edge regression passes.
6. `rg --sort path -n 'NewSingleRequestExecutor|SetSingleRequestExecutor|reasoning_effort|SingleRequestArtifactReview|finalizing|repairing' apps/edge/internal/openai apps/edge/internal/input --glob '*.go'` — installation, high Review option, repair, REVIEW persistence, and finalization ordering are explicit and test-covered.
7. `rg --sort path -n 'Plan|Work|Review|repair|active|claude-smoke|S12|deferred' agent-contract/outer/anthropic-compatible-api.md agent-spec/runtime/edge-node-execution.md` — documents describe active local behavior and leave external qualification deferred.
8. `git diff --check` — no whitespace errors.
Actual provider/Claude full-cycle evidence remains intentionally outside this packet and belongs to SDD S12 `claude-smoke`.
After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.