<!-- task=m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence plan=7 tag=REVIEW_OFR-S07-TERMINAL-FRAMING-7 -->

# Close the Chat tunnel terminal contract before one fresh S07 run

## For the Implementing Agent

Filling implementation-owned sections in `CODE_REVIEW-cloud-G10.md` is mandatory. Implement the scoped changes, run every applicable verification command, record actual notes/output in the review file, keep the active pair in place, and report ready for official review.

If blocked, record the exact blocker, attempted command/output, mutation and invocation counts, 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, write `complete.log`, or modify roadmap state. Review finalization belongs to the code-review skill.

The remote portion authorizes one isolated source overlay, one candidate Edge build, one controlled Edge replacement/restart, and at most one new foreground S07 model invocation on the fresh plan-7 artifact path after every gate passes. A failed candidate readiness gate may restore and restart the preserved prior Edge binary once; in that case stop with `invocation_count=0`.

## Background

The plan-6 live smoke exposed a real contract defect: after an accepted Chat tunnel prefix was committed, repeat recovery exhausted its three dispatches and Core committed an error terminal, but the tunnel release sink wrote neither an error SSE event nor `[DONE]`. The caller therefore received a truncated `200` stream, and the live validator would also reject the correct error-event-plus-`[DONE]` sequence because it currently counts those two frames as two terminals. This follow-up fixes both ends of that contract, proves them locally, deploys only the reviewed Edge candidate through an isolated remote source tree, and permits one non-retryable S07 run at a fresh path.

## Archive Evidence Snapshot

- `plan_cloud_G10_6.log` / `code_review_cloud_G10_6.log`: FAIL with two Required findings. The preserved plan-6 artifact has no accepted summary; its first caller response has zero error events and zero `[DONE]` markers even though correlated observations show four repeat violations, three recovery dispatches, and one committed internal error terminal.
- The first Required finding is in `apps/edge/internal/openai/stream_gate_release_sink.go`: a post-header tunnel error returns `TerminalCommitted` without caller-visible terminal wire. The Chat tunnel path must append one sanitized error event and exactly one `[DONE]` without replaying rejected provider bytes.
- The second Required finding is in `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`: `validateDevRepeatGuardSSE` treats an error event and its required following `[DONE]` as two terminals. It must validate one logical terminal sequence.
- Fresh reviewer checks passed the current focused fixtures with `go1.26.2 linux/arm64`. The remote dev checkout is clean at `750cb1d1cb88066a10d3c703c99f1326306d8e15`; the two production files currently match the local workspace byte-for-byte, while the live test file intentionally differs because the local workspace contains the task's pending evidence improvements.
- Remote preflight found Darwin/arm64, `/opt/homebrew/bin/go` `go1.26.3`, Edge PID `91797` with parent `1`, executable/config `build/dev-runtime/bin/edge` / `build/dev-runtime/edge.yaml`, listeners `18001/18083/18084/19093`, four connected nodes, idle healthy OneXPlayer/RTX5090 capacity `3+1`, no live harness, preserved plan-6 artifact without summary, and an absent plan-7 result path.
- Preserve every existing `/tmp/iop-repeat-guard-live/repeat-guard-task-03-*` artifact. New paths are `/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source`, `/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-edge-backup`, and `/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7`.

## 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

- `apps/edge/internal/openai/stream_gate_release_sink.go`
- `apps/edge/internal/openai/stream_gate_tunnel_codec.go`
- `apps/edge/internal/openai/stream_gate_runtime.go`
- `apps/edge/internal/openai/sse_writer.go`
- `apps/edge/internal/openai/stream_gate_pipeline_test.go`
- `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`
- `go.mod`
- `Makefile`
- `docs/edge-local-dev-guide.md`
- `agent-ops/rules/project/domain/edge/rules.md`
- `agent-ops/rules/project/domain/testing/rules.md`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`
- `agent-test/local/testing-smoke.md`
- `agent-spec/runtime/stream-evidence-gate.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/inner/edge-node-runtime-wire.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/openai-compatible-output-validation-filters.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/sdd/openai-compatible-output-validation-filters.md`
- `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/plan_cloud_G10_6.log`
- `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/code_review_cloud_G10_6.log`

### SDD Criteria

- SDD: `agent-roadmap/phase/knowledge-tool-optimization-extension/sdd/openai-compatible-output-validation-filters.md`; status is approved and the implementation lock is released.
- Targeted Acceptance Scenario S03 requires a repeated live stream to continue safely and end with exactly one `[DONE]`.
- Targeted Acceptance Scenario S07 requires `ornith:35b`, `stream=true`, capacity+1 concurrency for at least three runs, with a sanitized reproduced fingerprint/offset or `not_reproduced` result.
- The Evidence Map associates S03 with `repeat-guard` deterministic continuation evidence and S07 with the live capacity smoke. This packet uses the deterministic post-open cap-exhaustion regression as the S03 gate and the single fresh 5-concurrent x 3-run invocation as the remaining S07 evidence.
- PASS reports only `repeat-guard`; it does not claim the broader `ops-evidence` row.

### Verification Context

- Handoff source: the archived plan-6 review provides the exact live failure, mutation/invocation counts, preserved artifact path, and two Required findings. Repository-native fallback evidence confirms the sink behavior, endpoint codec state, SSE writer framing, validator state machine, and existing fixtures.
- Local runner: current workspace, branch `feature/openai-compatible-output-validation-filters`, HEAD `213eee4e28dfa69ff1e412faf23978ee9a9a3b9f`, dirty with pre-existing user/task changes. Go is `go1.26.2 linux/arm64`; `go env GOMOD` must resolve to this workspace.
- Local baseline: `go test -count=1 ./apps/edge/internal/openai -run '^(TestStreamGateProviderPoolExhaustionTerminatesWithoutPathLeak|TestRepeatGuardStreamOpenNoDuplicatePrefix|TestDevRepeatGuardSmokeEvidence)$'` passed before planning.
- Required local profile: `go test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai`, plus the new focused terminal and validator regressions and `git diff --check`.
- The user explicitly prohibited invoking `dispatch.py` or `orchestrate-agent-task-loop`; therefore plan write claims are manually constrained to the exact files in `Modified Files Summary` and no dispatcher validation command is part of this packet.

#### External Verification Preflight

- Runner/workdir: `ssh toki@toki-labs.com`, source checkout `/Users/toki/agent-work/iop-dev`, Darwin/arm64.
- Remote source: clean branch `feature/openai-compatible-output-validation-filters`, HEAD `750cb1d1cb88066a10d3c703c99f1326306d8e15`. Do not edit it. Build/test from the fresh isolated plan-7 source tree populated from that HEAD plus the three reviewed local files.
- Dependency: `/Users/toki/agent-work/proto-socket/go` supplies the sibling `go.mod` replace target and must be copied into the isolated plan-7 root before testing.
- Toolchain: `/opt/homebrew/bin/go` `go1.26.3 darwin/arm64`; `/usr/bin/tar`, `/usr/bin/ditto`, `/usr/bin/shasum`, `/usr/bin/curl`, `/opt/homebrew/bin/jq`, `/opt/homebrew/bin/sops`, and `docker` are required.
- Runtime identity: native Edge `edge-toki-labs-dev`; current command `build/dev-runtime/bin/edge --config build/dev-runtime/edge.yaml serve`; Control Plane HTTP `18001`; Edge OpenAI `18083`; refresh `18084`; node transport `19093`.
- Runtime state: current executable hash matches `build/dev-runtime/bin/edge`; four nodes are connected; selected providers are `onexplayer-lemonade` capacity 3 and `rtx5090-lemonade` capacity 1, both healthy/available with `in_flight=0 queued=0`; no smoke harness is running.
- Source sync mismatch: the remote checkout cannot represent the pending local fix. Create an isolated remote archive from remote HEAD, overlay exactly `stream_gate_release_sink.go`, `stream_gate_tunnel_codec.go`, and `stream_gate_vertical_slice_test.go`, verify their SHA-256 manifest, run tests/build there, then install only the candidate binary. Keep the remote checkout clean.
- Deployment boundary: preserve the current binary at the fresh backup path, stop the current Edge once, atomically install the candidate, start once, and require a new PID, candidate hash, all four listeners, four reconnected nodes, and idle `3+1` providers. A readiness failure authorizes one rollback to the preserved binary and forbids the model invocation.
- Credential boundary: use only host-local SOPS token ref `toki-dev-pi`, never print the token/header/hash, and require authenticated `/v1/models` HTTP 200.
- Evidence/artifacts: plan-6 is preserved and has no summary; plan-7 source, backup, and result paths must all be absent before their first use. The model invocation remains caller-owned in the foreground and is never retried after `remote_live_start`.
- Confidence: high for the code and deployment diagnosis because the exact sink branch, remote process identity, source hashes, and correlated terminal observation agree. The model's repeat outcome remains probabilistic, so both accepted S07 classifications remain valid.

### Test Coverage Gaps

- Existing normalized Chat and Responses sinks already cover their endpoint-native error terminals, but no current test drives a Chat tunnel through accepted-prefix commit, repeat recovery exhaustion, and post-open error terminal rendering. Add this production-path regression.
- Existing tunnel codec tests cover endpoint parsing and byte-preserving success terminals, but they do not expose endpoint identity to the release sink for post-open host-generated terminal framing. Add endpoint-state assertions through the new regression without changing Responses framing.
- `TestDevRepeatGuardSmokeEvidence` currently accepts an error event without `[DONE]` and lacks invalid order/duplication/mixed-state cases. Expand its table to prove the logical terminal grammar.
- Local fixtures cannot prove deployment identity, provider capacity, or the probabilistic S07 outcome. The isolated remote build, binary hash/readiness gates, and one fresh live run close those gaps.

### Symbol References

- No public symbol is renamed or removed.
- `newOpenAITunnelEndpointCodec` call sites are in `stream_gate_runtime.go`, `stream_gate_pipeline_test.go`, and `stream_gate_vertical_slice_test.go`; the plan preserves its signature and records endpoint identity in the shared codec state.
- `openAITunnelCodecStateForSink` and `openAITunnelReleaseSink.CommitTerminal` are the internal ownership boundary. The state must remain request-local and reset-safe across recovery attempts.
- `validateDevRepeatGuardSSE` is used only by the live smoke attempt and its focused evidence test.

### Split Judgment

Keep the fix, local proof, deployment, and one live run in one packet. The indivisible invariant is that the same endpoint-aware terminal grammar must be produced by the deployed Chat tunnel and accepted by the evidence validator; a split could pass one half while preserving the exact live truncation or a false validator rejection.

### Scope Rationale

- Modify only the tunnel codec state, tunnel release sink, and vertical-slice tests. `stream_gate_runtime.go`, normalized Chat/Responses sinks, non-stream tunnel behavior, provider raw non-2xx passthrough, Core recovery policy, configs, contracts, and public schemas are excluded.
- Do not normalize or rewrite provider success frames. The only new host-authored wire is the sanitized Chat error event plus one `[DONE]` after a committed Chat SSE prefix.
- Responses post-open behavior is explicitly out of scope and must remain byte-compatible.
- Remote writes are limited to the three fresh plan-7 temporary paths, the candidate Edge binary installation, and its process lifecycle. Do not change remote tracked source, Control Plane, Nodes, providers, configs, credentials, or prior artifacts.

### Final Routing

- `evaluation_mode=isolated-reassessment`
- `finalizer=finalize-task-policy.sh`, `finalizer_mode=pair`
- Build closure: complete repository implementation, local deterministic verification, isolated remote source sync/build, controlled deployment, and one bounded live smoke; scores `2/2/2/2/2`; base/final route basis `grade-boundary`; lane `cloud`; grade `G10`; filename `PLAN-cloud-G10.md`.
- Review closure: official correctness, API-contract, evidence, deployment, and SDD review; scores `2/2/2/2/2`; route basis `official-review`; lane `cloud`; grade `G10`; filename `CODE_REVIEW-cloud-G10.md`; adapter `codex`, model `gpt-5.6-sol`, reasoning effort `xhigh`.
- `large_indivisible_context=false`
- Matched loop-risk signatures: `temporal_state`, `boundary_contract`, `structured_interpretation`; `loop_risk_count=3`.
- `review_rework_count=7`
- `evidence_integrity_failure=false`
- Capability gap: none. The cloud route follows the G10 grade boundary; the recovery boundary is also present but does not replace the base route basis.

## Implementation Checklist

- [ ] [REVIEW_OFR-S07-TERMINAL-FRAMING-7-1] Make the request-local tunnel codec state expose its Chat/Responses endpoint safely, render exactly one sanitized Chat error event plus one `[DONE]` when an error terminal is committed after a Chat SSE prefix, preserve all pre-header/non-stream/Responses behavior, and add a production-path cap-exhaustion regression.
- [ ] [REVIEW_OFR-S07-TERMINAL-FRAMING-7-2] Rewrite the live SSE validator as a logical terminal-sequence validator and expand focused evidence tests for valid success/error sequences and every missing, duplicate, mixed, or post-`[DONE]` rejection case; run fresh local focused and profile tests.
- [ ] [REVIEW_OFR-S07-TERMINAL-FRAMING-7-3] Build and test an isolated remote source overlay containing exactly the three reviewed files, replace/restart the dev Edge once with verified rollback protection, then run at most one foreground 5-concurrent x 3-run S07 invocation on the fresh plan-7 artifact path and validate sanitized summary/cleanup evidence.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_OFR-S07-TERMINAL-FRAMING-7-1] Render the post-open Chat tunnel error terminal

#### Problem

`apps/edge/internal/openai/stream_gate_release_sink.go:388` treats an error after `wroteHeader` as a legacy truncated tunnel and returns without terminal wire. In the plan-6 failure, an accepted provider prefix opened a `200` Chat SSE response, repeat recovery later exhausted, and that branch discarded the caller's only terminal signal. `openAITunnelReleaseSink` is shared with Responses and buffered tunnel paths, so unconditional Chat framing would corrupt other endpoint contracts.

#### Solution

Record the validated endpoint in `openAITunnelCodecState` when `newOpenAITunnelEndpointCodec` is constructed. Keep that endpoint binding request-local and stable across per-attempt `reset`; do not change the codec constructor signature or the runtime call sites.

Before:

```go
if !s.wroteHeader {
    writeError(...)
    return streamgate.CommitStateTerminalCommitted, nil
}
return streamgate.CommitStateTerminalCommitted, nil
```

After:

```go
if !s.wroteHeader {
    writeError(...)
    return streamgate.CommitStateTerminalCommitted, nil
}
if s.codec.endpointIsChat() && !s.buffered {
    writeSSEErrorWithType(s.w, s.flusher, "run_error", openAIStreamGateErrorMessage(tr))
}
return streamgate.CommitStateTerminalCommitted, nil
```

Use a lock-safe endpoint query. The existing `writeSSEErrorWithType` is the canonical sanitized `data: {"error":...}` plus `data: [DONE]` renderer. Do not replay the codec's rejected release/terminal queues, change the already-committed status, or emit this framing for Responses/non-stream/pre-header/provider-raw-error branches.

Add a vertical-slice regression that opens a Chat tunnel, releases one accepted prefix exactly once, drives repeat violations through all three allowed recovery dispatches, and asserts one committed error terminal. The caller wire must contain the accepted prefix, one sanitized error envelope, exactly one `[DONE]`, no rejected attempt fragment, no event after `[DONE]`, and no duplicate terminal. Assert terminal status and dispatch count as well.

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/stream_gate_tunnel_codec.go` - bind/query endpoint identity in request-local codec state without changing public or runtime signatures.
- [ ] `apps/edge/internal/openai/stream_gate_release_sink.go` - render only the post-open streaming Chat error terminal with the canonical SSE helper.
- [ ] `apps/edge/internal/openai/stream_gate_vertical_slice_test.go` - add the post-open Chat tunnel recovery-cap regression and preserve Responses/raw passthrough coverage.
- [ ] `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G10.md` - record design, exact test names, outputs, and any deviations.

#### Test Strategy

Write a deterministic vertical-slice test using existing scripted provider-pool/tunnel fixtures and observation helpers. It must exercise the production codec, Core recovery loop, and release sink together rather than calling the new endpoint query in isolation. Existing pipeline tests remain regression coverage for Chat/Responses success wire and raw non-2xx passthrough.

### [REVIEW_OFR-S07-TERMINAL-FRAMING-7-2] Validate one logical SSE terminal sequence

#### Problem

`validateDevRepeatGuardSSE` increments `terminalCount` once for an error envelope and again for the mandatory following `[DONE]`. Its current test therefore calls an error event without `[DONE]` valid, contradicting the endpoint contract that every streaming Chat sequence ends with exactly one `[DONE]`.

#### Solution

Replace the scalar terminal count with explicit sequence state: event count, `sawError`, `sawSuccessFinish`, `sawDone`, and `doneWasFinal`. Parse Chat `choices[].finish_reason` so a successful completion can be distinguished from an error terminal. Enforce:

- success: zero errors, one success finish, then exactly one final `[DONE]`;
- error: exactly one error envelope, zero success finishes, then exactly one final `[DONE]`;
- all other data after `[DONE]`, duplicate `[DONE]`, duplicate error, missing `[DONE]`, error plus success finish, or success finish plus error are invalid;
- provider response identity remains required, stable, and provider-native; the host-authored error frame may omit `id` after an earlier provider frame established it.

Return terminal classification `done` for success and `error` for error even though both physical sequences end in `[DONE]`.

Expand `TestDevRepeatGuardSmokeEvidence` with valid success and valid error+`[DONE]`, missing error `[DONE]`, duplicate error, duplicate `[DONE]`, event after `[DONE]`, mixed finish/error in both orders, missing success finish when applicable, malformed JSON, missing/mixed identity, and non-2xx cases.

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/stream_gate_vertical_slice_test.go` - implement the sequence state machine and focused table coverage.
- [ ] `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G10.md` - record focused/profile test commands and uncached results.

#### Test Strategy

Run:

```bash
go version
go env GOMOD
go test -count=1 ./apps/edge/internal/openai -run '^(TestStreamGateChatTunnelRepeatRecoveryExhaustionTerminatesSSE|TestDevRepeatGuardSmokeEvidence)$'
go test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
git diff --check
```

Use the exact new regression name shown above. All Go tests must execute uncached and exit `0`.

### [REVIEW_OFR-S07-TERMINAL-FRAMING-7-3] Deploy the reviewed candidate and run one fresh S07 smoke

#### Problem

Local fixtures cannot prove the dev Edge serves the fixed bytes or that S07 reaches the required `3+1` capacity boundary for three runs. The clean remote checkout predates the pending local work, so running its binary/test again would only reproduce the known truncation.

#### Solution

Use the remote clean checkout only as an immutable base. Create a fresh isolated source root, copy its clean HEAD through `git archive`, copy the clean sibling `proto-socket/go`, and overlay exactly the three workspace files claimed by this plan. Generate a local SHA-256 manifest and require the remote overlay to verify against it.

From the local workspace:

```bash
set -euo pipefail
remote=toki@toki-labs.com
remote_repo=/Users/toki/agent-work/iop-dev
stage_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source
source_root="$stage_root/iop"
manifest=$(/usr/bin/mktemp -t iop-plan-7-overlay.XXXXXX)
trap '/bin/rm -f "$manifest"' EXIT
files=(
  apps/edge/internal/openai/stream_gate_release_sink.go
  apps/edge/internal/openai/stream_gate_tunnel_codec.go
  apps/edge/internal/openai/stream_gate_vertical_slice_test.go
)
sha256sum "${files[@]}" >"$manifest"

ssh -o BatchMode=yes -o ConnectTimeout=15 "$remote" '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
remote_repo=/Users/toki/agent-work/iop-dev
stage_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source
source_root="$stage_root/iop"
test ! -e "$stage_root"
test "$(cd "$remote_repo" && git rev-parse HEAD)" = 750cb1d1cb88066a10d3c703c99f1326306d8e15
test -z "$(cd "$remote_repo" && git status --porcelain)"
/bin/mkdir -p "$source_root" "$stage_root/proto-socket"
(cd "$remote_repo" && git archive HEAD) | /usr/bin/tar -xf - -C "$source_root"
/usr/bin/ditto /Users/toki/agent-work/proto-socket/go "$stage_root/proto-socket/go"
print -r -- 750cb1d1cb88066a10d3c703c99f1326306d8e15 >"$stage_root/base-head"
REMOTE

/usr/bin/tar -cf - "${files[@]}" |
  ssh -o BatchMode=yes -o ConnectTimeout=15 "$remote" \
    "/usr/bin/tar -xf - -C '$source_root'"
scp -q -o BatchMode=yes -o ConnectTimeout=15 "$manifest" "$remote:$stage_root/overlay.sha256"
ssh -o BatchMode=yes -o ConnectTimeout=15 "$remote" \
  "cd '$source_root' && /usr/bin/shasum -a 256 -c '$stage_root/overlay.sha256'"
```

On the remote host, run the full profile test from the isolated root, build a candidate, and config-check it:

```bash
ssh -o BatchMode=yes -o ConnectTimeout=15 toki@toki-labs.com '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
stage_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source
source_root="$stage_root/iop"
candidate="$stage_root/edge.candidate"
cd "$source_root"
/usr/bin/shasum -a 256 -c "$stage_root/overlay.sha256"
/opt/homebrew/bin/go version
/opt/homebrew/bin/go test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
/opt/homebrew/bin/go build -trimpath -o "$candidate" ./apps/edge/cmd/edge
"$candidate" --config /Users/toki/agent-work/iop-dev/build/dev-runtime/edge.yaml config check >/dev/null
print -r -- "remote_candidate_gate=PASS base_head=$(<"$stage_root/base-head") candidate_hash=$(/usr/bin/shasum -a 256 "$candidate" | /usr/bin/awk '{print $1}')"
REMOTE
```

Then perform one controlled replacement. Preserve the prior binary at the fresh backup path before stopping it. Atomically install the candidate, start it with the existing command/config/log, and require a different PID, matching candidate hash, all listeners, four connected nodes, and healthy/idle selected providers at `3+1`. If any post-stop/install/start/readiness assertion fails, the exit trap terminates the candidate if present, atomically restores the backup, starts the prior command once, verifies its listeners, records `edge_rollback_count=1 invocation_count=0`, and stops this packet.

```bash
ssh -o BatchMode=yes -o ConnectTimeout=15 toki@toki-labs.com '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
runtime_root=/Users/toki/agent-work/iop-dev
stage_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source
candidate="$stage_root/edge.candidate"
backup=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-edge-backup
runtime_bin="$runtime_root/build/dev-runtime/bin/edge"
config="$runtime_root/build/dev-runtime/edge.yaml"
edge_log="$runtime_root/build/dev-runtime/bin/logs/edge.log"
status_file=$(/usr/bin/mktemp -t iop-plan-7-deploy.XXXXXX)
replacement_started=false

rollback_prior() {
  set +e
  live_pid=$(/usr/sbin/lsof -tiTCP:18083 -sTCP:LISTEN | /usr/bin/head -1)
  if [[ -n "$live_pid" ]]; then
    /bin/kill -TERM "$live_pid"
    for _ in {1..30}; do
      /bin/kill -0 "$live_pid" 2>/dev/null || break
      /bin/sleep 1
    done
    if /bin/kill -0 "$live_pid" 2>/dev/null; then
      /bin/kill -KILL "$live_pid"
    fi
  fi
  /bin/cp "$backup" "$runtime_bin.plan7-rollback"
  /bin/chmod 755 "$runtime_bin.plan7-rollback"
  /bin/mv -f "$runtime_bin.plan7-rollback" "$runtime_bin"
  /usr/bin/nohup "$runtime_bin" --config "$config" serve >>"$edge_log" 2>&1 </dev/null &
  rollback_pid=$!
  rollback_ready=false
  for _ in {1..120}; do
    if [[ "$(/usr/sbin/lsof -tiTCP:18083 -sTCP:LISTEN | /usr/bin/head -1)" = "$rollback_pid" ]] &&
       [[ "$(/usr/sbin/lsof -tiTCP:18084 -sTCP:LISTEN | /usr/bin/head -1)" = "$rollback_pid" ]] &&
       [[ "$(/usr/sbin/lsof -tiTCP:19093 -sTCP:LISTEN | /usr/bin/head -1)" = "$rollback_pid" ]]; then
      rollback_ready=true
      break
    fi
    /bin/sleep 1
  done
  print -r -- "edge_deploy_gate=ROLLED_BACK rollback_ready=$rollback_ready edge_restart_count=1 edge_rollback_count=1 invocation_count=0"
}

finish() {
  rc=$?
  trap - EXIT
  /bin/rm -f -- "$status_file"
  if [[ "$rc" -ne 0 && "$replacement_started" = true ]]; then
    rollback_prior
  fi
  exit "$rc"
}
trap finish EXIT

test -x "$candidate"
test -x "$runtime_bin"
test -r "$config"
test ! -e "$backup"
test -z "$(cd "$runtime_root" && git status --porcelain)"
old_pid=$(/usr/sbin/lsof -tiTCP:18083 -sTCP:LISTEN | /usr/bin/head -1)
test -n "$old_pid"
test "$(/usr/sbin/lsof -tiTCP:18084 -sTCP:LISTEN | /usr/bin/head -1)" = "$old_pid"
test "$(/usr/sbin/lsof -tiTCP:19093 -sTCP:LISTEN | /usr/bin/head -1)" = "$old_pid"
old_hash=$(/usr/bin/shasum -a 256 "$runtime_bin" | /usr/bin/awk '{print $1}')
candidate_hash=$(/usr/bin/shasum -a 256 "$candidate" | /usr/bin/awk '{print $1}')
test "$old_hash" != "$candidate_hash"
/bin/cp "$runtime_bin" "$backup"
test "$(/usr/bin/shasum -a 256 "$backup" | /usr/bin/awk '{print $1}')" = "$old_hash"

replacement_started=true
/bin/kill -TERM "$old_pid"
for _ in {1..60}; do
  /bin/kill -0 "$old_pid" 2>/dev/null || break
  /bin/sleep 1
done
! /bin/kill -0 "$old_pid" 2>/dev/null

/bin/cp "$candidate" "$runtime_bin.plan7-next"
/bin/chmod 755 "$runtime_bin.plan7-next"
/bin/mv -f "$runtime_bin.plan7-next" "$runtime_bin"
test "$(/usr/bin/shasum -a 256 "$runtime_bin" | /usr/bin/awk '{print $1}')" = "$candidate_hash"
/usr/bin/nohup "$runtime_bin" --config "$config" serve >>"$edge_log" 2>&1 </dev/null &
new_pid=$!
test "$new_pid" != "$old_pid"

ready=false
for _ in {1..180}; do
  if [[ "$(/usr/sbin/lsof -tiTCP:18083 -sTCP:LISTEN | /usr/bin/head -1)" = "$new_pid" ]] &&
     [[ "$(/usr/sbin/lsof -tiTCP:18084 -sTCP:LISTEN | /usr/bin/head -1)" = "$new_pid" ]] &&
     [[ "$(/usr/sbin/lsof -tiTCP:19093 -sTCP:LISTEN | /usr/bin/head -1)" = "$new_pid" ]] &&
     /usr/bin/curl -fsS http://127.0.0.1:18001/edges/edge-toki-labs-dev/status >"$status_file" 2>/dev/null &&
     /opt/homebrew/bin/jq -e '
       def provider($id): first(.nodes[]?.provider_snapshots[]? | select(.id == $id));
       ((.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; then
    ready=true
    break
  fi
  /bin/sleep 1
done
test "$ready" = true
test "$(/usr/sbin/lsof -tiTCP:18001 -sTCP:LISTEN | /usr/bin/wc -l | /usr/bin/tr -d ' ')" = 1
test "$(/usr/bin/shasum -a 256 "$runtime_bin" | /usr/bin/awk '{print $1}')" = "$candidate_hash"
test -z "$(cd "$runtime_root" && git status --porcelain)"

replacement_started=false
trap - EXIT
/bin/rm -f -- "$status_file"
print -r -- "edge_deploy_gate=PASS old_pid=$old_pid new_pid=$new_pid old_hash=$old_hash candidate_hash=$candidate_hash listeners=4 nodes=4 providers=3+1_idle edge_restart_count=1 edge_rollback_count=0 invocation_count=0"
REMOTE
```

Required successful deployment evidence:

```text
edge_deploy_gate=PASS old_pid=<old> new_pid=<new> old_hash=<old> candidate_hash=<new> listeners=4 nodes=4 providers=3+1_idle edge_restart_count=1 edge_rollback_count=0 invocation_count=0
```

No model request is allowed unless that exact gate passes. The implementing agent must record the concrete stop/install/start/readiness commands and outputs in the review; do not improvise another process manager, config, port, or retry.

After deployment, run the existing S07 command once in a caller-owned foreground SSH session from the isolated source root, changing only the plan path:

```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
source_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source/iop
stage_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source
artifact_dir=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7
runtime_root=/Users/toki/agent-work/iop-dev
secret=/Users/toki/.config/iop/secrets/dev-openai-toki.sops.yaml
age_key=/Users/toki/.config/sops/age/keys.txt
status_file=$(/usr/bin/mktemp -t iop-repeat-live-status.XXXXXX)
api_key=''
cleanup() {
  /bin/rm -f -- "$status_file"
  unset api_key
}
trap cleanup EXIT

test ! -e "$artifact_dir"
! /usr/bin/pgrep -fl '[T]estDevRepeatGuardOrnithSmoke|[r]epeat-guard-task-03-plan-7' >/dev/null
cd "$source_root"
/usr/bin/shasum -a 256 -c "$stage_root/overlay.sha256"
candidate_hash=$(/usr/bin/shasum -a 256 "$stage_root/edge.candidate" | /usr/bin/awk '{print $1}')
runtime_hash=$(/usr/bin/shasum -a 256 "$runtime_root/build/dev-runtime/bin/edge" | /usr/bin/awk '{print $1}')
test "$runtime_hash" = "$candidate_hash"

test -x /opt/homebrew/bin/sops
test -r "$age_key"
test -r "$secret"
test "$(/usr/bin/stat -f %Lp "$secret")" = 600
api_key=$(SOPS_AGE_KEY_FILE="$age_key" /opt/homebrew/bin/sops decrypt --extract '["tokens"]["toki-dev-pi"]' "$secret")
test -n "$api_key"

/usr/bin/curl -fsS http://127.0.0.1:18001/edges/edge-toki-labs-dev/status >"$status_file"
/opt/homebrew/bin/jq -e '
  def provider($id): first(.nodes[]?.provider_snapshots[]? | select(.id == $id));
  ((.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

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

print -r -- 'remote_live_start invocation_count=1 ownership=foreground artifact=plan-7'
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 \
/opt/homebrew/bin/go test -timeout 90m -count=1 -v ./apps/edge/internal/openai -run '^TestDevRepeatGuardOrnithSmoke$'
REMOTE
```

Any exit after `remote_live_start` consumes the one allowed invocation. Do not retry, reuse the path, or synthesize a summary.

#### Modified Files and Checklist

- [ ] `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G10.md` - record manifest hashes, remote tests/build, exact deployment or rollback counts, the one foreground invocation, and sanitized summary/cleanup evidence.
- [ ] No tracked remote source/config, Control Plane, Node, provider, credential, roadmap, or prior artifact change.

#### Test Strategy

Use only the isolated source overlay, profile tests, candidate hash/readiness gates, and existing five-concurrent by three-run live test. Do not accept tests from the stale checkout, an unverified binary, degraded provider capacity, detached/background model execution, a second invocation, raw SSE in the review, or a synthesized result.

After a successful foreground run, validate `summary.json` without printing it:

```bash
ssh -o BatchMode=yes -o ConnectTimeout=15 toki@toki-labs.com '/bin/zsh -lc "exec /bin/zsh -s"' <<'REMOTE'
set -euo pipefail
summary=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7/summary.json
stage_root=/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-source
runtime_root=/Users/toki/agent-work/iop-dev
status_file=$(/usr/bin/mktemp -t iop-repeat-cleanup.XXXXXX)
trap '/bin/rm -f "$status_file"' EXIT

test -f "$summary"
/opt/homebrew/bin/jq -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
result_evidence=$(/opt/homebrew/bin/jq -r '
  if .result == "reproduced" then
    first(.lifecycles[] | select(.result == "reproduced") |
      "result=reproduced fingerprint=\(.fingerprint) offset=\(.offset)")
  else "result=not_reproduced" end
' "$summary")

/usr/bin/curl -fsS http://127.0.0.1:18001/edges/edge-toki-labs-dev/status >"$status_file"
/opt/homebrew/bin/jq -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|[r]epeat-guard-task-03-plan-7' >/dev/null
test "$(/usr/bin/shasum -a 256 "$stage_root/edge.candidate" | /usr/bin/awk '{print $1}')" = \
  "$(/usr/bin/shasum -a 256 "$runtime_root/build/dev-runtime/bin/edge" | /usr/bin/awk '{print $1}')"
test -z "$(cd "$runtime_root" && git status --porcelain)"
test -d /tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-6

print -r -- "remote_cleanup=PASS $result_evidence invocation_count=1 provider_responses=15 edge_correlations=15 capacity_runs=3 configured_capacity=4 peak_in_flight=4 queued_pressure=present providers=idle harness=absent candidate=deployed checkout=clean prior_artifacts=preserved"
REMOTE
```

Expected: exit `0` and only sanitized evidence. Do not print `summary.json`, raw SSE, prompt/output, status payload, token, token hash, Authorization header, or secret path contents.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/stream_gate_release_sink.go` | REVIEW_OFR-S07-TERMINAL-FRAMING-7-1 |
| `apps/edge/internal/openai/stream_gate_tunnel_codec.go` | REVIEW_OFR-S07-TERMINAL-FRAMING-7-1 |
| `apps/edge/internal/openai/stream_gate_vertical_slice_test.go` | REVIEW_OFR-S07-TERMINAL-FRAMING-7-1, REVIEW_OFR-S07-TERMINAL-FRAMING-7-2 |
| `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G10.md` | REVIEW_OFR-S07-TERMINAL-FRAMING-7-1, REVIEW_OFR-S07-TERMINAL-FRAMING-7-2, REVIEW_OFR-S07-TERMINAL-FRAMING-7-3 |

## Dependencies and Execution Order

1. Implement endpoint binding and the Chat-only post-open error terminal.
2. Implement the logical validator and all deterministic regression cases.
3. Run focused and complete local profile tests uncached; stop before any remote write on failure.
4. Require all three remote temporary paths to be fresh, the checkout/dependency/toolchain identities to match, and providers to remain idle.
5. Create and verify the isolated source overlay, run the same profile tests remotely, build/config-check the candidate, and preserve the prior binary.
6. Replace/restart the Edge once. On failed readiness, roll back once and stop with zero model invocations.
7. Only after the successful candidate deployment gate, authenticate without exposing credentials and start the S07 Go test once in the foreground.
8. Validate the raw-free summary, cleanup, candidate identity, clean checkout, and artifact preservation; fill the active review and stop for official review.

## Final Verification

PASS requires: exact scoped source changes; a production-path Chat tunnel regression proving accepted prefix plus one sanitized error plus one final `[DONE]`, no rejected bytes, no duplicate/later event, and three recovery dispatches; validator tests accepting success+`[DONE]` and error+`[DONE]` while rejecting every invalid sequence; uncached local and isolated-remote profile tests; a verified three-file source manifest; candidate config check; exactly one successful Edge replacement/restart with a new PID and matching hash; four listeners; four connected nodes; idle healthy `3+1` providers; protected SOPS authentication HTTP 200; exactly one caller-owned 5-concurrent x 3-run invocation; 15 unique provider responses; 15 unique Edge correlations; three capacity rows at configured capacity 4 with peak in-flight 4 and queue pressure; accepted `reproduced` fingerprint/offset or `not_reproduced`; idle cleanup; absent harness; clean remote checkout; preserved prior artifacts; `git diff --check`; and no raw secret/model output in tracked evidence.

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