feat(epic): single-request 작업을 준비한다

This commit is contained in:
toki 2026-08-06 08:45:29 +09:00
parent 3331e5f8d2
commit b3085786d4
16 changed files with 2990 additions and 0 deletions

View file

@ -0,0 +1,129 @@
<!-- task=m-iop-owned-single-request-agent-execution/01_preset_config plan=1 tag=API milestone-task=preset-binding -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/01_preset_config, plan=1, tag=API
## Archive Evidence Snapshot
- Superseded pair: `plan_local_G07_0.log`, `code_review_cloud_G07_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: use the real domain-rule paths and add the package-profile vet check. The packet's schema/refresh ownership remains valid.
## For the Review Agent
> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G07.md``code_review_cloud_G07_1.log` and `PLAN-local-G07.md``plan_local_G07_1.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/01_preset_config/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=preset-binding` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Add the typed fixed single-request policy | [ ] |
| API-2 Preserve refresh semantics and publish the schema | [ ] |
## Implementation Checklist
- [ ] Add and validate the optional fixed single-request preset policy, deep-clone it, and prove valid, boundary, invalid, legacy, and clone-isolation cases.
- [ ] Classify policy changes as live-applied, add a secret-free commented config example, and synchronize the config contract and current implementation spec.
- [ ] Run targeted, package, vet, full profile regression, and `git diff --check` verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G07_1.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_local_G07_1.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/01_preset_config/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=preset-binding` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Unmarked direct/light presets remain source- and behavior-compatible.
- Marked presets fail closed for dynamic modes, malformed stage sets, option leakage, and legacy caller tools.
- Policy and nested stage maps are defensive copies.
- YAML/docs contain no secret, endpoint, credential, Node id, or raw path.
## Verification Results
### Config policy
Command: `go test ./packages/go/config -run 'Test(LoadEdgeSingleRequestExecutionPreset|CloneExecutionPresetSingleRequestIsolation|LoadEdgeExecutionPresetCatalog|LoadEdgeExecutionPresetRejectsInvalidShape)$' -count=1`
_Actual output:_
### Refresh classification
Command: `go test ./apps/edge/internal/configrefresh -run 'TestClassifyExecutionPresetLiveApply$' -count=1`
_Actual output:_
### Final regression
Commands:
- `go test ./packages/go/config ./apps/edge/internal/configrefresh -count=1`
- `go vet ./packages/go/...`
- `go test ./packages/go/... ./apps/edge/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]``[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]``[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,205 @@
<!-- task=m-iop-owned-single-request-agent-execution/01_preset_config plan=1 tag=API milestone-task=preset-binding -->
# Fixed Single-request Preset Config
## For the Implementing Agent
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 both active files in place, and report ready for review. Finalization belongs only to the code-review skill. If blocked, record the exact blocker, attempted commands/output, and resume condition in implementation-owned evidence fields; 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_G07_0.log`, `code_review_cloud_G07_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: use the real domain-rule paths and add the package-profile vet check. The packet's schema/refresh ownership remains valid.
## Background
The execution-preset schema has generic `direct` and caller-continuation `light` forms but no operator-owned marker for the approved fixed single-request path. SDD S02 requires an opaque workspace capability plus immutable request/stage limits while preserving existing preset compatibility and live-refresh generation isolation.
## 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-ops/rules/project/domain/platform-common/rules.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`
- `agent-test/local/platform-common-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`
- `packages/go/config/execution_preset_config_test.go`
- `apps/edge/internal/configrefresh/classify.go`
- `apps/edge/internal/configrefresh/execution_preset_classify_test.go`
- `configs/edge.yaml`
- `agent-contract/inner/edge-config-runtime-refresh.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 decode/authorization/model-echo/workspace-snapshot evidence under `preset-binding`. This packet supplies decode, validation, cloning, refresh, and schema evidence; packet 02 supplies authorization/model echo.
- Those rows require the config boundary and refresh checks in the implementation checklist and fresh config/configrefresh commands in Final Verification.
### Verification Context
- No separate verification handoff was supplied. Repository-native fallback came from the local test rules, platform/Edge smoke profiles, existing preset tests, refresh classifier tests, and approved SDD.
- Starting HEAD is `3331e5f8d20e2137d1cd1ae5600efedb42be291e`; no implementation change existed when replanning began.
- Preconditions: none. Constraints: ordinary presets remain compatible; no external runner/provider is used. Gap: runtime authorization is packet 02 and actual Claude/provider evidence belongs to later Milestone work.
- Commands were selected from `platform-common-smoke.md` and `edge-smoke.md`: focused/package Go tests, `go vet`, full package regression, and `git diff --check`. Confidence is high for local schema and refresh behavior.
### Test Coverage Gaps
- Existing config tests do not cover a fixed single-request marker, typed limits, legacy workspace-tool exclusion, dynamic-mode rejection, or deep-clone isolation.
- Existing refresh tests do not report this policy as its own live-applied path.
### Symbol References
- No symbol is renamed or removed. `ExecutionPreset.Clone`, `CloneExecutionPresetCatalog`, and `appendExecutionPresetChanges` are the existing consumers extended by this packet.
### Split Judgment
- Stable child contract: a validated, cloned, refresh-aware typed preset independently passes config/configrefresh tests. It has no predecessor and produces the schema consumed by packet 02.
### Scope Rationale
- Exclude Edge route resolution, handlers, provider execution, Node/workspace execution, protobuf, and SSE because they do not participate in config validation/refresh.
- Keep unmarked direct/light presets compatible. `workspace_ref` remains opaque; add no endpoint, credential, Node id, raw path, dynamic selection, or silent default.
### Final Routing
- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh` in `pair` mode.
- Build closures scope/context/verification/evidence/ownership/decision are true; scores 2/1/2/1/1 = G07; base/final route `local-fit`; lane `local`; canonical filename `PLAN-local-G07.md`.
- Build signals: `large_indivisible_context=false`; positive loop risks `boundary_contract`, `structured_interpretation`, `variant_product` (3); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
- Review closures are true; scores 2/1/2/1/1 = G07; route `official-review`; lane `cloud`; canonical filename `CODE_REVIEW-cloud-G07.md`.
## Implementation Checklist
- [ ] Add and validate the optional fixed single-request preset policy, deep-clone it, and prove valid, boundary, invalid, legacy, and clone-isolation cases.
- [ ] Classify policy changes as live-applied, add a secret-free commented config example, and synchronize the config contract and current implementation spec.
- [ ] Run targeted, package, vet, full profile 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] Add the typed fixed single-request policy
**Problem**
- `packages/go/config/execution_preset_types.go:13` defines no marker that distinguishes operator-owned single-request execution from generic caller-continuation light presets.
- `ExecutionPreset.Clone` at line 61 does not have a policy pointer/nested map to clone, and `validatePreset` at line 281 cannot enforce the approved fixed shape.
**Solution**
Before (`packages/go/config/execution_preset_types.go:15`):
```go
ID string `mapstructure:"id" yaml:"id"`
// Selector is the fused selector/planner model binding and options.
Selector ExecutionModelBinding `mapstructure:"selector" yaml:"selector"`
// AllowedModes is the set of registered mode descriptors this preset permits.
AllowedModes []string `mapstructure:"allowed_modes" yaml:"allowed_modes"`
// Routes maps each allowed mode descriptor to its ordered downstream stages.
Routes map[string]ExecutionRoute `mapstructure:"routes" yaml:"routes"`
```
After:
```go
// Existing fields stay source-compatible.
SingleRequest *ExecutionSingleRequestPolicy `mapstructure:"single_request" yaml:"single_request,omitempty"`
```
Add typed workspace/limit structs and server-owned absolute caps: wall clock 30 minutes, each stage timeout 10 minutes, 64 tool iterations per stage, and 16 MiB output per stage. Require every configured value in `1..cap`, each stage timeout not to exceed the request wall clock, and the stage map to contain exactly `plan`, `work`, and `review`. A marked preset allows only `light`, binds selector/review to high reasoning, rejects high reasoning on work, and rejects legacy caller `workspace_tools`. Preserve unmarked validation. Deep-copy the pointer and nested stage map.
**Modified Files and Checklist**
- [ ] `packages/go/config/execution_preset_types.go` — add typed policy, named absolute caps, normalization, fail-closed validation, and deep cloning.
- [ ] `packages/go/config/single_request_execution_preset_config_test.go` — cover valid decode, cap/cap+1 and timeout-vs-wall-clock boundaries, missing/extra stages, dynamic modes, option leakage, legacy tools, unknown fields, and clone isolation.
**Test Strategy**
- Add `TestLoadEdgeSingleRequestExecutionPreset`, `TestLoadEdgeSingleRequestExecutionPresetRejectsInvalidShape`, and `TestCloneExecutionPresetSingleRequestIsolation` using Gemini plan/review, ornith-fast work, an opaque workspace ref, and explicit positive bounded limits. Include zero, exact cap, cap+1, and stage-timeout-greater-than-wall-clock rows for every limit family.
- Rerun existing generic catalog/rejection tests to prove compatibility.
**Verification**
- `go test ./packages/go/config -run 'Test(LoadEdgeSingleRequestExecutionPreset|CloneExecutionPresetSingleRequestIsolation|LoadEdgeExecutionPresetCatalog|LoadEdgeExecutionPresetRejectsInvalidShape)$' -count=1`
- Expected: valid/exact-cap and legacy cases pass; zero/cap+1/cross-limit/malformed shapes fail; clone mutation cannot affect the source.
### [API-2] Preserve refresh semantics and publish the schema
**Problem**
- `apps/edge/internal/configrefresh/classify.go:371` compares selector, modes, routes, and workspace tools but cannot report the new policy independently.
- `configs/edge.yaml` and the refresh contract/spec do not describe a secret-free fixed single-request generation.
**Solution**
Before (`apps/edge/internal/configrefresh/classify.go:383`):
```go
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].selector", id), StatusApplied, cur.Selector, next.Selector)
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].allowed_modes", id), StatusApplied, cur.AllowedModes, next.AllowedModes)
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].routes", id), StatusApplied, cur.Routes, next.Routes)
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].workspace_tools", id), StatusApplied, cur.WorkspaceTools, next.WorkspaceTools)
```
After:
```go
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].routes", id), StatusApplied, cur.Routes, next.Routes)
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].single_request", id), StatusApplied, cur.SingleRequest, next.SingleRequest)
appendDeepIfChanged(changes, fmt.Sprintf("execution_presets[%q].workspace_tools", id), StatusApplied, cur.WorkspaceTools, next.WorkspaceTools)
```
Classify the policy as live-applied and document the exact absolute caps plus the rule that refresh affects only new request snapshots. Add only a commented, secret-free YAML example; synchronize contract/spec without claiming runtime execution.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/configrefresh/classify.go` — emit the precise single-request change path.
- [ ] `apps/edge/internal/configrefresh/execution_preset_classify_test.go` — prove value capture and deterministic ordering.
- [ ] `configs/edge.yaml` — add a commented fixed-light example only.
- [ ] `agent-contract/inner/edge-config-runtime-refresh.md` — define validation, compatibility, refresh generation, and secret rules.
- [ ] `agent-spec/runtime/provider-pool-config-refresh.md` — synchronize current schema and executable evidence.
**Test Strategy**
- Extend `TestClassifyExecutionPresetLiveApply` with differing policy snapshots and assert the exact sorted change path plus previous/next values.
- Use the config loader tests from API-1 as the decoder/validator oracle; no external config smoke is needed.
**Verification**
- `go test ./apps/edge/internal/configrefresh -run 'TestClassifyExecutionPresetLiveApply$' -count=1`
- Expected: the classifier reports the policy path as applied with deterministic ordering.
## Modified Files Summary
| File | Item |
|------|------|
| `packages/go/config/execution_preset_types.go` | API-1 |
| `packages/go/config/single_request_execution_preset_config_test.go` | API-1 |
| `apps/edge/internal/configrefresh/classify.go` | API-2 |
| `apps/edge/internal/configrefresh/execution_preset_classify_test.go` | API-2 |
| `configs/edge.yaml` | API-2 |
| `agent-contract/inner/edge-config-runtime-refresh.md` | API-2 |
| `agent-spec/runtime/provider-pool-config-refresh.md` | API-2 |
| `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/CODE_REVIEW-cloud-G07.md` | API-1, API-2 |
## Final Verification
1. `go test ./packages/go/config -run 'Test(LoadEdgeSingleRequestExecutionPreset|CloneExecutionPresetSingleRequestIsolation|LoadEdgeExecutionPresetCatalog|LoadEdgeExecutionPresetRejectsInvalidShape)$' -count=1`
2. `go test ./apps/edge/internal/configrefresh -run 'TestClassifyExecutionPresetLiveApply$' -count=1`
3. `go test ./packages/go/config ./apps/edge/internal/configrefresh -count=1`
4. `go vet ./packages/go/...`
5. `go test ./packages/go/... ./apps/edge/... -count=1`
6. `git diff --check`
Expected: all commands exit 0; ordinary presets stay compatible; invalid marked shapes fail closed; refresh reports the new path. Actual Claude/provider execution remains outside this packet.
**After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.**

View file

@ -0,0 +1,124 @@
<!-- task=m-iop-owned-single-request-agent-execution/01_preset_config plan=0 tag=API milestone-task=preset-binding -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/01_preset_config, plan=0, tag=API
## For the Review Agent
> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G07.md` → `code_review_cloud_G07_0.log` and `PLAN-local-G07.md` → `plan_local_G07_0.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/01_preset_config/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=preset-binding` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Add the typed fixed single-request policy | [ ] |
| API-2 Preserve refresh semantics and publish the schema | [ ] |
## Implementation Checklist
- [ ] Add and validate the optional fixed single-request preset policy, deep-clone it, and prove valid/boundary/legacy cases with focused config tests.
- [ ] Classify single-request policy changes as live-applied, add a secret-free commented config example, and synchronize the config contract and implementation spec.
- [ ] Run the targeted and package-level fresh Go tests plus `git diff --check`.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G07_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_local_G07_0.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/01_preset_config/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=preset-binding` for runtime aggregation without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove the empty active parent only when no sibling remains.
- [ ] If WARN/FAIL, write the next filesystem state matching the verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- The optional policy is deeply cloned and has no silent defaults.
- Fixed single-request presets accept only one light route, keep work free of planner/reviewer high effort, and cannot carry legacy caller workspace tools.
- Unmarked direct/light presets retain current behavior.
- Refresh reports the exact single-request path as applied and docs contain no private path, endpoint, Node id, or credential.
- Absolute runtime exhaustion is not falsely claimed by this packet.
## Verification Results
Paste actual stdout/stderr for every command. If a command changes, record the replacement and reason in `Deviations from Plan`.
### API-1 targeted config verification
Command: `go test ./packages/go/config -run 'Test(LoadEdgeSingleRequestExecutionPreset|CloneExecutionPresetSingleRequestIsolation|LoadEdgeExecutionPresetCatalog|LoadEdgeExecutionPresetRejectsInvalidShape)$' -count=1`
_Actual output:_
### API-2 targeted refresh verification
Command: `go test ./apps/edge/internal/configrefresh -run 'TestClassifyExecutionPresetLiveApply$' -count=1`
_Actual output:_
### Package verification
Commands:
- `go test ./packages/go/config ./apps/edge/internal/configrefresh -count=1`
- `go test ./packages/go/... ./apps/edge/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these |
| Implementation Item Completion | Implementing agent | Check `[ ]` → `[x]` only |
| Implementation Checklist | Implementing agent | Check `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholders with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results | Implementing agent | Fill actual stdout/stderr; command changes require a deviation |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,226 @@
<!-- task=m-iop-owned-single-request-agent-execution/01_preset_config plan=0 tag=API milestone-task=preset-binding -->
# Fixed Single-request Preset Config
## For the Implementing Agent
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 both active files in place, and report ready for review. Finalization belongs only to the code-review skill. If blocked, record the exact blocker, attempted commands/output, and resume condition in implementation-owned evidence fields; 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
The existing execution preset schema distinguishes generic `direct` and caller-continuation `light` shapes but has no marker for the approved fixed single-request path. SDD S02 requires an operator-owned workspace capability and immutable request/stage limits while preserving existing generic preset compatibility and live-refresh generation isolation.
## 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.md`
- `agent-ops/rules/project/domain/platform-common.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`
- `agent-test/local/platform-common-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`
- `packages/go/config/execution_preset_config_test.go`
- `packages/go/config/model_execution_preset_config_test.go`
- `apps/edge/internal/configrefresh/classify.go`
- `apps/edge/internal/configrefresh/execution_preset_classify_test.go`
- `configs/edge.yaml`
- `agent-contract/inner/edge-config-runtime-refresh.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 lock released.
- Milestone task: `preset-binding`.
- Acceptance Scenario: S02.
- Evidence Map: fixed-light decode/authorization/model echo/workspace snapshot tests and config contract sync under the `preset-binding` evidence aggregate.
- This packet supplies the decode, validation, cloning, refresh classification, and documented schema portion of S02. Runtime route authorization and public-model echo remain in `02+01_preset_binding`.
### Verification Context
- No separate verification handoff was supplied. Repository-native evidence came from the local test rules, the existing preset config tests, the config-refresh classifier tests, and the approved SDD.
- Baseline command `go test ./packages/go/config ./apps/edge/internal/configrefresh ./apps/edge/internal/openai -count=1` passed at starting HEAD `3331e5f8d20e2137d1cd1ae5600efedb42be291e`.
- Preconditions: implement after no predecessor; keep ordinary direct/light presets backward compatible; use no external runner.
- Constraint: actual Claude/provider execution is not evidence for this packet and belongs to `claude-smoke`.
- Confidence: high for local schema and refresh behavior. Absolute runtime exhaustion behavior is intentionally left to `error-cancel`; this packet only validates positive typed values and immutable snapshots.
### Test Coverage Gaps
- Existing tests cover generic direct/light normalization, mode ordering, workspace-tool validation, virtual-model one-of rules, and preset live-refresh classification.
- No existing test covers an optional single-request marker, opaque `workspace_ref`, typed per-request/per-stage limits, legacy workspace-tool exclusion, or dynamic-mode rejection. Add focused config tests.
- Existing refresh tests do not identify the new field as its own live-applied path. Extend the classifier test.
### Symbol References
- No symbol is renamed or removed.
- `ExecutionPreset` is cloned by `CloneExecutionPresetCatalog` and read by Edge routing; the new optional field must participate in deep cloning without changing existing callers.
- `appendExecutionPresetChanges` currently compares selector, modes, routes, and workspace tools only.
### Split Judgment
- `01_preset_config` owns the stable YAML/Go config contract and passes config plus refresh tests independently.
- `02+01_preset_binding` consumes the typed schema to compile an authorized immutable request binding.
- `03+02_single_ingress` consumes that binding in the coordinator.
- `04+03_stream_terminal` consumes coordinator public events for SSE.
- This first packet has no predecessor. The numbered split is topological and each child has an independent PASS oracle.
### Scope Rationale
- Do not modify Edge route resolution, Anthropic handlers, Node runtime, protobuf, workspace containment, tool execution, or SSE code here.
- Do not hardcode provider endpoints, credentials, Node ids, raw paths, or private config. `workspace_ref` remains an opaque operator capability reference.
- Do not introduce dynamic mode selection. The marker is valid only with exactly one allowed `light` route.
### Final Routing
- evaluation_mode: `first-pass`; finalizer: `finalize-task-policy.sh` in `pair` mode.
- Build closures: scope/context/verification/evidence/ownership/decision all true. Scores 2/1/2/1/1 = G07; base/final route `local-fit`; lane `local`; filename `PLAN-local-G07.md`.
- Build signals: `large_indivisible_context=false`; positive loop risks `boundary_contract`, `structured_interpretation`, `variant_product` (3); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
- Review closures all true. Scores 2/1/2/1/1 = G07; route `official-review`; lane `cloud` with Codex `gpt-5.6-sol` xhigh; filename `CODE_REVIEW-cloud-G07.md`.
## Implementation Checklist
- [ ] Add and validate the optional fixed single-request preset policy, deep-clone it, and prove valid/boundary/legacy cases with focused config tests.
- [ ] Classify single-request policy changes as live-applied, add a secret-free commented config example, and synchronize the config contract and implementation spec.
- [ ] Run the targeted and package-level fresh Go tests plus `git diff --check`.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
## Implementation Plan
### [API-1] Add the typed fixed single-request policy
**Problem**
- `packages/go/config/execution_preset_types.go:13`-`23` has no field that distinguishes a fixed single-request preset from the generic caller-tool `light` shape.
- `packages/go/config/execution_preset_types.go:281`-`365` validates modes/routes, while `packages/go/config/execution_preset_types.go:421`-`507` always requires legacy caller workspace tools for every light preset.
**Solution**
Before (`packages/go/config/execution_preset_types.go:13`):
type ExecutionPreset struct {
ID string
Selector ExecutionModelBinding
AllowedModes []string
Routes map[string]ExecutionRoute
WorkspaceTools []ExecutionWorkspaceToolAlternative
}
After:
type ExecutionPreset struct {
// existing fields remain source-compatible
SingleRequest *ExecutionSingleRequestPolicy `mapstructure:"single_request" yaml:"single_request,omitempty"`
}
type ExecutionSingleRequestPolicy struct {
WorkspaceRef string `mapstructure:"workspace_ref" yaml:"workspace_ref"`
Limits ExecutionSingleRequestLimits `mapstructure:"limits" yaml:"limits"`
}
type ExecutionSingleRequestLimits struct {
WallClockMS int `mapstructure:"wall_clock_ms" yaml:"wall_clock_ms"`
Stages map[string]ExecutionSingleRequestStageLimits `mapstructure:"stages" yaml:"stages"`
}
type ExecutionSingleRequestStageLimits struct {
TimeoutMS int `mapstructure:"timeout_ms" yaml:"timeout_ms"`
MaxToolIterations int `mapstructure:"max_tool_iterations" yaml:"max_tool_iterations"`
MaxOutputBytes int `mapstructure:"max_output_bytes" yaml:"max_output_bytes"`
}
- Deep-clone the pointer and stage-limit map.
- When `single_request` is present, normalize a non-empty `workspace_ref`, require `allowed_modes == ["light"]`, require exactly `plan`/`work`/`review` positive limit entries, require selector/review `reasoning_effort=high`, reject that option on work, and reject legacy `workspace_tools` so caller tool binding cannot compete with the internal workspace runtime.
- Keep unmarked direct/light validation byte-for-byte compatible. Do not add silent defaults.
**Modified Files and Checklist**
- [ ] `packages/go/config/execution_preset_types.go` — add types, cloning, normalization, and fail-closed validation.
- [ ] `packages/go/config/single_request_execution_preset_config_test.go` — add valid, boundary, unknown-field, dynamic-mode, missing-limit, option-leak, legacy-tool, and deep-clone cases.
**Test Strategy**
- Write `TestLoadEdgeSingleRequestExecutionPreset` with canonical fixtures `gemini-3.6-flash` for selector/review, `ornith-fast` for work, an opaque Mac workspace ref, positive limits, and no legacy caller tools.
- Write `TestLoadEdgeSingleRequestExecutionPresetRejectsInvalidShape` as a table for missing workspace, direct/hybrid/dynamic modes, missing/extra stage keys, non-positive limits, absent review high, and work high leakage.
- Write `TestCloneExecutionPresetSingleRequestIsolation` to mutate nested cloned limits and prove the source remains unchanged.
- Rerun existing `TestLoadEdgeExecutionPresetCatalog` and `TestLoadEdgeExecutionPresetRejectsInvalidShape` for compatibility.
**Verification**
- `go test ./packages/go/config -run 'Test(LoadEdgeSingleRequestExecutionPreset|CloneExecutionPresetSingleRequestIsolation|LoadEdgeExecutionPresetCatalog|LoadEdgeExecutionPresetRejectsInvalidShape)$' -count=1`
- Expected: all fixed and legacy preset cases pass with fresh execution.
### [API-2] Preserve refresh semantics and publish the schema
**Problem**
- `apps/edge/internal/configrefresh/classify.go:371`-`388` does not report the new policy independently.
- `configs/edge.yaml:331` onward documents provider models but no secret-free fixed single-request virtual model/preset example.
- The current config contract/spec describe generic frozen presets but not the fixed-light workspace/limit snapshot.
**Solution**
Before (`apps/edge/internal/configrefresh/classify.go:383`):
appendDeepIfChanged(changes, ..., cur.Routes, next.Routes)
appendDeepIfChanged(changes, ..., cur.WorkspaceTools, next.WorkspaceTools)
After:
appendDeepIfChanged(changes, ..., cur.Routes, next.Routes)
appendDeepIfChanged(changes, ..., cur.SingleRequest, next.SingleRequest)
appendDeepIfChanged(changes, ..., cur.WorkspaceTools, next.WorkspaceTools)
- Classify `execution_presets["id"].single_request` as `applied`. Runtime request pinning remains a consumer responsibility, but the contract must state that refreshed values affect only new requests.
- Add only a commented, secret-free example showing public virtual model → preset, Gemini plan/review high, ornith-fast work without high, opaque `workspace_ref`, and explicit positive limits. Do not add non-resolving active config entries.
- Synchronize the inner contract and current implementation spec with schema, compatibility, and generation semantics.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/configrefresh/classify.go` — add the exact live-applied diff path.
- [ ] `apps/edge/internal/configrefresh/execution_preset_classify_test.go` — assert the new sorted change path and previous/next values.
- [ ] `configs/edge.yaml` — add the commented public example only.
- [ ] `agent-contract/inner/edge-config-runtime-refresh.md` — define validation, refresh, and no-secret rules.
- [ ] `agent-spec/runtime/provider-pool-config-refresh.md` — synchronize current schema and tests.
**Test Strategy**
- Extend `TestClassifyExecutionPresetLiveApply` with differing policy snapshots and expect `execution_presets["preset-m-mod"].single_request` in deterministic lexical order.
- Do not add an external config smoke; `LoadEdge` temp-file tests provide the exact decoder/validator path.
**Verification**
- `go test ./apps/edge/internal/configrefresh -run 'TestClassifyExecutionPresetLiveApply$' -count=1`
- Expected: the classifier reports the new path as applied with stable ordering.
## Modified Files Summary
| File | Item |
|------|------|
| `packages/go/config/execution_preset_types.go` | API-1 |
| `packages/go/config/single_request_execution_preset_config_test.go` | API-1 |
| `apps/edge/internal/configrefresh/classify.go` | API-2 |
| `apps/edge/internal/configrefresh/execution_preset_classify_test.go` | API-2 |
| `configs/edge.yaml` | API-2 |
| `agent-contract/inner/edge-config-runtime-refresh.md` | API-2 |
| `agent-spec/runtime/provider-pool-config-refresh.md` | API-2 |
| `agent-task/m-iop-owned-single-request-agent-execution/01_preset_config/CODE_REVIEW-cloud-G07.md` | API-1, API-2 |
## Final Verification
Run with the Go test cache disabled:
1. `go test ./packages/go/config -run 'Test(LoadEdgeSingleRequestExecutionPreset|CloneExecutionPresetSingleRequestIsolation|LoadEdgeExecutionPresetCatalog|LoadEdgeExecutionPresetRejectsInvalidShape)$' -count=1`
2. `go test ./apps/edge/internal/configrefresh -run 'TestClassifyExecutionPresetLiveApply$' -count=1`
3. `go test ./packages/go/config ./apps/edge/internal/configrefresh -count=1`
4. `go test ./packages/go/... ./apps/edge/... -count=1`
5. `git diff --check`
Expected: all commands exit 0; generic presets remain compatible; invalid fixed shapes fail closed; refresh identifies the single-request policy as live-applied. Cached 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`.**

View file

@ -0,0 +1,144 @@
<!-- task=m-iop-owned-single-request-agent-execution/02+01_preset_binding plan=1 tag=API milestone-task=preset-binding -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/02+01_preset_binding, plan=1, tag=API
## Archive Evidence Snapshot
- Superseded pair: `plan_local_G06_0.log`, `code_review_cloud_G07_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: the immutable binding is a surface-neutral service DTO, not an OpenAI-private type. Route resolution may populate it, but the coordinator must consume it without importing an endpoint package. Edge vet coverage is also restored.
## For the Review Agent
> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G07.md``code_review_cloud_G07_1.log` and `PLAN-local-G06.md``plan_local_G06_1.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/02+01_preset_binding/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=preset-binding` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Own the immutable admission DTO in service | [ ] |
| API-2 Compile only an authorized fixed binding at route resolution | [ ] |
| API-3 Synchronize the admission boundary | [ ] |
## 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.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G07_1.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_local_G06_1.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/02+01_preset_binding/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=preset-binding` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Packet 01 completion evidence existed before implementation.
- `service` owns the binding and imports no endpoint package.
- Managed and unmanaged routes authorize every stage before compilation.
- Public model identity is retained while canonical/provider/credential/workspace details stay private.
- Refresh or caller mutation cannot alter an admitted request.
## Verification Results
### Dependency
Command: `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 .`
_Actual output/status:_
### Service DTO
Command: `go test ./apps/edge/internal/service -run 'TestSingleRequestBinding' -count=1`
_Actual output:_
### Route compiler
Command: `go test ./apps/edge/internal/openai -run 'Test(SingleRequestPresetBinding|VirtualPresetModelAuthorizationMatrix)' -count=1`
_Actual output:_
### Documentation
Command: `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`
_Actual output:_
### Final regression
Commands:
- `go test ./apps/edge/internal/service ./apps/edge/internal/openai -count=1`
- `go vet ./apps/edge/...`
- `go test ./apps/edge/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]``[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]``[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,245 @@
<!-- task=m-iop-owned-single-request-agent-execution/02+01_preset_binding plan=1 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_0.log`, `code_review_cloud_G07_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: the immutable binding is a surface-neutral service DTO, not an OpenAI-private type. Route resolution may populate it, but the coordinator must consume it without importing an endpoint package. Edge vet coverage is also restored.
## 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` 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**
- The Anthropic contract and current specs describe generic preset resolution but not a service-owned, request-generation single-request binding.
**Solution**
Add a marked-preset subsection to the existing virtual-preset contract and corresponding specs. Document one-generation snapshot semantics, compilation only after principal authorization, requested public identity, 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**
- No standalone documentation test. 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 || 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/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`.**

View file

@ -0,0 +1,140 @@
<!-- task=m-iop-owned-single-request-agent-execution/02+01_preset_binding plan=0 tag=API milestone-task=preset-binding -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/02+01_preset_binding, plan=0, tag=API
## For the Review Agent
> **[REVIEW AGENT ONLY]** Implementing agents must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G07.md` → `code_review_cloud_G07_0.log` and `PLAN-local-G06.md` → `plan_local_G06_0.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/02+01_preset_binding/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=preset-binding` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Compile the fixed runtime value in unmanaged routing | [ ] |
| API-2 Preserve managed authorization, discovery, and public identity | [ ] |
## 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.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** Implementing agents must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` routing signals to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G07_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_local_G06_0.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/02+01_preset_binding/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=preset-binding` for runtime aggregation without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching the verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations and rationale._
## Key Design Decisions
_Record implementation decisions._
## Reviewer Checkpoints
- Predecessor 01 was complete before implementation began.
- Managed and unmanaged paths use one compiler and reject malformed marked presets.
- Every nested option/limit is copied into the admitted binding.
- Selector credential authority and requested virtual public identity stay distinct.
- Generic preset, Chat, provider, Node, and SSE behavior is unchanged.
## Verification Results
Paste actual stdout/stderr. Command changes require a documented deviation.
### Dependency
Command: `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 .`
_Actual output/status:_
### API-1
Command: `go test ./apps/edge/internal/openai -run 'TestSingleRequestPresetBinding(Unmanaged|RejectsDynamicOrIncompleteShape)$' -count=1`
_Actual output:_
### API-1 and API-2 aggregate
Command: `go test ./apps/edge/internal/openai -run 'TestSingleRequestPresetBinding' -count=1`
_Actual output:_
### API-2
Command: `go test ./apps/edge/internal/openai -run 'Test(SingleRequestPresetBindingManagedAuthorization|SingleRequestPresetBindingRefreshIsolation|SingleRequestPresetBindingPreservesPublicModel|VirtualPresetModelAuthorizationMatrix|VirtualPresetModelHandlersPreservePublicIdentity)$' -count=1`
_Actual output:_
### API-2 existing public-identity regression
Command: `go test ./apps/edge/internal/openai -run 'Test(VirtualPresetModelAuthorizationMatrix|VirtualPresetModelHandlersPreservePublicIdentity)$' -count=1`
_Actual output:_
### Final regression
Commands:
- `go test ./apps/edge/internal/openai -count=1`
- `go test ./apps/edge/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> Leave review-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results | Fixed headings/commands; implementing agent output | Fill actual stdout/stderr; command changes require a deviation |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,207 @@
<!-- 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`.**

View file

@ -0,0 +1,146 @@
<!-- task=m-iop-owned-single-request-agent-execution/03+02_single_ingress plan=1 tag=API milestone-task=single-ingress -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/03+02_single_ingress, plan=1, tag=API
## Archive Evidence Snapshot
- Superseded pair: `plan_cloud_G09_0.log`, `code_review_cloud_G10_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: coordinator/state ownership moves from `openai.Server` to the surface-neutral `service` package, `repairing` is restored to the approved state machine, and endpoint integration uses a separate optional interface instead of widening the legacy `runService` contract. Edge vet coverage is restored.
## For the Review Agent
> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G10.md``code_review_cloud_G10_1.log` and `PLAN-cloud-G09.md``plan_cloud_G09_1.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/03+02_single_ingress/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=single-ingress` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Implement the coordinator in service | [ ] |
| API-2 Admit marked Anthropic requests exactly once | [ ] |
| API-3 Synchronize the coordinator boundary | [ ] |
## Implementation Checklist
- [ ] Implement the surface-neutral request-local coordinator, executor port, complete approved state graph including repair/internal-tool resume, immutable admission, cancellation, and one-shot endpoint terminal acknowledgement before `completed`.
- [ ] Route marked Anthropic Messages requests through a separate optional service capability before legacy admission, keep one HTTP lifetime, and prove one actual POST with a multi-stage fake.
- [ ] Preserve unmarked Anthropic, Chat, and count-tokens behavior; expose only sanitized progress/final/error values and synchronize the boundary documents.
- [ ] Run dependency, targeted race, 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.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G10_1.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_1.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/03+02_single_ingress/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=single-ingress` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Packet 02 completion evidence existed before implementation.
- Coordinator/state ownership is in `service`; no endpoint wire type crosses into it.
- All approved states, especially `repairing` and saved-stage `internal_tool`, are tested.
- Success remains `finalizing` until one endpoint terminal acknowledgement; duplicate/write-failure/cancel races cannot also complete.
- Exactly one outcome wins and all executor work is cancelled/joined.
- Marked routing precedes legacy pool/continuation; actual handler POST count is one.
- Public output has no reasoning, tool wire, provider/route/credential/workspace data, or caller `tool_use` continuation.
## Verification Results
### Dependency
Command: `test -f agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log' -print | sort | grep -q .`
_Actual output/status:_
### Coordinator race and state graph
Command: `go test -race ./apps/edge/internal/service -run 'TestSingleRequest' -count=1`
_Actual output:_
### One ingress and compatibility
Command: `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
_Actual output:_
### Documentation
Command: `rg --sort path -n 'single-request|one POST|repairing|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
_Actual output:_
### Final regression
Commands:
- `go test ./apps/edge/internal/service ./apps/edge/internal/openai -count=1`
- `go vet ./apps/edge/...`
- `go test ./apps/edge/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]``[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]``[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,259 @@
<!-- task=m-iop-owned-single-request-agent-execution/03+02_single_ingress plan=1 tag=API milestone-task=single-ingress -->
# Surface-neutral Single-request Coordinator and Ingress
## 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-G10.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_cloud_G09_0.log`, `code_review_cloud_G10_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: coordinator/state ownership moves from `openai.Server` to the surface-neutral `service` package, `repairing` is restored to the approved state machine, and endpoint integration uses a separate optional interface instead of widening the legacy `runService` contract. Edge vet coverage is restored.
## Background
The current Anthropic path may expose caller-mediated preset/tool continuations across turns. The marked path needs exactly one accepted `/v1/messages` request whose immutable binding drives a request-local coordinator through all internal stages and yields one sanitized result or failure. The endpoint package owns translation only; coordinator semantics must remain reusable by other surfaces.
## 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`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/route_resolution.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/anthropic_surface_test.go`
- `apps/edge/internal/openai/request_identity_handler_test.go`
- `apps/edge/internal/openai/provider_test_support_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/edge-node-execution.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: `single-ingress`; targeted Acceptance Scenario: S01.
- Evidence Map row S01 requires one actual `/v1/messages` POST, immutable identity, complete internal multi-stage execution via the coordinator/API boundary, and one final/error. Those facts directly produce API-1/API-2 and the POST-count/race commands in Final Verification.
### Verification Context
- No separate verification handoff was supplied. Repository-native fallback came from the service lifecycle code, Anthropic handler/identity regressions, test fake interface shape, Edge test profile, and approved SDD.
- Precondition: packet 02 completion. Constraints: current checkout only; no external runner/provider; concrete Node/workspace executor stays deferred. Gap: streamed SSE projection is packet 04 and actual Claude smoke is later Milestone evidence.
- Commands use service race tests, endpoint POST/compatibility tests, deterministic doc search, `go vet`, full Edge regression, and `git diff --check`. Confidence is high for coordinator/ingress behavior with an injected multi-stage fake.
### State and Concurrency Findings
- Approved states: `accepted`, `planning`, `working`, `reviewing`, `repairing`, `internal_tool`, `finalizing`, `completed`, `failed`, `cancelled`.
- `internal_tool` must return only to its saved active stage. Stage sequence and retries are validated from internal envelopes; stale, duplicate, or illegal transitions fail closed.
- One terminal wins under completion, failure, cancellation, and duplicate/racing internal events. No goroutine or stage survives request termination.
### Test Coverage Gaps
- No service test exercises the full state graph, repair path, temporary internal-tool state, immutable admission, cancellation, or terminal races.
- Existing endpoint tests do not count one marked HTTP handler POST across a multi-stage executor or prove that the marked branch bypasses legacy caller continuation.
### Symbol References
- No existing symbol is renamed or removed.
- `runService` is implemented by `*service.Service` and multiple OpenAI test fakes. It must not gain the new method; the marked handler uses a separate narrow optional interface.
- `routeDispatch` is the call-site carrier for packet 02's binding; `handleAnthropicMessages` is the endpoint branch point.
### Split Judgment
- Stable child contract: the service coordinator plus marked buffered ingress independently prove S01 with an injected executor and one POST, without depending on SSE projection.
- Predecessor index 02 resolves to `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/`; its `complete.log` is currently missing, so implementation remains pending and unambiguous.
### Scope Rationale
- Exclude generic Anthropic relay, Chat bridge, count-tokens, unmarked preset continuation, and streaming projection because they have separate compatibility/packet ownership.
- Exclude concrete provider/Node/workspace protocol and actual Claude smoke. Do not expose reasoning, tool protocol, route/provider/credential/workspace data, or internal terminals.
### Final Routing
- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh` in `pair` mode.
- Build closures are true; scores 2/2/2/1/2 = G09; base/final route `grade-boundary`; lane `cloud`; canonical filename `PLAN-cloud-G09.md`.
- Build signals: `large_indivisible_context=false`; positive loop risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`, `variant_product` (5); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
- Review closures are true; scores 2/2/2/2/2 = G10; route `official-review`; lane `cloud`; canonical filename `CODE_REVIEW-cloud-G10.md`.
## Dependencies and Execution Order
1. Verify packet 02 completion evidence.
2. Implement and race-test the service coordinator before endpoint integration.
3. Add the marked handler branch before legacy pool/continuation admission.
4. Prove one HTTP POST and generic path compatibility, then synchronize contracts/specs.
## Implementation Checklist
- [ ] Implement the surface-neutral request-local coordinator, executor port, complete approved state graph including repair/internal-tool resume, immutable admission, cancellation, and one-shot endpoint terminal acknowledgement before `completed`.
- [ ] Route marked Anthropic Messages requests through a separate optional service capability before legacy admission, keep one HTTP lifetime, and prove one actual POST with a multi-stage fake.
- [ ] Preserve unmarked Anthropic, Chat, and count-tokens behavior; expose only sanitized progress/final/error values and synchronize the boundary documents.
- [ ] Run dependency, targeted race, 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] Implement the coordinator in service
**Problem**
- `apps/edge/internal/service/service.go:28` owns Edge request/runtime state but exposes no fixed single-request executor/coordinator API.
- The superseded plan placed state in the endpoint server and omitted approved `repairing`, which would violate the surface-neutral domain boundary and reject a valid SDD transition.
**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
}
```
After:
```go
type Service struct {
// Existing fields remain.
singleRequestExecutor SingleRequestExecutor
}
func (s *Service) StartSingleRequest(ctx context.Context, req SingleRequestRequest) (SingleRequestExecution, error)
```
Define a service-owned executor that accepts a frozen binding/input and emits typed internal envelopes. Validate request/stage identity and the full state graph, including the repair loop and saved-stage `internal_tool` detour. Copy mutable inputs and expose only closed progress/result enums. Return a request-scoped execution handle that holds a successful terminal candidate in `finalizing`; it may enter `completed` only after the endpoint calls a one-shot success acknowledgement after its terminal write. Duplicate/stale acknowledgement fails closed; write failure or caller cancellation selects `failed`/`cancelled`. Serialize outcome/ack selection, cancel the executor on exit, and fail within-request if unavailable. Do not import endpoint wire types or implement Node/tool wire.
**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, state validation, redacted progress, cancellation, and terminal ownership.
- [ ] `apps/edge/internal/service/single_request_test.go` — cover success held in finalizing until ack, duplicate/write-failure ack, repair, internal-tool resume, illegal/stale/duplicate events, immutable admission, unavailable executor, cancel, and terminal races under `-race`.
**Test Strategy**
- Add `TestSingleRequestSuccessWaitsForTerminalAck`, duplicate/write-failure acknowledgement cases, `...RepairFlow`, `...InternalToolResumesSavedStage`, invalid envelope/transition tables, `...ImmutableAdmission`, `...ExecutorUnavailable`, `...Cancel`, and terminal race cases.
- Use an injected channel-driven fake executor and run all `TestSingleRequest` cases under the race detector.
**Verification**
- `go test -race ./apps/edge/internal/service -run 'TestSingleRequest' -count=1`
- Expected: all approved paths including repair pass, success cannot reach completed before endpoint acknowledgement, invalid/stale events fail closed, and exactly one outcome/ack wins without races.
### [API-2] Admit marked Anthropic requests exactly once
**Problem**
- `apps/edge/internal/openai/anthropic_handler.go:66` reaches `anthropicPoolRequest`/legacy continuation after dispatch resolution and has no marked one-request branch.
- `apps/edge/internal/openai/server.go:23` defines a widely faked `runService`; widening it would break unrelated test implementations and couple the new capability to generic endpoints.
**Solution**
Before (`apps/edge/internal/openai/server.go:23`):
```go
type runService interface {
SubmitRun(context.Context, edgeservice.SubmitRunRequest) (edgeservice.RunResult, error)
SubmitProviderTunnel(context.Context, edgeservice.SubmitProviderTunnelRequest) (edgeservice.ProviderTunnelResult, error)
SubmitProviderPool(context.Context, edgeservice.ProviderPoolDispatchRequest) (*edgeservice.ProviderPoolDispatchResult, error)
OllamaAPI(context.Context, edgeservice.OllamaAPIRequest) (edgeservice.OllamaAPIView, error)
CancelRun(context.Context, edgeservice.CancelRunRequest) (edgeservice.CommandResult, error)
}
```
After, without changing that interface:
```go
type singleRequestService interface {
StartSingleRequest(context.Context, service.SingleRequestRequest) (service.SingleRequestExecution, error)
}
```
Assert the separate capability only for a marked dispatch. Branch after request validation/authorization but before pool/legacy continuation, copy request input, preserve the public model, and translate one buffered sanitized final/error. Acknowledge success only after the endpoint terminal is written; propagate write failure/cancellation to the handle. Never return caller `tool_use` or re-enter the generic branch.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/server.go` — declare/wire the separate optional single-request capability without expanding `runService`.
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — branch marked admission before legacy execution and translate buffered final/error output.
- [ ] `apps/edge/internal/openai/single_request_handler_test.go` — count real handler POST entry, drive multi-stage/repair fake events, assert one response terminal and private-value absence, and cover missing capability/failure/cancellation.
**Test Strategy**
- Add `TestAnthropicSingleRequestUsesOnePost`, multi-stage/repair success, terminal-write acknowledgement/failure, unavailable capability/failure/cancel, public-model, and private-sentinel assertions in the dedicated test file.
- Rerun `TestPresetRequestIdentityAcrossAnthropicTurns` and `TestPresetRequestIdentityAnthropicCountTokensBypassesCoordinator` unchanged from their existing test file.
**Verification**
- `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
- Expected: a marked multi-stage fake enters the HTTP handler once and returns one sanitized terminal; generic continuation/count-tokens behavior is unchanged.
### [API-3] Synchronize the coordinator boundary
**Problem**
- The current outer contract describes caller replay/tool continuation for generic compatibility, and the specs do not distinguish the marked service coordinator boundary.
**Solution**
Add a marked-path exception to the existing virtual-preset Hot Path contract and corresponding specs. Document immutable service admission, one Messages POST, no caller continuation tool wire, public model retention, same-request sanitized failure, and unchanged generic/Chat/count-tokens behavior. Describe the executor as an internal port without claiming concrete workspace/Node implementation or real-provider smoke.
**Modified Files and Checklist**
- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define one-ingress semantics, compatibility, and private/public boundaries.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize marked handler behavior and executable evidence.
- [ ] `agent-spec/runtime/edge-node-execution.md` — record the surface-neutral coordinator port and explicit implementation deferral.
**Test Strategy**
- No standalone documentation test. API-2's named one-POST/privacy/compatibility tests are the executable contract oracle.
**Verification**
- `rg --sort path -n 'single-request|one POST|repairing|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
- Expected: marked behavior and deferrals are explicit, while generic compatibility remains documented.
## 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 |
| `apps/edge/internal/openai/server.go` | API-2 |
| `apps/edge/internal/openai/anthropic_handler.go` | API-2 |
| `apps/edge/internal/openai/single_request_handler_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/edge-node-execution.md` | API-3 |
| `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/CODE_REVIEW-cloud-G10.md` | API-1, API-2, API-3 |
## Final Verification
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log' -print | sort | grep -q .`
2. `go test -race ./apps/edge/internal/service -run 'TestSingleRequest' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
4. `rg --sort path -n 'single-request|one POST|repairing|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.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; service race/state tests pass; one marked handler POST yields one sanitized final/error without caller continuation; generic regressions pass. Concrete workspace execution and actual Claude smoke remain unclaimed.
**After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.**

View file

@ -0,0 +1,136 @@
<!-- task=m-iop-owned-single-request-agent-execution/03+02_single_ingress plan=0 tag=API milestone-task=single-ingress -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/03+02_single_ingress, plan=0, tag=API
## For the Review Agent
> **[REVIEW AGENT ONLY]** Implementers must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G10.md` → `code_review_cloud_G10_0.log` and `PLAN-cloud-G09.md` → `plan_cloud_G09_0.log`.
3. If PASS, write `complete.log` and move the active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/03+02_single_ingress/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=single-ingress` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Add the request-local coordinator kernel | [ ] |
| API-2 Give marked Messages requests one HTTP lifetime | [ ] |
| API-3 Synchronize the boundary documentation | [ ] |
## Implementation Checklist
- [ ] Implement the request-local single-request state machine and executor event boundary with immutable admission, one active stage, fail-closed transitions, cancellation, and exactly-once terminal tests.
- [ ] Route marked Anthropic Messages requests through that coordinator before legacy preset ingress, keep one HTTP lifetime, return one sanitized final/error, and prove actual Edge ingress POST count 1 with a multi-stage fake.
- [ ] Preserve unmarked preset/Chat/count-tokens behavior and synchronize the Anthropic contract plus current implementation specs.
- [ ] Run targeted, race, full Edge regression, and `git diff --check` verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** Implementers must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` routing signals to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G10_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_0.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/03+02_single_ingress/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=single-ingress` for runtime aggregation without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching the verdict and do not write `complete.log`.
## Deviations from Plan
_Record deviations and rationale._
## Key Design Decisions
_Record decisions._
## Reviewer Checkpoints
- Predecessor 02 was complete before work.
- Exactly one coordinator terminal wins under duplicate, stale, cancel, and complete races.
- The marked branch occurs before legacy continuation admission; generic paths remain unchanged.
- The ingress test counts actual HTTP POST handler entry, not request id or prompt.
- Public output contains no internal reasoning, tool protocol, route/credential data, or `tool_use` terminal.
- Executor unavailability fails within the same request; S06/S12 are not claimed.
## Verification Results
Paste actual stdout/stderr; deviations must explain replacement commands.
### Dependency
Command: `test -f agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log' -print | sort | grep -q .`
_Actual output/status:_
### Coordinator race
Command: `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestCoordinator' -count=1`
_Actual output:_
### One-ingress and compatibility
Command: `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
_Actual output:_
### Documentation
Command: `rg --sort path -n 'single-request|one POST|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
_Actual output:_
### Final regression
Commands:
- `go test ./apps/edge/internal/openai -count=1`
- `go test ./apps/edge/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Fill every implementation-owned section and leave review-only sections unchanged.**
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results | Fixed headings/commands; implementing agent output | Fill actual stdout/stderr; command changes require a deviation |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,249 @@
<!-- task=m-iop-owned-single-request-agent-execution/03+02_single_ingress plan=0 tag=API milestone-task=single-ingress -->
# One-POST Single-request Coordinator
## For the Implementing Agent
Do not start until predecessor 02 has `complete.log`. Implement only this packet, run every command, and fill all implementation-owned sections of `CODE_REVIEW-cloud-G10.md` with actual notes and stdout/stderr before reporting ready for review. Keep active files in place; finalization is code-review-only. If blocked, record the exact blocker, attempts/output, and resume condition in the evidence fields. 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
The current Anthropic preset path joins caller `tool_result` continuations across multiple HTTP requests and binds one codec per HTTP turn. SDD S01 instead requires one actual `POST /v1/messages` whose immutable request and preset snapshot remain owned by Edge until all internal stage events converge to one result.
## 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`
- `apps/edge/internal/openai/server.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/request_coordinator.go`
- `apps/edge/internal/openai/request_coordinator_test.go`
- `apps/edge/internal/openai/request_identity_handler_test.go`
- `apps/edge/internal/openai/anthropic_surface_test.go`
- `apps/edge/internal/openai/anthropic_stream.go`
- `apps/edge/internal/openai/hot_path_light.go`
- `apps/edge/internal/openai/hot_path_dispatch.go`
- `apps/edge/internal/openai/hot_path_terminal_control.go`
- `apps/edge/internal/openai/hot_path_terminal_control_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/inner/execution-runtime.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/edge-node-execution.md`
- `agent-test/local/edge-smoke.md`
### SDD Criteria
- SDD approved; Milestone task `single-ingress`; Acceptance Scenario S01.
- Evidence Map requires a Claude-invocation-style integration test whose Edge-observed `/v1/messages` POST count is exactly one and whose final response needs no caller ingress.
- This packet implements the Edge state machine, executor boundary, and Anthropic handler ownership needed for S01. It does not claim the actual Claude smoke in S12 or the concrete workspace tool loop in S06.
### Verification Context
- No separate handoff was supplied. Repository-native evidence is the current two-turn Anthropic request-identity test, handler call graph, terminal race tests, and local edge profile.
- Baseline related package tests passed at starting HEAD.
- Precondition: `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log`.
- External preflight is not applicable: exact ingress count is deterministically measured at the in-process Edge handler. Real Claude/provider/Node execution is intentionally excluded and belongs to `claude-smoke`.
- Confidence: high for Edge ownership and HTTP-count evidence; concrete provider/tool behavior is represented by a deterministic executor fake and remains owned by other Milestone tasks.
### Test Coverage Gaps
- `TestPresetRequestIdentityAcrossAnthropicTurns` proves the old generic preset continuation behavior with two requests; it must remain for unmarked presets.
- No test measures actual Edge POST count for a marked fixed preset while multiple internal plan/work/tool/review events occur.
- No test covers the approved state set, immutable admission clone, one-active-stage rule, duplicate/stale event rejection, caller cancellation, or exactly-once final selection. Add coordinator and handler tests, including `-race`.
### Symbol References
- No symbol is renamed or removed.
- `handleAnthropicMessages` is the sole Messages handler for canonical and alias paths.
- `joinPresetAnthropicIngress` remains referenced by Chat and generic preset paths; this packet must bypass it only when `dispatch.SingleRequest != nil`.
- `Server` construction is centralized in `NewServer`; add coordinator/runtime ownership without changing `runService` or protobuf.
### Split Judgment
- This packet's indivisible invariant is one Edge-owned state machine and one HTTP handler lifetime. Splitting state transition selection from handler cancellation/terminal ownership would leave no independently meaningful ingress proof.
- Predecessor index 02 resolves to active sibling `agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/`; at planning time its `complete.log` is missing, so implementation is pending that exact evidence and is not ambiguous.
- Successor `04+03_stream_terminal` consumes the closed public progress/result event boundary defined here.
### Scope Rationale
- Do not implement Node workspace RPC, tool execution, tool-loop continuation, plan prompts, work behavior, review repair, budget policy, cleanup metrics, or real Claude smoke.
- Do not modify generic Chat or generic preset continuation behavior.
- The runtime executor port is real coordination architecture, not a fake production success path: absence/unavailability fails on the same request without fallback or a second caller request.
### Final Routing
- evaluation_mode `first-pass`; finalizer `finalize-task-policy.sh` pair.
- Build closures all true. Scores 2/2/2/1/2 = G09; base/final route `grade-boundary`; lane `cloud`; filename `PLAN-cloud-G09.md`.
- Build signals: `large_indivisible_context=false`; risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`, `variant_product` (5); risk boundary matched but grade basis retained; rework 0; evidence integrity false; no capability gap.
- Review closures all true. Scores 2/2/2/2/2 = G10; `official-review` on cloud Codex `gpt-5.6-sol` xhigh; filename `CODE_REVIEW-cloud-G10.md`.
## Dependencies and Execution Order
1. Require predecessor 02 `complete.log` at its active path or matching same-group archive path.
2. Implement coordinator kernel before wiring the handler inside this packet.
3. Leave the typed public progress/result boundary stable for successor 04; do not implement its SSE projector here.
## Implementation Checklist
- [ ] Implement the request-local single-request state machine and executor event boundary with immutable admission, one active stage, fail-closed transitions, cancellation, and exactly-once terminal tests.
- [ ] Route marked Anthropic Messages requests through that coordinator before legacy preset ingress, keep one HTTP lifetime, return one sanitized final/error, and prove actual Edge ingress POST count 1 with a multi-stage fake.
- [ ] Preserve unmarked preset/Chat/count-tokens behavior and synchronize the Anthropic contract plus current implementation specs.
- [ ] Run targeted, race, 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] Add the request-local coordinator kernel
**Problem**
- `apps/edge/internal/openai/request_coordinator.go` models `agent_tool_wait` and caller `resumed` states for cross-request continuations, not the SDD single-request stage lifecycle.
- `apps/edge/internal/openai/server.go:58`-`77` owns only the legacy logical coordinator, artifact frontier, and light-flow store.
**Solution**
Before (`apps/edge/internal/openai/server.go:71`):
executionPresets []config.ExecutionPreset
requestCoordinator *logicalRequestCoordinator
artifactFrontiers *artifactFrontierStore
lightFlows *hotPathLightStore
After:
executionPresets []config.ExecutionPreset
requestCoordinator *logicalRequestCoordinator
singleRequestCoordinator *singleRequestCoordinator
singleRequestExecutor SingleRequestExecutor
artifactFrontiers *artifactFrontierStore
lightFlows *hotPathLightStore
- Add `single_request_coordinator.go` with approved states `accepted`, `planning`, `working`, `internal_tool`, `reviewing`, `finalizing`, `completed`, `failed`, and `cancelled`.
- Define a narrow typed executor boundary that accepts an immutable copy of request bytes, request/public model/preset identity, compiled stage routes, workspace ref, and limits, then emits a closed event vocabulary. It must not accept caller-selected Node/path/model overrides.
- Enforce one active stage generation, legal ordered transitions, stale/duplicate event rejection, mutually exclusive terminal states, and exactly one final result. Copy maps/slices/raw bytes at admission.
- Expose only closed phase progress plus sanitized final/error to the outer handler. Raw provider reasoning, tool calls/results, route credentials, and internal terminal data never cross the public-event boundary.
- Propagate request context cancellation once to the active executor and converge to `cancelled` without inventing a success terminal. An unavailable executor returns a same-request fail-closed error.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/single_request_coordinator.go` — implement state, immutable admission, executor/events, transition and terminal ownership.
- [ ] `apps/edge/internal/openai/single_request_coordinator_test.go` — add table, stale/duplicate, immutability, cancel/complete race, and terminal-count tests.
- [ ] `apps/edge/internal/openai/server.go` — install coordinator and executor ownership without changing `runService`.
**Test Strategy**
- Write `TestSingleRequestCoordinatorStateMachine` for plan → work → internal tool → work → review → finalizing → completed.
- Write `TestSingleRequestCoordinatorRejectsStaleOrDuplicateEvents` and `TestSingleRequestCoordinatorAdmissionIsImmutable`.
- Write `TestSingleRequestCoordinatorCancelCompleteRaceHasOneTerminal` with repeated race iterations under `go test -race`.
- Use an in-memory deterministic executor only; no Node/proto or external provider fixture.
**Verification**
- `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestCoordinator' -count=1`
- Expected: all transitions and race iterations have one winner and no race report.
### [API-2] Give marked Messages requests one HTTP lifetime
**Problem**
- `apps/edge/internal/openai/anthropic_handler.go:101`-`163` builds legacy preset ingress before dispatch and may return a caller tool terminal.
- `apps/edge/internal/openai/request_identity_ingress.go:168`-`266` explicitly consumes Anthropic continuation structure from a later request.
**Solution**
Before (`apps/edge/internal/openai/anthropic_handler.go:101`):
dispatch, err := s.resolveRouteDispatchForPrincipal(...)
...
poolReq, presetIngress, err := s.anthropicPoolRequest(...)
After:
dispatch, err := s.resolveRouteDispatchForPrincipal(...)
...
if dispatch.SingleRequest != nil {
s.handleAnthropicSingleRequest(w, r, dispatch, envelope, body, *tokenLimit.MaxTokens)
return
}
poolReq, presetIngress, err := s.anthropicPoolRequest(...)
- Branch only marked fixed presets before `anthropicPoolRequest`/`joinPresetAnthropicIngress`. The one handler invocation owns the coordinator until result, error, or caller disconnect.
- Use the existing Anthropic codec for a buffered final response in both JSON and stream modes at this stage; emit only validated final text with the requested public model and never `tool_use`, private reasoning, or internal stage terminals.
- Accept a public-event observer callback but keep progress emission nil/buffered until successor 04. This creates a stable projector boundary without changing the current endpoint framing yet.
- On handler cancellation, stop writing and cancel the coordinator/executor. On executor unavailable/error, return one standard sanitized Anthropic error in the same request.
- Keep count-tokens, unmarked presets, native routes, Chat bridge, and canonical/alias endpoint registration unchanged.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — add the marked branch and single-lifetime response handling.
- [ ] `apps/edge/internal/openai/single_request_handler_test.go` — add exact ingress counter and compatibility tests.
**Test Strategy**
- Write `TestAnthropicSingleRequestIngressCountIsOne` around `srv.routes()` with an HTTP counting wrapper. Send one client POST; have the executor fake emit plan/work/internal-tool/review/final; assert counter 1, executor starts once, public model echo, final text, no `tool_use`, and no follow-up request.
- Write `TestAnthropicSingleRequestIngressSnapshotIsImmutable` by mutating original config/body after admission and comparing the executor snapshot.
- Write `TestAnthropicSingleRequestFailureDoesNotRequestContinuation` and `TestAnthropicSingleRequestCountTokensBypassesCoordinator`.
- Rerun `TestPresetRequestIdentityAcrossAnthropicTurns` unchanged to prove the legacy unmarked path remains compatible.
**Verification**
- `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
- Expected: marked path observes exactly one POST and generic continuation/count-tokens tests remain unchanged.
### [API-3] Synchronize the boundary documentation
**Problem**
- The outer Anthropic contract currently describes the virtual-preset Hot Path as per-turn structural classification and documents caller replay for Chat bridge tools.
- Current specs do not distinguish the new marked fixed path from that generic compatibility behavior.
**Solution**
- Document the fixed marker exception: one `/v1/messages` POST, immutable request binding, internal event consumption, no caller `tool_use` continuation, requested public model retention, same-request failure, and unchanged generic/Chat/count-tokens paths.
- Record the executor port as an Edge-owned request coordinator boundary; concrete workspace wire/tool loop remains outside this task and must not be represented as complete.
**Modified Files and Checklist**
- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define one-POST semantics and compatibility boundary.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize handler behavior and test evidence.
- [ ] `agent-spec/runtime/edge-node-execution.md` — describe the Edge coordinator port without claiming Node workspace implementation.
**Test Strategy**
- No separate doc test. API-2 integration assertions are the contract oracle; review must compare prose to the named tests.
**Verification**
- `rg --sort path -n 'single-request|one POST|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
- Expected: the fixed path and exclusions are explicit, with no private endpoint, credential, or raw path.
## Modified Files Summary
| File | Item |
|------|------|
| `apps/edge/internal/openai/single_request_coordinator.go` | API-1 |
| `apps/edge/internal/openai/single_request_coordinator_test.go` | API-1 |
| `apps/edge/internal/openai/server.go` | API-1 |
| `apps/edge/internal/openai/anthropic_handler.go` | API-2 |
| `apps/edge/internal/openai/single_request_handler_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/edge-node-execution.md` | API-3 |
| `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/CODE_REVIEW-cloud-G10.md` | API-1, API-2, API-3 |
## Final Verification
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/02+01_preset_binding/complete.log' -print | sort | grep -q .`
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestCoordinator' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequest|PresetRequestIdentityAcrossAnthropicTurns|PresetRequestIdentityAnthropicCountTokensBypassesCoordinator)' -count=1`
4. `rg --sort path -n 'single-request|one POST|tool_use|count_tokens' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/edge-node-execution.md`
5. `go test ./apps/edge/internal/openai -count=1`
6. `go test ./apps/edge/... -count=1`
7. `git diff --check`
Expected: dependency evidence exists; state/race tests pass; one client call produces one Edge POST and one final/error without caller continuation; all generic regressions pass. Fresh Go execution is mandatory via `-count=1`. Actual Claude S12 remains explicitly unclaimed.
**After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.**

View file

@ -0,0 +1,146 @@
<!-- task=m-iop-owned-single-request-agent-execution/04+03_stream_terminal plan=1 tag=API milestone-task=stream-terminal -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/04+03_stream_terminal, plan=1, tag=API
## Archive Evidence Snapshot
- Superseded pair: `plan_cloud_G09_0.log`, `code_review_cloud_G10_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: the closed public phase set now includes defect/repair (`repairing`) progress required by the SDD, and Edge vet coverage is restored. The isolated endpoint projector ownership remains valid.
## For the Review Agent
> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G10.md``code_review_cloud_G10_1.log` and `PLAN-cloud-G09.md``plan_cloud_G09_1.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=stream-terminal` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Add a privacy-closed Anthropic stream projector | [ ] |
| API-2 Pump coordinator progress and liveness on the same request | [ ] |
| API-3 Synchronize SSE and compatibility contracts | [ ] |
## Implementation Checklist
- [ ] Implement a serialized single-request Anthropic SSE projector with one envelope, fixed plan/work/review/repair summaries, liveness ping, final text/error, and exactly-once terminal ownership.
- [ ] Integrate it only with the marked coordinator stream, stop and join liveness before terminal/return, acknowledge service completion only after the one wire terminal succeeds, and prove one POST plus no private wire across fragmented multi-stage and repair events.
- [ ] Preserve ordinary Anthropic/Hot Path behavior and synchronize the outer contract and current specs without expanding generic Stream Evidence Gate semantics.
- [ ] Run dependency, exact-wire race, package, vet, full Edge/streamgate regression, and `git diff --check` verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G10_1.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_1.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=stream-terminal` for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-iop-owned-single-request-agent-execution/` or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.
## Deviations from Plan
_Record any deviations from the plan and the rationale here._
## Key Design Decisions
_Record key design decisions here._
## Reviewer Checkpoints
- Packet 03 completion evidence existed before implementation and its exact public event types were reused.
- Closed progress includes defect/repair and rejects unknown/arbitrary strings.
- One lock owns block indices, pings, flushes, and terminal selection.
- Ping worker is stopped and joined before terminal/return; post-terminal bytes never change.
- Service completion is acknowledged only after `message_stop`; write failure/disconnect cannot also complete.
- Exact wire contains no reasoning, tool/provider/route/credential/workspace/raw-command sentinels.
- Ordinary Anthropic/Hot Path and Stream Evidence Gate behavior is unchanged.
## Verification Results
### Dependency
Command: `test -f agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log' -print | sort | grep -q .`
_Actual output/status:_
### Exact-wire and terminal race
Command: `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestAnthropicStream' -count=1`
_Actual output:_
### Integration and compatibility
Command: `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream|HotPathAnthropic)' -count=1`
_Actual output:_
### Documentation
Command: `rg --sort path -n 'single-request|repair|event: ping|message_start|message_stop|private|tool_use' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/stream-evidence-gate.md`
_Actual output:_
### Final regression
Commands:
- `go test -race ./apps/edge/internal/openai -count=1`
- `go vet ./apps/edge/...`
- `go test ./apps/edge/... ./packages/go/streamgate/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]``[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]``[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,252 @@
<!-- task=m-iop-owned-single-request-agent-execution/04+03_stream_terminal plan=1 tag=API milestone-task=stream-terminal -->
# Single-request Anthropic SSE Projection
## For the Implementing Agent
Do not start until packet 03 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-G10.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_cloud_G09_0.log`, `code_review_cloud_G10_0.log`.
- The superseded pair contained no implementation evidence or review verdict; implementation has not started.
- Self-review correction: the closed public phase set now includes defect/repair (`repairing`) progress required by the SDD, and Edge vet coverage is restored. The isolated endpoint projector ownership remains valid.
## Background
The generic Anthropic Hot Path codec can expose normalized reasoning and tool blocks and is scoped to a caller turn. SDD S03 requires a stricter endpoint projector for the single-request coordinator: one envelope, fixed redacted plan/work/review/repair progress, liveness ping, no private internal wire, and exactly one endpoint-native terminal after all internal work.
## 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-ops/rules/project/domain/platform-common/rules.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`
- `agent-test/local/platform-common-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/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_stream.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/hot_path_anthropic_gate_test.go`
- `apps/edge/internal/openai/request_identity_handler_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/stream-evidence-gate.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: `stream-terminal`; targeted Acceptance Scenario: S03.
- Evidence Map row S03 requires fragmented multi-stage SSE with fixed redacted progress/ping, one envelope, collision-free blocks, forbidden-private-value absence, and exactly one terminal. Those facts directly shape API-1/API-2 and the exact-wire/race commands in Final Verification.
### Verification Context
- No separate verification handoff was supplied. Repository-native fallback came from the current Anthropic codec/framing helper, Hot Path exact-wire and terminal race tests, Edge/platform test profiles, outer contract, and approved SDD.
- Precondition: packet 03 completion. Constraints: in-process deterministic writer/manual tick verification only; no external provider/runner. Gap: real Claude liveness remains later Milestone smoke evidence.
- Commands use exact-wire race tests, marked/generic endpoint regressions, deterministic doc search, `go vet`, full Edge/streamgate regression, and `git diff --check`. Confidence is high for framing/privacy/concurrency; real network latency remains outside scope.
### Wire and Concurrency Findings
- One `message_start` uses the coordinator message id and requested public model.
- Fixed Edge-owned summaries may represent plan, work, review, and detected defect/repair (`repairing`). `finalizing`/cleanup remains internal, and arbitrary internal strings cannot become progress.
- `event: ping` is permitted only before terminal and does not open content blocks.
- Success emits ordered final text, one `message_delta` with `end_turn`, then one `message_stop`. Streamed error/cancel emits one sanitized `error` and never a success terminal.
- One serialized writer/terminal lock owns every content index, ping, flush, and terminal decision. Ticker shutdown is joined before handler return.
### Test Coverage Gaps
- Existing generic codec tests intentionally permit reasoning/tool deltas and therefore cannot prove this closed privacy boundary.
- No test covers repair progress, pings across delayed stages, one envelope, forbidden sentinels, monotonic indices, or ping/final/cancel races.
### Symbol References
- No symbol is renamed or removed. `writeDirectAnthropicEvent` is reused for framing only. `anthropicHotPathCodec` remains the generic codec and is not a valid projector for closed single-request events.
### Split Judgment
- Indivisible invariant: one serialized projector owns envelope, content indices, pings, flushes, and terminal. Splitting ping and terminal ownership would permit post-terminal writes.
- Predecessor index 03 resolves to `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/`; its `complete.log` is currently missing, so implementation remains pending and unambiguous.
### Scope Rationale
- Exclude ordinary Anthropic relay, Chat bridge, generic Hot Path codec, Stream Evidence Gate filters, provider decoding, Node wire, and workspace/tool execution because this packet projects already-classified service events only.
- Never emit provider reasoning, tool names/arguments/results, route/provider/credential ids, workspace paths, raw commands, or internal stage terminals.
### Final Routing
- `evaluation_mode=isolated-reassessment`; finalizer `finalize-task-policy.sh` in `pair` mode.
- Build closures are true; scores 2/2/2/1/2 = G09; base/final route `grade-boundary`; lane `cloud`; canonical filename `PLAN-cloud-G09.md`.
- Build signals: `large_indivisible_context=false`; positive loop risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`, `variant_product` (5); `review_rework_count=0`; `evidence_integrity_failure=false`; no capability gap.
- Review closures are true; scores 2/2/2/2/2 = G10; route `official-review`; lane `cloud`; canonical filename `CODE_REVIEW-cloud-G10.md`.
## Dependencies and Execution Order
1. Verify packet 03 completion evidence and use its exact public progress/result types.
2. Build and race-test the isolated projector.
3. Integrate the projector/ticker into marked streaming only.
4. Prove exact wire privacy and ordinary path compatibility before updating docs/specs.
## Implementation Checklist
- [ ] Implement a serialized single-request Anthropic SSE projector with one envelope, fixed plan/work/review/repair summaries, liveness ping, final text/error, and exactly-once terminal ownership.
- [ ] Integrate it only with the marked coordinator stream, stop and join liveness before terminal/return, acknowledge service completion only after the one wire terminal succeeds, and prove one POST plus no private wire across fragmented multi-stage and repair events.
- [ ] Preserve ordinary Anthropic/Hot Path behavior and synchronize the outer contract and current specs without expanding generic Stream Evidence Gate semantics.
- [ ] Run dependency, exact-wire race, package, vet, full Edge/streamgate 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] Add a privacy-closed Anthropic stream projector
**Problem**
- `apps/edge/internal/openai/anthropic_stream.go:339` owns a generic codec that can accept reasoning and tool fragments, which is too permissive for the fixed single-request privacy boundary.
- `apps/edge/internal/openai/hot_path_direct.go:474` provides framing but no closed progress vocabulary, liveness ping, or unified ping/terminal lock.
**Solution**
Before (`apps/edge/internal/openai/anthropic_stream.go:339`):
```go
type anthropicHotPathCodec struct {
mu sync.Mutex
w http.ResponseWriter
model string
stream bool
requestID string
}
```
After, in an isolated file:
```go
type singleRequestAnthropicStream struct {
mu sync.Mutex
started bool
terminal bool
nextBlock int
}
```
Accept only predecessor-defined public enums/results. Reuse `writeDirectAnthropicEvent` for framing only. Map plan/work/review/repair to fixed Edge summaries, keep finalizing/cleanup internal, reject unknown phases, serialize block indices/pings/flush/terminal, and make every post-terminal call a no-op returning the established result.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream.go` — implement the closed projector, fixed phase map including repair, ping, final/error, and serialized terminal state.
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream_test.go` — parse exact wire and cover one envelope/terminal, monotonic blocks, repair summary, ping ordering, forbidden sentinels, and concurrent terminal races.
**Test Strategy**
- Add `TestSingleRequestAnthropicStreamOneEnvelopeOneTerminal`, `...PingAndProgressOrdering`, `...RepairSummary`, `...RedactsPrivateEvents`, and `...ErrorTerminalRace` with a deterministic flushing recorder and sentinel fixtures.
- Run this test prefix under the race detector because every writer/terminal path is concurrent-sensitive.
**Verification**
- `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestAnthropicStream' -count=1`
- Expected: exact event counts/order and privacy assertions pass with no race or duplicate terminal.
### [API-2] Pump coordinator progress and liveness on the same request
**Problem**
- `apps/edge/internal/openai/anthropic_handler.go:66` has no marked-stream pump spanning all internal stages.
- A standalone ticker goroutine could write after final/cancel or after the `ResponseWriter` lifetime unless shutdown and terminal ownership are explicitly joined.
**Solution**
Before (`apps/edge/internal/openai/anthropic_handler.go:66`):
```go
func (s *Server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeAnthropicError(w, http.StatusMethodNotAllowed, "invalid_request_error", "method not allowed")
return
}
}
```
After, inside the packet 03 marked branch:
```go
if dispatch.SingleRequest != nil && request.Stream {
return s.handleAnthropicSingleRequestStream(w, r, dispatch, request)
}
```
Start the closed projector and execute the coordinator with its public progress callback. Use an injectable ticker factory/manual channel. Stop, signal, and join the ping worker before final/error and before handler return. Acknowledge the predecessor execution handle as completed only after `message_stop` is written successfully; terminal write failure or caller disconnect selects failure/cancellation and cannot synthesize success. Marked non-stream behavior stays unchanged.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — select the projector for marked streaming and own coordinator/ticker lifetime.
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream.go` — add the deterministic progress/ticker pump and shutdown join.
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream_test.go` — cover delayed fragmented stages, repair, manual pings, success acknowledgement after stop, terminal write failure, disconnect, terminal order, and one real handler POST.
**Test Strategy**
- Add `TestAnthropicSingleRequestStreamingUsesOnePost`, `...AcknowledgesAfterMessageStop`, `...TerminalWriteFailureDoesNotComplete`, `...StopsPingBeforeTerminal`, and `...DisconnectStopsWriter` using the packet 03 fake coordinator plus manual ticks.
- Rerun `TestHotPathAnthropic*` unchanged to prove generic codec behavior is not weakened.
**Verification**
- `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream|HotPathAnthropic)' -count=1`
- Expected: one handler POST holds the stream across delayed stages; pings cease before terminal/return; generic tests remain unchanged.
### [API-3] Synchronize SSE and compatibility contracts
**Problem**
- The Anthropic contract and current specs do not define a closed marked SSE subset, repair progress, ping ownership, or terminal/privacy exclusivity.
**Solution**
Add a marked single-request subsection to the existing streaming contract and corresponding specs. Document exact event/order rules, requested model retention, fixed progress including repair, endpoint-native ping, forbidden private values, exclusive success/error terminal, and generic Stream Evidence Gate non-expansion. Do not claim real-provider/Claude smoke.
**Modified Files and Checklist**
- [ ] `agent-contract/outer/anthropic-compatible-api.md` — define the marked SSE subset, repair progress, privacy, and terminal/error rules.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize endpoint integration and tests.
- [ ] `agent-spec/runtime/stream-evidence-gate.md` — record the separate service-to-endpoint projection boundary and generic-filter non-expansion.
**Test Strategy**
- No standalone documentation test. API-1/API-2 exact-wire parser and forbidden-sentinel assertions are the executable oracle.
**Verification**
- `rg --sort path -n 'single-request|repair|event: ping|message_start|message_stop|private|tool_use' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/stream-evidence-gate.md`
- Expected: allowed/forbidden wire behavior is explicit and matches the exact-wire tests.
## Modified Files Summary
| File | Item |
|------|------|
| `apps/edge/internal/openai/single_request_anthropic_stream.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_anthropic_stream_test.go` | API-1, API-2 |
| `apps/edge/internal/openai/anthropic_handler.go` | API-2 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-3 |
| `agent-spec/input/openai-compatible-surface.md` | API-3 |
| `agent-spec/runtime/stream-evidence-gate.md` | API-3 |
| `agent-task/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/CODE_REVIEW-cloud-G10.md` | API-1, API-2, API-3 |
## Final Verification
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log' -print | sort | grep -q .`
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestAnthropicStream' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream|HotPathAnthropic)' -count=1`
4. `rg --sort path -n 'single-request|repair|event: ping|message_start|message_stop|private|tool_use' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/stream-evidence-gate.md`
5. `go test -race ./apps/edge/internal/openai -count=1`
6. `go vet ./apps/edge/...`
7. `go test ./apps/edge/... ./packages/go/streamgate/... -count=1`
8. `git diff --check`
Expected: predecessor evidence exists; exact-wire/race/privacy tests pass; pings stop before one terminal; ordinary Anthropic/Hot Path regressions pass. Actual Claude/provider smoke remains outside this packet.
**After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.**

View file

@ -0,0 +1,142 @@
<!-- task=m-iop-owned-single-request-agent-execution/04+03_stream_terminal plan=0 tag=API milestone-task=stream-terminal -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> Execute the plan's selected root cause, scope, files, and dependency decisions as written. Do not choose another owner, narrow/expand the write boundary, or replace a fix with another verification attempt.
> If implementation is blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## Overview
date=2026-08-06
task=m-iop-owned-single-request-agent-execution/04+03_stream_terminal, plan=0, tag=API
## For the Review Agent
> **[REVIEW AGENT ONLY]** Implementers must not execute this section.
Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:
1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G10.md` → `code_review_cloud_G10_0.log` and `PLAN-cloud-G09.md` → `plan_cloud_G09_0.log`.
3. If PASS, write `complete.log` and move the active task directory to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS, preserve `milestone-task=stream-terminal` in `complete.log` and report it for runtime aggregation. Roadmap state evaluation belongs to `sync-milestone-workstate`.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.
---
## Implementation Item Completion
| Item | Status |
|------|--------|
| API-1 Add a privacy-closed Anthropic stream projector | [ ] |
| API-2 Pump coordinator progress and liveness on the same request | [ ] |
| API-3 Synchronize SSE and compatibility contracts | [ ] |
## Implementation Checklist
- [ ] Implement a serialized single-request Anthropic SSE projector with one envelope, fixed redacted progress, injectable liveness ping, final text/error, and exactly-once terminal ownership.
- [ ] Integrate the projector with the marked coordinator stream lifetime, stop ping before terminal/cancel, and prove one POST plus no private wire across fragmented multi-stage events.
- [ ] Preserve ordinary Anthropic/Hot Path behavior and synchronize the outer contract and matching current specs.
- [ ] Run targeted exact-wire, race, package regression, and `git diff --check` verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.
## Review-Only Checklist
> **[REVIEW AGENT ONLY]** Implementers must not modify or check this section.
- [ ] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` routing signals to `Code Review Result`.
- [ ] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [ ] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G10_0.log`.
- [ ] Archive active `PLAN-*-G??.md` to `plan_cloud_G09_0.log`.
- [ ] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/` to `agent-task/archive/YYYY/MM/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/` and update this checklist at the final archive path.
- [ ] If PASS, preserve and report `milestone-task=stream-terminal` for runtime aggregation without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent or verify it was kept due to remaining siblings/files.
- [ ] If WARN/FAIL, write the next filesystem state matching the verdict and do not write `complete.log`.
## Deviations from Plan
_Record deviations and rationale._
## Key Design Decisions
_Record decisions._
## Reviewer Checkpoints
- Predecessor 03 was complete before work.
- One mutex serializes envelope, progress blocks, ping, final/error, and terminal state.
- Only closed Edge-owned phase summaries and final user text can reach the wire.
- Ping stops before terminal; post-terminal calls write zero bytes.
- Success and error terminal events are mutually exclusive under race.
- Ordinary Anthropic/Hot Path/Stream Evidence Gate behavior remains unchanged and S12 is not claimed.
## Verification Results
Paste actual stdout/stderr; command changes require a documented deviation.
### Dependency
Command: `test -f agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log' -print | sort | grep -q .`
_Actual output/status:_
### Projector exact-wire and race
Command: `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestAnthropicStream' -count=1`
_Actual output:_
### Handler and generic regression
Command: `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream)' -count=1`
_Actual output:_
### Final handler and generic regression
Command: `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream|HotPathAnthropic)' -count=1`
_Actual output:_
### Documentation
Command: `rg --sort path -n 'single-request|event: ping|message_start|message_stop|private|tool_use' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/stream-evidence-gate.md`
_Actual output:_
### Final regression
Commands:
- `go test -race ./apps/edge/internal/openai -count=1`
- `go test ./apps/edge/... ./packages/go/streamgate/... -count=1`
- `git diff --check`
_Actual output:_
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Fill every implementation-owned section and leave review-only sections unchanged.**
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results | Fixed headings/commands; implementing agent output | Fill actual stdout/stderr; command changes require a deviation |
| Code Review Result | Review agent appends | Not included in stub |

View file

@ -0,0 +1,240 @@
<!-- task=m-iop-owned-single-request-agent-execution/04+03_stream_terminal plan=0 tag=API milestone-task=stream-terminal -->
# Single-request Anthropic SSE Projection
## For the Implementing Agent
Do not start until predecessor 03 has `complete.log`. Implement only this plan, run every verification command, fill every implementation-owned section of `CODE_REVIEW-cloud-G10.md` with actual notes and stdout/stderr, leave active files in place, and report ready for review. Finalization belongs only to the code-review skill. If blocked, record the exact blocker, attempts/output, and resume condition; do not ask the user, call user-input tools, create stop files, classify the next state, archive logs, or write `complete.log`.
## Background
The existing Anthropic Hot Path codec can progressively expose normalized reasoning and tool blocks and is scoped to one caller turn. SDD S03 requires a stricter projector for the single-request coordinator: one outer envelope, closed redacted progress, liveness ping, no private stage/provider/tool wire, and one endpoint-native terminal after all internal stages.
## 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`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/anthropic_stream.go`
- `apps/edge/internal/openai/hot_path_direct.go`
- `apps/edge/internal/openai/hot_path_anthropic_gate_test.go`
- `apps/edge/internal/openai/hot_path_terminal_control.go`
- `apps/edge/internal/openai/hot_path_terminal_control_test.go`
- `apps/edge/internal/openai/request_identity_handler_test.go`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-spec/runtime/stream-evidence-gate.md`
- `agent-test/local/edge-smoke.md`
- `agent-test/local/platform-common-smoke.md`
### SDD Criteria
- SDD approved; Milestone task `stream-terminal`; Acceptance Scenario S03.
- Evidence Map requires fragmented multi-stage SSE proof with redacted progress/ping, one envelope, collision-free blocks, and one terminal.
- The checklist and verification directly count wire events, check block indices/order, scan forbidden private fixtures, and race terminal/ping/cancel paths.
### Verification Context
- No separate handoff was supplied. Repository-native evidence is the current Anthropic codec, exact-wire Hot Path gate tests, terminal race tests, and outer contract.
- Baseline relevant tests passed at starting HEAD.
- Precondition: `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log`.
- No external runner is required. In-process flushing recorder and manual tick channel provide deterministic progress/ping ordering; actual Claude liveness remains S12.
- Confidence: high for framing/privacy/exactly-once behavior. Provider-specific latency and real network proxy behavior are explicitly outside this packet.
### Test Coverage Gaps
- Existing codec tests cover ordinary progressive reasoning/text/tool blocks and error-after-commit, but that behavior is too permissive for fixed single-request output.
- No test covers endpoint-native `ping`, fixed redacted phase summaries, a stream held across several internal stages, or forbidden-value absence.
- Add a separate projector and exact-wire/race tests rather than weakening generic Hot Path behavior.
### Symbol References
- No symbol is renamed or removed.
- Reuse `writeDirectAnthropicEvent` from `hot_path_direct.go` for framing only.
- Do not route coordinator events through `anthropicHotPathCodec.writeProgressiveDelta` because that method accepts reasoning and tool-call fragments.
### Split Judgment
- The indivisible invariant is one serialized projector lock owning message start, block sequence, ping, and terminal. Splitting ping from terminal ownership would create post-terminal and concurrent-write races.
- Predecessor index 03 resolves to active sibling `agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/`; at planning time its `complete.log` is missing, so implementation is pending and unambiguous.
- This is the final packet in the Epic preparation chain; Node tool loop, error budget matrix, cleanup observation, and real Claude smoke remain separate Milestone tasks.
### Scope Rationale
- Do not change ordinary Anthropic native relay, Chat bridge, generic preset codec semantics, provider decoding, Stream Evidence Gate filters, Node wire, or tool execution.
- Do not emit provider reasoning, tool names/arguments/results, route/provider ids, credentials, raw command output, or internal stage terminals.
- Do not claim multiple review cycles or durable stream resume.
### Final Routing
- evaluation_mode `first-pass`; finalizer `finalize-task-policy.sh` pair.
- Build closures all true. Scores 2/2/2/1/2 = G09; route `grade-boundary`; lane `cloud`; filename `PLAN-cloud-G09.md`.
- Build signals: `large_indivisible_context=false`; risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`, `variant_product` (5); risk matched but grade basis retained; rework 0; evidence integrity false; no capability gap.
- Review closures all true. Scores 2/2/2/2/2 = G10; `official-review` on cloud Codex `gpt-5.6-sol` xhigh; filename `CODE_REVIEW-cloud-G10.md`.
## Dependencies and Execution Order
1. Require predecessor 03 `complete.log` at its active path or matching same-group archive path.
2. Implement the isolated projector and exact-wire tests first.
3. Integrate the predecessor coordinator callback and tick lifecycle into the marked streaming handler.
4. Keep non-stream and every unmarked route on predecessor/existing codecs.
## Implementation Checklist
- [ ] Implement a serialized single-request Anthropic SSE projector with one envelope, fixed redacted progress, injectable liveness ping, final text/error, and exactly-once terminal ownership.
- [ ] Integrate the projector with the marked coordinator stream lifetime, stop ping before terminal/cancel, and prove one POST plus no private wire across fragmented multi-stage events.
- [ ] Preserve ordinary Anthropic/Hot Path behavior and synchronize the outer contract and matching current specs.
- [ ] Run targeted exact-wire, race, 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] Add a privacy-closed Anthropic stream projector
**Problem**
- `apps/edge/internal/openai/anthropic_stream.go:339`-`365` stores generic progressive state including tool release.
- `apps/edge/internal/openai/anthropic_stream.go:463`-`501` explicitly accepts reasoning, text, and tool-call fragments.
- `apps/edge/internal/openai/anthropic_stream.go:870`-`943` owns one start/terminal but has no ping or closed single-request phase vocabulary.
**Solution**
Before (`apps/edge/internal/openai/anthropic_stream.go:482`):
switch delta.Kind {
case streamgate.EventKindReasoningDelta:
...
case streamgate.EventKindTextDelta:
...
case streamgate.EventKindToolCallFragment:
...
}
After, in a new isolated projector:
type singleRequestAnthropicStream struct {
mu sync.Mutex
writer http.ResponseWriter
flusher http.Flusher
model string
messageID string
started bool
terminal bool
nextBlock int
}
func (s *singleRequestAnthropicStream) Progress(phase singleRequestPublicPhase) error
func (s *singleRequestAnthropicStream) Ping() error
func (s *singleRequestAnthropicStream) Final(text string, usage json.RawMessage) error
func (s *singleRequestAnthropicStream) Error(kind, message string) error
- Start one `message_start` with the coordinator message id and requested public model before internal work.
- Map only the closed phases plan/work/review/finalizing to fixed redacted text owned by Edge. Never accept arbitrary provider text as progress.
- Emit Anthropic `event: ping` with `{"type":"ping"}` while nonterminal and flush it without opening/closing content blocks.
- Emit progress/final text as ordered content blocks with monotonically increasing indices. Final success closes any block, emits one `message_delta` with `end_turn`, then one `message_stop`.
- Before stream commit, a validation failure may use normal JSON error. After start, an error/cancel race emits at most one terminal `error` event and never also emits `message_stop`.
- Guard every write and terminal check with one mutex. Post-terminal progress/ping/final calls return the established terminal error and write nothing.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream.go` — implement closed framing, fixed phase mapping, ping, final/error, and terminal lock.
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream_test.go` — add deterministic recorder, parser, wire-order, privacy, and terminal tests.
**Test Strategy**
- Write `TestSingleRequestAnthropicStreamOneEnvelopeOneTerminal` and assert exact counts for `message_start`, `message_delta`, `message_stop` and strictly increasing block indices.
- Write `TestSingleRequestAnthropicStreamPingAndProgressOrdering` using explicit `Ping()` calls/manual ticks.
- Write `TestSingleRequestAnthropicStreamRedactsPrivateEvents` with sentinel reasoning, provider id, credential ref, tool name/args/result, raw command output, and internal terminal; assert none occur on wire.
- Write `TestSingleRequestAnthropicStreamErrorTerminalRace` under `-race` and assert one of error or success terminal, never both.
**Verification**
- `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestAnthropicStream' -count=1`
- Expected: exact-wire and race tests pass with no data race or duplicate terminal.
### [API-2] Pump coordinator progress and liveness on the same request
**Problem**
- The predecessor marked handler buffers the coordinator result and uses the generic final codec.
- Long provider/tool stages need liveness without allowing a ping goroutine to race final/cancel writes.
**Solution**
- In `handleAnthropicSingleRequest`, keep non-stream behavior unchanged. For `stream=true`, create/start the new projector and run the coordinator with its closed public phase callback.
- Add a helper whose ticker channel/factory is injected for tests and defaults to a conservative endpoint liveness interval in production. All tick writes go through the projector lock.
- Stop and drain/close the ticker before committing final/error. Wait for the ping worker to exit before returning from the handler so no write occurs after terminal or after `ResponseWriter` lifetime.
- On caller disconnect, cancel the coordinator, stop liveness, and do not invent a wire success. On coordinator error after start, emit one sanitized endpoint-native error.
**Modified Files and Checklist**
- [ ] `apps/edge/internal/openai/anthropic_handler.go` — select the new projector only for marked streaming requests and own ticker shutdown.
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream.go` — add the deterministic coordinator/ticker pump.
- [ ] `apps/edge/internal/openai/single_request_anthropic_stream_test.go` — add fragmented multi-stage handler integration and disconnect/terminal ordering.
**Test Strategy**
- Write `TestAnthropicSingleRequestStreamingUsesOnePost` with an actual HTTP counting wrapper, delayed stage events, manual ticks, and final success.
- Assert one POST, one message envelope, at least one ping during the delay, fixed progress only, no internal sentinels, and one final terminal.
- Write `TestAnthropicSingleRequestStreamStopsPingBeforeTerminal` and `TestAnthropicSingleRequestStreamDisconnectStopsWriter`.
**Verification**
- `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream)' -count=1`
- Expected: same connection remains live, post-terminal bytes do not change, and actual POST count is one.
### [API-3] Synchronize SSE and compatibility contracts
**Problem**
- `agent-contract/outer/anthropic-compatible-api.md` documents ordinary Anthropic SSE and generic Hot Path behavior but not the fixed single-request event subset.
- The input and Stream Evidence Gate specs do not identify this projector's privacy/terminal boundary.
**Solution**
- Document the exact allowed event/order set, public model identity, fixed progress semantics, endpoint-native ping, success/error terminal exclusivity, and forbidden private values.
- State that this projector consumes already classified coordinator events and does not make raw internal provider/tool events public or alter ordinary Hot Path/Stream Evidence Gate behavior.
- Link source/test evidence in the current specs without claiming real-provider or Claude smoke.
**Modified Files and Checklist**
- [ ] `agent-contract/outer/anthropic-compatible-api.md` — add fixed single-request SSE contract and terminal/error rules.
- [ ] `agent-spec/input/openai-compatible-surface.md` — synchronize endpoint behavior and tests.
- [ ] `agent-spec/runtime/stream-evidence-gate.md` — record the separate coordinator projection boundary and non-expansion of generic filters.
**Test Strategy**
- No standalone prose test. The exact-wire parser and forbidden-sentinel assertions are the normative executable evidence.
**Verification**
- `rg --sort path -n 'single-request|event: ping|message_start|message_stop|private|tool_use' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/stream-evidence-gate.md`
- Expected: allowed and forbidden behavior is explicit and consistent with tests.
## Modified Files Summary
| File | Item |
|------|------|
| `apps/edge/internal/openai/single_request_anthropic_stream.go` | API-1, API-2 |
| `apps/edge/internal/openai/single_request_anthropic_stream_test.go` | API-1, API-2 |
| `apps/edge/internal/openai/anthropic_handler.go` | API-2 |
| `agent-contract/outer/anthropic-compatible-api.md` | API-3 |
| `agent-spec/input/openai-compatible-surface.md` | API-3 |
| `agent-spec/runtime/stream-evidence-gate.md` | API-3 |
| `agent-task/m-iop-owned-single-request-agent-execution/04+03_stream_terminal/CODE_REVIEW-cloud-G10.md` | API-1, API-2, API-3 |
## Final Verification
1. `test -f agent-task/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log || find agent-task/archive -type f -path '*/m-iop-owned-single-request-agent-execution/03+02_single_ingress/complete.log' -print | sort | grep -q .`
2. `go test -race ./apps/edge/internal/openai -run 'TestSingleRequestAnthropicStream' -count=1`
3. `go test ./apps/edge/internal/openai -run 'Test(AnthropicSingleRequestStreaming|AnthropicSingleRequestStream|HotPathAnthropic)' -count=1`
4. `rg --sort path -n 'single-request|event: ping|message_start|message_stop|private|tool_use' agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md agent-spec/runtime/stream-evidence-gate.md`
5. `go test -race ./apps/edge/internal/openai -count=1`
6. `go test ./apps/edge/... ./packages/go/streamgate/... -count=1`
7. `git diff --check`
Expected: dependency exists; one-envelope/one-terminal ordering and privacy tests pass; no race or post-terminal ping occurs; ordinary Anthropic/Hot Path regressions pass. All Go results are fresh via `-count=1`. Actual Claude/provider smoke remains outside this packet.
**After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.**