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

# Code Review Reference - REVIEW_OFR-REPEAT-2

> **[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, 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-29
task=m-openai-compatible-output-validation-filters/02+01_repeat_guard, plan=2, tag=REVIEW_OFR-REPEAT-2

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

- 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`.
- First failed loop: `plan_cloud_G10_0.log` and `code_review_cloud_G10_0.log`.
- Immediate prior plan/review: `plan_cloud_G10_1.log` and `code_review_cloud_G10_1.log`; verdict FAIL.
- Required follow-up:
  - make assistant-history anchors invariant to novel prefixes and event boundaries;
  - prove split Chat/Responses action hold, block, and release through configured Core and release sinks;
  - remove observation-order correlation fallback and prove capacity peak/queue/final recovery in the clean same-ref live run.
- Reviewer local verification passed, but a fresh assistant-anchor probe failed with `decision = "pass", want violation`.
- Dev blocker: no clean remotely addressable ref currently contains the reviewed implementation. Resume only after an authorized ref exists, followed by same-ref rebuild/redeploy/restart and identity proof.

## 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_2.log` and `PLAN-cloud-G10.md` → `plan_cloud_G10_2.log`.
3. If PASS, write `complete.log` and move active task directory to `agent-task/archive/YYYY/MM/m-openai-compatible-output-validation-filters/02+01_repeat_guard/`. 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-REPEAT-2-1 | [x] |
| REVIEW_OFR-REPEAT-2-2 | [x] |
| REVIEW_OFR-REPEAT-2-3 | [x] |

## Implementation Checklist

- [x] [REVIEW_OFR-REPEAT-2-1] Make assistant-history anchor matching bounded, raw-free, and invariant to novel prefixes and provider event boundaries.
- [x] [REVIEW_OFR-REPEAT-2-2] Prove split Chat and Responses action fragments through the configured production Core and release sink.
- [x] [REVIEW_OFR-REPEAT-2-3] Require exact per-request observation correlation and record/assert Ornith capacity, queue, and final recovery in the dev harness.
- [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_2.log`.
- [x] Archive active `PLAN-*-G??.md` to `plan_cloud_G10_2.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/02+01_repeat_guard/` to `agent-task/archive/YYYY/MM/m-openai-compatible-output-validation-filters/02+01_repeat_guard/` 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 production split-action matrix exposed a Core precedence defect outside the planned OpenAI-only file list: a blocking fatal filter evaluated on a provider success terminal produced `ArbitrationActionTerminal` with a filter attribution, but `RequestRuntime` committed the base success terminal before considering that attribution. `packages/go/streamgate/runtime.go` now gives an attributed terminal arbitration precedence over the base success disposition, and `packages/go/streamgate/runtime_test.go` pins the error terminal and filter/rule cause. This is the minimum production-path correction needed for the planned no-tool-wire assertion and aligns the existing terminal arbitration contract.
- Dev preflight and live verification were not run. The reviewed implementation remains dirty local feature work and no authorized clean remotely addressable ref containing it was supplied. The plan explicitly prohibits stale runtime evidence; the exact blocker and resume condition are recorded below.

## Key Design Decisions

- Assistant candidates retain only fingerprint, count, and normalized rune length. Admission remains globally capped at 1,024 raw-free fingerprints; already admitted fingerprints can still receive a later user occurrence so the provenance exclusion cannot be bypassed after the cap fills.
- Matching normalizes only the bounded rolling tail, transiently maps normalized runes back to original UTF-8 byte offsets, hashes candidate-sized windows, and selects the earliest source match with a longer-window tie break. No request-history text is retained.
- Rolling repeated-suffix matches that consume committed look-behind resume at the released boundary, preserving the existing one-safe-prefix contract. Assistant-history anchors retain an exact novel pending prefix when the anchor starts after that boundary.
- The action lifecycle test uses raw split Chat and Responses provider frames, the configured production registry, Core runtime, endpoint codec, and real tunnel release sink. It asserts zero pre-terminal caller wire, fatal/no-tool-wire behavior for repetition, and exact-once lifecycle release for a distinct action.
- Live evidence now requires an SSE-derived request correlation for every result and rejects missing, unknown, reused, or order-inferred mappings. Status parsing selects only the configured provider IDs, aggregates their capacity counters, and records one validated `4/4/>=1/0/0` row per run. The summary is accepted only with 15 attempts and three capacity rows.
- No contract or agent-spec correction was required by this follow-up; the implementation restores the already documented raw-free, terminal-gated, request-local behavior.

## Reviewer Checkpoints

- Assistant anchors are detected at the same UTF-8-safe cursor with a novel prefix in one event, separate events, and across pending/look-behind; user occurrence and completed progress still exclude the candidate.
- Candidate metadata remains bounded and raw-free; no raw history, caller/session/TTL, or inferred lineage is introduced.
- Raw split Chat and Responses tool frames enter the configured repeat-action filter through production Core and the endpoint release sink.
- Incomplete/repeated actions produce no downstream tool wire; a distinct completed action stays held until terminal evaluation and releases exactly once.
- Every live response has one explicit expected correlation matching one unused observation group; no log-order fallback remains.
- Each of three Ornith runs records capacity `4`, peak in-flight `4`, queued at least `1`, and final in-flight/queued `0/0`.
- Dev evidence comes from one clean reviewed ref with matching Edge/Node source, build, deploy, restart, and process identities.
- Raw prompt/SSE/token/provider payloads remain under ignored runtime paths and never enter stdout or tracked artifacts.

## Verification Results

### Local focused

```bash
go version && go env GOMOD
git diff --check
go test -race -count=1 ./apps/edge/internal/openai -run 'Test(OpenAIRepeatHistoryAssistantCandidateMetadata|RepeatGuardAssistantHistoryAnchorBoundaries|StreamGateConfiguredRepeatActionSplitLifecycle|DevRepeatGuardObservationCorrelation|DevRepeatGuardCapacityEvidence)'
```

Result:

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

$ git diff --check
[no output; exit 0]

$ go test -race -count=1 ./apps/edge/internal/openai -run 'Test(OpenAIRepeatHistoryAssistantCandidateMetadata|RepeatGuardAssistantHistoryAnchorBoundaries|StreamGateConfiguredRepeatActionSplitLifecycle|DevRepeatGuardObservationCorrelation|DevRepeatGuardCapacityEvidence)'
ok  	iop/apps/edge/internal/openai	1.419s

Additional plan-item probes:
$ go test -race -count=1 ./apps/edge/internal/openai -run 'Test(OpenAIRepeatHistoryAssistantCandidateMetadata|RepeatGuardAssistantHistoryAnchorBoundaries|RepeatGuardAssistantHistoryAnchorDecision)'
ok  	iop/apps/edge/internal/openai	1.051s

$ go test -race -count=1 ./apps/edge/internal/openai -run 'Test(StreamGateConfiguredRepeatActionSplitLifecycle|RepeatGuardSplitToolArguments|OpenAITunnelCodecSemanticFrames)'
ok  	iop/apps/edge/internal/openai	1.097s

$ go test -count=1 ./apps/edge/internal/openai -run 'TestDevRepeatGuard(SmokeEvidence|ObservationCorrelation|CapacityEvidence)'
ok  	iop/apps/edge/internal/openai	0.326s
```

### Local full

```bash
go test -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai
make test
```

Result:

```text
$ go test -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai
ok  	iop/packages/go/streamgate	0.934s
ok  	iop/packages/go/config	0.115s
ok  	iop/apps/edge/internal/openai	7.370s

$ make test
go test ./...
ok  	iop/apps/control-plane/cmd/control-plane	(cached)
ok  	iop/apps/control-plane/internal/wire	(cached)
ok  	iop/apps/edge/cmd/edge	(cached)
ok  	iop/apps/edge/internal/bootstrap	(cached)
ok  	iop/apps/edge/internal/configrefresh	(cached)
ok  	iop/apps/edge/internal/controlplane	(cached)
ok  	iop/apps/edge/internal/edgecmd	(cached)
ok  	iop/apps/edge/internal/edgevalidate	(cached)
ok  	iop/apps/edge/internal/events	(cached)
ok  	iop/apps/edge/internal/input	(cached)
ok  	iop/apps/edge/internal/input/a2a	(cached)
ok  	iop/apps/edge/internal/node	(cached)
ok  	iop/apps/edge/internal/openai	7.411s
ok  	iop/apps/edge/internal/opsconsole	(cached)
ok  	iop/apps/edge/internal/service	(cached)
ok  	iop/apps/edge/internal/transport	(cached)
ok  	iop/apps/node/cmd/node	(cached)
ok  	iop/apps/node/internal/adapters	(cached)
?   	iop/apps/node/internal/adapters/mock	[no test files]
ok  	iop/apps/node/internal/adapters/ollama	(cached)
ok  	iop/apps/node/internal/adapters/openai_compat	(cached)
ok  	iop/apps/node/internal/adapters/vllm	(cached)
ok  	iop/apps/node/internal/bootstrap	(cached)
ok  	iop/apps/node/internal/node	(cached)
ok  	iop/apps/node/internal/router	(cached)
ok  	iop/apps/node/internal/store	(cached)
ok  	iop/apps/node/internal/transport	(cached)
?   	iop/apps/worker/cmd/worker	[no test files]
ok  	iop/cmd/iop-provider-smoke	(cached)
ok  	iop/packages/go/agentconfig	(cached)
ok  	iop/packages/go/agentguard	(cached)
ok  	iop/packages/go/agentprovider/catalog	(cached)
ok  	iop/packages/go/agentprovider/cli	(cached)
?   	iop/packages/go/agentprovider/cli/internal/testutil	[no test files]
ok  	iop/packages/go/agentprovider/cli/status	(cached)
ok  	iop/packages/go/agentruntime	(cached)
ok  	iop/packages/go/agenttask	(cached)
ok  	iop/packages/go/audit	(cached)
?   	iop/packages/go/auth	[no test files]
ok  	iop/packages/go/config	(cached)
?   	iop/packages/go/events	[no test files]
ok  	iop/packages/go/hostsetup	(cached)
?   	iop/packages/go/jobs	[no test files]
?   	iop/packages/go/metadata	[no test files]
ok  	iop/packages/go/observability	(cached)
?   	iop/packages/go/policy	[no test files]
ok  	iop/packages/go/streamgate	(cached)
?   	iop/packages/go/version	[no test files]
?   	iop/proto/gen/iop	[no test files]
ok  	iop/scripts/inventory-query	(cached)
```

### Dev preflight

```bash
git status --short
git rev-parse --abbrev-ref HEAD
git rev-parse HEAD
git fetch origin main
git rev-parse origin/main
go version && go env GOMOD
./build/dev-runtime/bin/edge --help
./build/dev-runtime/bin/edge version
shasum -a 256 ./build/dev-runtime/bin/edge
go test -count=1 ./apps/edge/...
./build/dev-runtime/bin/edge smoke openai --base-url http://127.0.0.1:18083
curl -fsS http://127.0.0.1:18001/edges/edge-toki-labs-dev/status |
  jq '[.nodes[].provider_snapshots[] | select(.id == "onexplayer-lemonade" or .id == "rtx5090-lemonade") | {id,capacity,in_flight,queued,health}]'
```

Record the clean approved ref, source sync, all participating Edge/Node rebuild/deploy/restart identities, Edge id/ports, provider capacities, process start times, and exact result. Do not run against stale binaries.

Result:

```text
NOT RUN — blocked before remote fetch, runtime inspection, build, deploy, restart,
or smoke execution.

Read-only local state:
$ git rev-parse --abbrev-ref HEAD
feature/openai-compatible-output-validation-filters

$ git rev-parse HEAD
1fe4b9adec02b5135cca8a4b674c92b7f3430948

$ git status --short | awk 'END {print "changed_paths=" NR}'
changed_paths=32

The reviewed implementation is present only as dirty local feature work, so the
current HEAD does not identify the reviewed source and cannot provide the clean
same-ref identity required by the plan. No authorized remotely addressable ref
containing these changes was supplied. Running the remaining preflight commands
would inspect or execute a stale runtime and was intentionally stopped.

Resume condition: provide an authorized clean ref containing the reviewed
changes; clean-sync the dev runner to that exact ref; rebuild, redeploy, and
restart Edge and every participating Node from it; record source commit, binary
checksums/help/version, process start times, ports, provider status, and aggregate
capacity 4; then run the preflight and live command exactly.
```

### Dev live repeat guard

```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=agent-test/runs/output-filter-recovery/repeat-prompt.txt \
IOP_OPENAI_SMOKE_ARTIFACT_DIR=agent-test/runs/output-filter-recovery/repeat-guard \
IOP_OPENAI_SMOKE_OBSERVATION_FILE=agent-test/runs/output-filter-recovery/repeat-guard/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 -count=1 -v ./apps/edge/internal/openai -run '^TestDevRepeatGuardOrnithSmoke$'
```

Expected: 15 exactly correlated sanitized attempts and three capacity rows with capacity/peak/queue/final values `4/4/>=1/0/0`.

Result:

```text
NOT RUN — the clean approved same-ref deployment prerequisite above is not
satisfied. No stale July 24 runtime or unrelated remote checkout was used, and
no live summary is claimed.

Resume only after the preflight proves one clean reviewed ref and matching
Edge/Node source, binaries, deployments, restarts, and process identities. Then
run the fixed command exactly and require exit 0, 15 explicitly correlated
sanitized attempts, and three capacity rows with
configured/peak/queued/final-in-flight/final-queued = 4/4/>=1/0/0.
```

---

> **[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
  - Completeness: Fail
  - Test coverage: Fail
  - API contract: Fail
  - Code quality: Pass
  - Implementation deviation: Fail
  - Verification trust: Fail
  - Spec conformance: Fail
- Findings:
  - Required — `packages/go/streamgate/runtime.go:1311`: the new blocking-filter precedence commits an error terminal to the release sink, but `terminal_committed` still branches only on the provider base disposition. When a fatal terminal-gated filter overrides a provider success terminal, the observation is therefore emitted with `terminal_reason="completed"` and no failure cause even though the caller path received an error terminal. This contradicts the raw-free terminal lifecycle contract used by the production repeat-action path and the dev evidence correlator. Branch the terminal observation on the attributed filter result before the base success disposition, emit the fatal causes, and add a runtime regression that asserts both the sink terminal and `terminal_committed` observation. A fresh reviewer-only probe reproduced `fatal terminal observation reason = "completed", want empty`; the probe file was removed.
  - Required — `agent-task/m-openai-compatible-output-validation-filters/02+01_repeat_guard/CODE_REVIEW-cloud-G10.md:262`: the S07 and `repeat-guard` completion evidence still lacks the required clean same-ref `ornith:35b` capacity+1 × 3 run. The local harness now enforces unique SSE-derived correlations and `4/4/>=1/0/0` capacity evidence, but no reviewed source/build/deploy/restart identity, 15-attempt sanitized summary, or three live capacity rows exists. Place the reviewed correction on an authorized clean ref, rebuild/redeploy/restart every participating Edge and Node from that exact ref, record identities, and execute the fixed live command before claiming the roadmap task complete.
- Routing Signals: `review_rework_count=3`, `evidence_integrity_failure=false`
- Next Step: Archive this failed pair and create the routed follow-up PLAN/CODE_REVIEW pair for the same task path.
