<!-- task=m-iop-owned-single-request-agent-execution/03+02_single_request_coordinator plan=3 tag=API milestone-task=single-ingress -->

# Surface-neutral Single-request Coordinator

## For the Implementing Agent

Do not start until packet 02 has `complete.log`. Implement this plan exactly within the listed write boundary, run every verification command, fill all implementation-owned sections of `CODE_REVIEW-cloud-G08.md` with actual notes and stdout/stderr, keep the active pair in place, and report ready for review. Finalization belongs only to the code-review skill. If blocked, record exact blocker evidence, attempted commands/output, and the resume condition; do not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, or write `complete.log`.

## Archive Evidence Snapshot

- Refined parent: `plan_cloud_G09_2.log`, `code_review_cloud_G10_2.log`; earlier intent remains in sibling logs `0` and `1`.
- The parent pair contained no implementation evidence or review verdict; implementation has not started.
- Fresh-context correction preserved in the parent: runtime Edge ingress-counter evidence and exact dependency lookup were added before this one-time split.
- Split allocation: this child owns the surface-neutral coordinator, state/terminal ownership, service tests, and coordinator runtime spec. Packet 05 owns HTTP admission, the ingress counter, endpoint tests, and outer/input documentation.

## Background

The marked Anthropic path needs one request-local coordinator that freezes identity and binding, drives approved internal stages, and selects one terminal without importing HTTP or Anthropic wire types. This packet establishes that independently testable service boundary before endpoint admission is added.

## 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/edge/rules.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.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`
- `apps/edge/internal/service/service.go`
- `apps/edge/internal/service/run_types.go`
- `apps/edge/internal/service/provider_pool.go`
- `agent-spec/runtime/edge-node-execution.md`

### SDD Criteria

- SDD status is approved and its implementation lock is released.
- First-line Milestone task: `single-ingress`; this child supplies S01's immutable coordinator/API foundation. Packet 05 supplies the actual one-POST Edge ingress evidence.
- Approved states are `accepted`, `planning`, `working`, `reviewing`, `repairing`, `internal_tool`, `finalizing`, `completed`, `failed`, and `cancelled`.

### Verification Context

- No separate verification handoff was supplied. Repository-native fallback is the service lifecycle code, approved SDD state graph, Edge test profile, and current runtime spec.
- Precondition: packet 02 completion. Constraints: current checkout only; an injected executor replaces external Node/workspace/provider infrastructure.
- Race-enabled service tests are the primary oracle for immutable admission, legal transitions, cancellation, and one-terminal ownership.

### State and Concurrency Findings

- `internal_tool` returns only to its saved active stage; `repairing` is a first-class approved state.
- Stale, duplicate, identity-mismatched, or illegal envelopes fail closed.
- A successful candidate remains `finalizing` until the surface acknowledges a successful terminal write. Completion, failure, cancellation, and acknowledgement races must select one outcome and stop executor work.

### Test Coverage Gaps

- No service test exercises the complete state graph, repair path, saved-stage internal-tool detour, immutable admission, cancellation, acknowledgement, or terminal races.
- `service.Service` has no optional fixed single-request executor/coordinator API.

### Symbol References

- No existing symbol is renamed or removed.
- The coordinator remains in `service`; it must not import endpoint wire types or widen the widely faked OpenAI `runService` interface.

### Refine Judgment

- This is the stable foundation child produced by the one-time refinement of the corrected parent.
- Further splitting would separate the executor contract from the state/terminal invariant it exists to enforce, so this child remains atomic and independently PASS-capable.

### Scope Rationale

- Include only the service-owned request/executor/envelope API, state graph, terminal acknowledgement, tests, and its runtime spec.
- Exclude HTTP admission, ingress metrics, Anthropic translation, streaming projection, concrete Node/workspace/provider protocol, and real Claude smoke.

### Final Routing

- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh` in `pair` mode.
- Build closures are true; scores 1/2/1/1/2 = G07; base/final route `local-fit`; lane `local`; canonical filename `PLAN-local-G07.md`.
- Build signals: `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.
- Review closures are true; scores 1/2/1/2/2 = G08; route `official-review`; lane `cloud`; canonical filename `CODE_REVIEW-cloud-G08.md`.

## Dependencies and Execution Order

1. Verify exactly one packet 02 completion candidate, preferring the active path.
2. Define the service-owned immutable request, executor envelopes, and request-scoped execution handle.
3. Implement and race-test the complete state graph and terminal acknowledgement.
4. Synchronize the coordinator runtime spec and run Edge regressions.

## Implementation Checklist

- [ ] Implement the surface-neutral request-local coordinator and executor port with copied immutable admission and the complete approved state graph, including repair and saved-stage internal-tool resume.
- [ ] Enforce cancellation, executor shutdown, fail-closed envelopes, one terminal outcome, and one-shot endpoint acknowledgement before `completed`.
- [ ] Synchronize the Edge runtime spec without claiming HTTP integration, concrete Node/workspace/provider execution, or real Claude smoke.
- [ ] Run exact dependency, targeted race, documentation, package, vet, full Edge, and `git diff --check` verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Implementation Plan

### [API-1] Implement the coordinator in service

**Problem**

- `apps/edge/internal/service/service.go:28` owns Edge runtime state but exposes no fixed single-request executor/coordinator API.
- `agent-spec/runtime/edge-node-execution.md:57` documents normalized execution but has no surface-neutral single-request state or terminal-acknowledgement boundary.

**Solution**

Before (`apps/edge/internal/service/service.go:28`):

```go
type Service struct {
	mu                   sync.RWMutex
	registry             *edgenode.Registry
	events               *edgeevents.Bus
	nodeStore            *edgenode.NodeStore
	queue                *modelQueueManager
	modelCatalog         []config.ModelCatalogEntry
	providerPoolPolicy   groupPolicy
	tunnels              *providerTunnelRouter
	credentialLeases     CredentialLeaseProvider
	credentialLeaseSlots chan struct{}
}
```

After:

```go
type Service struct {
	// Existing fields remain.
	singleRequestExecutor SingleRequestExecutor
}

func (s *Service) SetSingleRequestExecutor(executor SingleRequestExecutor) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.singleRequestExecutor = executor
}

func (s *Service) StartSingleRequest(
	ctx context.Context,
	req SingleRequestRequest,
) (SingleRequestExecution, error) {
	s.mu.RLock()
	executor := s.singleRequestExecutor
	s.mu.RUnlock()
	return startSingleRequest(ctx, executor, req)
}
```

Define the new service types in `single_request.go` with the required standard-library imports and no endpoint import:

```go
import (
	"context"
	"sync"
)
```

The setter updates the optional executor under `Service.mu`; `StartSingleRequest` snapshots it under the same lock and fails closed when absent. The request copies its immutable input/binding. Typed internal envelopes carry request/stage identity and closed stage/terminal values. Validate the full state graph, saved-stage `internal_tool` return, ordering, duplicates, and identity. Hold a successful candidate in `finalizing` until the endpoint handle receives one successful terminal acknowledgement; failure, cancellation, or write-failure acknowledgement selects the sole alternative terminal. Cancel and join executor work on every exit. Do not implement concrete Node/tool transport.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/service/service.go` — configure the optional executor and expose the surface-neutral request API.
- [ ] `apps/edge/internal/service/single_request.go` — implement executor/envelope types, immutable admission, state validation, redacted progress, cancellation, and terminal ownership.
- [ ] `apps/edge/internal/service/single_request_test.go` — cover success/ack, repair, internal-tool resume, invalid envelopes, cancellation, unavailability, and terminal races under `-race`.

**Test Strategy**

- Use a channel-driven fake executor.
- Cover success held in `finalizing`, duplicate and write-failure acknowledgement, repair flow, internal-tool resume, illegal/stale/duplicate/identity-mismatched envelopes, immutable admission, unavailable executor, cancellation, and competing terminals.

**Verification**

- `go test -race ./apps/edge/internal/service -run 'TestSingleRequest' -count=1`
- Expected: all legal paths pass, invalid envelopes fail closed, success cannot complete before acknowledgement, and exactly one terminal wins without races or surviving work.

### [API-2] Synchronize the coordinator runtime boundary

**Problem**

- `agent-spec/runtime/edge-node-execution.md:57` has only the generic normalized-execution row and no surface-neutral coordinator/executor port or explicit deferral boundary.

**Solution**

Before (`agent-spec/runtime/edge-node-execution.md:57`):

```markdown
| normalized execution | `adapter + target`으로 provider 실행을 선택하고 ordered `RunEvent` stream을 반환한다. |
```

After, add a separate current-runtime row/section:

```markdown
| single-request coordinator | Immutable admission과 closed stage envelope을 service-owned state graph로 처리하고 surface terminal acknowledgement 뒤에만 completed로 전이한다. |
```

Document executor-envelope privacy and the deferral of HTTP wiring plus concrete Node/workspace/provider execution. Do not claim S01's ingress counter or real-provider evidence here.

**Modified Files and Checklist**

- [ ] `agent-spec/runtime/edge-node-execution.md` — record the coordinator port, state/terminal ownership, privacy boundary, and explicit deferrals.

**Test Strategy**

- Skip a standalone documentation-only test because API-1's named race tests are the executable oracle; deterministic search checks the synchronized state and deferral language.

**Verification**

- `rg --sort path -n 'single-request|repairing|internal_tool|finalizing|acknowledg|defer' agent-spec/runtime/edge-node-execution.md`
- Expected: the service boundary and deferrals are explicit without claiming endpoint or provider completion.

## Modified Files Summary

| File | Item |
|------|------|
| `apps/edge/internal/service/service.go` | API-1 |
| `apps/edge/internal/service/single_request.go` | API-1 |
| `apps/edge/internal/service/single_request_test.go` | API-1 |
| `agent-spec/runtime/edge-node-execution.md` | API-2 |
| `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_request_coordinator/CODE_REVIEW-cloud-G08.md` | API-1, API-2 |

## Final Verification

1. `test -f agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log || test "$(compgen -G 'agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log' | wc -l)" -eq 1`
2. `go test -race ./apps/edge/internal/service -run 'TestSingleRequest' -count=1`
3. `rg --sort path -n 'single-request|repairing|internal_tool|finalizing|acknowledg|defer' agent-spec/runtime/edge-node-execution.md`
4. `go test ./apps/edge/internal/service -count=1`
5. `go vet ./apps/edge/...`
6. `go test ./apps/edge/... -count=1`
7. `git diff --check`

Expected: exactly one predecessor completion candidate exists; the surface-neutral state graph and acknowledgement invariant pass under race testing; the runtime spec matches; all Edge checks pass. HTTP ingress, streaming projection, concrete workspace execution, and actual Claude smoke remain unclaimed.

**After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.**
