<!-- task=m-principal-provider-credential-slot-routing/09+08_migration_attribution plan=1 tag=API milestone-task=compat-migration,slot-attribution -->

# 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.
> 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-01
task=m-principal-provider-credential-slot-routing/09+08_migration_attribution, plan=1, tag=API

## Roadmap Targets

- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/principal-provider-credential-slot-routing.md`
- Milestone link: [Milestone 문서](agent-roadmap/phase/operational-observability-provider-management/milestones/principal-provider-credential-slot-routing.md)
- Task ids:
  - `compat-migration`: legacy-only와 CP-only credential source 전환/rollback
  - `slot-attribution`: safe slot ref/revision dispatch와 usage 귀속
- Completion mode: check-on-pass

## Archive Evidence Snapshot

- `agent-task/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/complete.log`: 현재 missing; 구현 전 exact path가 필요하다.
- 03/04/07 evidence는 08을 통해 transitively 소비하며 별도 archive 탐색을 하지 않는다.
- prior unimplemented pair: `plan_cloud_G09_0.log`, `code_review_cloud_G10_0.log`.

## For the Review Agent

> **[REVIEW AGENT ONLY]** Implementing agents must not execute this section.

1. Compare all items and evidence to current source.
2. Append verdict and routing signals.
3. Archive review to `code_review_cloud_G10_1.log` and plan to `plan_cloud_G09_1.log`.
4. On PASS write `complete.log`, archive the task directory and report milestone event metadata; otherwise write the required next state.
5. Complete the review-only checklist at the final log location.

---

## Implementation Item Completion

| Item | Status |
|------|---------|
| API-1 Exhaustive migration and rollback state machine | [x] |
| API-2 Enabled-mode caller rejection and surface compatibility | [x] |
| API-3 Immutable slot usage attribution | [x] |

## Implementation Checklist

- [x] Complete one explicit disabled-legacy/enabled-Control-Plane-only state machine and restart/apply classification without a second activation mechanism.
- [x] Prove dual-source and caller provider-auth rejection in enabled mode while preserving disabled behavior and Chat/Responses/Anthropic public schemas.
- [x] Carry immutable trusted credential slot ref/revision through dispatch, retry and provider-attempt usage separately from inbound token ref.
- [x] Add fresh migration/rollback/all-surface/two-slot/race and label/secret audits.
- [x] 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.

- [x] Append one verdict and verified `review_rework_count`, `evidence_integrity_failure`.
- [x] Verify verdict, dimensions and finding classifications match.
- [x] Archive active review to `code_review_cloud_G10_1.log`.
- [x] Archive active plan to `plan_cloud_G09_1.log`.
- [x] Verify `.gitignore` Agent-Ops managed block.
- [ ] If PASS, write `complete.log` and leave no active `.md` files.
- [ ] If PASS, archive this task directory and update this checklist there.
- [ ] If PASS, report milestone metadata without roadmap mutation.
- [ ] If PASS for split work, preserve active parent because sibling 10 remains.
- [x] If WARN/FAIL, write the matching next state and no `complete.log`.

## Deviations from Plan

- The prerequisite active `08+03,04,07_secure_delivery/complete.log` path had already been archived. The exact completion evidence at `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/complete.log` records `verdict=PASS`, so implementation proceeded without inspecting sibling archive contents.
- No second activation switch was added. The 09-specific source selector is derived from the existing `credential_plane.enabled` field. Existing 08 load/runtime/dispatch-context wiring was retained where it already met the plan, while `configrefresh`, input-manager, OpenAI server/routes, handler error mapping, and safe dispatch logs were updated where the explicit mode and attribution needed to be completed.
- Managed source-conflict validation was extended beyond the three OpenAI legacy fields to provider/adapter credential headers, credential-bearing environment variables and arguments, and URL user-info. Validation reports only the safe config path and never the configured value. Non-secret token settings such as `TOKENIZERS_PARALLELISM` and `MAX_TOKENS` have a regression fixture.
- The host mounts `/tmp` with `noexec`. An initial full bootstrap-package probe therefore failed when its existing real-node fixture tried to execute a nested binary from `t.TempDir` (`permission denied`). Final fresh verification set `TMPDIR=/config/workspace/iop-s0/.agent-g09-test-tmp`, reran the unchanged required Go commands successfully, and removed the empty temporary directory afterward.

## Key Design Decisions

- `EdgeCredentialPlaneConf.Mode()` is the single effective two-state selector: omitted/false is legacy, true is managed. Disabled input construction does not create or install a projection cache. Managed construction installs one immediately and authentication fails closed while it is unavailable, unmanaged, stale, expired, revoked, or unmatched; it never consults static bearer/principal configuration.
- Managed validation requires the complete 08 TLS/Control Plane/OpenAI HTTPS composition and rejects every competing raw credential source before listener startup. Refresh deep-diffs credential-plane state as restart-required. Transition, secure key rotation, legacy source change, and rollback fixtures confirm that restart-required candidates do not partially replace the active runtime config.
- Managed caller provider credentials are rejected in `withAuth` after IOP principal authentication but before route resolution, lease acquisition, or provider dispatch. OpenAI-compatible surfaces return the existing top-level OpenAI error envelope; Anthropic returns its existing `type`/`error` envelope. The dedicated legacy provider header remains available only in legacy mode, and inbound IOP `Authorization`/Anthropic `x-api-key` is never reused as an outbound provider credential.
- Managed candidate admission is tunnel-only and keeps the authenticated projection route predicate frozen across recovery. A provider lease is accepted only when every returned scope binding fact exactly matches the selected principal/slot/route/profile/target/node/key/revision/generation tuple.
- `RunDispatch.CredentialSlotRef` and `CredentialRevision` are populated from that verified returned lease scope, not caller metadata or the pre-lease request alone. Retry bindings therefore preserve the immutable pair unless a separate admission selects a different binding.
- Provider-attempt token and reasoning metrics add only `credential_slot_ref` and decimal `credential_revision`. Inbound `token_ref` remains separate. Request-terminal labels and exactly-once semantics are unchanged; slot alias, lease ID, recipient key, raw secret, and target URL remain excluded.

## Reviewer Checkpoints

- Confirm there is exactly one activation setting and 08/09 did not create competing state machines.
- Confirm disabled/omitted is behavior-compatible, enabled is CP-only, and rollback requires a validated restart rather than runtime fallback.
- Confirm caller provider auth and IOP-token reuse are rejected before route/lease/upstream in enabled mode without echoing values.
- Confirm Chat/Responses/Anthropic schemas and model discovery remain compatible.
- Confirm slot ref/revision come from trusted immutable lease scope and stay separate from inbound `token_ref`.
- Confirm metric labels exclude alias, lease id, secret and target URL and do not alter request-terminal once semantics.

## Verification Results

### Environment and migration matrix

Command:

```bash
command -v go && go version && go env GOROOT
git status --short --branch
go test -count=1 ./packages/go/config ./apps/edge/internal/bootstrap ./apps/edge/internal/input
```

Output and exit status:

The commands were executed with `TMPDIR=/config/workspace/iop-s0/.agent-g09-test-tmp` because the host `/tmp` mount is `noexec`.

```text
/config/.local/bin/go
go version go1.26.2 linux/arm64
/config/opt/go
## agent/dispatcher-work-log-artifact-loop...origin/agent/dispatcher-work-log-artifact-loop
git status: 74 modified, 22 deleted, and 25 untracked entries (121 total), including pre-existing 08 and dispatcher work; no unrelated changes were reverted.
ok  	iop/packages/go/config                 1.391s
ok  	iop/apps/edge/internal/bootstrap      6.023s
ok  	iop/apps/edge/internal/input          0.057s
```

Exit status: `0`.

### Surface, attribution and race tests

Command:

```bash
go test -count=1 ./apps/edge/internal/openai ./apps/edge/internal/service
go test -count=1 -race ./apps/edge/internal/openai ./apps/edge/internal/service
```

Output and exit status:

```text
ok  	iop/apps/edge/internal/openai  7.471s
ok  	iop/apps/edge/internal/service 5.917s
ok  	iop/apps/edge/internal/openai  8.856s
ok  	iop/apps/edge/internal/service 6.954s
```

Both commands used the executable `TMPDIR` described above. Exit status: `0` for each command.

### Vet, diff and label audits

Command:

```bash
go vet ./apps/edge/... ./packages/go/...
git diff --check
rg --sort path -n 'credential_slot_ref|credential_revision|token_ref' apps/edge/internal/openai apps/edge/internal/service docs/openai-usage-grafana.md
if rg --sort path -n '"(slot_alias|lease_id|provider_secret|target_url)"' apps/edge/internal/openai/usage_metrics.go; then exit 1; fi
```

Output and exit status:

`go vet` and `git diff --check` produced no output. The identity audit produced these intentional matches:

```text
apps/edge/internal/openai/chat_handler.go:215: zap.String("credential_slot_ref", disp.CredentialSlotRef),
apps/edge/internal/openai/chat_handler.go:216: zap.Uint64("credential_revision", disp.CredentialRevision),
apps/edge/internal/openai/principal.go:37: principalMetaToken = "iop_token_ref"
apps/edge/internal/openai/principal.go:41: credentialSlotMeta = "iop_credential_slot_ref"
apps/edge/internal/openai/principal.go:42: credentialRevisionMeta = "iop_credential_revision"
apps/edge/internal/openai/provider_tunnel.go:279: zap.String("credential_slot_ref", handle.Dispatch().CredentialSlotRef),
apps/edge/internal/openai/provider_tunnel.go:280: zap.Uint64("credential_revision", handle.Dispatch().CredentialRevision),
apps/edge/internal/openai/responses_handler.go:490: zap.String("credential_slot_ref", result.DispatchInfo.CredentialSlotRef),
apps/edge/internal/openai/responses_handler.go:491: zap.Uint64("credential_revision", result.DispatchInfo.CredentialRevision),
apps/edge/internal/openai/usage_metrics.go:58: "edge_id", "principal_ref", "principal_alias", "token_ref",
apps/edge/internal/openai/usage_metrics.go:62: "edge_id", "principal_ref", "principal_alias", "token_ref",
apps/edge/internal/openai/usage_metrics.go:63: "credential_slot_ref", "credential_revision",
apps/edge/internal/openai/usage_metrics.go:68: "edge_id", "principal_ref", "principal_alias", "token_ref",
apps/edge/internal/openai/usage_metrics.go:69: "credential_slot_ref", "credential_revision",
apps/edge/internal/openai/usage_metrics.go:74: "edge_id", "principal_ref", "principal_alias", "token_ref",
apps/edge/internal/openai/usage_metrics.go:75: "credential_slot_ref", "credential_revision",
```

Additional intentional matches were limited to identity/metadata assertions, caller-spoof overwrite fixtures, metric allowlist tests, and the Grafana label table/PromQL examples. The guarded forbidden-label scan of `usage_metrics.go` produced no output. Exit status: `0` for the combined audit command.

---

> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, fill it before saving. Leave review-only sections unchanged.

## Section Ownership

| Section | Owner | Note |
|---------|-------|------|
| Header, Overview, Review Agent Instructions | Fixed | Implementer must not modify/execute |
| Roadmap Targets | Fixed | Implementer must not modify |
| Archive Evidence Snapshot | Fixed | Read only cited evidence when needed |
| Implementation Item Completion | Fixed names | Implementer checks status only |
| Implementation Checklist | Fixed text/order | Implementer checks status only |
| Review-Only Checklist | Review agent only | Implementer must not modify |
| Deviations, Key Design Decisions | Implementing agent | Replace placeholders |
| Reviewer Checkpoints | Fixed | Pre-filled from plan |
| Verification Results | Fixed commands | Implementer fills actual output only |
| Code Review Result | Review agent appends | Not in stub |

## Code Review Result

- **Overall Verdict:** FAIL
- **Finding Counts:** Required=1, Suggested=0, Nit=0

### Dimension Assessment

| Dimension | Result | Evidence |
|-----------|--------|----------|
| Correctness | Fail | Managed mode accepts static credentials declared through the resolved protocol profile. |
| Completeness | Fail | The planned exhaustive competing-source rejection omits profile-derived header and URL sources. |
| Test coverage | Fail | The competing-source matrix has no custom profile auth-header or profile URL user-info cases. |
| API contract | Fail | This violates the approved S14 single-source/CP-only startup contract for managed mode. |
| Code quality | Pass | The reviewed implementation has no relevant debug residue, dead code, or unrelated structural change. |
| Plan deviation | Fail | API-1 required exhaustive static-source rejection; the documented extension is not exhaustive. |
| Verification trust | Pass | Fresh focused, surface, race, vet, diff, and deterministic label scans reproduced the submitted passing results. |
| Spec conformance | Fail | Managed mode does not yet reject every competing raw credential source before listener startup. |

### Findings

1. **Required — `packages/go/config/validate.go:88`: managed mode accepts profile-declared static provider credentials.** `managedRawProviderCredentialSource` recognizes only heuristic header names and the legacy provider `endpoint`/`base_url` fields. It does not compare configured provider headers with `provider.RuntimeProfile.Auth.Header`, and it does not inspect the resolved profile base URL or absolute operation URLs for URL user-info. A focused reviewer reproducer with auth header `X-Custom-Key` and `https://user:secret@provider.invalid/v1` returned `nil` from `validateEdgeCredentialPlane`, so an enabled managed configuration can still retain a competing raw provider credential source. Fix the validator to correlate headers with the effective resolved auth-header name and reject user-info in the resolved base/absolute-operation URLs, reporting only safe config paths. Extend `TestCredentialPlaneEnabledRejectsEveryCompetingSource` with custom-header and profile-URL cases plus accepted non-secret-header coverage.

### Reviewer Verification

- With executable `TMPDIR=/config/workspace/iop-s0/.agent-g10-review-tmp`, fresh `go test -count=1 ./packages/go/config ./apps/edge/internal/bootstrap ./apps/edge/internal/input`, OpenAI/service focused and race suites, `go vet ./apps/edge/... ./packages/go/...`, `git diff --check`, and deterministic attribution-label scans all exited `0`.
- A temporary reviewer-only test that exercised the custom auth header and profile base-URL user-info failed because managed validation returned `nil`; the temporary file and temporary directory were removed, and a final `git diff --check` exited `0`.

- **Routing Signals:** `review_rework_count=1`, `evidence_integrity_failure=false`
- **Next Step:** Create a scoped follow-up PLAN/review pair for the Required managed-source validation fix; do not write `complete.log` or update the Milestone.
