<!-- task=m-openai-compatible-output-validation-filters/02+01_repeat_guard plan=11 tag=REVIEW_OFR-REPEAT-10 -->

# Repeat guard review follow-up: correct live evidence identity and isolation

## For the Implementing Agent

Filling the implementation-owned sections in `CODE_REVIEW-*-G??.md` is mandatory. Run every verification command, paste actual notes and stdout/stderr into the active review file, keep the active PLAN/CODE_REVIEW files in place, and report ready for review; only the code-review skill may finalize or archive the task. If blocked, record only the exact blocker, attempted commands/output, and resume conditions in implementation-owned evidence fields. Do not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, or write `complete.log`.

## Background

The tenth review found that the one authorized live run was contaminated by an unmatched same-model request and that the harness incorrectly equates provider-native SSE response IDs with Edge correlations derived from internal dispatch run IDs. The production repeat guard and its deterministic fixtures remain unchanged, but SDD S07 still lacks an isolated three-run dev result. This follow-up repairs only the live test oracle and then permits one fresh bounded invocation after deterministic and external preconditions pass.

## Archive Evidence Snapshot

- Predecessor dependency: `agent-task/archive/2026/07/m-openai-compatible-output-validation-filters/01_resume_notice_builder/complete.log` records PASS and satisfies subtask `+01`.
- Earlier same-task loops: `plan_cloud_G10_0.log` through `plan_cloud_G10_9.log` and their matching review logs remain the bounded history.
- Current failed pair after archival: `plan_cloud_G09_10.log` and `code_review_cloud_G09_10.log`. Its single Required finding records six complete same-model observation groups for five run-1 requests, including unmatched `req.manual-1785324426339266000`, and no intersection between five provider SSE-derived IDs and six Edge correlation IDs.
- Trustworthy evidence: fresh `git diff --check`, the focused Core terminal-fidelity race test, and the focused Edge correlation/capacity race tests passed. The exact-ref runtime/gate/capacity preflight and post-failure idle state are valid; the failed run produced neither a 15-correlation summary nor three accepted capacity rows.
- Required follow-up: make provider response identity and Edge lifecycle correlation independent evidence sets, reject any non-exact observation segment, add deterministic regression coverage, and only then run one fresh `ornith:35b` 5-concurrent × 3 smoke under an exclusive/quiescent observation window.

## 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 rules: `agent-ops/rules/project/rules.md`, `agent-ops/rules/private/rules.md`, `agent-ops/rules/common/rules-roadmap.md`, `agent-ops/rules/common/rules-agent-spec.md`, `agent-ops/skills/common/router.md`, `agent-ops/skills/common/code-review/SKILL.md`, `agent-ops/skills/common/plan/SKILL.md`, `agent-ops/skills/common/finalize-task-routing/SKILL.md`, `agent-ops/skills/common/plan/templates/review-stub-template.md`, `agent-ops/rules/project/domain/edge/rules.md`, `agent-ops/rules/project/domain/platform-common/rules.md`, and `agent-ops/rules/project/domain/testing/rules.md`.
- Verification profiles: `agent-test/local/rules.md`, `agent-test/local/edge-smoke.md`, `agent-test/local/platform-common-smoke.md`, and `agent-test/local/testing-smoke.md`.
- Roadmap and design: `agent-roadmap/current.md`, `agent-roadmap/phase/knowledge-tool-optimization-extension/PHASE.md`, `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/openai-compatible-output-validation-filters.md`, and `agent-roadmap/sdd/knowledge-tool-optimization-extension/openai-compatible-output-validation-filters/SDD.md`.
- Contracts and specs: `agent-contract/index.md`, `agent-contract/outer/openai-compatible-api.md`, `agent-contract/inner/edge-config-runtime-refresh.md`, `agent-spec/index.md`, `agent-spec/runtime/stream-evidence-gate.md`, `agent-spec/runtime/provider-pool-config-refresh.md`, and `agent-spec/input/openai-compatible-surface.md`.
- Source and tests: complete `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`, relevant `apps/edge/internal/openai/stream_gate_runtime.go`, `apps/edge/internal/openai/stream_gate_release_sink.go`, and `packages/go/streamgate/runtime_test.go`.
- Task evidence: the active plan/review pair, its same-task log verdicts, and the exact predecessor completion log cited above.

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/openai-compatible-output-validation-filters/SDD.md`; status approved; SDD lock released.
- Deterministic repeat-guard coverage already targets S03, S04, and S09-S12. The remaining dev smoke is the repeat-guard portion of S07 and its Evidence Map: capacity+1 concurrent long-Korean streaming, minimum three runs, sanitized lifecycle/capacity evidence, and either a real fingerprint/offset decision or `not_reproduced`.
- The checklist therefore requires a regression for the invalid cross-identity assumption and strict segment cardinality before a single fresh external run. PASS requires 15 unique Edge correlations, five valid provider SSE responses per run, and three accepted capacity rows; provider response IDs are not accepted as Edge correlations.

### Verification Context

- No separate `verification_context` handoff was supplied. Repository rules, approved SDD, current task evidence, and fresh reviewer commands are the fallback context.
- Fresh local reviewer evidence on 2026-07-29: Go `1.26.2`, module `/config/workspace/iop-s1/go.mod`; `git diff --check`, the focused Core terminal-fidelity race test, and focused Edge correlation/capacity race tests exited 0.
- The live failure is trustworthy: exactly one invocation exited 1 after run 1 with six complete groups for five requests, one unmatched manual group, five terminal SSE files, zero accepted persisted capacity rows, and idle providers afterward. No retry is authorized by the archived plan.
- External Verification Preflight: runner `/Users/toki/agent-work/iop-dev` on macOS/arm64; reviewed production ref `d1e32b6e06f7153a4db5a5a08b7026d6dd49fcfb`; OpenAI `127.0.0.1:18083`, Node transport `18084`, admin `19093`, and status `127.0.0.1:18001/edges/edge-toki-labs-dev/status`; provider capacities 3 and 1. Before live execution, prove the runner's non-test tree matches the reviewed ref, the only allowed runner source delta is `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`, all running production binaries/processes/listeners still identify the reviewed ref, both providers are healthy and idle, the blocking gate and sanitized sink are active, and the observation file offset stays unchanged during a quiet-window probe immediately before launch.
- Keep raw prompt, SSE, outputs, credentials, and tokens outside the repository under `/tmp/iop-repeat-guard-live/`. Only sanitized provider identity, Edge correlation/lifecycle, capacity, fingerprint/offset, and command status may enter tracked evidence.
- Confidence is high that the local oracle correction is bounded and that the current runtime contract requires separate identities. Confidence in live acceptance remains conditional on isolation and one successful fresh invocation.

### Test Coverage Gaps

- Existing `TestDevRepeatGuardSmokeEvidence` validates provider SSE framing but incorrectly converts `chatcmpl-*` into a presumed Edge `req.*` correlation.
- Existing `TestDevRepeatGuardObservationCorrelation` requires exact per-request equality and does not prove that disjoint provider and Edge IDs form a valid isolated batch.
- Existing observation cardinality rejects extra groups, but no deterministic test proves that behavior together with the new batch-level identity split and pre-launch quiescence.
- The final external gap remains one isolated 5-concurrent × 3 dev run producing 15 Edge lifecycle groups and three accepted capacity rows.

### Symbol References

- Test-only symbols to change are `devRepeatGuardSSEEvidence.expectedCorrelation`, `devRepeatGuardSmokeEvidence.expectedCorrelation`, `validateDevRepeatGuardSSE`, and `correlateDevRepeatGuardBatch`. All references are in `apps/edge/internal/openai/stream_gate_vertical_slice_test.go`.
- No production or public symbol is renamed or removed.

### Split Judgment

- Keep one follow-up because SSE validation, observation isolation, batch lifecycle validation, and the live acceptance command form one evidence invariant. A test-only correction without its deterministic regressions cannot independently PASS, and the live run must not occur before those corrections pass.
- Dependency `+01` is satisfied by `agent-task/archive/2026/07/m-openai-compatible-output-validation-filters/01_resume_notice_builder/complete.log`.

### Scope Rationale

- Modify only the existing Edge live-harness test and the active review evidence artifact. Do not modify production code, Core correlation semantics, provider passthrough behavior, contracts, specs, tracked configuration, repeat thresholds, queue behavior, or provider selection.
- Do not filter an extra observation group after collection or infer a per-request mapping from timestamps or provider response IDs. The whole post-offset same-model segment must contain exactly five complete Edge groups.
- The external runner may carry the test-file patch only. Deployed production artifacts remain at the reviewed ref; a non-test source delta, unquiet observation sink, failed precondition, or failed single live invocation stops the item without retry.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closures: scope/context/verification/evidence/ownership/decision closed; grade scores `2/2/1/2/2`; base and final route basis `grade-boundary`; lane `cloud`; grade `G09`; canonical file `PLAN-cloud-G09.md`.
- Review closures: scope/context/verification/evidence/ownership/decision closed; grade scores `2/2/1/2/2`; route `official-review`; lane `cloud`; grade `G09`; adapter `codex`; model `gpt-5.6-sol`; reasoning effort `xhigh`; canonical file `CODE_REVIEW-cloud-G09.md`.
- `large_indivisible_context=false`.
- Positive loop risks: `temporal_state`, `concurrent_consistency`, `boundary_contract`, `structured_interpretation`, and `variant_product`; count `5`.
- Recovery signals: `review_rework_count=10`, `evidence_integrity_failure=false`; risk and recovery boundaries matched without replacing the grade-boundary basis.
- Capability gap: none; the work is a bounded test-oracle correction and external verification.

## Implementation Checklist

- [ ] [REVIEW_OFR-REPEAT-10-1] Separate provider SSE identity from Edge correlation, enforce an exact uncontaminated observation batch, add deterministic regressions, and complete one fresh `ornith:35b` 5-concurrent × 3 live invocation with 15 Edge correlations and three accepted capacity rows.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_OFR-REPEAT-10-1] Correct and complete the live repeat-guard evidence

#### Problem

`apps/edge/internal/openai/stream_gate_vertical_slice_test.go:2994` converts the provider-native `chatcmpl-*` response ID to `req.*`, while `apps/edge/internal/openai/stream_gate_runtime.go:1415` derives the Stream Evidence Gate correlation from internal `dispatch.RunID`; the raw tunnel sink at `apps/edge/internal/openai/stream_gate_release_sink.go:197` preserves provider framing. `apps/edge/internal/openai/stream_gate_vertical_slice_test.go:3180-3222` then requires those unrelated values to match per request. The archived live result also reached `apps/edge/internal/openai/stream_gate_vertical_slice_test.go:3041-3075` with six complete groups instead of five, so SDD S07 has no isolated three-run evidence.

Before (`apps/edge/internal/openai/stream_gate_vertical_slice_test.go:2420-2423`, `2994`, `3194-3208`):

```go
type devRepeatGuardSSEEvidence struct {
	terminal            string
	expectedCorrelation string
}

evidence.expectedCorrelation = openAIStreamGateSafeToken("req", runID)

correlation := strings.TrimSpace(request.expectedCorrelation)
if _, found := groups[correlation]; !found {
	return nil, fmt.Errorf("expected correlation has no observation group")
}
```

After:

```go
type devRepeatGuardSSEEvidence struct {
	terminal           string
	providerResponseID string
}

// Validate provider-native SSE identities independently.
// Derive sanitized lifecycle rows only from the exact Edge observation groups.
```

#### Solution

- Rename the private SSE field to provider-response identity, retain strict OpenAI SSE framing/terminal/unique-ID validation, and remove all `chatcmpl-*` to `req.*` transformation or equality claims.
- Refactor the sanitized live summary so five provider responses and five Edge lifecycle groups are validated as separate batch evidence. Sort Edge group keys for deterministic output, derive every lifecycle row's `CorrelationID`, provider/model, terminal reason, decision, recovery sequence, fingerprint, and offset only from that group, and use batch-level terminal/released-repeat checks without inventing a per-request mapping.
- Require exactly one terminal observation and one valid repeat-guard decision lifecycle for each of exactly five Edge correlations. Require exactly five successful request results and unique non-empty provider response IDs separately. If a fatal/safe-stop response mix cannot be reconciled by exact batch-level terminal cardinality, fail closed instead of pairing by order or timestamps.
- Add a bounded quiet-window helper that verifies the observation file remains the same regular file and its size is unchanged immediately before each run. Record the offset only after the quiet window. Do not launch while another same-model smoke/manual source is active.
- Keep `waitDevRepeatGuardObservationSegment` strict: any sixth same-model group, incomplete group, truncation/rotation, forbidden raw value, or timeout fails the run. Do not post-filter unmatched groups.
- Add deterministic tests proving that disjoint provider IDs and Edge correlations pass as an exact batch, an extra same-model group fails, duplicate/missing provider identity fails, and observation-file movement during the quiet window fails.
- After all local checks pass, sync only the test-file delta to the external runner, prove its non-test tree and deployed artifacts remain at the reviewed ref, prove the observation sink is quiet and providers idle, then invoke the exact live command once. Stop without retry on any failure.

#### Modified Files and Checklist

- [ ] `apps/edge/internal/openai/stream_gate_vertical_slice_test.go` — separate identity domains, strict exact-batch/quiescence behavior, summary correction, and deterministic regressions.
- [ ] `agent-task/m-openai-compatible-output-validation-filters/02+01_repeat_guard/CODE_REVIEW-cloud-G09.md` — actual local/external commands, sanitized evidence, invocation count, and result.
- [ ] No production, contract, spec, tracked config, or tracked raw-evidence changes.

#### Test Strategy

- Update `TestDevRepeatGuardSmokeEvidence` to assert provider-native identity without deriving an Edge correlation.
- Update `TestDevRepeatGuardObservationCorrelation` with disjoint-ID success, exact Edge lifecycle validation, extra-group rejection, and duplicate/missing provider-identity rejection.
- Add a focused observation quiescence test using a temporary regular file, including unchanged success and concurrent append/rotation failure.
- Run fresh focused tests, race-enabled Core/Edge checks, both relevant packages, and the repository suite before external verification. Go test cache is not acceptable; use `-count=1`.
- Run the external live harness exactly once only after every precondition passes.

#### Verification

```bash
go version && go env GOMOD
gofmt -d apps/edge/internal/openai/stream_gate_vertical_slice_test.go
git diff --check
go test -count=1 ./apps/edge/internal/openai -run 'TestDevRepeatGuard(SmokeEvidence|ObservationCorrelation|ObservationQuiescence|CapacityEvidence)'
go test -race -count=1 ./packages/go/streamgate -run '^TestRequestRuntimeTerminalFailureFidelity/fatal_filter_overrides_success_terminal$'
go test -race -count=1 ./apps/edge/internal/openai -run 'TestDevRepeatGuard(SmokeEvidence|ObservationCorrelation|ObservationQuiescence|CapacityEvidence)'
go test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
make test
```

Expected: all commands exit 0 with no formatting diff; the regressions prove disjoint identity acceptance and strict contamination rejection.

After syncing only the test-file delta and proving the non-test tree/runtime identity, exact gate/capacity/prompt bounds, idle providers, writable sanitized sink, and unchanged observation-file offset during the quiet window:

```bash
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=/tmp/iop-repeat-guard-live/repeat-guard \
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 \
go test -timeout 90m -count=1 -v ./apps/edge/internal/openai -run '^TestDevRepeatGuardOrnithSmoke$'
```

Expected: one invocation exits 0; five unique provider response IDs and five exact Edge correlations per run, 15 total unique Edge correlations, and three accepted capacity rows satisfying `configured=4`, `peak_in_flight=4`, `peak_queued>=1`, `final_in_flight=0`, and `final_queued=0`. The result is `reproduced` with sanitized fingerprint/offset or `not_reproduced`; no raw or secret value enters tracked artifacts or stdout.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/stream_gate_vertical_slice_test.go` | REVIEW_OFR-REPEAT-10-1 |
| `agent-task/m-openai-compatible-output-validation-filters/02+01_repeat_guard/CODE_REVIEW-cloud-G09.md` | REVIEW_OFR-REPEAT-10-1 evidence |

## Dependencies and Execution Order

1. Dependency `01_resume_notice_builder` is satisfied by the cited predecessor `complete.log`.
2. Correct the test oracle and add deterministic regressions.
3. Complete all fresh local verification.
4. Sync only the test delta and prove the external non-test tree, deployed runtime, gate, capacity, prompt, sink, and quiet-window preconditions.
5. Invoke the live harness once, record sanitized results and cleanup, and fill every implementation-owned review section.

## Final Verification

```bash
go version && go env GOMOD
gofmt -d apps/edge/internal/openai/stream_gate_vertical_slice_test.go
git diff --check
go test -count=1 ./apps/edge/internal/openai -run 'TestDevRepeatGuard(SmokeEvidence|ObservationCorrelation|ObservationQuiescence|CapacityEvidence)'
go test -race -count=1 ./packages/go/streamgate -run '^TestRequestRuntimeTerminalFailureFidelity/fatal_filter_overrides_success_terminal$'
go test -race -count=1 ./apps/edge/internal/openai -run 'TestDevRepeatGuard(SmokeEvidence|ObservationCorrelation|ObservationQuiescence|CapacityEvidence)'
go test -count=1 ./packages/go/streamgate ./apps/edge/internal/openai
make test
```

All local commands must exit 0 uncached. Before the live command, prove one allowed test-only runner delta and an otherwise exact reviewed production tree/runtime, both healthy idle providers with aggregate capacity 4, the enabled blocking gate, the bounded worker-owned prompt, the writable sanitized sink, and an unchanged observation offset during the quiet window. Then run the item command exactly once and require 15 unique Edge correlations, five valid provider responses per run, three accepted `4/4/>=1/0/0` capacity rows, post-run idle cleanup, and raw-free tracked evidence.

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