<!-- task=m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence plan=0 tag=OFR-S07-REMOTE-AUTH-0 -->

# Capture authenticated S07 repeat-guard evidence on the dev SSH runner

## For the Implementing Agent

Filling every implementation-owned section in `CODE_REVIEW-cloud-G08.md` is mandatory. Keep the active PLAN/CODE_REVIEW files in place and report ready for official review. Do not archive this task, write `complete.log`, update roadmap state, create `USER_REVIEW.md`, or ask the user for a credential or authorization.

This task authorizes at most one newly started live S07 invocation, and only after the non-live source/runtime/provider/authentication preflight passes. A preflight failure consumes zero invocations. Once the Go live test starts, do not retry it for any reason. Never print a raw token, prompt, response, SSE body, private endpoint material, or full token hash.

## Background

Task `02+01_repeat_guard` was explicitly superseded and archived incomplete at the user's direction. Its final remote invocation reached the correct Darwin runner but omitted the live harness's existing `IOP_OPENAI_API_KEY` input, so all five first-run requests returned HTTP 401. Its official reviewer then disappeared while dispatcher state remained `running`.

The incomplete predecessor is preserved at `agent-task/archive/2026/07/m-openai-compatible-output-validation-filters/02+01_repeat_guard/` without `complete.log`. Do not reopen its loop or derive routing/rework history from its logs. The only inherited facts needed here are:

- the remote source/test/runtime/provider preflight passed;
- the single old invocation is consumed and must not be retried;
- no S07 summary was produced;
- the post-failure cleanup probe showed both selected providers idle, no harness process, and unchanged source;
- the harness already reads `IOP_OPENAI_API_KEY` and sends `Authorization: Bearer <token>`.

This task is an independent `03_...` subtask rather than `03+02_...`: incomplete task 02 has no `complete.log`, and encoding it as a runtime predecessor would permanently deadlock scheduling.

## Roadmap Targets

- Milestone: `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/openai-compatible-output-validation-filters.md`
- Milestone link: [Milestone document](agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/openai-compatible-output-validation-filters.md)
- Task ids:
  - `repeat-guard`: rolling content/history/action repetition detection and safe continuation
- Completion mode: check-on-pass

## Analysis

### Files Read

- Workflow and routing: project `AGENTS.md`, project/private rules, roadmap rules, router, plan, code-review, finalize-task-routing, and task-loop orchestration skills.
- Domain and verification: Edge/testing domain rules, `agent-test/dev/rules.md`, `agent-test/dev/edge-smoke.md`, and the dev runtime deployment skill.
- Contract: `agent-contract/outer/openai-compatible-api.md` and `agent-contract/inner/edge-config-runtime-refresh.md`.
- Source oracle: `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`.
- Roadmap/design: the active Phase, Milestone, and approved SDD for OpenAI-compatible output validation filters.
- Narrow predecessor evidence: the active task 02 plan/review and its orphan dispatcher locator before the directory was superseded.

### SDD Criteria

- S07 requires three 5-concurrent runs against `ornith:35b`.
- PASS evidence requires 15 sanitized provider response identities, 15 correlated Edge lifecycles, three capacity rows proving configured capacity 4 with peak in-flight 4 and queued pressure, a valid sanitized final result, and idle cleanup.
- Existing deterministic coverage already supplies S03/S04/S09-S12 evidence. This packet owns only authenticated S07 remote evidence and cleanup.

### Authentication Contract and Root Cause

- When `openai.principal_tokens[]` is configured, callers must send `Authorization: Bearer <token>` whose SHA-256 matches an active mapping; otherwise Edge returns HTTP 401.
- `TestDevRepeatGuardOrnithSmoke` already reads `IOP_OPENAI_API_KEY`, sets the Bearer header, and uses the token only for raw-free observation correlation.
- The task 02 launch command did not set `IOP_OPENAI_API_KEY`. This is the complete explanation for the observed five HTTP 401 responses; no production authentication defect is established.
- The remote `build/dev-runtime/.secrets/openai-principal-tokens.yaml` is mode 0600 and contains only hash/reference metadata. It cannot reconstruct the raw token.
- Read-only preflight found no `IOP_OPENAI_API_KEY` in the non-interactive remote environment and no repository-local `token/` store. Therefore the live command may run only if an operator-controlled raw token is already available either as the remote `IOP_OPENAI_API_KEY` environment variable or through a readable mode-0600 file named by `IOP_OPENAI_SMOKE_API_KEY_FILE`.
- If neither source is available, record `auth_source=missing`, invocation count 0, and the resume condition. The official reviewer must stop through the `external-execution` user-review gate; it must not generate another equivalent plan.

### Verification Context

- Runner: `ssh toki@toki-labs.com`.
- Workdir: `/Users/toki/agent-work/iop-dev`.
- OS/toolchain: Darwin/arm64, `/bin/zsh`, Go 1.26.3.
- Reviewed source baseline: branch `feature/openai-compatible-output-validation-filters`, HEAD `d1e32b6e06f7153a4db5a5a08b7026d6dd49fcfb`, exactly one modified file `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`, SHA-256 `8f0c767d6fb69175c6856fcd58f1398e89b9e13c6597dc950672b14b4013bd21`.
- Runtime: Edge listeners at 18001/18083/18084/19093, four connected nodes, selected providers `onexplayer-lemonade` and `rtx5090-lemonade`, aggregate capacity `3+1`.
- Isolation: prompt and observation sink under `/tmp/iop-repeat-guard-live`; new artifact directory `/tmp/iop-repeat-guard-live/repeat-guard-task-03` must be absent before launch.
- Raw credential source and live authorization are external ownership boundaries. The implementation agent may consume a pre-provisioned credential but may not create, rotate, reveal, or request one.

### Test Coverage Gaps

- No production or test source change is planned. The existing harness already covers authenticated header injection, raw-free correlation, capacity sampling, result classification, summary generation, and cleanup assertions.
- The only missing evidence is a successful authenticated invocation against the declared remote runtime.

### Symbol References

- No symbol is renamed or removed.
- Relevant existing inputs: `IOP_OPENAI_API_KEY`, `IOP_OPENAI_BASE_URL`, and the `IOP_OPENAI_SMOKE_*` variables consumed by `TestDevRepeatGuardOrnithSmoke`.

### Split Judgment

- Keep this as one evidence packet because authentication, provider responses, lifecycle correlations, capacity pressure, result classification, and cleanup must refer to one isolated invocation.
- Task 03 is runtime-independent from superseded task 02. It relies on the current reviewed source/runtime identity, not on predecessor completion.

### Scope Rationale

- Modify only `CODE_REVIEW-cloud-G08.md` with sanitized execution evidence.
- Do not modify production/test source, contracts, specs, tracked config, deployed binaries/config, provider state, prompt content, or archived task 02.
- Remote writes are limited to ignored `/tmp/iop-repeat-guard-live/repeat-guard-task-03` artifacts created by the existing live harness.
- On missing credential, rejected auth probe, source/runtime drift, or consumed live failure, stop and record the exact blocker. Do not repair external state and do not retry.

### Final Routing

- `evaluation_mode=first-pass`; all build/review closures are true; no capability gap is delegated to cloud.
- Build scores `1/2/1/2/2`; base basis `local-fit`; matched risks `temporal_state`, `concurrent_consistency`, `boundary_contract`, and `structured_interpretation`; risk boundary matched; lane `cloud`; grade `G08`; file `PLAN-cloud-G08.md`.
- Review scores `1/2/1/2/2`; basis `official-review`; lane `cloud`; grade `G08`; file `CODE_REVIEW-cloud-G08.md`; adapter `codex`; model `gpt-5.6-sol`; reasoning effort `xhigh`.
- `large_indivisible_context=false`, `review_rework_count=0`, `evidence_integrity_failure=false`.

## Implementation Checklist

- [ ] [OFR-S07-REMOTE-AUTH-0-1] Run the read-only remote source/runtime/provider/authentication preflight. Prove the credential matches an active principal-token hash and `/v1/models` returns HTTP 200 without printing credential material. If unavailable or rejected, record invocation count 0 and stop.
- [ ] [OFR-S07-REMOTE-AUTH-0-2] After every preflight assertion passes, start exactly one fresh 5-concurrent × 3 live invocation, validate the sanitized S07 summary and cleanup, and record only raw-free evidence.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [OFR-S07-REMOTE-AUTH-0-1] Prove the remote runner and authenticated caller path

#### Problem

The prior invocation proved network reachability but sent no IOP Bearer token. Retrying without a credential preflight would consume another live authorization and reproduce the same HTTP 401 failure.

#### Solution

- Resolve a raw token only from the remote `IOP_OPENAI_API_KEY` environment variable or a mode-0600 file named by `IOP_OPENAI_SMOKE_API_KEY_FILE`.
- Compare its SHA-256 internally against the active private principal-token mapping without printing either value.
- Make a non-provider `/v1/models` request through stdin-fed curl configuration and require HTTP 200.
- Reprove source identity, deterministic tests, runtime/listener identity, provider capacity/health/idle state, observation quiescence, and artifact isolation.
- Emit only one sanitized `remote_preflight=PASS ... auth=PASS` line.

#### Modified Files and Checklist

- [ ] `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G08.md` — record sanitized preflight evidence or blocker.
- [ ] No source, config, runtime, or archived-task changes.

#### Test Strategy

Execute the existing focused and package tests with `-count=1` on the same remote checkout. The auth probe is read-only and must not contact a provider.

#### Verification

```bash
ssh -o BatchMode=yes -o ConnectTimeout=15 toki@toki-labs.com '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
set +x
repo=/Users/toki/agent-work/iop-dev
expected_head=d1e32b6e06f7153a4db5a5a08b7026d6dd49fcfb
expected_test_hash=8f0c767d6fb69175c6856fcd58f1398e89b9e13c6597dc950672b14b4013bd21
test_file=apps/edge/internal/openai/stream_gate_vertical_slice_test.go
mapping_file=build/dev-runtime/.secrets/openai-principal-tokens.yaml
artifact_dir=/tmp/iop-repeat-guard-live/repeat-guard-task-03
prompt_file=/tmp/iop-repeat-guard-live/repeat-prompt.txt
observation_file=/tmp/iop-repeat-guard-live/edge-observations.jsonl
cd "$repo"

api_key=${IOP_OPENAI_API_KEY:-}
if [[ -z "$api_key" ]]; then
  api_key_file=${IOP_OPENAI_SMOKE_API_KEY_FILE:-}
  if [[ -z "$api_key_file" || ! -r "$api_key_file" ]]; then
    print 'remote_preflight=BLOCKED auth_source=missing invocation_count=0'
    exit 42
  fi
  test "$(/usr/bin/stat -f %Lp "$api_key_file")" = 600
  IFS= read -r api_key < "$api_key_file"
fi
test -n "$api_key"
test -r "$mapping_file"
test "$(/usr/bin/stat -f %Lp "$mapping_file")" = 600
api_key_hash=$(printf '%s' "$api_key" | /usr/bin/shasum -a 256 | /usr/bin/awk '{print $1}')
/usr/bin/grep -Fq "token_hash_sha256: $api_key_hash" "$mapping_file"

auth_status=$(
  {
    print 'silent'
    print 'show-error'
    print 'output = "/dev/null"'
    printf 'header = "Authorization: Bearer %s"\n' "$api_key"
  } | /usr/bin/curl --config - --write-out '%{http_code}' http://127.0.0.1:18083/v1/models
)
test "$auth_status" = 200

go_bin=$(command -v go)
jq_bin=$(command -v jq)
test "$(uname -s)" = Darwin
test "$(uname -m)" = arm64
test "$("$go_bin" env GOMOD)" = "$repo/go.mod"
test "$(git branch --show-current)" = feature/openai-compatible-output-validation-filters
test "$(git rev-parse HEAD)" = "$expected_head"
test "$(git diff --name-only)" = "$test_file"
test "$(/usr/bin/shasum -a 256 "$test_file" | /usr/bin/awk '{print $1}')" = "$expected_test_hash"
git diff --check
"$go_bin" test -count=1 ./apps/edge/internal/openai -run 'TestDevRepeatGuard(SmokeEvidence|ObservationCorrelation|ObservationQuiescence|CapacityEvidence)'
"$go_bin" test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
"$go_bin" test -count=1 ./packages/go/config
build/dev-runtime/bin/edge --config build/dev-runtime/edge.yaml config check >/dev/null
for port in 18001 18083 18084 19093; do /usr/bin/nc -z 127.0.0.1 "$port"; done
test -s "$prompt_file"
test -f "$observation_file"
test -w "$observation_file"
test ! -e "$artifact_dir"
before=$(/usr/bin/stat -f %z "$observation_file")
sleep 2
after=$(/usr/bin/stat -f %z "$observation_file")
test "$before" = "$after"
! /usr/bin/pgrep -fl '[T]estDevRepeatGuardOrnithSmoke' >/dev/null

edge_pid=$(/usr/sbin/lsof -tiTCP:18083 -sTCP:LISTEN)
test -n "$edge_pid"
edge_exe=$(/usr/sbin/lsof -a -p "$edge_pid" -d txt -Fn | /usr/bin/sed -n 's/^n//p' | /usr/bin/head -1)
test "$(/usr/bin/shasum -a 256 "$edge_exe" | /usr/bin/awk '{print $1}')" = "$(/usr/bin/shasum -a 256 build/dev-runtime/bin/edge | /usr/bin/awk '{print $1}')"

status_file=$(/usr/bin/mktemp -t iop-repeat-status.XXXXXX)
trap '/bin/rm -f "$status_file"; unset api_key api_key_hash' EXIT
/usr/bin/curl -fsS http://127.0.0.1:18001/edges/edge-toki-labs-dev/status > "$status_file"
"$jq_bin" -e '
  def provider($id): first(.nodes[].provider_snapshots[] | select(.id == $id));
  (.edge_id == "edge-toki-labs-dev") and
  ((.nodes | length) == 4) and
  (all(.nodes[]; .connected == true)) and
  (provider("onexplayer-lemonade").capacity == 3) and
  (provider("onexplayer-lemonade").health == "healthy") and
  (provider("onexplayer-lemonade").in_flight == 0) and
  (provider("onexplayer-lemonade").queued == 0) and
  (provider("rtx5090-lemonade").capacity == 1) and
  (provider("rtx5090-lemonade").health == "healthy") and
  (provider("rtx5090-lemonade").in_flight == 0) and
  (provider("rtx5090-lemonade").queued == 0)
' "$status_file" >/dev/null
print "remote_preflight=PASS head=$expected_head test_hash=$expected_test_hash edge_pid=$edge_pid providers=3+1_idle auth=PASS"
REMOTE
```

Expected: exit 0 and a single final sanitized PASS line. Exit 42 with `auth_source=missing` is an external-execution blocker and consumes zero invocations.

### [OFR-S07-REMOTE-AUTH-0-2] Capture one authenticated S07 invocation and cleanup

#### Problem

S07 is incomplete until one isolated invocation produces correlated provider/lifecycle/capacity evidence and returns providers to idle.

#### Solution

- Resolve and internally hash-check the same credential again without output.
- Start the live Go test exactly once with the fresh task-03 artifact directory and `IOP_OPENAI_API_KEY`.
- Do not retry after the Go test process starts, including on HTTP, provider, timeout, SSH, or assertion failure.
- On success, validate only `summary.json` cardinality, uniqueness, capacity, result classification, provider idle recovery, process cleanup, and unchanged source identity.

#### Modified Files and Checklist

- [ ] `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G08.md` — record invocation count 1 and sanitized result/cleanup evidence, or the exact consumed-invocation blocker.
- [ ] No production/test/config/runtime change.

#### Test Strategy

The existing environment-gated `TestDevRepeatGuardOrnithSmoke` is the integrated oracle. Fresh execution is mandatory.

#### Verification

Single authorized invocation:

```bash
ssh -o BatchMode=yes -o ConnectTimeout=15 toki@toki-labs.com '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
set +x
cd /Users/toki/agent-work/iop-dev
mapping_file=build/dev-runtime/.secrets/openai-principal-tokens.yaml
artifact_dir=/tmp/iop-repeat-guard-live/repeat-guard-task-03
api_key=${IOP_OPENAI_API_KEY:-}
if [[ -z "$api_key" ]]; then
  api_key_file=${IOP_OPENAI_SMOKE_API_KEY_FILE:-}
  test -n "$api_key_file"
  test -r "$api_key_file"
  test "$(/usr/bin/stat -f %Lp "$api_key_file")" = 600
  IFS= read -r api_key < "$api_key_file"
fi
test -n "$api_key"
api_key_hash=$(printf '%s' "$api_key" | /usr/bin/shasum -a 256 | /usr/bin/awk '{print $1}')
/usr/bin/grep -Fq "token_hash_sha256: $api_key_hash" "$mapping_file"
test ! -e "$artifact_dir"

IOP_OPENAI_API_KEY="$api_key" \
IOP_OPENAI_BASE_URL=http://127.0.0.1:18083 \
IOP_OPENAI_MODEL=ornith:35b \
IOP_OPENAI_SMOKE_CONCURRENCY=5 \
IOP_OPENAI_SMOKE_RUNS=3 \
IOP_OPENAI_SMOKE_PROMPT_FILE=/tmp/iop-repeat-guard-live/repeat-prompt.txt \
IOP_OPENAI_SMOKE_ARTIFACT_DIR="$artifact_dir" \
IOP_OPENAI_SMOKE_OBSERVATION_FILE=/tmp/iop-repeat-guard-live/edge-observations.jsonl \
IOP_OPENAI_SMOKE_STATUS_URL=http://127.0.0.1:18001/edges/edge-toki-labs-dev/status \
IOP_OPENAI_SMOKE_PROVIDER_IDS=onexplayer-lemonade,rtx5090-lemonade \
"$(command -v go)" test -timeout 90m -count=1 -v ./apps/edge/internal/openai -run '^TestDevRepeatGuardOrnithSmoke$'
REMOTE
```

Expected: invocation count 1 and exit 0. Any started-test failure consumes the invocation and must not be retried.

Sanitized summary and cleanup:

```bash
ssh -o BatchMode=yes -o ConnectTimeout=15 toki@toki-labs.com '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
cd /Users/toki/agent-work/iop-dev
summary=/tmp/iop-repeat-guard-live/repeat-guard-task-03/summary.json
jq_bin=$(command -v jq)
test -f "$summary"
"$jq_bin" -e '
  (.model == "ornith:35b") and (.concurrency == 5) and (.runs == 3) and
  ((.provider_responses | length) == 15) and
  (([.provider_responses[].provider_response_id] | unique | length) == 15) and
  ((.lifecycles | length) == 15) and
  (([.lifecycles[].correlation_id] | unique | length) == 15) and
  ((.capacity_runs | length) == 3) and
  (all(.capacity_runs[];
    (.configured_capacity == 4) and (.peak_in_flight == 4) and
    (.peak_queued >= 1) and (.final_in_flight == 0) and (.final_queued == 0))) and
  ((.result == "not_reproduced") or
    ((.result == "reproduced") and
     any(.lifecycles[];
       (.result == "reproduced") and
       ((.fingerprint // "") | length > 0) and
       (.offset >= 0))))
' "$summary" >/dev/null

status_file=$(/usr/bin/mktemp -t iop-repeat-cleanup.XXXXXX)
trap '/bin/rm -f "$status_file"' EXIT
/usr/bin/curl -fsS http://127.0.0.1:18001/edges/edge-toki-labs-dev/status > "$status_file"
"$jq_bin" -e '
  def provider($id): first(.nodes[].provider_snapshots[] | select(.id == $id));
  (provider("onexplayer-lemonade").in_flight == 0) and
  (provider("onexplayer-lemonade").queued == 0) and
  (provider("rtx5090-lemonade").in_flight == 0) and
  (provider("rtx5090-lemonade").queued == 0)
' "$status_file" >/dev/null
! /usr/bin/pgrep -fl '[T]estDevRepeatGuardOrnithSmoke' >/dev/null
test "$(git rev-parse HEAD)" = d1e32b6e06f7153a4db5a5a08b7026d6dd49fcfb
test "$(git diff --name-only)" = apps/edge/internal/openai/stream_gate_vertical_slice_test.go
test "$(/usr/bin/shasum -a 256 apps/edge/internal/openai/stream_gate_vertical_slice_test.go | /usr/bin/awk '{print $1}')" = 8f0c767d6fb69175c6856fcd58f1398e89b9e13c6597dc950672b14b4013bd21
print 'remote_cleanup=PASS provider_responses=15 edge_correlations=15 capacity_runs=3 providers=idle harness=absent source=unchanged'
REMOTE
```

Expected: exit 0 and the sanitized cleanup PASS line. Do not print `summary.json`.

## Modified Files Summary

| File | Items |
|------|-------|
| `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G08.md` | OFR-S07-REMOTE-AUTH-0-1, OFR-S07-REMOTE-AUTH-0-2 |

## Dependencies and Execution Order

1. Task 03 has no runtime predecessor. Do not wait for or restore incomplete task 02.
2. Run the complete source/runtime/provider/authentication preflight.
3. If the preflight reports missing/rejected authentication or any other mismatch, record invocation count 0 and stop.
4. Only after preflight PASS, start the live Go test exactly once.
5. Run the sanitized summary/cleanup verification and fill all implementation-owned review fields.
6. Official review decides PASS or creates the `external-execution` user-review stop. It must not generate an identical automated follow-up.

## Final Verification

PASS requires: remote preflight exit 0; authenticated `/v1/models` HTTP 200; one and only one started live invocation exiting 0; 15 unique provider responses; 15 unique Edge correlations; three valid capacity rows; an accepted sanitized result; both providers idle; no live harness; unchanged reviewed source/runtime identity; and no secret or raw evidence in tracked files or recorded output.

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