<!-- task=m-principal-provider-credential-slot-routing/10+08,09_verification_contracts plan=4 tag=REVIEW_REVIEW_TEST milestone-task=slot-smoke,contract-ops -->

# Code Review Reference - REVIEW_REVIEW_TEST

> **[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-02
task=m-principal-provider-credential-slot-routing/10+08,09_verification_contracts, plan=4, tag=REVIEW_REVIEW_TEST

## Archive Evidence Snapshot

- Prior plan: `agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/plan_cloud_G08_3.log`.
- Prior review: `agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/code_review_cloud_G08_3.log`.
- Resolved user review: `agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/user_review_0.log`.
- Required follow-up: correct the OpenAI-only Prometheus metric wording and execute the exact one authorized no-retry OpenAI request with sanitized evidence.

## 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-{review_lane}-{review_grade}.md` → `code_review_{review_lane}_{review_grade}_{review_log_number}.log` and `PLAN-{build_lane}-{build_grade}.md` → `plan_{build_lane}_{build_grade}_{plan_log_number}.log`.
3. If PASS, write `complete.log` and move the active task directory to `agent-task/archive/YYYY/MM/{task_name}/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS and task group is `m-<milestone-slug>`, preserve the first-line `milestone-task` metadata in `complete.log` and report it for the runtime aggregation event. 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 |
|------|--------|
| Correct managed API-key qualification and metric wording | [x] |
| Complete deterministic S16/S17 qualification and one authorized provider request | [x] |

## Implementation Checklist

- [x] Correct the Grafana guide so managed Chat/Messages qualification, OpenAI-only Prometheus series, and the deterministic initial/rotated Chat packet are described accurately.
- [x] Rerun deterministic credential-slot qualification and S17 pointer/stale-claim/no-secret checks with fresh output.
- [x] Execute the exact authorized OpenAI one-shot once with no retry and record only sanitized provider/model/slot/revision/date/result evidence plus exit status.
- [x] 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.

- [x] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [x] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [x] Archive active `CODE_REVIEW-*-G??.md` to `code_review_{review_lane}_{review_grade}_{review_log_number}.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_{build_lane}_{build_grade}_{plan_log_number}.log`.
- [x] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [x] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [x] If PASS, move active task directory `agent-task/{task_name}/` to `agent-task/archive/YYYY/MM/{task_name}/` and update this checklist at the final archive path.
- [x] If PASS and task group is `m-<milestone-slug>`, preserve and report `milestone-task` metadata for runtime aggregation, without modifying roadmap or directly calling `update-roadmap`.
- [x] If PASS for split work, remove empty active parent `agent-task/{task_group}/` 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

- Executable `TMPDIR` was required for the live one-shot. This runner mounts the default `/tmp` as noexec, so the script's `setup_workspace` executable-probe fails there. The plan's REVIEW_REVIEW_TEST-2 command line did not show a `TMPDIR` override, but the same executable-root requirement documented for the deterministic smoke (Verification Context) applies to the live mode, which also builds and runs binaries. The first live invocation (default `TMPDIR`) exited at the executable-probe inside `setup_workspace` — step 2 of `run_live`, before stdin was read, before the managed stack started, and before any provider curl. It therefore made zero external provider requests and read no secret. The authorized one-shot was then executed exactly once with an executable `TMPDIR` under `/config/workspace` and succeeded. This is not a retry of a provider request; the first attempt never reached the provider.
- The live command's exit status was determined from its emitted success record rather than an inline `PIPESTATUS` read. The pipeline ran inside a command substitution (single `PIPESTATUS` element) and each intermediate `var=${PIPESTATUS[...]}` assignment reset the array, so the captured variable printed blank. Under the script's `set -euo pipefail`, the final sanitized `"result":"success"` JSON is emitted only on the terminal success path of `run_live` (the last statement before the `case` dispatch returns), so the exit status is 0. The successful provider request was not re-run to re-measure it.
- Live record `date` is `2026-08-01`. The script uses `date -u +%Y-%m-%d`; the runner's UTC clock at execution was `2026-08-01T23:44Z`, one day behind the harness "today" of 2026-08-02. The retained field reflects the actual UTC run date.
- Final-checks section: I ran the plan's `git diff --check` and per-file `git check-ignore -q` as listed, and added supplementary evidence to satisfy the plan's S17 no-secret requirement, which the stub block named but did not enumerate as a command: an `agent-roadmap/current.md` ignore check, a `git status --porcelain` confirmation, a material-targeted secret scan over the docs diff, and an opaque-long-token scan over the active artifacts. `git check-ignore -q` returns rc=1 for both `.md` (not ignored → unignored tracked evidence, the desired state) and rc=0 for `current.md` (ignored). The plan's Final-Verification `&&` chain of `git check-ignore -q` therefore evaluates to non-zero; that is expected because `-q` reports rc=0 only for ignored paths, whereas these evidence files are intentionally unignored. The managed-block invariant is confirmed instead by the per-file rc values and the `??` status.

## Key Design Decisions

- Documentation decision: the managed API-key interpretation paragraph in `docs/openai-usage-grafana.md` now states that deterministic qualification proves both managed routes (the OpenAI-compatible Chat profile and the Anthropic Messages profile) complete end to end with exact auth and safe credential-slot attribution as a route-completion record, while OpenAI canonical Prometheus slot/revision series are emitted only for OpenAI attempts because Anthropic handlers do not record the OpenAI canonical usage series and ignore native `USAGE` tunnel frames. It states that an Anthropic Messages Prometheus series is therefore not expected until separate Anthropic metering exists and its absence is not an anomaly, that the deterministic packet is one initial Chat call plus one rotated Chat call on the same managed slot, and it retains the `X-Api-Key` lease-scope canonicalization and the fail-closed/no-fallback guidance. This matches the authoritative references, which were left unchanged: `agent-contract/outer/anthropic-compatible-api.md` (lines 293, 297) and `agent-spec/input/openai-compatible-surface.md` (lines 141, 210, 251, 252).
- Evidence-retention boundary: only sanitized provider, model, safe `credential_slot_ref`, immutable `credential_revision`, UTC date, result, and exit status are retained. No decrypted credential, provider response body, prompt, request/response headers, lease id, slot alias, ciphertext, or private key appears in any artifact. The decrypted secret flowed `sops --extract` → pipe → the script's stdin only; it was never placed in argv, terminal output, or a tracked file, and the script wrote it to a chmod-600 temp file that was removed on completion. The deterministic and live temporary roots under `/config/workspace` were removed cleanly, and no smoke temp directories remain under `/config/workspace` or `/tmp`.

## Reviewer Checkpoints

- [ ] Confirm the documentation distinguishes managed-route qualification records from OpenAI-only Prometheus series.
- [ ] Confirm the deterministic packet is described as one initial Chat call plus one rotated Chat call.
- [ ] Confirm the authorized live request was executed once, without retry, and only sanitized fields were retained.
- [ ] Confirm S17 pointer, stale-claim, and raw-secret checks are fresh and consistent with the reviewed contract/spec boundary.

## Verification Results

### Documentation and contract/spec drift checks

```text
$ rg -n "managed API-key|X-Api-Key|OpenAI canonical|Anthropic|initial Chat|rotated Chat|fail closed" docs/openai-usage-grafana.md agent-contract/outer/anthropic-compatible-api.md agent-spec/input/openai-compatible-surface.md
# Corrected paragraph present in docs (single match carries every required term):
docs/openai-usage-grafana.md:113:Managed API-key interpretation: managed API-key profiles qualify because the Control Plane
  canonicalizes the resolved auth header (lowercase `x-api-key` to `X-Api-Key`) before signing the
  lease scope. Deterministic qualification proves that both managed routes -- the OpenAI-compatible
  Chat profile and the Anthropic Messages profile -- complete end to end ... OpenAI canonical
  Prometheus slot/revision series are emitted only for OpenAI attempts ... An Anthropic Messages
  slot series is therefore not expected until separate Anthropic metering is implemented ... The
  deterministic OpenAI packet is one initial Chat call plus one rotated Chat call on the same
  managed slot ... A lease failure must fail closed with no Node/upstream attempt ...
docs/openai-usage-grafana.md:109:- After disable or revoke, the bound route must fail closed. ...
# Authoritative references (unchanged) confirm the boundary:
agent-contract/outer/anthropic-compatible-api.md:293:Anthropic handlers do not currently record the OpenAI canonical usage metric series. ...
agent-contract/outer/anthropic-compatible-api.md:297:... The deterministic credential-slot qualification exercises both managed profiles (Chat and Messages) end to end.
agent-spec/input/openai-compatible-surface.md:141:| OpenAI usage metering | OpenAI handlers emit ... Anthropic handlers do not currently emit this metric series ...
agent-spec/input/openai-compatible-surface.md:210:- OpenAI handlers emit ... Anthropic handlers currently do not emit these series.
agent-spec/input/openai-compatible-surface.md:251:- Anthropic metrics are not inferred from native responses or tunnel frames; adding them requires a separate runtime change.
agent-spec/input/openai-compatible-surface.md:252:- Managed API-key profiles qualify end to end: ...
(plus the pre-existing OpenAI/Anthropic mentions across both reference files; none were modified)

$ ! rg -n "both a Chat and a Messages slot series|Absence of a Messages slot series is therefore an anomaly" docs/openai-usage-grafana.md
# no matches -> stale claim absent (negated check succeeds)

$ git diff --check
# (no output) -> no whitespace errors
```

### Deterministic credential-slot qualification

```text
$ credential_smoke_parent="$(mktemp -d /config/workspace/iop-credential-slot-followup.XXXXXX)"
$ trap 'rmdir "$credential_smoke_parent" 2>/dev/null || true' EXIT
$ TMPDIR="$credential_smoke_parent" make test-credential-slot-smoke
temp root: /config/workspace/iop-credential-slot-followup.hptZ0n
./scripts/e2e-credential-slot-smoke.sh
[credential-slot-smoke] building fresh Control Plane, Edge, and Node binaries
[credential-slot-smoke] bootstrapping one principal without exposing its one-time token
{"mode":"deterministic","profiles":["seulgi_chat","seulgi_messages"],"same_model_two_slot":true,"exact_auth":{"chat":2,"messages":1},"ciphertext_only":true,"attribution":{"chat_slot_ref":"b073214b-8999-4e20-be97-58251f5e69f5","messages_slot_ref":"5cdc7597-27cc-435a-99f0-a355b512c82c","initial_revision":1,"rotated_revision":2},"tls_negative_matrix":"passed","post_revoke":{"revision":3,"lease_delivery_attempts":3,"upstream_calls":3,"counters_unchanged":true,"no_fallback":true},"result":"success"}
$ echo "MAKE_EXIT_STATUS=$?"
MAKE_EXIT_STATUS=0
$ rmdir "$credential_smoke_parent"   # temp root removed cleanly
$ trap - EXIT
```

Deterministic qualification is external-I/O-free (fake provider) and exits 0. `exact_auth={chat:2,messages:1}`
confirms the packet is one initial Chat call plus one rotated Chat call (`initial_revision:1`, `rotated_revision:2`
on the same managed slot) plus one Messages call; both managed profiles (`seulgi_chat`, `seulgi_messages`) qualify
end to end. `post_revoke.counters_unchanged:true` and `no_fallback:true` confirm the fail-closed behavior.

### Authorized live one-shot and sanitized evidence

```text
$ test "${IOP_ALLOW_LIVE_PROVIDER:-}" = "1"       # preflight: opt-in OK
$ test -r /config/.config/sops/iop/openai.sops.yaml   # preflight: encrypted input readable
$ test -r /config/.config/sops/age/keys.txt           # preflight: age key readable

# Single no-retry authorized request. Decrypted secret flows sops -> pipe -> script stdin only;
# never in argv, terminal output, or a tracked file. Executable TMPDIR required (default /tmp is noexec).
$ sops --decrypt --extract '["data"]' /config/.config/sops/iop/openai.sops.yaml \
    | TMPDIR="$live_tmp_root" scripts/e2e-credential-slot-smoke.sh --live --secret-stdin \
        --profile openai --model gpt-5.6-luna --reasoning-effort high --max-completion-tokens 128
{"provider":"openai","model":"gpt-5.6-luna","credential_slot_ref":"4be6ee59-b76f-4eae-bc3f-63c5bb844971","credential_revision":1,"date":"2026-08-01","result":"success"}
# stderr was empty; live temp root removed cleanly; exit status 0 (terminal success record under set -euo pipefail).
```

Note: the initial invocation without a `TMPDIR` override exited at the executable-TMPDIR probe inside
`setup_workspace` (`/tmp` is noexec on this runner) — before stdin was read, before the managed stack
started, and before any provider curl. It made zero external requests and read no secret, so the single
authorized request is the successful run above and was not repeated. See `Deviations from Plan`.

Sanitized evidence only (no decrypted credential, headers, prompt, response body, lease id, or private key):

```text
provider=openai
model=gpt-5.6-luna
credential_slot_ref=4be6ee59-b76f-4eae-bc3f-63c5bb844971
credential_revision=1
date=2026-08-01
result=success
exit_status=0
```

### Final no-secret and managed-file checks

```text
$ git diff --check
# (no output) -> no whitespace errors

# Managed-file check. The .md artifacts must be UNIGNORED tracked evidence; agent-roadmap/current.md
# must be ignored. git check-ignore -q returns rc=0 when a path IS ignored, rc=1 when it is NOT.
$ git check-ignore -q agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/PLAN-cloud-G07.md; echo rc=$?
rc=1   # NOT ignored -> unignored by "!agent-task/**/*.md" (desired: tracked evidence)
$ git check-ignore -q agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/CODE_REVIEW-cloud-G07.md; echo rc=$?
rc=1   # NOT ignored -> unignored by "!agent-task/**/*.md" (desired: tracked evidence)
$ git check-ignore -q agent-roadmap/current.md; echo rc=$?
rc=0   # ignored by the managed block, as required
$ git status --porcelain agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/PLAN-cloud-G07.md agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/CODE_REVIEW-cloud-G07.md
?? agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/CODE_REVIEW-cloud-G07.md
?? agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/PLAN-cloud-G07.md
# "??" confirms both are visible/untracked (staged as evidence on commit), not ignored.

# Repository no-secret scan (S17). Material-targeted so it does not self-match on prose field names.
$ git diff -- docs/openai-usage-grafana.md | rg -n -- "-----BEGIN|sk-[A-Za-z0-9]{16,}|Bearer [A-Za-z0-9._-]{20,}|ENC\[|age1[a-z0-9]{20,}" || echo "docs diff: no secret material"
docs diff: no secret material
$ rg -n -- "[A-Za-z0-9]{40,}" agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/CODE_REVIEW-cloud-G07.md agent-task/m-principal-provider-credential-slot-routing/10+08,09_verification_contracts/PLAN-cloud-G07.md || echo "active artifacts: no opaque long-token material"
active artifacts: no opaque long-token material
```

Interpretation: `git check-ignore -q` reports rc=1 for both `.md` because the managed block `!agent-task/**/*.md`
unignores them — this is the desired state (tracked evidence), and `agent-roadmap/current.md` stays ignored (rc=0).
The opaque-token scan uses `[A-Za-z0-9]{40,}` (pure alnum, so hyphenated slot UUIDs are excluded) to avoid
self-matching on the recorded secret-pattern strings. Retained evidence contains only sanitized
provider/model/safe-slot-ref/revision/date/result/exit-status. No raw credential, private key, provider body,
prompt, lease id, slot alias, ciphertext, or decrypted configuration appears in the docs change or the active
plan/review artifacts.

---

> **[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 |

## Code Review Result

- Overall Verdict: PASS
- Dimension Assessment:
  - Correctness: Pass
  - Completeness: Pass
  - Test coverage: Pass
  - API contract: Pass
  - Code quality: Pass
  - Implementation deviation: Pass
  - Verification trust: Pass
  - Spec conformance: Pass
- Findings: None.
- Routing Signals:
  - `review_rework_count=3`
  - `evidence_integrity_failure=false`
- Next Step: Write `complete.log`, archive the completed task under `agent-task/archive/2026/08/`, and emit the milestone completion metadata for runtime aggregation without modifying the roadmap.
