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

# Immutable Single-request Runtime Binding

## For the Implementing Agent

Do not start until the predecessor named below 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 files 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`.

## Background

Generic preset resolution currently returns a cloned preset and a map of canonical model routes, leaving downstream code to reinterpret selector/local/review semantics. SDD S02 requires one request-start snapshot that binds the public model, fixed stage roles, authorized routes, workspace capability, and limits without refresh mutation or dynamic mode fallback.

## Analysis

### Files Read

- `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/openai/route_resolution.go`
- `apps/edge/internal/openai/principal_routes.go`
- `apps/edge/internal/openai/principal_routes_test.go`
- `apps/edge/internal/openai/workspace_tool_binding_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`
- `agent-test/local/edge-smoke.md`

### SDD Criteria

- SDD status: approved, lock released.
- Milestone task: `preset-binding`; Acceptance Scenario S02.
- Evidence Map requires authorization, public model echo, workspace snapshot, and fixed-light binding evidence.
- This packet completes the runtime admission/snapshot half of S02 after `01_preset_config` supplies the schema. It does not execute provider or workspace stages.

### Verification Context

- No separate handoff was supplied. Repository-native evidence is the managed virtual-preset authorization matrix, unmanaged route resolver, current clone-on-`SetExecutionPresets` behavior, and edge test profile.
- The related package baseline passed at starting HEAD through `go test ./packages/go/config ./apps/edge/internal/configrefresh ./apps/edge/internal/openai -count=1`.
- Preconditions: `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/complete.log` must exist before implementation; its typed config names are authoritative.
- No external verification is required. Actual provider execution and Claude POST counting remain later tasks.
- Confidence: high. Managed and unmanaged resolution already produce one authorized route per canonical ref; this packet compiles those facts into a closed immutable binding.

### Test Coverage Gaps

- `TestVirtualPresetModelAuthorizationMatrix` covers zero/one/many managed canonical bindings and selector credential identity, but not the fixed single-request semantic compiler.
- Existing tests preserve virtual public identity but do not assert plan/work/review option separation, workspace ref, limits, defensive rejection, or refresh isolation of the compiled binding.
- Add a focused test file; keep generic virtual preset tests unchanged as regression coverage.

### Symbol References

- No symbol is renamed or removed.
- `routeDispatch` is created in `resolveRouteDispatch` and `resolveVirtualPresetModelForPrincipal` and consumed throughout the OpenAI-compatible handlers. Add one optional field without changing ordinary dispatch behavior.

### Split Judgment

- Stable contract: turn the predecessor's validated config into a closed request-start runtime value. PASS is determined entirely by route-resolution tests.
- Predecessor index 01 resolves to active sibling `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/`. At planning time it has no `complete.log`, so predecessor status is pending, not ambiguous.
- `03+02_single_ingress` depends on this packet's runtime value; `04+03_stream_terminal` depends transitively through the coordinator.

### Scope Rationale

- Do not change the config schema owned by predecessor 01, start provider stages, accept HTTP requests, implement Node workspace authorization, or emit SSE.
- Do not hardcode endpoints, credentials, provider ids, or Node ids. Canonical model names in tests are operator config data only.
- Preserve generic direct/light preset admission and Pi/OpenAI Chat behavior.

### Final Routing

- evaluation_mode `first-pass`; finalizer `finalize-task-policy.sh` pair.
- Build closures all true. Scores 2/1/1/1/1 = G06; base/final `local-fit`; lane `local`; filename `PLAN-local-G06.md`.
- Build signals: `large_indivisible_context=false`; positive risks `boundary_contract`, `concurrent_consistency`, `variant_product` (3); rework 0; evidence integrity false; no capability gap.
- Review closures all true. Scores 2/1/1/1/2 = G07; `official-review` on cloud Codex `gpt-5.6-sol` xhigh; filename `CODE_REVIEW-cloud-G07.md`.

## Dependencies and Execution Order

1. Wait for predecessor 01 to have `complete.log` at its active path or matching same-group archive path.
2. Implement this packet only after that evidence exists. The directory name `02+01_preset_binding` encodes the sole dependency.
3. Do not start or prepare successor implementation from this plan.

## Implementation Checklist

- [ ] Compile validated single-request config into an immutable plan/work/review route binding in unmanaged resolution, with defensive fail-closed checks and focused tests.
- [ ] Apply the same compiler to managed principal resolution/model discovery, prove public identity and refresh isolation, and synchronize the external contract/current spec.
- [ ] Run targeted, race-free package 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] Compile the fixed runtime value in unmanaged routing

**Problem**

- `apps/edge/internal/openai/route_resolution.go:51`-`85` stores a generic preset and mutable-looking map but no semantic plan/work/review binding.
- `apps/edge/internal/openai/route_resolution.go:144`-`186` resolves canonical refs recursively and returns without defensively compiling the fixed single-request contract.

**Solution**

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

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

After:

    IsPreset               bool
    PresetID               string
    ExternalModelID        string
    Preset                 config.ExecutionPreset
    PresetResolvedBindings map[string]routeDispatch
    SingleRequest          *singleRequestPresetBinding

- Add `single_request_preset_binding.go` with a closed immutable value containing public model id, preset id, workspace ref, copied limits, and explicit `Plan`/`Work`/`Review` stage bindings.
- Compile selector as plan, light stage 0 (`local`) as work, and light stage 1 as review. Copy options and nested limits so later config/catalog refresh cannot mutate an admitted request.
- Defensively reject marked presets whose modes, stage count/order, high-effort separation, workspace ref, limits, or canonical resolved routes disagree, even if tests construct config structs without `LoadEdge`.
- In unmanaged resolution, return false when compilation fails; ordinary unmarked presets keep their current result.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/openai/route_resolution.go` — add the optional compiled binding and call the compiler after canonical routes resolve.
- [ ] `apps/edge/internal/openai/single_request_preset_binding.go` — define the closed value, copying helpers, and defensive compiler.
- [ ] `apps/edge/internal/openai/single_request_preset_binding_test.go` — cover valid unmanaged mapping, option separation, and fail-closed shapes.

**Test Strategy**

- Write `TestSingleRequestPresetBindingUnmanaged` with public model `claude-agent`, plan/review `gemini-3.6-flash` high, work `ornith-fast` without high, and three distinct resolved routes.
- Write `TestSingleRequestPresetBindingRejectsDynamicOrIncompleteShape` for hybrid/direct modes, missing route, ambiguous semantic role, missing binding, and work option leakage.
- Assert mutations to `SetExecutionPresets` input or refreshed server catalog do not change the already returned binding.

**Verification**

- `go test ./apps/edge/internal/openai -run 'TestSingleRequestPresetBinding(Unmanaged|RejectsDynamicOrIncompleteShape)$' -count=1`
- Expected: valid mapping is exact and every unsupported shape returns no route.

### [API-2] Preserve managed authorization, discovery, and public identity

**Problem**

- `apps/edge/internal/openai/principal_routes.go:95`-`147` authorizes each canonical ref and copies selector authority but returns only the generic preset map.
- `apps/edge/internal/openai/principal_routes.go:61`-`66` advertises a virtual model whenever generic resolution succeeds, so invalid fixed semantics would otherwise remain discoverable.

**Solution**

Before (`apps/edge/internal/openai/principal_routes.go:140`):

    result.Preset = preset
    result.PresetResolvedBindings = bindings
    return result, nil

After:

    result.Preset = preset
    result.PresetResolvedBindings = bindings
    result.SingleRequest, err = compileSingleRequestPresetBinding(...)
    if err != nil { return routeDispatch{}, ErrRouteNotFound }
    return result, nil

- Run the same compiler after exact managed canonical authorization. Invalid fixed shapes become `ErrRouteNotFound` and are omitted by `advertisedModelsForPrincipal`.
- Preserve the selector's projected credential authority and the caller's virtual id solely as public response identity.
- Test generation isolation: retain binding A, apply a new preset snapshot, resolve binding B, and prove A is unchanged while B uses the new workspace/limits.
- Synchronize contract/spec with fixed binding admission and clarify that workspace capability authorization/execution is a later typed runtime boundary.

**Modified Files and Checklist**

- [ ] `apps/edge/internal/openai/principal_routes.go` — compile or reject the fixed binding after managed authorization.
- [ ] `apps/edge/internal/openai/single_request_preset_binding_test.go` — add managed authorization/discovery/public-id/refresh matrix.
- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define discoverability/admission and public-model identity for marked fixed presets.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize current route-binding behavior and test evidence.

**Test Strategy**

- Write `TestSingleRequestPresetBindingManagedAuthorization` using zero/one/many projected routes and assert only exactly-one bindings advertise/resolve.
- Write `TestSingleRequestPresetBindingRefreshIsolation` and `TestSingleRequestPresetBindingPreservesPublicModel`.
- Rerun `TestVirtualPresetModelAuthorizationMatrix` and `TestVirtualPresetModelHandlersPreservePublicIdentity` unchanged.

**Verification**

- `go test ./apps/edge/internal/openai -run 'Test(SingleRequestPresetBindingManagedAuthorization|SingleRequestPresetBindingRefreshIsolation|SingleRequestPresetBindingPreservesPublicModel|VirtualPresetModelAuthorizationMatrix|VirtualPresetModelHandlersPreservePublicIdentity)$' -count=1`
- Expected: managed authorization is fail closed, old snapshots remain immutable, and public identity is unchanged.

## Modified Files Summary

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

## Final Verification

1. `test -f agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/01_preset_config/complete.log' -print | sort | grep -q .`
2. `go test ./apps/edge/internal/openai -run 'TestSingleRequestPresetBinding' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(VirtualPresetModelAuthorizationMatrix|VirtualPresetModelHandlersPreservePublicIdentity)$' -count=1`
4. `go test ./apps/edge/internal/openai -count=1`
5. `go test ./apps/edge/... -count=1`
6. `git diff --check`

Expected: predecessor evidence exists; all commands exit 0; fixed bindings are immutable and authorized; invalid fixed presets are neither listed nor admitted. Go cache output is not acceptable because every Go command uses `-count=1`.

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