<!-- task=m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap plan=2 tag=REVIEW_REVIEW_API -->

# Make Host-Local Bootstrap Contention and Wire Guards Production-Real

## For the Implementing Agent

Filling implementation-owned sections of `CODE_REVIEW-cloud-G08.md` is mandatory. Run every verification command, paste actual output, keep the active files in place, and report ready for review; only code-review may append a verdict, rename logs, write `complete.log`, or archive the task. If blocked, record the exact blocker, attempted commands/output, and resume condition only 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 store-owned first-principal transaction prevents duplicate commits, but its test serializes through one connection and production SQLite callers fail with `database is locked` instead of the documented typed refusal. The committed wire guard reads the right files but its narrow shared regex misses valid credential-management naming variants. This follow-up makes both acceptance oracles representative of the actual host-local and Client wire boundaries.

## Archive Evidence Snapshot

- Current pair after archive: `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/plan_local_G07_1.log`, `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/code_review_cloud_G07_1.log`.
- Verdict: FAIL with two Required findings, zero Suggested findings, and zero remaining Nits.
- Required scope: make separate SQLite pools/processes wait for the first bootstrap commit and return `ErrPrincipalAlreadyExists`; replace the narrow shared source regex with file-specific proto/ClientServer/Dart guards plus sensitivity fixtures.
- Affected files: `apps/control-plane/internal/credentialstore/store.go`, `apps/control-plane/internal/credentialstore/principal_test.go`, and `apps/control-plane/cmd/control-plane/credential_commands_test.go`.
- Fresh reviewer evidence: all focused/repeated Control Plane tests, vet, formatting, deterministic search, sequential compiled bootstrap, predecessor checks, and `git diff --check` passed; a five-process compiled race yielded `successes=1 token_outputs=1 already_exists=0 locked=4`, and four forbidden source candidates all missed the current regex; `evidence_integrity_failure=false`.
- Roadmap carryover: this packet remains preparatory and must not check `credential-management`; later encrypted-store and confidential transport rollout remains required.

## Analysis

### Files Read

- `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/PLAN-local-G07.md`
- `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/CODE_REVIEW-cloud-G07.md`
- `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/plan_local_G06_0.log`
- `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/code_review_cloud_G06_0.log`
- `apps/control-plane/internal/credentialstore/store.go`
- `apps/control-plane/internal/credentialstore/schema.go`
- `apps/control-plane/internal/credentialstore/principal.go`
- `apps/control-plane/internal/credentialstore/principal_test.go`
- `apps/control-plane/internal/credentialstore/projection.go`
- `apps/control-plane/cmd/control-plane/main.go`
- `apps/control-plane/cmd/control-plane/credential_commands.go`
- `apps/control-plane/cmd/control-plane/credential_commands_test.go`
- `apps/control-plane/cmd/control-plane/credential_store_test.go`
- `apps/control-plane/internal/wire/client.go`
- `proto/iop/control.proto`
- `apps/client/lib/iop_wire/client_wire_client.dart`
- `apps/client/lib/iop_wire/parser_map.dart`
- `agent-contract/inner/client-control-plane-wire.md`
- `agent-contract/inner/control-plane-edge-wire.md`
- `agent-spec/control/control-plane-operations.md`
- `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`
- `/config/go/pkg/mod/modernc.org/sqlite@v1.33.1/all_test.go`
- `/config/go/pkg/mod/modernc.org/sqlite@v1.33.1/sqlite.go`

### SDD Criteria

- SDD: `agent-roadmap/sdd/operational-observability-provider-management/principal-provider-credential-slot-routing/SDD.md`; status `[승인됨]`, lock released, and no `USER_REVIEW.md`.
- S01 / `principal-store`: first issuance returns one raw token and persists only its digest. The S01-S03 Evidence Map row drives the separate-pool concurrency, restart, one-time output, and redaction checks without reopening the already completed roadmap Task.
- S08 / `credential-management`: bootstrap stays host-local and no remote bootstrap operation may enter the current Client wire. The S04-S08 Evidence Map row drives file-specific proto/ClientServer/Dart absence checks and mutation fixtures.
- This repair does not complete the full S08 management surface and intentionally omits `Roadmap Targets`.

### Verification Context

- No external handoff was supplied. Repository-native evidence came from the active pair, exact prior-loop logs, approved SDD, current wire contracts/spec, domain/local test rules, current source/tests, and fresh reviewer commands.
- Environment preflight: `/config/.local/bin/go`, Go 1.26.2 linux/arm64, `GOROOT=/config/opt/go`, workspace `/config/workspace/iop-s0`, and an intentional dirty worktree with sibling Milestone changes.
- The installed `modernc.org/sqlite` v1.33.1 driver supports connection DSN `_pragma=busy_timeout%3dN`; a reviewer rerun with `_pragma=busy_timeout%3d5000` changed the five-process result to `successes=1 token_outputs=1 already_exists=4 locked=0`.
- Fresh baseline commands passed: predecessor checks, formatting, `go test -count=50 -race` for the current first-principal test, focused bootstrap tests, `go test -count=1 ./apps/control-plane/...`, `go vet ./apps/control-plane/...`, the existing deterministic search, sequential compiled bootstrap/reopen refusal, and `git diff --check`.
- Required verification remains in the current checkout, uses temporary SQLite state, does not invoke `iop-agent`, and needs no external service, credential, device, or user authorization. Fresh `-count=1`/`-count=50` results are required; cached Go output is not accepted. Confidence: high.

### Test Coverage Gaps

- `TestCreateFirstPrincipalWithTokenAllowsExactlyOneConcurrentCaller` covers concurrent goroutines only after `SetMaxOpenConns(1)` serializes them at the pool. It does not exercise the production ten-connection pool or independent process/store contention and cannot catch removal of the singleton lock.
- The current production flow safely commits only one principal, but separate SQLite processes return lock errors instead of the method's `ErrPrincipalAlreadyExists` loser contract.
- `TestBootstrapManagementIsAbsentFromWireSources` reads every required source but misses `PrincipalCreateRequest`, `CredentialRequest`, lower-camel Dart methods, and matching parser entries. It has no sensitivity fixture proving representative forbidden additions fail.
- Sequential bootstrap, stdout failure propagation/redaction, persistence, ordinary Control Plane regression, and the current absence state are covered and must remain green.

### Symbol References

- No production symbol is renamed or removed.
- `credentialstore.Open` remains the shared constructor for Control Plane startup, bootstrap, and credential-store tests; SQLite DSN normalization must preserve all existing plain-path and `file:` query forms and leave PostgreSQL unchanged.

### Split Judgment

- Keep one compact repair packet. Both findings are inherited blockers on the same host-local bootstrap acceptance boundary; neither a contention-only nor a guard-only child could complete this existing subtask independently, and the combined verification remains deterministic.
- Runtime predecessors encoded by `06+01,02_host_local_bootstrap` are satisfied by `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/01_principal_store/complete.log` and `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/02+01_credential_catalog/complete.log`.

### Scope Rationale

- Modify only SQLite connection contention configuration and its first-bootstrap regression, plus test-only source guard logic and fixtures.
- Do not change principal/token schema, PostgreSQL transaction semantics, bootstrap output, protobuf, ClientServer, Dart client/parser, server wiring, credential management operations, encryption, or transport activation.
- Do not complete or claim roadmap Task `credential-management`.

### Final Routing

- `status=routed`, `evaluation_mode=isolated-reassessment`, finalizer=`finalize-task-policy.sh`, mode=`pair`; all build/review scope, context, verification, evidence, ownership, and decision closures are true; capability gap: none.
- Build scores: `scope_coupling=1`, `state_concurrency=2`, `blast_irreversibility=2`, `evidence_diagnosis=2`, `verification_complexity=1` => G08; base=`local-fit`, route=`recovery-boundary`, lane=`cloud`, canonical=`PLAN-cloud-G08.md`.
- Review scores: `1+2+2+2+1=G08`; route=`official-review`, lane=`cloud`, adapter=`codex`, model=`gpt-5.6-sol`, reasoning=`xhigh`, canonical=`CODE_REVIEW-cloud-G08.md`.
- `large_indivisible_context=false`; positive risks=`concurrent_consistency`, `boundary_contract` (2); `review_rework_count=2`; `evidence_integrity_failure=false`; risk boundary is false and recovery boundary is true.

## Dependencies and Execution Order

1. `01_principal_store` is satisfied by `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/01_principal_store/complete.log`.
2. `02+01_credential_catalog` is satisfied by `agent-task/archive/2026/08/m-principal-provider-credential-slot-routing/02+01_credential_catalog/complete.log`.
3. Apply the SQLite connection contention behavior before replacing the single-connection race test, then harden the source guard and run the compiled multi-process oracle.

## Implementation Checklist

- [ ] Make every SQLite credential-store connection wait through bounded first-bootstrap contention and prove independent stores/processes return exactly one token plus typed `already exists` losers.
- [ ] Replace the narrow shared wire-absence regex with file-specific proto/ClientServer/Dart checks and mutation fixtures that reject representative management variants while allowing the reserved projection foundation.
- [ ] Run fresh separate-store race, guard sensitivity, focused bootstrap, Control Plane regression, vet, compiled multi-process, formatting, predecessor, and diff verification.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_REVIEW_API-1] Make SQLite first-bootstrap contention deterministic

**Problem:** `apps/control-plane/internal/credentialstore/store.go:101-106` opens SQLite with a ten-connection pool and no busy timeout, while `apps/control-plane/internal/credentialstore/principal_test.go:116` forces one connection before its concurrency test. Separate compiled bootstrap processes therefore hit the singleton update at `apps/control-plane/internal/credentialstore/principal.go:183` concurrently and return `database is locked` instead of waiting to observe the committed principal and returning `ErrPrincipalAlreadyExists`.

**Solution:** Normalize only SQLite data sources before `sql.Open` by appending a final `modernc.org/sqlite` `_pragma=busy_timeout%3d5000` query value while preserving plain file paths, `file:` URLs, existing query options, in-memory forms, and fragments. Keep the caller-provided URL out of errors/logs and leave PostgreSQL unchanged. Replace the one-store/one-connection test setup with independently opened stores over one initialized file so every loser waits, sees the winner, and returns the typed refusal.

Before (`apps/control-plane/internal/credentialstore/store.go:101-106`):

```go
db, err := sql.Open(dia, databaseURL)
if err != nil {
    return nil, fmt.Errorf("credentialstore: open %s: %w", dia, err)
}
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(2)
```

After:

```go
dataSource := databaseURL
if dia == dialectSQLite {
    dataSource = sqliteDataSourceWithBusyTimeout(databaseURL)
}
db, err := sql.Open(dia, dataSource)
```

Before (`apps/control-plane/internal/credentialstore/principal_test.go:111-117`):

```go
store, err := Open(ctx, tmpFile)
if err != nil {
    t.Fatalf("open store: %v", err)
}
defer store.Close()
store.db.SetMaxOpenConns(1)
```

After:

```go
stores := openIndependentTestStores(t, ctx, tmpFile, numCallers)
```

**Modified Files and Checklist:**

- [ ] `apps/control-plane/internal/credentialstore/store.go`: apply a bounded per-connection SQLite busy timeout without changing PostgreSQL or exposing the raw DSN.
- [ ] `apps/control-plane/internal/credentialstore/principal_test.go`: replace the pool-serialized race with independent store handles and assert one success, four `ErrPrincipalAlreadyExists` results, one principal, and one token.

**Test Strategy:** Update `TestCreateFirstPrincipalWithTokenAllowsExactlyOneConcurrentCaller` to initialize one file, open five independent `Store` instances sequentially, synchronize distinct-alias calls, and assert exact typed outcomes and row counts. Retain the `-count=50 -race` repetition and add the compiled five-process final oracle so connection-pool and process boundaries are both exercised without printing raw tokens.

**Verification:** `GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go test -count=50 -race ./apps/control-plane/internal/credentialstore -run 'CreateFirstPrincipalWithToken'` exits zero with no SQLite busy/locked error.

### [REVIEW_REVIEW_API-2] Make the wire-absence guard sensitive to real variants

**Problem:** `apps/control-plane/cmd/control-plane/credential_commands_test.go:427` uses one case-sensitive regex whose small list misses common forbidden proto names, lower-camel Dart management methods, and parser variants. The production sources are currently safe, but the test does not enforce the plan's boundary.

**Solution:** Replace the shared regex with file-specific test helpers. Parse proto message declarations and reject names containing bootstrap/credential/principal except the exact reserved projection allowlist; scan ClientServer and both Dart sources case-insensitively for bootstrap/principal/credential management symbols and imports. Add a table-driven sensitivity test whose forbidden fixtures include `PrincipalCreateRequest`, `CredentialRequest`, `createPrincipal`, and a `PrincipalCreateRequest` parser, plus an allowed reserved projection fixture.

Before (`apps/control-plane/cmd/control-plane/credential_commands_test.go:427-435`):

```go
denyPattern := regexp.MustCompile(`(Bootstrap(Request|Response)|Credential(Operation|Management)|PrincipalManagement|CreatePrincipalRequest|IssueTokenRequest|AddRequestListenerTyped.*(Bootstrap|Credential|Principal))`)

for _, relPath := range wireFiles {
    content, err := os.ReadFile(relPath)
    if err != nil {
        t.Fatalf("read wire source %s: %v", relPath, err)
    }
    if matches := denyPattern.FindAllString(string(content), -1); len(matches) > 0 {
        t.Fatalf("wire source %s contains forbidden management patterns: %v", relPath, matches)
    }
}
```

After:

```go
for _, source := range wireSources {
    content, err := os.ReadFile(source.path)
    if err != nil {
        t.Fatalf("read wire source %s: %v", source.path, err)
    }
    if violation := source.check(string(content)); violation != "" {
        t.Fatalf("wire source %s: %s", source.path, violation)
    }
}
```

**Modified Files and Checklist:**

- [ ] `apps/control-plane/cmd/control-plane/credential_commands_test.go`: add file-specific source checkers, a projection allowlist, and table-driven forbidden/safe sensitivity fixtures while retaining the real-file and CLI-only checks.

**Test Strategy:** Keep `TestBootstrapManagementIsAbsentFromWireSources` as the committed production-source oracle and add `TestBootstrapManagementGuardRejectsForbiddenVariants`. Assert every concrete reviewer candidate fails, current `ClientHello*` remains allowed, and the exact `ProjectedPrincipal*`/`PrincipalProjection*` reserved foundation remains allowed.

**Verification:** `GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go test -count=1 ./apps/control-plane/cmd/control-plane -run 'BootstrapManagement(IsAbsentFromWireSources|GuardRejectsForbiddenVariants)|BootstrapCommandRemainsCLIOnly'` exits zero.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/control-plane/internal/credentialstore/store.go` | REVIEW_REVIEW_API-1 |
| `apps/control-plane/internal/credentialstore/principal_test.go` | REVIEW_REVIEW_API-1 |
| `apps/control-plane/cmd/control-plane/credential_commands_test.go` | REVIEW_REVIEW_API-2 |
| `agent-task/m-principal-provider-credential-slot-routing/06+01,02_host_local_bootstrap/CODE_REVIEW-cloud-G08.md` | REVIEW_REVIEW_API-1, REVIEW_REVIEW_API-2 |

## Final Verification

Run from `/config/workspace/iop-s0`; all Go tests must be fresh and no command may print a raw token.

1. `test "$(find agent-task/archive -type f -path '*/m-principal-provider-credential-slot-routing/01_principal_store/complete.log' -print | wc -l)" -eq 1 && test "$(find agent-task/archive -type f -path '*/m-principal-provider-credential-slot-routing/02+01_credential_catalog/complete.log' -print | wc -l)" -eq 1` — both runtime predecessors exist exactly once.
2. `gofmt -d apps/control-plane/internal/credentialstore/store.go apps/control-plane/internal/credentialstore/principal_test.go apps/control-plane/cmd/control-plane/credential_commands.go apps/control-plane/cmd/control-plane/credential_commands_test.go` — no output.
3. `GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go test -count=50 -race ./apps/control-plane/internal/credentialstore -run 'CreateFirstPrincipalWithToken'` — independent-store first-bootstrap contention passes repeatedly with typed losers.
4. `GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go test -count=1 ./apps/control-plane/cmd/control-plane -run 'PrincipalBootstrap|Bootstrap'` — stdout failure, CLI-only, guard sensitivity, restart, refusal, and redaction tests pass.
5. `GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go test -count=1 ./apps/control-plane/...` — Control Plane regression passes.
6. `GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go vet ./apps/control-plane/...` — no findings.
7. Run exactly:

```bash
set -euo pipefail
bootstrap_race_dir=$(mktemp -d /config/workspace/iop-s0/.cache/bootstrap-race-final.XXXXXX)
case "$bootstrap_race_dir" in
  /config/workspace/iop-s0/.cache/bootstrap-race-final.*) ;;
  *) exit 97 ;;
esac
bootstrap_race_bin="$bootstrap_race_dir/control-plane"
bootstrap_race_db="$bootstrap_race_dir/race.db"
cleanup_bootstrap_race() {
  shopt -s nullglob
  for bootstrap_race_path in "$bootstrap_race_dir"/*; do
    if [ -f "$bootstrap_race_path" ]; then
      unlink "$bootstrap_race_path"
    fi
  done
  rmdir "$bootstrap_race_dir"
}
trap cleanup_bootstrap_race EXIT
GOTMPDIR=/config/workspace/iop-s0/.cache/go-build GOCACHE=/config/workspace/iop-s0/.cache/go-cache go build -o "$bootstrap_race_bin" ./apps/control-plane/cmd/control-plane
set +e
timeout 2s env IOP_DATABASE_URL="$bootstrap_race_db" IOP_LISTEN=127.0.0.1:0 IOP_WIRE_LISTEN=127.0.0.1:0 IOP_EDGE_WIRE_LISTEN=127.0.0.1:0 "$bootstrap_race_bin" --config configs/control-plane.yaml serve >"$bootstrap_race_dir/init.out" 2>"$bootstrap_race_dir/init.err"
bootstrap_init_status=$?
set -e
if [ "$bootstrap_init_status" -ne 0 ] && [ "$bootstrap_init_status" -ne 124 ]; then
  exit 96
fi
test -f "$bootstrap_race_db"
bootstrap_race_pids=()
for i in 1 2 3 4 5; do
  env IOP_DATABASE_URL="$bootstrap_race_db" "$bootstrap_race_bin" --config configs/control-plane.yaml principal bootstrap --alias "race-$i" >"$bootstrap_race_dir/out.$i" 2>"$bootstrap_race_dir/err.$i" &
  bootstrap_race_pids+=("$!")
done
bootstrap_race_statuses=()
for bootstrap_race_pid in "${bootstrap_race_pids[@]}"; do
  set +e
  wait "$bootstrap_race_pid"
  bootstrap_race_statuses+=("$?")
  set -e
done
bootstrap_successes=0
bootstrap_already_exists=0
bootstrap_locked=0
bootstrap_other=0
bootstrap_token_outputs=0
for i in 1 2 3 4 5; do
  if [ "${bootstrap_race_statuses[$((i-1))]}" -eq 0 ]; then
    bootstrap_successes=$((bootstrap_successes+1))
  fi
  if rg -q 'already exists' "$bootstrap_race_dir/err.$i"; then
    bootstrap_already_exists=$((bootstrap_already_exists+1))
  elif rg -q 'locked|SQLITE_BUSY|database is busy' "$bootstrap_race_dir/err.$i"; then
    bootstrap_locked=$((bootstrap_locked+1))
  elif [ "${bootstrap_race_statuses[$((i-1))]}" -ne 0 ]; then
    bootstrap_other=$((bootstrap_other+1))
  fi
  bootstrap_output=$(tr -d '\r\n' < "$bootstrap_race_dir/out.$i")
  if [ "${#bootstrap_output}" -eq 64 ] && [[ "$bootstrap_output" != *[!0-9a-f]* ]]; then
    bootstrap_token_outputs=$((bootstrap_token_outputs+1))
  fi
done
test "$bootstrap_successes" -eq 1
test "$bootstrap_token_outputs" -eq 1
test "$bootstrap_already_exists" -eq 4
test "$bootstrap_locked" -eq 0
test "$bootstrap_other" -eq 0
printf '%s\n' 'PASS: five compiled bootstrap processes produced one token and four typed refusals'
```

8. `git diff --check` — no whitespace errors.

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