<!-- task=m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery plan=7 tag=REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API milestone-task=secure-transport,credential-lease,adapter-injection,revocation -->

# Deterministic Queued-Refresh Stop Evidence Follow-up

## For the Implementing Agent

Filling the implementation-owned sections of `CODE_REVIEW-cloud-G04.md` is mandatory. Implement the item below, run every verification command exactly, paste actual notes and stdout/stderr into the review artifact, keep both active files in place, and report ready for review. Final verdicts, log archives, `complete.log`, task moves, user-review classification, and control-plane stop files belong only to the code-review workflow. If blocked, record the exact blocker, attempted commands/output, and resume condition only in implementation-owned evidence; do not ask the user or classify the next state.

## Background

Context-aware projection batch admission now fixes the production cancellation defect and all fresh verification passes. The queued-refresh `Stop` regression still relies on a fixed sleep and never proves that the refresh broadcast reached the occupied gate, so it can pass without exercising the claimed path. This follow-up makes only that shutdown evidence deterministic.

## Archive Evidence Snapshot

- `plan_cloud_G06_6.log` and `code_review_cloud_G06_6.log`: current-pair predicted archives; verdict `FAIL` with 1 Required, 0 Suggested, and 0 Nit findings. Fresh focused, wire race, package, affected race, process, vet, diff, and secret guards passed. Production channel admission is correct, but `TestEdgeServerStopCancelsProjectionRefreshWaitingForPriorBatch` uses `time.Sleep(50 * time.Millisecond)` without observing a queued waiter.
- `plan_cloud_G07_5.log` and `code_review_cloud_G07_5.log`: prior production finding requiring context-aware batch admission. The current source satisfies that production requirement.
- `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/03+01,02_projection_auth/complete.log`, `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/04+03_principal_routes/complete.log`, and `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material/complete.log`: projection, route-binding, and secret-at-rest predecessors remain satisfied.

## Analysis

### Files Read

- `apps/control-plane/internal/wire/edge_server.go`
- `apps/control-plane/internal/wire/edge_server_test.go`
- `apps/control-plane/cmd/control-plane/server.go`
- `agent-roadmap/phase/operational-observability-provider-management/PHASE.md`
- `agent-roadmap/phase/operational-observability-provider-management/milestones/principal-provider-credential-slot-routing.md`
- `agent-roadmap/sdd/operational-observability-provider-management/principal-provider-credential-slot-routing/SDD.md`
- `agent-contract/inner/control-plane-edge-wire.md`
- `agent-spec/control/control-plane-operations.md`
- `agent-task/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/PLAN-cloud-G06.md`
- `agent-task/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/CODE_REVIEW-cloud-G06.md`
- `agent-task/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/plan_cloud_G07_5.log`
- `agent-task/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/code_review_cloud_G07_5.log`

### SDD Criteria

- SDD: `agent-roadmap/sdd/operational-observability-provider-management/principal-provider-credential-slot-routing/SDD.md`; status approved and lock released.
- First-line Milestone tasks remain `secure-transport,credential-lease,adapter-injection,revocation`.
- Acceptance S02 and S10-S13 require bounded authenticated projection refresh, lease delivery, adapter admission, and revocation behavior.
- Evidence Map S09-S13 requires TLS, lease, upstream-auth, revocation-order, and secret-scan evidence. The implementation checklist adds deterministic queued-refresh cancellation evidence and retains the secure-delivery race, process, and secret guards for those rows.

### Verification Context

- No external handoff was supplied. Repository-native evidence came from the active pair, approved SDD, current source/tests, domain test rules, and fresh reviewer execution.
- Fresh focused cancellation, wire race, shared package, Control Plane/Edge/Node package, affected race, process smoke, three-process secure-delivery, vet, diff, and secret-structure commands all exited 0.
- Static review proves the remaining gap: `apps/control-plane/internal/wire/edge_server_test.go:1139` sleeps and then checks only `Stop`, without an observable precondition that `BroadcastProjection` evaluated admission while the gate was occupied.
- Verification stays in the current checkout with `GOCACHE=/config/tmp/gocache-secure-delivery`, `GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery`, and `TMPDIR=/config/workspace/.gotmp-iop-secure-delivery`. No external runner, credential, or user authorization is required. Confidence: high.

### Test Coverage Gaps

- Direct caller cancellation while queued behind an occupied projection batch is covered deterministically.
- Refresh shutdown while queued behind an occupied batch is not deterministic because the test has no waiter-entry observation and would pass if the periodic refresh never ran.

### Symbol References

None. No production symbol needs renaming or removal.

### Split Judgment

Keep one plan. Replacing one sleep-driven concurrency test with an observable queued-wait precondition is one compact evidence invariant and has one deterministic PASS boundary.

### Scope Rationale

- Do not change `EdgeServer` production admission, fan-out, projection content, transport, lease, revision, or revocation behavior; fresh review already proves those paths.
- Change only `apps/control-plane/internal/wire/edge_server_test.go` plus the mandatory review evidence artifact. Do not update proto, contracts, specs, roadmap, config, or tracked docs.

### Final Routing

- Evaluation mode: `isolated-reassessment`.
- Finalizer: `finalize-task-policy.sh`, mode `pair`; build and review closures are true for scope, context, verification, evidence, ownership, and decision. Capability gap: none.
- Build scores: scope coupling 0, state/concurrency 2, blast/irreversibility 0, evidence/diagnosis 1, verification complexity 1; grade G04, base route `local-fit`, final route `recovery-boundary`, lane `cloud`, filename `PLAN-cloud-G04.md`.
- Review scores: 0/2/0/1/1; grade G04, route `official-review`, lane `cloud`, filename `CODE_REVIEW-cloud-G04.md`.
- `large_indivisible_context=false`; positive loop-risk signatures are `temporal_state` and `concurrent_consistency` (`loop_risk_count=2`).
- Recovery signals: `review_rework_count=6`, `evidence_integrity_failure=true`; recovery boundary is matched.

## Implementation Checklist

- [ ] Replace the sleep-driven queued-refresh `Stop` regression with an observable, deterministic waiter-entry precondition; prove `Stop` cancels and joins that refresh before the occupied batch gate is released.
- [ ] Run the focused, race, full secure-delivery, vet, diff, and secret-structure verification commands with fresh output.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-1] Make queued-refresh shutdown evidence deterministic

**Problem:** `apps/control-plane/internal/wire/edge_server_test.go:1139` uses `time.Sleep(50 * time.Millisecond)` after `Start`, then checks only that `Stop` returns. The test has no evidence that the refresh goroutine evaluated `acquireProjectionBatch` while the gate was occupied, so refresh startup or ticker-broadcast regressions can pass it unchanged.

**Before (`apps/control-plane/internal/wire/edge_server_test.go:1133-1142`):**

```go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := server.Start(ctx); err != nil {
	t.Fatal(err)
}

time.Sleep(50 * time.Millisecond)

stopped := make(chan error, 1)
go func() { stopped <- server.Stop() }()
```

**Solution:** Replace the timer assumption with a deterministic test-owned refresh lifecycle. Wrap a cancellable context with a test context whose `Done()` method closes a one-shot observation channel when admission evaluates the cancellation arm. Install that cancel/done lifecycle under `refreshMu`, run `BroadcastProjection` in the refresh goroutine while the batch gate is occupied, wait for the `Done()` observation before calling `Stop`, and assert both `Stop` and the broadcast return `context.Canceled` before releasing the gate. Start the wire server with automatic refresh disabled so only the installed lifecycle owns the test.

**After (`apps/control-plane/internal/wire/edge_server_test.go`):**

```go
type doneObservedContext struct {
	context.Context
	observed chan struct{}
	once     sync.Once
}

func (c *doneObservedContext) Done() <-chan struct{} {
	c.once.Do(func() { close(c.observed) })
	return c.Context.Done()
}
```

The test must wait on `observed` before calling `Stop`, keep the original gate occupied until `Stop` returns, and assert `errors.Is(broadcastErr, context.Canceled)`.

**Modified Files and Checklist:**

- [ ] `apps/control-plane/internal/wire/edge_server_test.go` — add the test-only observed context/lifecycle and remove the sleep-driven queued-refresh setup.

**Test Strategy:** Update `TestEdgeServerStopCancelsProjectionRefreshWaitingForPriorBatch`. The occupied gate is the fixture; the observed `Done()` evaluation is the deterministic proof that the refresh reached cancellable admission; `Stop` completion and `context.Canceled` are asserted before gate release. Retain the direct queued-broadcast cancellation, stalled-client, fan-out, and periodic refresh tests and run the wire package under `-race`.

**Verification:**

```bash
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery go test -count=20 ./apps/control-plane/internal/wire -run 'TestEdgeServer(BroadcastProjectionCancellationDoesNotWaitForPriorBatch|StopCancelsProjectionRefreshWaitingForPriorBatch)$'
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery go test -count=1 -race ./apps/control-plane/internal/wire
```

Expected: both commands exit 0; every repeated run observes admission before cancellation, `Stop` and the queued broadcast return before gate release, and race detection reports no issue.

## Modified Files Summary

| File | Item |
|------|------|
| `apps/control-plane/internal/wire/edge_server_test.go` | REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-1 |
| `agent-task/m-principal-provider-credential-slot-routing/08+03,04,07_secure_delivery/CODE_REVIEW-cloud-G04.md` | REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_REVIEW_API-1 |

## Final Verification

Fresh execution is required; cached `go test` output is not acceptable.

```bash
command -v go && go version && go env GOROOT
test -f agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/03+01,02_projection_auth/complete.log
test -f agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/04+03_principal_routes/complete.log
test -f agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/07+01,02,05_secret_material/complete.log
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery go test -count=1 ./packages/go/auth ./packages/go/config ./packages/go/credentiallease
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery go test -count=1 ./apps/control-plane/... ./apps/edge/... ./apps/node/...
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery go test -count=1 -race ./packages/go/auth ./packages/go/credentiallease ./apps/control-plane/internal/credentiallease ./apps/control-plane/internal/wire ./apps/edge/internal/authprojection ./apps/edge/internal/controlplane ./apps/edge/internal/service ./apps/edge/internal/transport ./apps/node/internal/node
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery make test-control-plane-edge-wire
env GOCACHE=/config/tmp/gocache-secure-delivery GOTMPDIR=/config/workspace/.gotmp-iop-secure-delivery TMPDIR=/config/workspace/.gotmp-iop-secure-delivery go vet ./apps/control-plane/... ./apps/edge/... ./apps/node/... ./packages/go/...
git diff --check
if rg --sort path -n 'bytes[[:space:]]+(secret|provider_secret)|map<string, string>[[:space:]]+(credential|provider_auth)' proto/iop/runtime.proto; then exit 1; fi
```

Expected: every command exits 0; deterministic queued-refresh cancellation, race safety, the existing secure-delivery process path, and secret-free runtime structure all remain proven.

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