<!-- 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 `f4dad6ba88ae442e08ab67f49a5b1a65dd4719e9`; only active Epic task-artifact refinement changes differ, with no direct production code/test/spec/contract delta from that checkpoint.
- 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 in this packet. Task 21 composes it after task 20 completes Review, and task 22 installs the composite.
- 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 Review, task 21 owns final composition, and task 22 owns production installation.

## 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. `test ! -e apps/edge/internal/openai/single_request_executor.go && bash -c 'set -euo pipefail; if rg --sort path -n "NewSingleRequestExecutor|SetSingleRequestExecutor" apps/edge/internal/input/manager.go; then exit 1; else test $? -eq 1; fi'` — exits zero with no output only when neither a production composite nor its installation exists.
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`.
