<!-- task=m-iop-owned-single-request-agent-execution/19+18_work_stage plan=2 tag=REVIEW_API milestone-task=work-stage -->

# Repair Work stage coordinator and authority boundaries

## For the Implementing Agent

Filling the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` is the mandatory last implementation step. Execute this plan's selected fixes and write boundary, run every verification command freshly, paste actual notes and output, keep both active files in place, and report ready for review. Finalization is code-review-skill only. If blocked, record only the exact blocker, attempted commands/output, and resume condition in implementation-owned evidence fields; do not ask the user, call a user-input tool, create a control-plane stop file, classify the next state, archive logs, or write `complete.log`.

## Background

The private Work runner passes its fake-only tests but cannot submit a standard OpenAI tool call through the real single-request coordinator. Its option, environment-schema, and continuation boundaries also admit data or duplicate delivery that the frozen binding forbids. This follow-up repairs those contracts and replaces the overclaimed evidence with real coordinator and failure-path coverage while keeping Work uninstalled.

## Archive Evidence Snapshot

- Prior plan: `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/plan_cloud_G08_1.log`.
- Prior review: `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/code_review_cloud_G08_1.log`; verdict `FAIL`, with Required R1-R5, no Suggested or Nit findings.
- R1-R5 affect `apps/edge/internal/openai/single_request_work_stage.go` and `apps/edge/internal/openai/single_request_work_stage_test.go`: coordinator identity/argument decoding, reserved options, environment schema, duplicate continuation delivery, and missing provider/tool/limit/cancel evidence.
- Fresh focused race, service compatibility, vet, and broad Edge commands passed, but the focused fake bypassed coordinator validation and did not contain the scenarios claimed by its evidence; `evidence_integrity_failure=true`.
- The predecessor remains satisfied by `agent-task/archive/2026/08/m-iop-owned-single-request-agent-execution/18+17_plan_stage/complete.log` (`PASS`). The Milestone carryover remains `milestone-task=work-stage`, SDD S09; S12 external Claude/Mac qualification remains deferred.

## Finding Resolution Map

| Finding | Mode | Exact fix/dependency evidence | Changed or satisfied precondition |
|---------|------|-------------------------------|-----------------------------------|
| R1 | direct-fix | Normalize the private coordinator stage id and strictly decode the OpenAI argument string in `apps/edge/internal/openai/single_request_work_stage.go`; add an actual service-controller write/verify fixture in `apps/edge/internal/openai/single_request_work_stage_test.go`. | A standard OpenAI tool call reaches the real coordinator as canonical `work` plus one strict inner JSON object instead of failing identity or argument decoding. |
| R2 | direct-fix | Reject case-folded aliases of every reserved Work body key in `apps/edge/internal/openai/single_request_work_stage.go` and cover initial/resumed bodies in `apps/edge/internal/openai/single_request_work_stage_test.go`. | No alias can serialize high reasoning, credentials, or structural request fields. |
| R3 | direct-fix | Build the command environment schema from `EnvironmentNames` with a closed object in `apps/edge/internal/openai/single_request_work_stage.go`; assert the provider-visible schema in `apps/edge/internal/openai/single_request_work_stage_test.go`. | Provider tool selection is limited to environment names frozen in the binding. |
| R4 | direct-fix | Atomically claim/remove a pending continuation before delivery in `apps/edge/internal/openai/single_request_work_stage.go`; add a synchronized duplicate race in `apps/edge/internal/openai/single_request_work_stage_test.go`. | Exactly one concurrent delivery succeeds and no waiter remains. |
| R5 | direct-fix | Add deterministic provider submit/frame, real coordinator tool denial/failure, output/iteration/deadline, and provider/tool cancellation cases in `apps/edge/internal/openai/single_request_work_stage_test.go`. | The claimed S09 and failure matrix becomes executable evidence rather than an unchanged fake-path assertion. |

## Analysis

### Files Read

- `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/execution-runtime.md`
- `agent-contract/inner/edge-node-runtime-wire.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `apps/edge/internal/openai/single_request_provider_stage.go`
- `apps/edge/internal/openai/single_request_work_stage.go`
- `apps/edge/internal/openai/single_request_work_stage_test.go`
- `apps/edge/internal/service/single_request.go`
- `apps/edge/internal/service/single_request_types.go`
- `apps/edge/internal/service/single_request_tool_loop.go`
- `apps/edge/internal/service/single_request_tool_loop_test.go`
- `apps/edge/internal/service/single_request_tool_types.go`
- `apps/edge/internal/service/single_request_tool_types_test.go`

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`; approved, implementation unlocked, no unresolved user decision.
- First-line metadata remains `milestone-task=work-stage` and maps to Acceptance Scenario S09.
- S09 requires canonical `ornith-fast` to read PLAN without inherited high reasoning, perform an actual workspace change and verification through IOP-owned tools, and return a completion candidate.
- The S09 Evidence Map requires an ornith-fast tool-work fixture, high-option absence test, and `work-stage` actual workspace/verification evidence. Those rows require the real coordinator fixture, closed option/schema assertions, failure-path coverage, and the focused `-race` command below. S12 `claude-smoke` is a separate later task and does not block this private inactive packet.

### Verification Context

- No neutral verification handoff was supplied. Repository-native fallback evidence came from the active review, selected SDD/spec/contracts, complete Work/coordinator sources, related tests, and fresh commands.
- Checkout: branch `feature/iop-owned-single-request-agent-execution`, HEAD `22a8b81201e89d75c1e6c92342a8081472e8e436`, dirty with same-Milestone predecessor and sibling work. Preserve all unrelated changes; the two files in `Modified Files Summary` are the production/test write boundary.
- Toolchain: `go version go1.26.2 linux/arm64`. Fresh review commands used `-count=1`; focused Work tests also used `-race`.
- Fresh process results passed for the predecessor resolver, focused Work race tests, service tool-loop/cleanup tests, OpenAI/service vet, broad Edge tests, activation guard, spec search, and `git diff --check`. Confidence is high in the defects because the service's canonical stage function requires `work`, its strict decoder requires an object, while the Work runner submits `working` plus a quoted JSON string and its fake controller performs neither validation.
- No external verification is required in this packet. Actual Claude/Mac execution is S12 and remains outside this checkout-local follow-up.

### Test Coverage Gaps

- Standard OpenAI argument decoding through the real coordinator: not covered; the current fake fabricates a result.
- Canonical Work stage identity: not covered by Work tests; service tests independently require `work`.
- Case-folded reserved keys and closed environment names: not covered.
- Concurrent duplicate continuation delivery: current race test uses distinct keys and does not synchronize duplicates.
- Provider submit/frame failures, real tool denial/failure, iteration/output/deadline limits, and provider/tool cancellation: not covered by the Work-stage test file despite being claimed.

### Symbol References

No public or existing symbol is renamed or removed. `singleRequestWorkProviderFunction.Arguments` is private and referenced only by the Work response decoder, envelope validation, `asChatToolCall`, and Work runner in `single_request_work_stage.go`; its tests construct responses through `workToolBody`.

### Split Judgment

Keep one plan. Provider argument decoding, coordinator identity, binding-derived schemas, continuation ownership, and failure evidence form one Work tool-call transaction invariant; no subset independently establishes S09 while the real coordinator rejects the call.

### Scope Rationale

Exclude service state-machine changes, workspace wire changes, preset/config changes, Review/repair, composite executor installation, public error mapping, spec wording, roadmap mutation, and S12 external qualification. The service contract is the oracle and should remain unchanged; the current spec becomes truthful once this private Work implementation and evidence are repaired.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build ownership, dependency, verification, decision, and external-execution closures are true. Scores `2/2/1/2/2` produce `cloud/G09`, base and final basis `grade-boundary`, route `worker/cloud/G09`, filename `PLAN-cloud-G09.md`.
- Review closures are true. Scores `2/2/1/2/2` produce `cloud/G09`, basis `official-review`, route `review/cloud/G09`, filename `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`; positive risks are `temporal_state`, `concurrent_consistency`, `boundary_contract`, and `structured_interpretation` (`count=4`).
- Recovery signals are `review_rework_count=1` and `evidence_integrity_failure=true`. There is no capability gap or user-review gate.

## Dependencies and Execution Order

1. Run the exact predecessor resolver in Final Verification before implementation. It must print exactly the archived task-18 `complete.log` and exit zero.
2. Repair codec/identity and boundary projection before constructing the actual service fixture, then add synchronized concurrency and failure/limit/cancel coverage against the repaired path.
3. Keep the runner uninstalled; later Review/composition tasks own activation.

## Implementation Checklist

- [ ] Make standard OpenAI Work tool calls consumable by the real coordinator and prove an actual write-plus-verification flow.
- [ ] Close reserved-option aliases and command environment schemas to the frozen Work binding.
- [ ] Make continuation delivery single-claim and add the missing provider, tool, budget, deadline, and cancellation regressions under `-race`.
- [ ] Run every dependency, focused, compatibility, vet, broad Edge, formatting, activation, spec, and diff verification command freshly.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_API-1] Restore the standard Work call/coordinator contract

**Problem**

At `apps/edge/internal/openai/single_request_work_stage.go:186-192`, Work submits `StageID="working"` and forwards the OpenAI JSON-string `function.arguments` as raw quoted bytes. The real coordinator requires canonical stage id `work` and a strict inner JSON object, while the test fake at `single_request_work_stage_test.go:37-46` bypasses both checks.

**Before** (`apps/edge/internal/openai/single_request_work_stage.go:186-192,286-288`)

```go
key := singleRequestWorkToolKey{requestID: req.RequestID, stageID: string(edgeservice.SingleRequestStateWorking), toolCallID: call.ID}
toolCall := &edgeservice.InternalWorkspaceToolCall{
    Arguments: append(json.RawMessage(nil), call.Function.Arguments...),
}

type singleRequestWorkProviderFunction struct {
    Name      string          `json:"name"`
    Arguments json.RawMessage `json:"arguments"`
}
```

**Solution**

Decode provider `arguments` as a string, validate that its contents are exactly one duplicate-free JSON object, and clone those inner bytes into the coordinator call. Use the private canonical id `work` for both the bridge key and `InternalWorkspaceToolCall`, while retaining the original string in the assistant continuation message.

```go
const singleRequestWorkStageID = "work"

type singleRequestWorkProviderFunction struct {
    Name      string `json:"name"`
    Arguments string `json:"arguments"`
}

arguments, err := decodeSingleRequestWorkToolArguments(call.Function.Arguments)
if err != nil {
    return nil, errSingleRequestWorkStage
}
key := singleRequestWorkToolKey{requestID: req.RequestID, stageID: singleRequestWorkStageID, toolCallID: call.ID}
```

**Modified Files and Checklist**

- [ ] Update provider argument decoding, canonical Work identity, coordinator call construction, and continuation serialization in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] In `apps/edge/internal/openai/single_request_work_stage_test.go`, add the existing-module imports needed for the real fixture, including `toki "git.toki-labs.com/toki/proto-socket/go"` and `edgenode "iop/apps/edge/internal/node"` when using the repository's typed wire pipe.
- [ ] Add `TestSingleRequestWorkStageRunsThroughServiceCoordinator`, using `service.StartSingleRequest`, a test executor adapter that writes the PLAN artifact before Work, and typed Node responders that observe one write and one verification command.

**Test Strategy**

Write the regression in `single_request_work_stage_test.go`. Standard `workToolBody` responses must pass through the actual service controller, produce wire requests with `stage_id=work`, change `result.txt`, execute the admitted `verify` command, return completion/verification evidence, and leave no pending bridge entry. Add malformed argument-string cases for non-object, duplicate field, trailing value, and quoted nested JSON.

**Verification**

Run `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1`; the real coordinator case and strict codec regressions pass without races.

### [REVIEW_API-2] Close Work request and schema authority

**Problem**

At `single_request_work_stage.go:151,384-393`, reserved keys are compared exactly, so aliases such as `Reasoning_Effort` and `Credential` are serialized. At lines 240-243, command `environment` advertises arbitrary string properties instead of the frozen `EnvironmentNames` allowlist.

**Before** (`apps/edge/internal/openai/single_request_work_stage.go:240-243,383-393`)

```go
"environment": map[string]any{
    "type": "object",
    "additionalProperties": map[string]any{"type": "string"},
}

for key, value := range options {
    switch key {
    case "model", "messages", "tools", "tool_choice", "parallel_tool_calls", "stream", "credential", "credential_binding", "reasoning_effort":
        continue
    }
    body[key] = value
}
```

**Solution**

Classify reserved keys using a case-folded comparison, reject every non-canonical alias before body construction, continue to reject exact `reasoning_effort`, and omit exact server-owned/credential fields. Build environment `properties` only from `workspace.EnvironmentNames` with `additionalProperties: false`; omit or close the environment field when no names are admitted.

```go
folded := strings.ToLower(key)
if isSingleRequestWorkReservedOption(folded) && key != folded {
    return nil, errSingleRequestWorkStage
}

environment := map[string]any{
    "type":                 "object",
    "additionalProperties": false,
    "properties":           admittedEnvironmentProperties,
}
```

**Modified Files and Checklist**

- [ ] Add one shared reserved-option classifier and fail-closed body construction in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Project only sorted/frozen environment names into the command schema in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Add `TestSingleRequestWorkStageRejectsReservedOptionAliases` and `TestSingleRequestWorkStageProjectsClosedEnvironmentSchema` in `apps/edge/internal/openai/single_request_work_stage_test.go`.

**Test Strategy**

Test every reserved key's case-folded alias, including reasoning and credential keys, and inspect both initial and resumed bodies. Decode the command schema and assert `SAFE` is the only environment property, `NOT_ALLOWED` is absent, and `additionalProperties` is false.

**Verification**

Run the focused Work race command and the exact test-name search in Final Verification; all aliases fail closed and the provider-visible schema is closed.

### [REVIEW_API-3] Make continuation ownership and failure evidence trustworthy

**Problem**

At `single_request_work_stage.go:81-91`, continuation delivery looks up under the mutex but does not claim/remove before sending, so concurrent duplicates may both succeed. At `single_request_work_stage_test.go:128-226`, the current cases do not exercise provider/frame failure, real tool denial/failure, budgets/deadlines, provider/tool cancellation, or synchronized duplicate delivery.

**Before** (`apps/edge/internal/openai/single_request_work_stage.go:81-91`)

```go
b.mu.Lock()
ch, ok := b.pending[key]
b.mu.Unlock()
if !ok {
    return errSingleRequestWorkStage
}
select {
case ch <- result.Clone():
    return nil
default:
    return errSingleRequestWorkStage
}
```

**Solution**

Atomically take and delete the waiter under the mutex, then send the cloned result outside the lock. Keep cancellation/unregister idempotent. Extend the actual coordinator fixture and deterministic provider doubles so every failure returns the generic Work error, the service preserves its typed budget/cancel result, no forbidden wire call occurs, and `pendingCount()` is zero.

```go
b.mu.Lock()
ch, ok := b.pending[key]
if ok {
    delete(b.pending, key)
}
b.mu.Unlock()
if !ok {
    return errSingleRequestWorkStage
}
ch <- result.Clone()
return nil
```

**Modified Files and Checklist**

- [ ] Atomically claim/remove bridge entries before delivery in `apps/edge/internal/openai/single_request_work_stage.go`.
- [ ] Add `TestSingleRequestWorkToolBridgeRejectsConcurrentDuplicate` with a barrier and exact one-success/one-error assertion in `apps/edge/internal/openai/single_request_work_stage_test.go`.
- [ ] Add `TestSingleRequestWorkStageFailuresAndLimits` for provider submit/frame errors, coordinator denial/failure, output/iteration/deadline limits, and `TestSingleRequestWorkStageCancellation` for provider and tool waits in `apps/edge/internal/openai/single_request_work_stage_test.go`.

**Test Strategy**

Use table-driven deterministic provider/tunnel and typed workspace responders. Assert errors with `errors.Is`, exact provider/wire/continuation counts, cancellation propagation, absence of raw provider/Node payloads in returned errors, and zero bridge entries after every case. Run all Work tests under `-race`.

**Verification**

Run the focused Work race command, unchanged service compatibility command, vet, and broad Edge suite in Final Verification.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/single_request_work_stage.go` | REVIEW_API-1, REVIEW_API-2, REVIEW_API-3 |
| `apps/edge/internal/openai/single_request_work_stage_test.go` | REVIEW_API-1, REVIEW_API-2, REVIEW_API-3 |
| `agent-task/m-iop-owned-single-request-agent-execution/19+18_work_stage/CODE_REVIEW-cloud-G09.md` | REVIEW_API-1, REVIEW_API-2, REVIEW_API-3 |

## Final Verification

Fresh output is required; Go tests must 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 `agent-task/archive/2026/08/m-iop-owned-single-request-agent-execution/18+17_plan_stage/complete.log` and exits zero before implementation.
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestWork(Stage|ToolBridge)' -count=1` — real coordinator, codec, authority, failure, limit, cancellation, and duplicate-delivery cases pass without races.
3. `go test ./apps/edge/internal/service -run 'TestSingleRequest(InternalToolLoop|Cleanup)' -count=1` — unchanged coordinator, tool-loop, cancellation, deadline, and cleanup oracles pass freshly.
4. `go vet ./apps/edge/internal/openai ./apps/edge/internal/service && go test ./apps/edge/... -count=1` — both touched boundaries vet cleanly and the broad Edge regression passes freshly.
5. `rg --sort path -n 'func TestSingleRequestWork(StageRunsThroughServiceCoordinator|StageRejectsReservedOptionAliases|StageProjectsClosedEnvironmentSchema|StageFailuresAndLimits|StageCancellation|ToolBridgeRejectsConcurrentDuplicate)' apps/edge/internal/openai/single_request_work_stage_test.go` — finds all six named regressions.
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; Work remains uninstalled.
7. `rg --sort path -n 'ornith-fast|Work stage|Review|not installed|deferred' agent-spec/runtime/edge-node-execution.md` — existing spec statements are supported by the repaired S09 evidence and later stages remain deferred.
8. `gofmt -d apps/edge/internal/openai/single_request_work_stage.go apps/edge/internal/openai/single_request_work_stage_test.go` — exits zero with no output.
9. `git diff --check` — exits zero with 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`.
