<!-- task=m-iop-owned-single-request-agent-execution/02+01_preset_binding plan=2 tag=API milestone-task=preset-binding -->

# Immutable Single-request Runtime Binding

## For the Implementing Agent

Do not start until packet 01 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-G07.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

- Superseded pair: `plan_local_G06_1.log`, `code_review_cloud_G07_1.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Fresh-review correction: preserve the surface-neutral immutable binding scope, and replace the broad archive scan with the exact predecessor candidate pattern required by the split dependency protocol.

## Background

Generic route resolution returns a cloned preset and canonical authorized routes but leaves downstream code to reinterpret selector/local/review semantics. SDD S02 requires a single request-start value that freezes public identity, the fixed stage routes, workspace capability, and limits without refresh mutation or dynamic fallback.

## 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`
- `packages/go/config/execution_preset_types.go`
- `apps/edge/internal/service/service.go`
- `apps/edge/internal/service/run_types.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/principal_routes.go`
- `apps/edge/internal/openai/principal_routes_test.go`
- `apps/edge/internal/openai/server.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/provider-pool-config-refresh.md`

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-owned-single-request-agent-execution/SDD.md`; status approved and implementation lock released.
- First-line Milestone task: `preset-binding`; targeted Acceptance Scenario: S02.
- Evidence Map: fixed-light authorization, public-model echo, workspace snapshot, and refresh isolation. Those rows require the managed/unmanaged authorization and copy-isolation checks in the checklist and Final Verification.

### Verification Context

- No separate verification handoff was supplied. Repository-native fallback came from managed-principal authorization tests, generic route resolution, clone-on-config behavior, the Edge test profile, and the approved SDD.
- Precondition: packet 01 completion evidence. Constraints: no external runner/provider, no concrete workspace execution, and generic routing compatibility. Gap: the coordinator begins in packet 03.
- Final commands use fresh focused/package tests, `go vet ./apps/edge/...`, full Edge regression, and `git diff --check`. Confidence is high because both managed and unmanaged resolution already produce authorized canonical routes.

### Test Coverage Gaps

- Existing managed/unmanaged virtual-preset tests cover route authorization and public identity, but not the fixed plan/work/review compiler, workspace/limit copies, fail-closed defenses, or refresh isolation of a compiled admission.

### Symbol References

- No symbol is renamed or removed. `routeDispatch` is produced by `resolveRouteDispatch` and `resolveVirtualPresetModelForPrincipal`; adding one optional field preserves ordinary consumers.

### Split Judgment

- Stable child contract: packet 01's validated config is compiled into an endpoint-neutral immutable admission value and independently passes service/openai tests.
- Predecessor index 01 resolves to `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/`; its `complete.log` is currently missing, so implementation remains pending and unambiguous.

### Scope Rationale

- Exclude HTTP admission, provider stages, concrete workspace authorization, Node wire, and SSE because this packet ends at route admission.
- Preserve generic direct/light behavior and public requested-model identity. Never expose canonical route/provider/credential/endpoint/raw workspace data.

### Final Routing

- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh` in `pair` mode.
- Build closures are true; scores 2/1/1/1/1 = G06; base/final route `local-fit`; lane `local`; canonical filename `PLAN-local-G06.md`.
- Build signals: `large_indivisible_context=false`; positive loop risks `boundary_contract`, `concurrent_consistency`, `variant_product` (3); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
- Review closures are true; scores 2/1/1/1/2 = G07; route `official-review`; lane `cloud`; canonical filename `CODE_REVIEW-cloud-G07.md`.

## Dependencies and Execution Order

1. Verify packet 01 completion evidence.
2. Define the endpoint-neutral DTO in `service`, then compile it in route resolution.
3. Prove managed/unmanaged authorization, public identity, and snapshot isolation before updating documents.

## Implementation Checklist

- [ ] Define the surface-neutral immutable single-request binding and compile fixed plan/work/review routes, public identity, workspace capability, and copied limits at route admission.
- [ ] Fail closed on missing or inconsistent authorization, preserve ordinary routes, and prove managed/unmanaged, option, model-echo, and refresh-isolation behavior.
- [ ] Synchronize the Anthropic boundary and current specs without claiming coordinator, workspace execution, or provider completion.
- [ ] Run dependency, targeted, package, vet, full Edge regression, 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] Own the immutable admission DTO in service

**Problem**

- `apps/edge/internal/openai/route_resolution.go:52` owns `routeDispatch`, but packet 03's coordinator must be surface-neutral and therefore cannot consume an OpenAI-private binding DTO.
- `apps/edge/internal/service/service.go:28` has no immutable type for requested identity, authorized stage routes, workspace capability, and copied limits.

**Solution**

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

```go
type SubmitRunRequest struct {
    NodeRef          string
    RunID            string
    ModelGroupKey    string
}
```

After, in a separate additive file:

```go
package service

type SingleRequestBinding struct {
    PublicModel  string
    WorkspaceRef string
    Plan, Work, Review SingleRequestStageBinding
    Limits SingleRequestLimits
}
```

Use service-package DTOs for the binding and stages. Store only frozen runtime inputs and provide constructors/copy helpers that reject incomplete stage sets and prevent retention of mutable config maps/slices. The service package must not import `openai` or endpoint wire types.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/service/single_request_types.go` — define the surface-neutral immutable binding and defensive copy/validation helpers.
- [ ] `apps/edge/internal/service/single_request_types_test.go` — prove copy isolation and fail-closed stage/limit invariants.

**Test Strategy**

- Add `TestSingleRequestBindingValid`, boundary/invalid table cases, and `TestSingleRequestBindingCloneIsolation` with nested option/limit mutation assertions.
- New service DTO tests are required because this is a new cross-component API.

**Verification**

- `go test ./apps/edge/internal/service -run 'TestSingleRequestBinding' -count=1`
- Expected: complete immutable bindings pass; missing/invalid stage facts fail closed; caller mutation is isolated.

### [API-2] Compile only an authorized fixed binding at route resolution

**Problem**

- `apps/edge/internal/openai/route_resolution.go:52` returns cloned preset/routes but no compiled single-request admission.
- `apps/edge/internal/openai/principal_routes.go:95` resolves principal-authorized canonical models, yet downstream reinterpretation could select a missing/unauthorized stage or observe later mutation.

**Solution**

Before (`apps/edge/internal/openai/route_resolution.go:76`):

```go
IsPreset               bool
PresetID               string
ExternalModelID        string
Preset                 config.ExecutionPreset
PresetResolvedBindings map[string]routeDispatch
```

After:

```go
type routeDispatch struct {
    // Existing fields remain.
    SingleRequest *edgeservice.SingleRequestBinding
}
```

When and only when the policy is present, compile `plan` from selector authority, `work` from the local route, and `review` from the review route already authorized for the principal. Reject missing, duplicate, unauthorized, dynamically selected, or option-inconsistent inputs without generic fallback. Keep external model echo equal to the requested public model.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/openai/route_resolution.go` — attach the optional service binding on unmanaged authorized resolution.
- [ ] `apps/edge/internal/openai/principal_routes.go` — attach it after managed-principal canonical authorization.
- [ ] `apps/edge/internal/openai/single_request_preset_binding.go` — compile validated config/routes into the service DTO without exposing private route data.
- [ ] `apps/edge/internal/openai/single_request_preset_binding_test.go` — cover managed/unmanaged authorization, fixed roles/options, public-model echo, defensive copies, refresh isolation, and invalid defense-in-depth cases.

**Test Strategy**

- Add `TestSingleRequestPresetBindingManaged`, `...Unmanaged`, `...RejectsInvalidDefenseInDepth`, and `...RefreshIsolation` using the existing principal/virtual-model fixtures.
- Rerun `TestVirtualPresetModelAuthorizationMatrix` unchanged for generic authorization regression.

**Verification**

- `go test ./apps/edge/internal/openai -run 'Test(SingleRequestPresetBinding|VirtualPresetModelAuthorizationMatrix)' -count=1`
- Expected: only authorized fixed bindings compile and public identity/snapshot isolation hold.

### [API-3] Synchronize the admission boundary

**Problem**

- `agent-contract/outer/anthropic-compatible-api.md:55` defines generic preset authorization but not a service-owned, request-generation single-request binding.
- `agent-spec/input/openai-compatible-surface.md:132` and `agent-spec/runtime/provider-pool-config-refresh.md:93` do not define marked admission or request-start binding isolation.

**Solution**

Before (`agent-contract/outer/anthropic-compatible-api.md:61`):

```markdown
Authentication and route resolution retain one immutable projection generation for a
request. A public `route_id` resolves only inside the verified managed gate to one
internal model group and selector-compatible provider resource set; it is distinct from
the provider resource and from `credential_slot_ref`.
```

After, add a separate marked-preset subsection and matching spec rows:

```markdown
An authorized fixed single-request preset compiles one service-owned admission value at
request start: requested public model, canonical plan/work/review bindings, opaque
workspace capability, limits, and projection/config generation. Later refresh cannot
mutate that value, and no private binding is echoed to the caller.
```

Document compilation only after principal authorization and surface-neutral ownership. Explicitly defer coordinator, provider/workspace execution, and HTTP/SSE completion.

**Modified Files and Checklist**

- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define marked admission and public/private identity boundaries.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize route-dispatch behavior and tests.
- [ ] `agent-spec/runtime/provider-pool-config-refresh.md` — record request-start snapshot isolation across refresh.

**Test Strategy**

- Skip a standalone documentation-only test because API-2's authorization/model-echo/refresh-isolation tests are the executable oracle; review compares prose to those named tests.

**Verification**

- `rg --sort path -n 'single-request|immutable|public model|refresh' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/provider-pool-config-refresh.md`
- Expected: the service-owned admission and its exclusions are explicit without private values.

## Modified Files Summary

| File | Item |
|------|------|
| `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/route_resolution.go` | API-2 |
| `apps/edge/internal/openai/principal_routes.go` | API-2 |
| `apps/edge/internal/openai/single_request_preset_binding.go` | API-2 |
| `apps/edge/internal/openai/single_request_preset_binding_test.go` | API-2 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-3 |
| `agent-spec/input/openai-compatible-surface.md` | API-3 |
| `agent-spec/runtime/provider-pool-config-refresh.md` | API-3 |
| `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/CODE_REVIEW-cloud-G07.md` | API-1, API-2, API-3 |

## Final Verification

1. `test -f agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/complete.log || test "$(compgen -G 'agent-task/archive/*/*/m-iop-owned-single-request-agent-execution/01_preset_config/complete.log' | wc -l)" -eq 1`
2. `go test ./apps/edge/internal/service -run 'TestSingleRequestBinding' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(SingleRequestPresetBinding|VirtualPresetModelAuthorizationMatrix)' -count=1`
4. `rg --sort path -n 'single-request|immutable|public model|refresh' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/provider-pool-config-refresh.md`
5. `go test ./apps/edge/internal/service ./apps/edge/internal/openai -count=1`
6. `go vet ./apps/edge/...`
7. `go test ./apps/edge/... -count=1`
8. `git diff --check`

Expected: predecessor evidence exists; only authorized fixed bindings compile; mutable config/refresh changes cannot affect an admitted request; generic dispatch regressions pass. No coordinator or execution completion is claimed.

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