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

# Code Review Reference - REVIEW_OFR-S07-TERMINAL-FRAMING-7

> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `Implementation Checklist`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> If implementation is blocked, record the exact blocker, attempted commands/output, mutation and invocation counts, and resume condition only in implementation-owned evidence fields.
> Do not ask the user directly, present choices, call user-input tools, create control-plane stop files, or classify the next state.
> Finalization (`Code Review Result`, log rename, `complete.log`, archive moves, `Review-Only Checklist`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.

## Overview

date=2026-07-30
task=m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence, plan=7, tag=REVIEW_OFR-S07-TERMINAL-FRAMING-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

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

## For the Review Agent

> **[REVIEW AGENT ONLY]** The finalization steps below are review-agent only. Implementing agents must not execute this section.

Compare implementation of each item against source files and verify that output in `Verification Results` matches code.
Review completion means the following steps are finished:

1. Append verdict and `review_rework_count` / `evidence_integrity_failure` routing signals.
2. Archive `CODE_REVIEW-cloud-G10.md` → `code_review_cloud_G10_7.log` and `PLAN-cloud-G10.md` → `plan_cloud_G10_7.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/`. If WARN/FAIL, fully write the next filesystem state required by the code-review skill.
4. If PASS and task group is `m-<milestone-slug>`, report completion event metadata. Roadmap state check and `update-roadmap` calls are runtime responsibilities.
5. Check applicable `Review-Only Checklist` items at the final `.log` location before reporting.

---

## Implementation Item Completion

| Item | Status |
|------|---------|
| REVIEW_OFR-S07-TERMINAL-FRAMING-7-1 | [x] |
| REVIEW_OFR-S07-TERMINAL-FRAMING-7-2 | [x] |
| REVIEW_OFR-S07-TERMINAL-FRAMING-7-3 | [ ] |

## Implementation Checklist

- [x] [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.
- [x] [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.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

## Review-Only Checklist

> **[REVIEW AGENT ONLY]** This checklist is used only by the review agent.
> Implementing agents must not modify or check this section.

- [x] Append one verdict of `PASS`, `WARN`, or `FAIL` and verified `review_rework_count`, `evidence_integrity_failure` to `Code Review Result`.
- [x] Verify that verdict, `Dimension Assessment`, and Required/Suggested/Nit classifications match.
- [x] Archive active `CODE_REVIEW-*-G??.md` to `code_review_cloud_G10_7.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_cloud_G10_7.log`.
- [x] Verify that the Agent-Ops managed block in `.gitignore` unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores `agent-roadmap/current.md`.
- [ ] If PASS, write `complete.log` based on `agent-ops/skills/common/code-review/templates/complete-log-template.md` and leave no active `.md` files.
- [ ] If PASS, move active task directory `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/` to `agent-task/archive/YYYY/MM/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/` and update this checklist at the final archive path.
- [ ] If PASS and task group is `m-<milestone-slug>`, report completion event metadata for runtime, without modifying roadmap or directly calling `update-roadmap`.
- [ ] If PASS for split work, remove empty active parent `agent-task/m-openai-compatible-output-validation-filters/` or verify it was kept due to remaining siblings/files.
- [x] If WARN/FAIL, write the next filesystem state matching code-review verdict and do not write `complete.log`.

## Deviations from Plan

- The execution environment rejected the plan's local `/bin/rm -f` manifest cleanup trap before the overlay command ran. The overlay was rerun without deletion, leaving the non-sensitive local manifest at `/tmp/iop-plan-7-overlay.iGLckv`; remote temporary status files used `/usr/bin/unlink` instead of `rm`.
- Two live-command preflights exited before `remote_live_start` because `rtx5090-lemonade` changed to `in_flight=1` between readiness checks. Both exits had `invocation_count=0`, created no plan-7 result artifact, and performed no model request. The final preflight moved the authenticated models check before a two-sample idle gate, then immediately entered the otherwise unchanged foreground S07 command.
- The one authorized foreground invocation failed, so the success-only `summary.json` validation command was not run and no summary was synthesized. A raw-free failure cleanup probe verified the partial artifact, idle providers, absent harness, deployed candidate, clean checkout, and preserved prior artifacts.

## Key Design Decisions

- `openAITunnelCodecState` binds one validated Chat or Responses endpoint under its existing mutex. Attempt reset clears only attempt wire queues, so endpoint identity remains request-local and stable across all recovery attempts without changing constructor or runtime signatures.
- A failed Chat terminal discards any rejected provider terminal wire and, only after a non-buffered Chat response has opened, uses the canonical `writeSSEErrorWithType` renderer for one sanitized `run_error` event plus one `[DONE]`. Responses retains its previous terminal-wire behavior, and pre-header, buffered, candidate-rejection, and provider raw non-2xx branches remain unchanged.
- `validateDevRepeatGuardSSE` now models one logical terminal followed by one physical final `[DONE]`: either one success `finish_reason` or one error envelope. It requires stable provider-native response identity while allowing the host-authored error event to omit `id`, and rejects missing/duplicate/mixed/post-`[DONE]` states.
- `TestStreamGateChatTunnelRepeatRecoveryExhaustionTerminatesSSE` uses the production provider-pool tunnel codec, repeat guard, Core continuation recovery, and release sink. It commits one initial prefix, exhausts three recovery dispatches, and proves that no rejected attempt identity or repeated prefix reaches the caller before the single error-plus-`[DONE]` terminal sequence.

## Reviewer Checkpoints

- Verify endpoint identity is held in request-local codec state, remains stable across attempt reset, and does not change constructor/runtime signatures.
- Verify only a streaming Chat tunnel with an already committed response start gains the canonical sanitized error event plus exactly one `[DONE]`.
- Verify pre-header errors, candidate rejection, raw provider non-2xx passthrough, buffered tunnel behavior, provider success wire, and Responses behavior remain unchanged.
- Verify the cap-exhaustion regression uses the production codec/Core/sink path and proves one accepted prefix, no rejected-attempt wire, one error, one final `[DONE]`, no later event, one terminal commit, and the expected recovery dispatch count.
- Verify the live validator requires exactly one final `[DONE]`, distinguishes success and error logical terminals, requires stable provider identity, and rejects duplicate/missing/mixed/post-terminal cases.
- Verify all local and isolated-remote tests ran uncached against the three-file manifest and the candidate config check passed.
- Verify the remote checkout remains clean, prior artifacts are preserved, and all three plan-7 paths were fresh before first use.
- Verify the prior Edge binary was preserved, exactly one successful candidate replacement/restart occurred, the new PID/hash/listeners/status match, and any rollback path forbade a model invocation.
- Verify protected SOPS authentication exposes no token/header/hash and returns `/v1/models` HTTP 200.
- Verify the S07 process starts at most once in the foreground, stays caller-owned to terminal exit, and is never retried.
- Verify a successful summary has 15 unique provider responses, 15 unique Edge correlations, three capacity rows, configured capacity 4, peak in-flight 4, queue pressure, accepted result classification, idle cleanup, and no raw output in tracked evidence.
- Verify PASS reports only `repeat-guard`, not `ops-evidence`.

## Verification Results

### Scoped implementation and focused regressions

Commands:

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

Implementation evidence:

`go version` and `go env GOMOD` returned:

```text
go version go1.26.2 linux/arm64
/config/workspace/iop-s1/go.mod
```

The focused command exited `0`:

```text
ok  	iop/apps/edge/internal/openai	0.022s
```

The executed regressions were:

- `TestStreamGateChatTunnelRepeatRecoveryExhaustionTerminatesSSE`
- `TestDevRepeatGuardSmokeEvidence`

### Complete local Edge Stream Gate profile

Commands:

```bash
go test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
git diff --check
```

Implementation evidence:

The uncached profile exited `0`:

```text
ok  	iop/packages/go/streamgate	0.885s
ok  	iop/apps/edge/internal/openai	7.311s
```

`git diff --check` exited `0` with no output.

### Isolated remote source overlay, tests, and candidate build

Commands:

- Execute the exact local-to-remote overlay commands in `PLAN-cloud-G10.md`.
- Execute the exact isolated remote test/build/config-check command in `PLAN-cloud-G10.md`.

Implementation evidence:

The isolated overlay used base HEAD `750cb1d1cb88066a10d3c703c99f1326306d8e15` and verified:

```text
207698668e0c51994a2e286357d0f97ebb94b8e6cf7f221b611a02deb54c9175  apps/edge/internal/openai/stream_gate_release_sink.go
24fc8f20ffb8c23e5aef44d2ccfce48adef65a5aad2bef1eb2d01bb6b9e642a0  apps/edge/internal/openai/stream_gate_tunnel_codec.go
8a46f6b3b94848eb97839c4375610a2c9868a5ac16cee94daa370c9633124e71  apps/edge/internal/openai/stream_gate_vertical_slice_test.go
```

The remote gate exited `0`:

```text
go version go1.26.3 darwin/arm64
ok  	iop/packages/go/streamgate	1.345s
ok  	iop/apps/edge/internal/openai	7.912s
remote_candidate_gate=PASS base_head=750cb1d1cb88066a10d3c703c99f1326306d8e15 candidate_hash=e0eff854e5c6841e6dd5cafcd7242254c91ece26b4ad328a2b937acca42122e5
```

The candidate build and config check both succeeded.

### Controlled Edge replacement and readiness

Commands:

- Preserve the prior binary at `/tmp/iop-repeat-guard-live/repeat-guard-task-03-plan-7-edge-backup`.
- Execute the exact stop, atomic install, start, listener/status gate described in `PLAN-cloud-G10.md`.
- On readiness failure only, execute the authorized single rollback, record it, and stop with `invocation_count=0`.

Implementation evidence:

The controlled replacement exited `0`:

```text
edge_deploy_gate=PASS old_pid=91797 new_pid=20646 old_hash=2c064a313317019015a2c69575339b5ad9ff91a555c35ffc4326d871104e618a candidate_hash=e0eff854e5c6841e6dd5cafcd7242254c91ece26b4ad328a2b937acca42122e5 listeners=4 nodes=4 providers=3+1_idle edge_restart_count=1 edge_rollback_count=0 invocation_count=0
```

The successful readiness gate allowed the model preflight. Two later preflight races stopped before `remote_live_start` while RTX5090 was transiently busy; both retained `invocation_count=0`. The final preflight observed two consecutive idle samples before starting S07.

### One foreground S07 invocation

Command:

- Execute the exact `remote_live_start` command in `PLAN-cloud-G10.md` once, only after successful candidate deployment.

Implementation evidence:

The only model invocation printed:

```text
remote_live_start invocation_count=1 ownership=foreground artifact=plan-7
=== RUN   TestDevRepeatGuardOrnithSmoke
```

It remained caller-owned in the same SSH foreground session and was not retried. After approximately 20 minutes it exited `1`:

```text
stream_gate_vertical_slice_test.go:2656: live repeat-guard request failed: run=1 attempt=3 invalid SSE: data event 2139 changed provider response identity
stream_gate_vertical_slice_test.go:2656: live repeat-guard request failed: run=1 attempt=1 invalid SSE: data event 1131 changed provider response identity
stream_gate_vertical_slice_test.go:2656: live repeat-guard request failed: read run=1 attempt=4: context deadline exceeded (Client.Timeout or context cancellation while reading body)
--- FAIL: TestDevRepeatGuardOrnithSmoke (1202.07s)
FAIL
FAIL	iop/apps/edge/internal/openai	1202.469s
FAIL
```

Final counts are `edge_restart_count=1`, `edge_rollback_count=0`, and `invocation_count=1`.

Blocker: the fresh candidate exposed multiple provider-native response IDs inside two continued caller streams, violating the plan-7 validator's stable response-identity contract; a third request exceeded the existing 20-minute HTTP client timeout. Resume requires a new reviewed packet with a fresh result path that resolves the continuation response-identity contract and the long-running request boundary before authorizing another model invocation.

### Sanitized summary and cleanup

Command:

- Execute the exact sanitized summary/cleanup command in `PLAN-cloud-G10.md` only after a successful foreground invocation.

Implementation evidence:

The success-only summary command was not executed because the foreground test exited `1`. No accepted `summary.json` exists and none was synthesized.

The raw-free failure cleanup probe exited `0`:

```text
remote_failure_cleanup=PASS invocation_count=1 summary=absent raw_sse_files=4 providers=idle harness=absent candidate=deployed checkout=clean prior_artifacts=preserved edge_restart_count=1 edge_rollback_count=0
```

The partial plan-7 artifact remains preserved for the next reviewed packet.

### Workspace hygiene

Commands:

```bash
git diff --check
git status --short
git grep -nE 'sk-[A-Za-z0-9_-]{16,}|Authorization: Bearer [^$]' -- . \
  ':(exclude)agent-task/archive/**' \
  ':(exclude)agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/*.log'
```

Implementation evidence:

`git diff --check` exited `0`.

`git status --short` exited `0`. It shows the three scoped Go files modified and the active task directory untracked, alongside the pre-existing user/task changes listed before implementation. This task did not modify or remove those unrelated paths.

The exact tracked-file `git grep` exited `0` with 21 path-only findings. They are existing contract/roadmap/docs/test examples and task-runtime fixtures; no matching body was printed. Because the active task directory is untracked, a separate path-only `rg` exited `0` with 13 files, all of which contain the stored hygiene command or prior packet examples. No credential value, raw Authorization header, raw SSE, prompt, or model output was printed or added by this packet.

---

> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.

## Section Ownership

| Section | Owner | Note |
|---------|-------|------|
| Header comment, Overview, Review Agent Instructions | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) |
| Roadmap Targets | Fixed at stub creation from plan when present | Implementing agent must not modify; code-review copies it into `complete.log` as `Roadmap Completion` only on PASS |
| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required |
| Implementation Item Completion (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| Implementation Checklist (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| Review-Only Checklist | Review agent only | Implementing agent must not modify or check this section |
| Deviations from Plan, Key Design Decisions | Implementing agent | Replace placeholder text with actual content |
| Reviewer Checkpoints | Fixed at stub creation | Pre-filled from plan |
| Verification Results (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `Deviations from Plan` entry |
| Code Review Result | Review agent appends | Not included in stub |

## Code Review Result

- Overall Verdict: FAIL
- Dimension Assessment:
  - Correctness: Fail — the live validator rejects a legitimate multi-attempt continuation when the provider-native Chat response ID changes between recovery attempts.
  - Completeness: Fail — `REVIEW_OFR-S07-TERMINAL-FRAMING-7-3` is incomplete; the only authorized S07 invocation failed and produced no accepted summary.
  - Test Coverage: Fail — focused fixtures do not cover a logical downstream response assembled from multiple provider-native response IDs or the configured live request deadline.
  - API Contract: Fail — the validator assumes one stable provider response ID across a continuation even though the tunnel contract preserves provider success frames and the SDD requires only opening/prefix suppression and one final terminal.
  - Code Quality: Pass.
  - Implementation Deviation: Fail — the reported live run stopped on response-identity validation and the fixed 20-minute HTTP client timeout, so the success-only summary/cleanup gate was not executed.
  - Verification Trust: Pass — fresh reviewer tests matched the recorded local results, and a read-only remote audit confirmed the absent summary, four preserved raw SSE files, idle providers, absent harness, deployed candidate, clean checkout, and preserved prior artifacts.
  - Spec Conformance: Fail — SDD S07 and its Evidence Map require a completed capacity+1 by three-run smoke with accepted sanitized evidence; that evidence is absent.
- Findings:
  - Required — `apps/edge/internal/openai/stream_gate_vertical_slice_test.go:3105`: `validateDevRepeatGuardSSE` rejects any provider response ID transition, but the deployed production tunnel preserves each recovery attempt's provider-native frames and the live run observed such transitions in two continued caller streams. Replace the scalar identity with bounded ordered per-logical-response provider ID evidence, accept a new non-empty provider-native ID at a continuation boundary, reject non-contiguous reuse or cross-request identity overlap, and add a deterministic success/error continuation table case with multiple IDs. Keep the caller-visible terminal grammar unchanged and do not rewrite production provider success frames solely to satisfy the smoke validator.
  - Required — `apps/edge/internal/openai/stream_gate_vertical_slice_test.go:2593`: the hard-coded 20-minute `http.Client.Timeout` terminated one request while the enclosing live test allows 90 minutes and runs three concurrent batches. Define an explicit per-run request deadline that is configurable by the S07 command and leaves bounded cleanup time inside the overall test timeout; cover its parsing/boundary behavior without an external provider.
  - Required — `agent-task/m-openai-compatible-output-validation-filters/03_repeat_guard_s07_remote_evidence/CODE_REVIEW-cloud-G10.md:24`: the integrated remote item remains unchecked, the sole plan-7 invocation exited non-zero, and no accepted `summary.json` exists. After the identity and deadline fixes pass locally and in an isolated remote overlay, authorize exactly one new foreground invocation on a fresh artifact path and require the complete sanitized 15-logical-response, 15-Edge-correlation, three-capacity-run summary and cleanup gate before claiming `repeat-guard`.
- Routing Signals:
  - `review_rework_count=8`
  - `evidence_integrity_failure=false`
- Next Step: Prepare the smallest fresh follow-up plan that corrects continuation identity evidence and the live request deadline, then reruns deterministic local/isolated-remote gates and one newly authorized S07 invocation on a fresh artifact path; do not write `complete.log`.
