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

# Code Review Reference - OFR-REPEAT

> **[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 `구현 체크리스트`; 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 (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only.
> Follow the ownership table at the bottom of this file for which sections you own.

## 개요

date=2026-07-28
task=m-openai-compatible-output-validation-filters/02+01_repeat_guard, plan=0, tag=OFR-REPEAT

## Roadmap Targets

- Milestone: `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/openai-compatible-output-validation-filters.md`
- Milestone link: [Milestone 문서](agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/openai-compatible-output-validation-filters.md)
- Task ids:
  - `repeat-guard`: rolling content/history/action 반복 감지와 safe continuation
- Completion mode: check-on-pass

## 이 파일을 읽는 리뷰 에이전트에게

> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.

각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.

1. 판정과 `review_rework_count` / `evidence_integrity_failure` 라우팅 신호를 append한다.
2. `CODE_REVIEW-cloud-G10.md` → `code_review_cloud_G10_0.log`, `PLAN-cloud-G10.md` → `plan_cloud_G10_0.log`로 아카이브한다.
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-openai-compatible-output-validation-filters/02+01_repeat_guard/`로 이동한다. WARN/FAIL이면 code-review skill이 요구하는 다음 filesystem state를 완전히 작성한다.
4. PASS이면 milestone 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.

---

## 구현 항목별 완료 여부

| 항목 | 완료 여부 |
|------|---------|
| OFR-REPEAT-1 caller-neutral history preflight | [x] |
| OFR-REPEAT-2 Unicode rolling 및 action filter | [x] |
| OFR-REPEAT-3 continuation dispatch와 downstream 단일성 | [x] |
| OFR-REPEAT-4 계약 동기화와 local/dev evidence | [ ] |

## 구현 체크리스트

- [x] [OFR-REPEAT-1] Chat/Responses raw history를 role/channel/action별 bounded semantic view로 preflight하고 no-lineage/no-unsafe-mutation 규칙을 테스트한다.
- [x] [OFR-REPEAT-2] Unicode rolling/look-behind repeat 및 action guard를 pure filter decision/typed continuation intent로 구현한다.
- [x] [OFR-REPEAT-3] resume builder와 연결해 safe prefix/cursor, temperature 후보, duplicate opening/prefix 및 single terminal 경계를 검증한다.
- [ ] [OFR-REPEAT-4] 계약/spec/config 예시를 갱신하고 결정론적 generic fixture와 dev `ornith:35b` capacity+1 × 3 smoke evidence를 완료한다.
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다.

## 코드리뷰 전용 체크리스트

> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.

- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정과 검증된 `review_rework_count`, `evidence_integrity_failure`를 append한다.
- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_cloud_G10_0.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_cloud_G10_0.log`로 아카이브한다.
- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
- [ ] PASS이면 active task 디렉터리를 월별 archive로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
- [ ] PASS이면 milestone 완료 이벤트 메타데이터를 보고하고 roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
- [ ] PASS split 작업이면 이동 후 빈 active parent를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
- [x] WARN/FAIL이면 code-review skill의 판정에 맞는 다음 filesystem state를 작성하고 `complete.log`를 작성하지 않는다.

## 계획 대비 변경 사항

- The predecessor completion file had already moved from the active path to `agent-task/archive/2026/07/m-openai-compatible-output-validation-filters/01_resume_notice_builder/complete.log`. The archived PASS evidence was used instead of treating the stale active-path check as an unmet dependency.
- No new config field was added. The existing `hold_evidence_runes` contract already provides the required omitted default (500), lower/upper validation (1..65536), request-start snapshot, and selector behavior.
- Known replacement-prefix suppression is implemented in the path-neutral request-local recovery event source rather than only in `stream_gate_tunnel_codec.go`. This applies the same byte-identical one-shot suppression to normalized and tunnel Chat/Responses attempts.
- The env-gated 5-concurrent × 3-run dev harness was implemented, but the live run was not executed. Dev rules require a clean deployment whose source commit/build identity matches the implementation. The implementation is an uncommitted local feature-worktree change, while the clean dev runner is pinned to `origin/main=e24207916a8ac83169a398af6458256a0f1332e0`; deploying a dirty patch would violate the required identity contract.

## 주요 설계 결정

- Chat and Responses keep separate raw decoders. Both produce a bounded request-local snapshot containing only text/action/result fingerprints, occurrence counts, and progress flags; no raw message, reasoning, tool argument/result, caller identity, session, TTL, or inferred lineage is retained.
- Assistant anchors require at least two assistant occurrences and are excluded by any matching user occurrence. Only plain Chat reasoning aliases and Responses reasoning text items participate; encrypted, signed, malformed, and unknown fields remain canonical-only.
- The repeat filter combines Core pending evidence with committed look-behind using Unicode runes. Its continuation directive uses a UTF-8 byte-boundary cursor. When look-behind is already committed, the cursor is fixed to the released channel boundary and all pending duplicate bytes are discarded.
- A content cursor directly indexes recorded content. A reasoning cursor uses `content_length + 1 + reasoning_offset`, allowing the existing single raw-free directive cursor to select either channel without adding raw state.
- The most recent consecutive identical completed action/result fingerprint is no-progress and a repeated held action terminates without repair. A changed completed result is progress; a different action alone is insufficient. Released tool evidence or a side-effect flag turns a content repeat into a fatal safe stop.
- Continuation attempts preserve explicit caller temperature. Omitted temperature selects `0.2`, `0.4`, then `0.6` by strategy attempt. The recovery source installs the safe assistant prefix as a one-attempt byte-exact suppression guard so replacement opening/prefix echo is removed once, while novel output disables suppression immediately.
- Raw live prompt/SSE stays under ignored `agent-test/runs/**`; the tracked review may contain only model, provider availability, status, sanitized decision, fingerprint, and offset.

## 리뷰어를 위한 체크포인트

- predecessor `01_resume_notice_builder`의 `complete.log`가 구현 시작 전에 존재했는가.
- request 밖 TTL/session/caller state를 사용하지 않고 role/channel provenance와 missing reasoning degradation을 지키는가.
- 500-rune default, Unicode boundary, committed look-behind, safe cursor가 byte/rune 혼동 없이 동작하는가.
- final content/tool/signed/encrypted/unknown field를 조용히 mutate하지 않고 side-effect 뒤 repair를 금지하는가.
- caller temperature 명시값을 보존하고 생략 때만 0.2/0.4/0.6을 적용하는가.
- response-start/role/prefix/[DONE]/dispatch가 recovery cycle에서 중복되지 않는가.
- live evidence의 raw prompt/SSE/output/token이 ignored path 밖이나 stdout/tracked 문서에 없는가.

## 검증 결과

### Dependency

```bash
test -f agent-task/m-openai-compatible-output-validation-filters/01_resume_notice_builder/complete.log
```

Result:

```text
active_complete_exit=1
archive_complete_exit=0
archived completion date=2026-07-29
archived final verdict=PASS
```

The stale active path is absent because the completed predecessor was archived. The exact dependency evidence is present at `agent-task/archive/2026/07/m-openai-compatible-output-validation-filters/01_resume_notice_builder/complete.log`.

### Local

```bash
go version && go env GOMOD
git diff --check
go test -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai
make test
```

Result (exit 0):

```text
go version go1.26.2 linux/arm64
/config/workspace/iop-s1/go.mod
git diff --check: no output
ok iop/packages/go/streamgate 0.968s
ok iop/packages/go/config 0.108s
ok iop/apps/edge/internal/openai 7.308s
make test -> go test ./...: PASS
```

Focused evidence also passed:

```text
go test -count=1 ./apps/edge/internal/openai -run 'Test(OpenAIRepeatHistory|RepeatGuard)': PASS
TestRepeatGuardStreamOpenNoDuplicatePrefix: PASS
TestDevRepeatGuardOrnithSmoke without live env: SKIP as designed
```

### Dev preflight/smoke

```bash
git status --short
git rev-parse --abbrev-ref HEAD
git rev-parse HEAD
git fetch origin
git rev-parse origin/main
go version && go env GOMOD
iop-edge --help
iop-edge version
go test ./apps/edge/...
iop-edge smoke openai --base-url http://127.0.0.1:18083
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 go test -count=1 -v ./apps/edge/internal/openai -run TestDevRepeatGuardOrnithSmoke
```

Preflight result:

```text
runner=ssh toki@toki-labs.com
workdir=/Users/toki/agent-work/iop-dev
branch=main
dirty=clean
HEAD=e24207916a8ac83169a398af6458256a0f1332e0
origin/main=e24207916a8ac83169a398af6458256a0f1332e0
go=go1.26.3 darwin/arm64
gomod=/Users/toki/agent-work/iop-dev/go.mod
configured_openai_port=18083
configured_ornith_capacity=4 (3+1)
PATH iop-edge command=missing
build/dev-runtime/bin/edge version=0.1.0
build/dev-runtime/bin/edge sha256=3547f03aee10b2834362a9808b672ca54ebbf2c4e32067f02bd84d6fa6f00a85
running_edge_started=2026-07-24
```

The runner was clean-synced from the previous `7bf153ea...` checkout to `origin/main=e2420791...`. Live rebuild/redeploy/smoke was stopped before execution because the implementation source is the local feature worktree (`feature/openai-compatible-output-validation-filters`, base `1b1640ef...`, uncommitted changes), not a clean remotely addressable commit. Therefore no valid source/build identity can be established without a commit/merge action outside this implementation task's authority. The existing July 24 runtime was not reused as evidence. No raw prompt, SSE, output, token, or credential was printed or added to this tracked file.

Resume condition: make the reviewed implementation available as a clean deployment-basis commit allowed by the dev policy, then clean-sync the runner to that ref, rebuild/redeploy/restart the Edge and all participating Nodes from the same ref, verify checksums/runtime identity, and run the listed smoke command. Record `reproduced` or sanitized `not_reproduced` from the ignored summary.

---

> **[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 | Owner | Note |
|---------|-------|------|
| Header comment, 개요, 리뷰 에이전트 지시 | 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 |
| Agent UI Completion | Mixed | Present only for plan-required agent-ui code work; not applicable here |
| 구현 항목별 완료 여부 (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only |
| 구현 체크리스트 (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only |
| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section |
| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text with actual content |
| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Pre-filled from plan |
| 검증 결과 (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `계획 대비 변경 사항` entry |
| 코드리뷰 결과 | Review agent appends | Not included in stub |

## Code Review Result

- Overall Verdict: FAIL
- Dimension Assessment:
  - Correctness: Fail
  - Completeness: Fail
  - Test coverage: Fail
  - API contract: Pass
  - Code quality: Pass
  - Implementation deviation: Fail
  - Verification trust: Fail
  - Spec conformance: Fail
- Findings:
  - Required — `apps/edge/internal/openai/stream_gate_filters.go:232`: the repeated-action path fingerprints each `ToolCallFragment` independently. Real Chat and Responses streams may split one JSON argument object across multiple deltas, so a repeated `lookup({"id":1})` emitted as `{"id":` and `1}` passes instead of stopping. Aggregate held fragments by stable tool-call identity/name before canonical fingerprinting, keep incomplete arguments held through a valid completion boundary, and add split-fragment regressions for both endpoint codecs. A fresh reviewer probe reproduced `decision = "pass", want fatal`.
  - Required — `apps/edge/internal/openai/stream_gate_policy.go:202`: `hasCompletedProgress` becomes permanently true when any earlier adjacent result changed, even when the latest two completed action/result pairs are identical no-progress churn. That suppresses the latest repeat candidate required by S11. Derive progress from the latest decision-relevant completed pair and add a mixed-history regression where an older result changes but the latest identical pair must remain no-progress. A fresh reviewer probe reproduced the incorrect `completedProgress() == true`.
  - Required — `apps/edge/internal/openai/stream_gate_vertical_slice_test.go:2413`: the dev smoke accepts non-2xx responses, hard-codes the provider as unavailable, and infers the guard decision only from repeated text that was already released downstream. A correctly blocked/recovered repeat is therefore indistinguishable from a provider run with no repeat, and the harness cannot prove the required guard decision, upstream abort, continuation/safe-stop outcome, or actual provider. Require a successful HTTP/SSE response, correlate each request with raw-free `streamgate_filter_observation` evidence, and record the selected provider, repeat decision, recovery/terminal result, and single downstream completion before running the clean same-ref `ornith:35b` capacity+1 × 3 verification.
  - Required — `apps/edge/internal/openai/stream_gate_filters_test.go:89`: the Korean rolling test duplicates one generated rune block in one event; it does not implement the S03 six-paragraph, chunked multibyte fixture or exercise an assistant-history anchor through the filter decision. Replace it with the required deterministic six-paragraph stream fixture across 200/500-rune pending and committed-look-behind boundaries, and assert the history-anchor/non-suppression cases from the Evidence Map.
- Routing Signals: `review_rework_count=1`, `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.
