<!-- task=m-iop-hot-path-one-shot-execution/11+09,10_cleanup plan=3 tag=REVIEW_REVIEW_REVIEW_API milestone-task=cleanup -->

# Review Follow-up: Correlation-Valid Artifact Receipt Cleanup

## For the Implementing Agent

Implement every checklist item, run every verification command with fresh output, and fill the implementation-owned sections in `CODE_REVIEW-cloud-G08.md`. Keep the active PLAN/review pair in place and report ready for review. If blocked, record only the exact blocker, attempted commands/output, and resume condition in the 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; finalization belongs to the code-review skill.

## Background

The current primary-error cleanup path handles artifact results with explicit error fields, but it rejects other exact receipt-matcher failures before entering cleanup. A partially successful Plan/Review pair can therefore leave a caller workspace artifact when the other exact result reports `{"written":false}`. SDD S09 requires every correlation-valid artifact-bearing failure to attempt caller-executed cleanup while preserving the original endpoint error.

## Dependencies and Execution Order

- `09+06,08_artifact_pair` is complete at `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/09+06,08_artifact_pair/complete.log`.
- `10+07,09_light_flow` is complete at `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log`.
- Both archived PASS records satisfy the dependencies encoded by `11+09,10_cleanup`; no new predecessor is introduced.

## Archive Evidence Snapshot

- Current review archive after finalization: `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/code_review_cloud_G09_2.log`.
- Earlier reviews: `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/code_review_cloud_G10_0.log` and `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/code_review_cloud_G10_1.log`.
- Current verdict: FAIL; findings: Required 1, Suggested 0, Nit 0.
- Required gap: `artifact_pair.go` promotes only explicit-error receipt failures to the primary-error cleanup transaction and immediately rejects other correlation-valid matcher failures.
- Reviewer reproduction: an exact successful Plan result plus Review result `{"written":false}` returned HTTP 400 on both OpenAI and Anthropic with no delete frontier.
- Trusted passing evidence: focused primary-error race tests, cleanup/TTL race tests, common package race tests, full Edge tests with an executable temporary directory, vet, format, and diff checks all passed; those suites omit the reproduced partial-pair matcher-failure variant.
- Affected implementation area: `artifact_pair.go`, the obsolete explicit-error classifier in `workspace_tool_codec.go`, and focused cleanup tests.
- Roadmap carryover: milestone task `cleanup`, approved and unlocked SDD Acceptance Scenario/Evidence Map row S09 only.

## Analysis

### Files Read

- `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/PLAN-cloud-G09.md`
- `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/CODE_REVIEW-cloud-G09.md`
- `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/code_review_cloud_G10_1.log`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-hot-path-one-shot-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `agent-contract/index.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `apps/edge/internal/openai/artifact_pair.go`
- `apps/edge/internal/openai/hot_path_cleanup.go`
- `apps/edge/internal/openai/hot_path_light.go`
- `apps/edge/internal/openai/hot_path_review.go`
- `apps/edge/internal/openai/request_identity_ingress.go`
- `apps/edge/internal/openai/request_coordinator.go`
- `apps/edge/internal/openai/request_coordinator_ttl.go`
- `apps/edge/internal/openai/workspace_tool_codec.go`
- `apps/edge/internal/openai/chat_handler.go`
- `apps/edge/internal/openai/anthropic_handler.go`
- `apps/edge/internal/openai/hot_path_cleanup_test.go`
- `apps/edge/internal/openai/workspace_tool_binding_test.go`

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`; status `[승인됨]`; SDD lock released.
- First-line milestone task: `cleanup`.
- Targeted Acceptance Scenario and Evidence Map row: S09.
- S09 requires artifact-bearing errors to attempt caller-executed cleanup, retain the endpoint primary error across cleanup acknowledgement failure, avoid hidden work after disconnect, and leave bounded TTL-owned orphan responsibility when cleanup cannot complete. The implementation checklist therefore separates trusted issue correlation from receipt success semantics and requires both protocol surfaces plus cleanup acknowledgement/error-precedence evidence.

### Verification Context

The active review handoff and fresh reviewer execution were consumed. Source paths are the files listed above. On Go 1.26.2 linux/arm64 in the current dirty checkout, the reviewer reran registration, focused primary-error races, cleanup/TTL races, common package races, full `./apps/edge/...` with `TMPDIR` under `/config/workspace`, vet, formatting, and diff checks; all exited 0. A temporary public-handler table reproducer then failed on both endpoints with HTTP 400 and no delete frontier for an exact partial pair containing `{"written":false}`; the temporary file was removed. Constraints exclude external services, credentials, real workspace deletion, and live provider smoke. Confidence is high because the failing case exercises both public handlers and the same scripted tool/frontier transaction as the passing suite. Repository-native fallback evidence is the Edge local test profile, existing scripted fixture, exact receipt matcher tests, and approved S09 criteria. No required verification leaves the checkout.

### Test Coverage Gaps

- Explicit-error prepare and pair receipts: covered by `TestHotPathCleanupPrimaryErrorPrecedence`.
- Correlation-valid pair receipt that fails only the configured matcher: not covered and reproduced as no-cleanup HTTP 400 on both endpoints.
- Malformed identity, lineage, or immutable issue correlation: covered by artifact/coordinator tests and must remain an immediate validation error rather than authorize cleanup.
- Cleanup acknowledgement failure after a stored primary error: covered for explicit-error variants; extend the same assertion to the matcher-failure variant.
- Local/review primary errors, cancellation, duplicate cleanup results, TTL races, redaction, and successful cleanup: covered and unchanged.

### Symbol References

No public symbol is renamed. `workspaceResultExplicitlyFailed` is referenced only by `artifactFrontierStore.consume`; remove it after the classifier no longer depends on the explicit-error subset. `matchResultCorrelation`, `matchResultReceipt`, and `beginPrimaryErrorCleanup` remain the shared issue-correlation, receipt, and cleanup boundaries.

### Split Judgment

Keep one plan. Receipt classification, primary-error storage, cleanup issue, acknowledgement precedence, and both endpoint fixtures form one transaction invariant; splitting the classifier from its regression evidence would leave an independently unverified artifact leak. Predecessor indices 09 and 10 are satisfied by the exact archived `complete.log` paths listed above.

### Scope Rationale

Exclude cleanup success-start failure, local/review dispatch changes, TTL redesign, actual filesystem deletion, durable orphan queues, public schema changes, S10+ terminal/usage work, and S16 live smoke. Preserve the existing correlation digest, request lineage, receipt matcher, endpoint error envelopes, caller-executed delete encoding, and cleanup coordinator transition. Only correlation-valid artifact receipt mismatches and their deterministic evidence are in scope.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`; capability gap: none.
- Build closures: `scope_closed=true`, `context_closed=true`, `verification_closed=true`, `evidence_trusted=true`, `ownership_closed=true`, `decision_closed=true`. Scores `(scope=1,state=2,blast=1,evidence=2,verification=1)` produce G07 with base `local-fit`; recovery signals select `recovery-boundary`, lane `cloud`, filename `PLAN-cloud-G07.md`.
- Review closures: all six closure fields true. Scores `(2,2,1,2,1)` produce G08 with `official-review`, lane `cloud`, adapter `codex`, model `gpt-5.6-sol`, reasoning effort `xhigh`, filename `CODE_REVIEW-cloud-G08.md`.
- `large_indivisible_context=false`; positive loop-risk signatures are `temporal_state`, `concurrent_consistency`, `boundary_contract`, and `variant_product` (`loop_risk_count=4`).
- Recovery signals: `review_rework_count=3`, `evidence_integrity_failure=true`; risk and recovery boundaries both match.

## Implementation Checklist

- [x] Promote every receipt mismatch with valid lineage, pending-call identity, and immutable issue correlation to the stored artifact primary error while preserving immediate rejection for invalid correlation.
- [x] Remove the obsolete explicit-error-only artifact classifier without changing receipt matcher or endpoint error semantics.
- [x] Add deterministic OpenAI and Anthropic partial-pair matcher-failure coverage for delete issue, cleanup acknowledgement failure, original error precedence, and provider-call count.
- [x] Run all focused and final verification commands with fresh output.
- [x] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_REVIEW_REVIEW_API-1] Admit every correlation-valid artifact receipt failure to primary cleanup

#### Problem

`artifactFrontierStore.consume` (`artifact_pair.go:444-455`) has already matched request lineage, pending public call identity, and the immutable issued payload, but it stores a primary error only when `workspaceResultExplicitlyFailed` sees an explicit status or `error` field. A result such as `{"written":false}` is equally exact and fails the configured success matcher, yet it returns before `consumeContinuationByLineage` and cannot issue cleanup after the sibling pair write may have succeeded.

#### Solution

Compute immutable issue correlation once for every mismatched receipt. If correlation is valid, store the first receipt mismatch as the primary endpoint error and continue consuming the exact frontier so cleanup can replace the resumed artifact stage. If correlation is invalid, keep the immediate validation rejection. Remove `workspaceResultExplicitlyFailed`, which becomes obsolete; do not weaken `matchResultReceipt`, `matchResultCorrelation`, lineage, owner, principal, or expected-set validation.

Before (`artifact_pair.go:444-455`):

```go
receipt := matchResultReceipt(record.binding, payload, result)
if !receipt.matched {
    if matchResultCorrelation(record.binding, payload, result) == "" && workspaceResultExplicitlyFailed(result) {
        if primaryFailure == nil {
            primaryFailure = &hotPathEndpointError{/* existing endpoint error */}
        }
        continue
    }
    return logicalRequestSnapshot{}, artifactDisposition{}, true, fmt.Errorf("artifact receipt rejected: %s", receipt.mismatchReason)
}
```

After:

```go
receipt := matchResultReceipt(record.binding, payload, result)
if !receipt.matched {
    if correlationReason := matchResultCorrelation(record.binding, payload, result); correlationReason != "" {
        return logicalRequestSnapshot{}, artifactDisposition{}, true,
            fmt.Errorf("artifact receipt rejected: %s", receipt.mismatchReason)
    }
    if primaryFailure == nil {
        primaryFailure = &hotPathEndpointError{/* existing endpoint error */}
    }
    continue
}
```

#### Modified Files and Checklist

- [x] `apps/edge/internal/openai/artifact_pair.go` — separate immutable issue-correlation rejection from correlation-valid receipt failure cleanup.
- [x] `apps/edge/internal/openai/workspace_tool_codec.go` — remove the now-unused explicit-error-only classifier.

#### Test Strategy

Do not add a codec-only test because `TestWorkspaceBindingReceipts` already proves that `{"written":false}` fails the configured matcher and wrong identity fails issue correlation. The public handler regression in the next item must prove the state transition and endpoint result.

#### Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run '^TestHotPathCleanupPrimaryErrorPrecedence$'
```

Expected: exit 0; correlation-valid matcher failures enter cleanup while existing explicit-error and precedence cases remain green.

### [REVIEW_REVIEW_REVIEW_API-2] Close partial-pair matcher-failure evidence

#### Problem

`TestHotPathCleanupPrimaryErrorPrecedence` covers explicit `error` fields but not a successful sibling write plus an exact result that fails only the configured receipt matcher. The required suite therefore passes while both public handlers still skip cleanup for a possible orphan.

#### Solution

Extend the existing precedence table with a partial pair whose Plan result matches and Review result is `{"written":false}`. For OpenAI and Anthropic, assert one canonical delete frontier, matching and failing cleanup acknowledgements, the original HTTP 400 type/message after cleanup, absence of `workspace cleanup failed`, exactly two selector provider calls, and removal of coordinator/light/artifact state after terminal commit. Retain the existing malformed correlation tests as the proof that untrusted results cannot authorize delete.

#### Modified Files and Checklist

- [x] `apps/edge/internal/openai/hot_path_cleanup_test.go` — add both-protocol partial-pair matcher-failure and cleanup-precedence cases.
- [x] `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/CODE_REVIEW-cloud-G08.md` — record implementation decisions, deviations, and raw output for every command.

#### Test Strategy

Extend `TestHotPathCleanupPrimaryErrorPrecedence` rather than create a disconnected test. Use the existing scripted public-handler fixture and endpoint table; no external workspace, provider, credential, or live smoke is required.

#### Verification

```bash
go test ./apps/edge/internal/openai -list '^TestHotPathCleanupPrimaryError' | rg '^TestHotPathCleanupPrimaryError'
go test -race -count=1 ./apps/edge/internal/openai -run '^TestHotPathCleanupPrimaryError'
```

Expected: exit 0; registration remains deterministic and every explicit-error or matcher-failure primary-error variant passes freshly under the race detector.

## Modified Files Summary

| File | Items |
|------|-------|
| `apps/edge/internal/openai/artifact_pair.go` | REVIEW_REVIEW_REVIEW_API-1 |
| `apps/edge/internal/openai/workspace_tool_codec.go` | REVIEW_REVIEW_REVIEW_API-1 |
| `apps/edge/internal/openai/hot_path_cleanup_test.go` | REVIEW_REVIEW_REVIEW_API-2 |
| `agent-task/m-iop-hot-path-one-shot-execution/11+09,10_cleanup/CODE_REVIEW-cloud-G08.md` | REVIEW_REVIEW_REVIEW_API-2 |

## Final Verification

```bash
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/09+06,08_artifact_pair/complete.log
test -f agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/10+07,09_light_flow/complete.log
go test ./apps/edge/internal/openai -list '^TestHotPathCleanupPrimaryError' | rg '^TestHotPathCleanupPrimaryError'
go test -race -count=1 ./apps/edge/internal/openai -run '^TestHotPathCleanupPrimaryError'
go test -race -count=1 ./apps/edge/internal/openai -run '^Test(LogicalRequestTTL|HotPathCleanup)'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
edge_test_tmpdir="$(mktemp -d /config/workspace/iop-edge-test.XXXXXX)"
chmod 700 "$edge_test_tmpdir"
TMPDIR="$edge_test_tmpdir" go test -count=1 ./apps/edge/...
edge_test_status=$?
rmdir "$edge_test_tmpdir"
exit "$edge_test_status"
```

Run the remaining static checks in a new shell after the full Edge command:

```bash
go vet ./apps/edge/...
gofmt -d apps/edge/internal/openai/artifact_pair.go apps/edge/internal/openai/workspace_tool_codec.go apps/edge/internal/openai/hot_path_cleanup_test.go
git diff --check
```

Expected: every command exits 0; registration lists the primary-error suite; focused and common race suites pass freshly; the full Edge suite passes with the executable temporary directory removed; `gofmt -d` and `git diff --check` print nothing. No external credential, real workspace mutation, or live provider is required.

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