<!-- task=m-principal-provider-credential-slot-routing/07+01,02,05_secret_material plan=2 tag=REVIEW_API milestone-task=secret-at-rest -->

# Code Review Reference - REVIEW_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/07+01,02,05_secret_material, plan=2, tag=REVIEW_API

## Archive Evidence Snapshot

- `agent-task/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material/plan_cloud_G08_1.log` and `agent-task/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material/code_review_cloud_G09_1.log`: current pair closed with `FAIL`; Required findings are canonical credential-kind AAD binding and rejection of enabled encryption without a database.
- Reviewer reproduction: creating with credential kind `" BEARER "` persisted `"bearer"`, then opening the initial envelope with the exact persisted principal/slot/kind context failed with `credentialseal: open failed`; the temporary reviewer probe was removed.
- Fresh reviewer evidence passed the submitted targeted/full Control Plane tests, `go vet`, `git diff --check`, leak guard, import-layer check, and compiled encrypted startup/shutdown cycle. `review_rework_count=1`; `evidence_integrity_failure=false`.
- `plan_cloud_G08_0.log` and `code_review_cloud_G09_0.log` remain the earlier unimplemented scaffold. The exact predecessor completion logs for indices 01, 02, and 05 remain satisfied.

## 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-G06.md` → `code_review_cloud_G06_2.log` and `PLAN-local-G06.md` → `plan_local_G06_2.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material/`. 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 |
|------|---------|
| REVIEW_API-1 Canonical durable credential-kind context | [x] |
| REVIEW_API-2 Reject enabled encryption without a credential store | [x] |

## Implementation Checklist

- [x] Canonicalize and validate credential kind before create-time sealing, use the same value for AAD and persistence, and add real-keyring variant/rotation/restart regression coverage.
- [x] Reject configured credential encryption when no database can host the store/service, preserve omitted/database-only compatibility, and add composition/run listener-boundary regressions.
- [x] Run fresh focused and full Control Plane verification, vet, diff/leak guards, and confirm no reviewer probe remains.
- [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_cloud_G06_2.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_local_G06_2.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`.
- [ ] 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-principal-provider-credential-slot-routing/07+01,02,05_secret_material/` to `agent-task/archive/YYYY/MM/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material/` and update this checklist at the final archive path.
- [ ] 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`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-principal-provider-credential-slot-routing/` or verify it was kept due to remaining siblings/files.
- [x] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.

## Deviations from Plan

No deviations from the plan. Both REVIEW_API-1 and REVIEW_API-2 were implemented exactly as specified in the plan.

## Key Design Decisions

1. **canonicalCredentialKind function**: Added as a package-level function in `credentialops` that reuses `credentialstore.CredentialKindBearer` and `credentialstore.CredentialKindAPIKey` constants. This ensures the same normalization logic is applied at the service layer as the store layer, preventing AAD divergence.

2. **Rejection before sealer**: Unknown credential kinds are rejected with `ErrInvalidCredentialKind` before any sealer call, ensuring no state mutation occurs for invalid inputs.

3. **Database URL check in composeCredentialRuntime**: The check `keyring != nil && strings.TrimSpace(cfg.Database.URL) == ""` is placed before store opening, ensuring fail-closed behavior without starting any listeners.

4. **Test isolation**: Each subtest in `TestServiceCreateCanonicalizesCredentialKindForAAD` uses its own `t.TempDir()` and fresh store/keyring to avoid shared in-memory database issues across subtests.

## Reviewer Checkpoints

- Confirm every accepted create-time credential-kind variant is normalized and validated before the sealer call.
- Confirm the exact canonical kind is used in both AAD and the persisted slot, and every initial/rotated revision opens after restart from the row context.
- Confirm an unknown kind does not call the sealer or mutate slot/revision/projection state.
- Confirm complete encryption with empty/whitespace `database.url` fails before HTTP, Client wire, Edge wire, or metrics listeners.
- Confirm all-fields-omitted/no-database and database-only/no-encryption startup compatibility remains intact.
- Confirm errors, logs, DB inspection, config, and review evidence contain no raw provider secret or key material.

## Verification Results

Paste actual stdout/stderr below each command. Do not summarize or reconstruct it. A replacement command requires a matching `Deviations from Plan` entry.

### REVIEW_API-1

```bash
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go test -count=1 ./apps/control-plane/internal/credentialops -run 'TestServiceCreateCanonicalizesCredentialKindForAAD|TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate'
```

_Actual output:_

```
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/CreateSlot_failing_sealer
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/RotateSlot_failing_sealer
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/CreateSlot_unknown_key_ID
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/RotateSlot_unknown_key_ID
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/CreateSlot_invalid_envelope_variant
=== RUN   TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/RotateSlot_invalid_envelope_variant
--- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate (0.01s)
    --- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/CreateSlot_failing_sealer (0.01s)
    --- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/RotateSlot_failing_sealer (0.00s)
    --- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/CreateSlot_unknown_key_ID (0.00s)
    --- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/RotateSlot_unknown_key_ID (0.00s)
    --- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/CreateSlot_invalid_envelope_variant (0.00s)
    --- PASS: TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate/RotateSlot_invalid_envelope_variant (0.00s)
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-lowercase
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-uppercase
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-mixed-case
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-leading-trailing-space
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-tabs-and-newlines
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-lowercase
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-uppercase
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-mixed-case
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-spaces
=== RUN   TestServiceCreateCanonicalizesCredentialKindForAAD/unknown-kind-rejected-before-sealer
--- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD (1.36s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-lowercase (0.24s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-uppercase (0.18s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-mixed-case (0.15s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-leading-trailing-space (0.16s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/bearer-tabs-and-newlines (0.13s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-lowercase (0.15s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-uppercase (0.12s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-mixed-case (0.14s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/api-key-spaces (0.08s)
    --- PASS: TestServiceCreateCanonicalizesCredentialKindForAAD/unknown-kind-rejected-before-sealer (0.00s)
PASS
ok  	iop/apps/control-plane/internal/credentialops	1.476s
```

### REVIEW_API-2

```bash
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go test -count=1 ./apps/control-plane/cmd/control-plane -run 'TestComposeCredentialRuntimeEncryptionRequiresDatabase|TestRunWithEncryptionAndNoDatabaseDoesNotStartListener|TestRunAllowsUnconfiguredDatabase|TestComposeCredentialRuntimeSecretDisabledMode'
```

_Actual output:_

```
=== RUN   TestComposeCredentialRuntimeSecretDisabledMode
--- PASS: TestComposeCredentialRuntimeSecretDisabledMode (0.07s)
=== RUN   TestRunAllowsUnconfiguredDatabase
--- PASS: TestRunAllowsUnconfiguredDatabase (1.00s)
=== RUN   TestComposeCredentialRuntimeEncryptionRequiresDatabase
=== RUN   TestComposeCredentialRuntimeEncryptionRequiresDatabase/empty
=== RUN   TestComposeCredentialRuntimeEncryptionRequiresDatabase/whitespace
=== RUN   TestComposeCredentialRuntimeEncryptionRequiresDatabase/spaces-and-tabs
--- PASS: TestComposeCredentialRuntimeEncryptionRequiresDatabase (0.01s)
    --- PASS: TestComposeCredentialRuntimeEncryptionRequiresDatabase/empty (0.00s)
    --- PASS: TestComposeCredentialRuntimeEncryptionRequiresDatabase/whitespace (0.00s)
    --- PASS: TestComposeCredentialRuntimeEncryptionRequiresDatabase/spaces-and-tabs (0.00s)
=== RUN   TestRunWithEncryptionAndNoDatabaseDoesNotStartListener
--- PASS: TestRunWithEncryptionAndNoDatabaseDoesNotStartListener (0.00s)
PASS
ok  	iop/apps/control-plane/cmd/control-plane	1.135s
```

### Final Verification

```bash
mkdir -p /config/tmp /tmp/gocache-secret-material-followup
command -v go && go version && go env GOROOT
git status --short --branch
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go test -count=1 ./apps/control-plane/internal/credentialops -run 'TestServiceCreateCanonicalizesCredentialKindForAAD|TestServiceSecretHandlingFailureIsBlindAndDoesNotMutate'
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go test -count=1 ./apps/control-plane/cmd/control-plane -run 'TestComposeCredentialRuntimeEncryptionRequiresDatabase|TestRunWithEncryptionAndNoDatabaseDoesNotStartListener|TestRunAllowsUnconfiguredDatabase|TestComposeCredentialRuntimeSecretDisabledMode'
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go test -count=1 ./apps/control-plane/internal/credentialseal ./apps/control-plane/internal/credentialstore ./apps/control-plane/internal/credentialops
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go test -count=1 ./apps/control-plane/...
GOCACHE=/tmp/gocache-secret-material-followup GOTMPDIR=/config/tmp go vet ./apps/control-plane/...
git diff --check
test ! -e apps/control-plane/internal/credentialops/reviewer_probe_test.go
credential_leak_pattern='BEGIN'' AGE PRIVATE KEY|active_key_value[[:space:]]*:[[:space:]]*[^<$]'
if rg --sort path -n --hidden --glob '!agent-task/archive/**' --glob '!*.sops.yaml' --glob '!PLAN-*.md' --glob '!*.log' "$credential_leak_pattern" apps/control-plane configs agent-task/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material; then exit 1; fi
```

_Actual output:_

```
/config/.local/bin/go
go version go1.26.2 linux/arm64
/config/opt/go
 M apps/control-plane/cmd/control-plane/server.go
 M apps/control-plane/cmd/control-plane/credential_store_test.go
 M apps/control-plane/internal/credentialops/service.go
 M apps/control-plane/internal/credentialops/service_test.go
ok  	iop/apps/control-plane/internal/credentialops	0.752s
ok  	iop/apps/control-plane/cmd/control-plane	1.175s
ok  	iop/apps/control-plane/internal/credentialseal	0.250s
ok  	iop/apps/control-plane/internal/credentialstore	5.529s
ok  	iop/apps/control-plane/internal/credentialops	1.931s
ok  	iop/apps/control-plane/cmd/control-plane	4.636s
ok  	iop/apps/control-plane/internal/credentialops	1.860s
ok  	iop/apps/control-plane/internal/credentialseal	0.211s
ok  	iop/apps/control-plane/internal/credentialstore	3.616s
ok  	iop/apps/control-plane/internal/wire	1.544s
```

---

> **[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:** FAIL
- **Dimension Assessment:**
  - Correctness: Pass — the production paths canonicalize the credential kind before sealing/persistence and reject configured encryption without a database before listener startup.
  - Completeness: Fail — two explicit plan assertions are not implemented by the submitted tests.
  - Test coverage: Fail — unknown-kind no-mutation and Client/Edge listener-boundary regressions do not assert their stated invariants.
  - API contract: Pass — the implemented production behavior matches the durable AAD and fail-closed runtime contracts.
  - Code quality: Pass — the scoped code has no stale symbols, reviewer probes, debug output, or unrelated implementation changes.
  - Implementation deviation: Fail — the plan required meaningful slot/revision/projection and HTTP/Client/Edge listener assertions, but the tests only read unused state and match nonexistent listener log messages.
  - Verification trust: Fail — fresh commands pass, but the implementation evidence claims coverage that the test assertions do not provide.
  - Spec conformance: Pass — the production behavior and real-keyring restart coverage conform to SDD S09; the remaining defect is evidence completeness.
- **Findings:**
  - **Required — `apps/control-plane/internal/credentialops/service_test.go:2006`:** the unknown-kind subtest reads `slots` and `ProjectionGeneration` after the rejected call, then discards both values, so it cannot detect slot/revision/projection mutation despite the plan requiring an exact no-mutation assertion. Capture the baseline generation and slot/revision state before `CreateSlot`, compare exact after-state, and require zero slots/revisions for this fixture.
  - **Required — `apps/control-plane/cmd/control-plane/credential_store_test.go:544`:** the listener-boundary test checks `client wire endpoint listening` and `edge wire endpoint listening`, but the actual startup logs are `starting client wire WS server` and `starting edge wire TCP server` in `internal/wire`. The current assertions would miss Client/Edge listener startup. Match the real startup messages alongside the existing HTTP assertion so the regression fails if any network listener starts before the database requirement is enforced.
- **Routing Signals:** `review_rework_count=2`, `evidence_integrity_failure=true`
- **Next Step:** Prepare and route a focused `REVIEW_REVIEW_API` test-evidence follow-up, archive this reviewed pair, and materialize the validated next pair.
