<!-- task=m-iop-owned-single-request-agent-execution/25+23,24_claude_smoke_qualification plan=4 tag=REVIEW_REVIEW_API milestone-task=workspace-binding,claude-smoke -->

# Repair Claude transport preflight and deterministic observation evidence

## For the Implementing Agent

Filling the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` is the mandatory last implementation step. Run every verification command, paste actual stdout/stderr, keep both active files in place, and report ready for review. Only the official code-review skill may append a verdict, archive files, write `complete.log`, create `USER_REVIEW.md`, or classify the next state. This packet permits repository fixes, the bounded disposable dev-candidate refresh, and `--preflight-only`; it expressly forbids `--run` and every other live Claude/provider invocation because the prior one-run authorization was consumed.

## Background

The prior packet generalized workspace admission and built the selected Darwin-arm64 dev candidate successfully, but its sole authorized Claude invocation failed before Edge ingress. The harness accepted `http://127.0.0.1:18083/v1` by probing `/v1/messages`, then passed that unchanged value as `ANTHROPIC_BASE_URL`; Claude Code appends `/v1/messages`, so the actual route shape was `/v1/v1/messages`. A fresh reviewer probe observed 401 at `/v1/messages`, 404 at `/v1/v1/messages`, ingress 0, and no manifest. The same review also observed one failure of the mandatory race suite at the integrated lifecycle metric snapshot even though isolated repeats and a later exact rerun passed. These repository-owned defects must be repaired before another external-execution decision is requested.

## Archive Evidence Snapshot

- Immediate prior plan/review: `agent-task/m-iop-owned-single-request-agent-execution/25+23,24_claude_smoke_qualification/plan_cloud_G10_3.log` and `agent-task/m-iop-owned-single-request-agent-execution/25+23,24_claude_smoke_qualification/code_review_cloud_G10_3.log`; verdict `FAIL`, `review_rework_count=2`, `evidence_integrity_failure=true`.
- Required R1: `scripts/e2e-single-request-claude.sh:652` validates a terminal-`/v1` base against a different Messages URL than Claude Code uses. The authorized live run exited 69, ingress remained 0, and no remote/local manifest was created.
- Required R2: `apps/edge/internal/openai/single_request_handler_test.go:936` reads lifecycle collectors through `prometheus.DefaultGatherer`; the fresh exact race suite once reported `work/success` counter delta 0, while `-race -count=10 -run '^TestAnthropicSingleRequestObservation$'` and a later exact rerun passed.
- Review-owned non-behavioral repair already present in the worktree: current deferred qualification language and the matching test comment now say “approved IOP Node”; dated historical Mac labels remain unchanged.
- The sole live invocation authorization recorded in `user_review_0.log` was consumed. Do not run Claude. A later official review must apply the `external-execution` user-review gate after repository repair and remote preflight are clean.
- Dependency evidence remains `agent-task/archive/2026/08/m-iop-owned-single-request-agent-execution/23+22_error_cancel/complete.log` and `agent-task/archive/2026/08/m-iop-owned-single-request-agent-execution/24+22_claude_smoke_harness/complete.log`.

## Finding Resolution Map

| Finding | Mode | Fix/evidence | Changed precondition |
|---------|------|--------------|----------------------|
| R1 | direct-fix | Make the harness accept only an origin-form IOP base, derive the exact `/healthz` and `/v1/messages` targets, add a terminal-`/v1` zero-child regression, refresh the disposable candidate/runtime identity, and pass origin-based remote preflight. | Preflight will validate the same base composition Claude Code would use; no provider request is needed. |
| R2 | direct-fix | Give the integrated lifecycle assertion a dedicated Prometheus registry through a narrow service test seam, snapshot that registry, and require repeated focused and full race passes. | Verification no longer depends on process-global lifecycle collector history and cannot treat a retry as the acceptance oracle. |

## Analysis

### Files Read

- Routing/rules: project, roadmap, agent-spec, contract, code-review, plan, finalize-task-routing, and local test rules selected by `agent-ops/skills/common/router.md`.
- Current owners: active Milestone and approved SDD; `agent-contract/index.md`; `agent-contract/outer/anthropic-compatible-api.md`; `agent-spec/index.md`; `agent-spec/input/openai-compatible-surface.md`; `agent-spec/runtime/edge-node-execution.md`.
- Complete implementation/test files in this write boundary: `scripts/e2e-single-request-claude.sh`, `apps/edge/internal/service/single_request_metrics.go`, and `apps/edge/internal/openai/single_request_handler_test.go`.
- Build/test context: `Makefile`, `scripts/fixtures/single-request-claude-smoke-manifest.schema.json`, and the prior archived plan/review paths listed above.
- External transport reference: Anthropic's official Claude Code LLM gateway documentation uses an origin-form `ANTHROPIC_BASE_URL`; the client owns the `/v1/messages` suffix.

### SDD Criteria

- S12 still requires one actual request, ingress delta 1, ordered `gemini -> ornith-fast -> gemini`, one terminal, stage/total timing, and verified workspace mutation. This repair packet must not claim S12 PASS or update the deferred outer contract because no new live run is authorized.
- S12 evidence identity requires source, Edge, Node, config, public model, workspace owner, observation log, and metrics to agree. Refresh the candidate binary and runtime-evidence digest after the repository repair before origin-based preflight.
- The `workspace-binding` contribution remains platform-neutral and host-exact. No workspace admission or wire behavior is reopened here.

### Verification Context

- Fresh review PASS: focused config/workspace/bootstrap tests, harness self-test, `bash -n`, `git diff --check`, unchanged proto digest, and `go test -count=1 ./...`.
- Fresh review conflict: the first exact required race command failed at `TestAnthropicSingleRequestObservation` with lifecycle `work/success` delta 0; an isolated `-race -count=10` run, a plain `-count=50` run, and the later exact rerun passed. The recorded prior PASS is therefore not trusted.
- Selected disposable source/workspace remain `/Users/toki/agent-work/iop-s12-validation-20260808/source` and `/Users/toki/agent-work/iop-s12-validation-20260808/workspace`; selected candidate Edge/Node and health/metrics listeners remained alive after the failed run. Preserve unrelated dev and provider processes.
- Canonical Claude executable is `/opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe`, version 2.1.177. The symlink `/opt/homebrew/bin/claude` is intentionally rejected by the harness.
- Safe reviewer probes returned 401 for `OPTIONS http://127.0.0.1:18083/v1/messages`, 404 for `OPTIONS http://127.0.0.1:18083/v1/v1/messages`, health 200, and ingress 0. No secret value or model request was used.
- Cached test output is not acceptable. All commands below use `-count=1` or explicit repeated fresh execution.

### Test Coverage Gaps

- The fake listener uses an `endswith("/v1/messages")` match, so it incorrectly accepts `/v1/v1/messages`; add an exact-path assertion and a terminal-`/v1` preflight-negative case with child count zero.
- The integrated observation test snapshots process-global lifecycle collectors. Inject a dedicated registry and assert the same bounded tuples/logs against it.
- No repository test can authorize or replace S12. This packet stops after a clean remote preflight and leaves the manifest absent.

### Symbol References

- No public HTTP, protobuf, config, schema, or manifest field changes.
- Add one narrow internal service test seam for a caller-supplied Prometheus registerer; production `SetSingleRequestObservationLogger` continues to use `prometheus.DefaultRegisterer` unchanged.
- `ANTHROPIC_BASE_URL`, `base_url_digest`, and `stage_binding_digest` remain existing names. Their selected value changes from terminal-`/v1` to the listener origin.

### Split Judgment

Keep one repair plan. The exact Claude base derivation, fake-listener regression, disposable runtime identity, origin-based preflight, and lifecycle evidence oracle jointly decide whether a later live run is safe. Splitting would allow remote preflight or race evidence to be accepted against an unrepaired half.

### Scope Rationale

Include only URL composition/preflight, the credential-free harness self-test, isolated lifecycle observation test registration, repeated race verification, disposable candidate refresh, and origin-based `--preflight-only`. Exclude `--run`, provider calls, manifest creation/copy, qualification promotion, workspace/config/wire changes, canonical checkout mutation, unrelated dev runtimes, provider-host deployment, credential persistence, and roadmap mutation.

### Final Routing

- `evaluation_mode=isolated-reassessment`; build/review closures `scope`, `context`, `verification`, `evidence`, `ownership`, and `decision` are all true; capability gap is absent.
- Finalizer `finalize-task-policy.sh`, mode `pair`. Build scores `2/2/1/2/2` => G09, base/final `grade-boundary`, `worker/cloud/G09`, `PLAN-cloud-G09.md`. Review scores `2/2/1/2/2` => G09, `official-review`, `review/cloud/G09`, `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`; matched risks are `temporal_state`, `concurrent_consistency`, `boundary_contract`, and `structured_interpretation` (4); `review_rework_count=2`; `evidence_integrity_failure=true`. Risk and recovery boundaries match, but grade-boundary remains authoritative.

## Dependencies and Execution Order

1. Preserve the accepted task-23/task-24 completion evidence and the current platform-neutral workspace implementation.
2. Implement R1 and R2 locally, then pass the harness self-test, focused repeated observation test, and the full required race suite three consecutive times.
3. Overlay only the reviewed changed source files into the disposable remote source, rebuild the selected candidate Edge from that source, replace only the selected candidate Edge process with exact PID/path/config checks and rollback, and regenerate runtime evidence with origin base `http://127.0.0.1:18083`.
4. Prove health, exact Messages route, metrics, source/binary/config/workspace identity, and zero ingress; then execute `--preflight-only` once with the canonical Claude executable. Do not invoke `--run` regardless of outcome.
5. Record all actual output in `CODE_REVIEW-cloud-G09.md`. The official reviewer owns the later external-execution decision.

## Implementation Checklist

- [ ] Make the S12 harness enforce origin-form Claude base composition and add exact-route, terminal-`/v1`, zero-child self-test coverage.
- [ ] Isolate the integrated single-request lifecycle metric registry and pass focused plus full race verification without retry-based acceptance.
- [ ] Refresh only the disposable selected candidate, regenerate origin-bound runtime identity, pass remote `--preflight-only` with no Claude child, and retain deferred S12 state with no manifest.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_REVIEW_API-1] Enforce the exact Claude Code base URL contract

**Problem**

`scripts/e2e-single-request-claude.sh:652-666` treats a path ending in `/v1` as already versioned and probes `/v1/messages`. At lines 771-794 the harness passes the same base to Claude Code, whose gateway contract appends `/v1/messages`; the successful preflight therefore approved a route shape different from the live client route. The self-test listener at lines 1293-1303 uses a suffix match and cannot expose the double-`/v1` defect.

**Solution**

Add a base-specific validator that accepts only `http|https` URLs with host and an empty/root path, no credentials, query, or fragment. Derive health as `<origin>/healthz` and Messages as `<origin>/v1/messages`; never strip or reinterpret a caller-supplied `/v1`. Change the fake listener to match `/v1/messages` exactly. Add one fixture whose base ends in `/v1`, whose runtime digest is internally consistent, and whose preflight must fail before a Claude child or output. Keep generic metrics URL validation unchanged because `/metrics` is valid there.

Before (`scripts/e2e-single-request-claude.sh:656`):

```python
path = parsed.path.rstrip("/")
if path.endswith("/v1"):
    listener_path = path[:-3]
    messages_path = path + "/messages"
else:
    listener_path = path
    messages_path = path + "/v1/messages"
```

After:

```python
if parsed.path not in {"", "/"}:
    raise SystemExit(1)
origin = urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))
print(origin + "/healthz")
print(origin + "/v1/messages")
```

**Modified Files and Checklist**

- [ ] Update `scripts/e2e-single-request-claude.sh` base validation, exact probe derivation, fake listener matching, positive fixtures, negative terminal-`/v1` fixture, and final self-test summary.

**Test Strategy**

Write the regression in the existing credential-free Python self-test. Assert origin-form positive/authenticated preflight still passes, terminal-`/v1` fails, Claude marker count remains zero, no output/partial publication remains, and error text contains no raw base or secret.

**Verification**

`bash -n scripts/e2e-single-request-claude.sh && make test-single-request-claude-smoke-self-test` must pass and the self-test output must mention exact Claude base-route coverage.

### [REVIEW_REVIEW_API-2] Isolate the integrated lifecycle observation oracle

**Problem**

`apps/edge/internal/openai/single_request_handler_test.go:854-861` installs the production default lifecycle collectors, and lines 936-959 snapshot them through `prometheus.DefaultGatherer`. The fresh mandatory race suite observed a zero `work/success` delta once, but focused repeats and a later exact rerun passed. A required integrated oracle must not depend on process-global collector history or pass only after retry.

**Solution**

Add a narrow internal service method that constructs `newSingleRequestObservability` with a caller-supplied `prometheus.Registerer` and logger, explicitly documented as an integration-test seam. Keep `SetSingleRequestObservationLogger` unchanged for production bootstrap. In `TestAnthropicSingleRequestObservation`, create one `prometheus.NewRegistry`, install it through the seam, and use it for both before/after lifecycle snapshots. Retain the default ingress counter assertion, exact eight log records, all bounded label tuples, privacy assertions, one HTTP request, two tools, one cleanup, and one terminal. Do not add sleeps or accept rerun success as a substitute.

Before (`apps/edge/internal/openai/single_request_handler_test.go:861`):

```go
service.SetSingleRequestObservationLogger(obsLogger)
beforeCounters, beforeHistograms, err := snapshotSingleRequestMetrics(prometheus.DefaultGatherer)
```

After:

```go
lifecycleRegistry := prometheus.NewRegistry()
service.SetSingleRequestObservationLoggerForTesting(lifecycleRegistry, obsLogger)
beforeCounters, beforeHistograms, err := snapshotSingleRequestMetrics(lifecycleRegistry)
```

**Modified Files and Checklist**

- [ ] Update `apps/edge/internal/service/single_request_metrics.go` with the narrow registerer-injection test seam while preserving production default registration.
- [ ] Update `apps/edge/internal/openai/single_request_handler_test.go` to use one dedicated lifecycle registry and retain every existing end-to-end assertion.

**Test Strategy**

Modify the existing integrated regression rather than adding a duplicate. Run it under `-race -count=20`, then run the complete required race package set three fresh consecutive times. Any failure fails the item; do not rerun until green.

**Verification**

`go test -race -count=20 ./apps/edge/internal/openai -run '^TestAnthropicSingleRequestObservation$'` must pass, followed by the three-run command in Final Verification.

### [REVIEW_REVIEW_API-3] Refresh the disposable candidate and stop after origin-based preflight

**Problem**

The disposable selected candidate and `build/s12/runtime/runtime-evidence.json` were built from the prior source and bind the incorrect terminal-`/v1` base. The current one-run authorization has already been consumed, so another live invocation would exceed authority even after the repository repair.

**Solution**

After all local tests pass, copy only the reviewed R1/R2 source changes into `/Users/toki/agent-work/iop-s12-validation-20260808/source`, verify its worktree, rebuild the selected Edge, and restart only its exact candidate Edge process with the existing candidate config and a rollback to the previous candidate binary/process on preflight setup failure. Leave the selected Node and all unrelated runtimes/providers untouched. Regenerate the closed runtime-evidence file so source worktree, Edge digest/version, origin `base_url_digest`, and derived `stage_binding_digest` match. Verify `/healthz`=200, `/v1/messages`=401 or 405, `/v1/v1/messages`=404, metrics ingress remains 0, and no manifest/workspace result exists. Run exactly one `--preflight-only` using the canonical non-symlink Claude executable and origin base. Never run `--run`.

**Modified Files and Checklist**

- [ ] Record exact non-secret overlay/build/process/rollback/runtime-evidence/route/metric/preflight facts in `agent-task/m-iop-owned-single-request-agent-execution/25+23,24_claude_smoke_qualification/CODE_REVIEW-cloud-G09.md`.
- [ ] Confirm `agent-test/evidence/iop-owned-single-request-agent-execution/claude-smoke-evidence.json` remains absent and all three current qualification owners remain deferred.

**Test Strategy**

No live integration test is authorized. Use the credential-free local self-test plus the remote IOP listener checks and `--preflight-only`. Capture only status codes, digests, versions, PIDs, paths, and closed harness messages; never capture the API-key value, prompt, model output, or raw provider response.

**Verification**

The remote commands in Final Verification must pass once with origin base and no Claude invocation. A setup or preflight failure is recorded and stops implementation; it never authorizes `--run`.

## Modified Files Summary

| File | Items |
|------|-------|
| `scripts/e2e-single-request-claude.sh` | REVIEW_REVIEW_API-1 |
| `apps/edge/internal/service/single_request_metrics.go` | REVIEW_REVIEW_API-2 |
| `apps/edge/internal/openai/single_request_handler_test.go` | REVIEW_REVIEW_API-2 |
| `agent-task/m-iop-owned-single-request-agent-execution/25+23,24_claude_smoke_qualification/CODE_REVIEW-cloud-G09.md` | REVIEW_REVIEW_API-1, REVIEW_REVIEW_API-2, REVIEW_REVIEW_API-3 |

## Final Verification

Fresh output is required. Commands 1-7 are local or read-only remote checks. Command 8 refreshes only the already-selected disposable candidate. Command 9 is `--preflight-only`. No command in this packet may contain `--run` or make a live Claude/provider request.

1. `bash -n scripts/e2e-single-request-claude.sh && make test-single-request-claude-smoke-self-test` — exact origin route, terminal-`/v1` rejection, zero-child preflight, binding, redaction, cleanup, signals, and atomic publication self-tests pass.
2. `go test -race -count=20 ./apps/edge/internal/openai -run '^TestAnthropicSingleRequestObservation$'` — the dedicated-registry integrated lifecycle test passes twenty fresh race iterations.
3. `bash -c 'set -euo pipefail; for run in 1 2 3; do go test -race -count=1 ./packages/go/config ./packages/go/streamgate ./apps/edge/internal/openai ./apps/edge/internal/service ./apps/node/internal/bootstrap ./apps/node/internal/node ./apps/node/internal/transport ./apps/node/internal/workspace; done'` — the exact required race suite passes three consecutive fresh runs; a failed iteration fails the command.
4. `go test -count=1 ./...` — the full Go suite passes freshly.
5. `make proto && git diff --exit-code -- proto/gen/iop` — generated protobuf output is unchanged.
6. `rg --sort path -n 'fixed to "darwin"|fixed Darwin|Mac Node|Actual Claude/Mac|workspace_os.*const.*darwin' --glob '!agent-task/archive/**' --glob '!agent-roadmap/archive/**' --glob '!agent-task/**/plan_*.log' --glob '!agent-task/**/code_review_*.log' --glob '!agent-task/**/user_review_*.log' agent-contract agent-spec agent-test configs packages apps scripts` — output is limited to dated history or selected-runner/build facts; no current normative Mac-only claim remains.
7. `ssh -o BatchMode=yes toki@toki-labs.com 'set -eu; cd /Users/toki/agent-work/iop-s12-validation-20260808/source; test -d /Users/toki/agent-work/iop-s12-validation-20260808/workspace; test -w /Users/toki/agent-work/iop-s12-validation-20260808/workspace; test ! -e /Users/toki/agent-work/iop-s12-validation-20260808/workspace/smoke-result.txt; test ! -e agent-test/evidence/iop-owned-single-request-agent-execution/claude-smoke-evidence.json; test "$(curl -sS -o /dev/null -w "%{http_code}" http://127.0.0.1:18083/healthz)" = 200; code="$(curl -sS -o /dev/null -w "%{http_code}" -X OPTIONS http://127.0.0.1:18083/v1/messages)"; test "$code" = 401 -o "$code" = 405; test "$(curl -sS -o /dev/null -w "%{http_code}" -X OPTIONS http://127.0.0.1:18083/v1/v1/messages)" = 404; curl -fsS http://127.0.0.1:19101/metrics | grep -Eq "^iop_anthropic_single_request_ingress_total 0(\\.0+)?$"'` — current candidate still has zero ingress and the good/bad route distinction is proven without credentials.
8. `ssh -o BatchMode=yes toki@toki-labs.com 'set -eu; cd /Users/toki/agent-work/iop-s12-validation-20260808/source; build/s12/bin/iop-edge config check --config build/s12/runtime/edge.yaml; build/s12/bin/iop-edge version; build/s12/bin/iop-node-darwin-arm64 version; test "$(uname -s)" = Darwin; test "$(uname -m)" = arm64; curl -fsS http://127.0.0.1:18083/healthz >/dev/null; curl -fsS http://127.0.0.1:19101/metrics | grep -Eq "^iop_anthropic_single_request_ingress_total 0(\\.0+)?$"; test ! -e agent-test/evidence/iop-owned-single-request-agent-execution/claude-smoke-evidence.json'` — after the reviewed overlay/build/restart/runtime-evidence refresh, exact binaries/config/host/listeners remain healthy with zero ingress and no manifest.
9. `ssh -o BatchMode=yes toki@toki-labs.com 'IFS= read -r ANTHROPIC_API_KEY; export ANTHROPIC_API_KEY; cd /Users/toki/agent-work/iop-s12-validation-20260808/source; exec ./scripts/e2e-single-request-claude.sh --preflight-only --claude /opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe --runtime-evidence build/s12/runtime/runtime-evidence.json --base-url http://127.0.0.1:18083 --model iop-single-request-light --edge-bin build/s12/bin/iop-edge --node-bin build/s12/bin/iop-node-darwin-arm64 --edge-config build/s12/runtime/edge.yaml --observation-file build/s12/runtime/edge.log --metrics-url http://127.0.0.1:19101/metrics --workspace /Users/toki/agent-work/iop-s12-validation-20260808/workspace --output /Users/toki/agent-work/iop-s12-validation-20260808/source/agent-test/evidence/iop-owned-single-request-agent-execution/claude-smoke-evidence.json --secret-env ANTHROPIC_API_KEY' < /config/workspace/iop/token/.claude` — exits zero with the origin base and without starting Claude; the secret is not printed.
10. `bash -c 'set -euo pipefail; test ! -e agent-test/evidence/iop-owned-single-request-agent-execution/claude-smoke-evidence.json; rg --sort path -n "actual external Claude qualification remains explicitly deferred|Actual Claude timing evidence on an approved IOP Node is explicitly deferred|actual Claude timing evidence on an approved IOP Node is explicitly deferred" agent-contract/outer/anthropic-compatible-api.md agent-spec/runtime/edge-node-execution.md agent-spec/input/openai-compatible-surface.md; git diff --check'` — no manifest or qualification promotion exists, the bounded owners remain deferred, and diff hygiene passes.

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