feat(manifest): run manifest coverage contract for review (#367)
Summary
Closes #367.
Adds a versioned, immutable RunManifest to ocr review that records per-item coverage (selected / completed / reused / failed / waived) and an authoritative terminal state (complete / partial / failed / skipped). On successful persistence, CLI JSON and session_end.run_manifest expose the same frozen manifest, so a partial review can no longer be mistaken for ordinary success or a complete no-findings result.
Built on top of PR #306's resumable sessions; this is a narrow output-contract follow-up, not a parallel persistence system.
- New
internal/session/manifest.go:RunManifestvalue object (schemaocr.run-manifest/v1),ManifestBuilder(single state table, unified transition entry,RegisterSelected/MarkCompleted/MarkReused/MarkFailed/MarkWaived),SealSelected(closes the selected denominator before dispatch),Finalize(elapsed) (RunManifest, error)with hard validation, structuredRunFailure+RunFailureClassenum, andsanitizeReasonredaction floor. internal/agent/agent.go: a pre-dispatch pass (registerCoverage) registers all post-filter, non-deleted items and seals them before resume reuse or goroutine dispatch;markCompleted/markReused/markFailedrecord per-item outcomes. The live--max-tokens-budgetgate recordsFailureBudgetas the pending-item failure cause, so only undispatched/pending items are swept tofailed(budget);BudgetExceeded()continues to feed the summary and warning.SetRunFailureis reserved for run-level stop causes at the trigger source (inputfailure onloadDiffs,internalfailure onregisterCoverage).initManifestinitializes requested input and execution metadata; resolved input and repository identity are captured from the actual run and attached before finalization.internal/diff/git.go:ResolveInputfreezes resolved base/head/exact range per input mode, including first-parent merge input to matchGetDiff --diff-merges=first-parent;RemoteIdentity/canonicalRemoteproduce a credential-free repository identity by canonicalizing the origin URL tohost[:port]/path(dropping userinfo/query/fragment) and SHA-256ing the result; local remotes omit identity.internal/session/history.go:NewManifestBuildermounts the builder onSessionHistory;Finalizenow returnserror(was void) and usessync.Oncesosession_endis written exactly once while replaying the first error on every call.internal/session/persist.go:WriteSessionEndwritessession_endas the last physical JSONL record, embeds the frozen manifest underrun_manifest, and surfaces write/flush/close errors.cmd/opencodereview: review JSON exposesmanifest; top-levelstatususes the four terminal states (scanstays legacy); aggregate-budget reporting remains available throughsummary.budget_exceeded; failed runs include the sanitized run-failure cause or failed/selected counts; text output no longer showsLooks good to me.forpartial/failed;session list/showand the viewer prefer a validsession_end.run_manifestand otherwise display legacy/unknown state without fakingcomplete.
Design (key invariants)
- Single source of truth. The terminal state is computed once in
Finalize. On successful persistence, CLI JSON andsession_end.run_manifestserialize the same frozen manifest value. JSON output no longer derives review status from warnings. - Single outcome entry. All per-item outcomes go through one transition function. Registration after seal, transitions after freeze, unknown item IDs, invalid failure classes, empty waiver reasons, and conflicting transitions return errors. Repeating the same outcome is idempotent; re-marking a failed item with a different classification is rejected.
- Seal before dispatch.
SealSelectedcloses the selected denominator after the pre-dispatch pass; resume-reused and to-be-dispatched items enter the same frozen set, soselected = completed ∪ reused ∪ failed ∪ waivedalways holds. - Explicit stop cause.
run_failureis recorded at the trigger source (input= diff resolution,internal= scheduler/invariant). It is never inferred fromctx.Err(). Ordinary aggregate budget exhaustion is a controlled coverage stop wired to--max-tokens-budget: it sets a pendingFailureBudgetcause and sweeps only uncovered items, without creatingrun_failure. Contract-level recorders forcancelledand run-leveltimeout, plusrun_failure.classification=budgetfor a genuine counter/scheduler anomaly, remain available but have no live trigger in this release (no new SIGINT handler or global deadline). - Coverage ≠ findings. Findings count never participates in terminal-state computation;
completemay have zero or many findings. - Manifest-safe redaction. Production manifest failure reasons use fixed, allow-listed summaries instead of raw provider errors.
sanitizeReasonprovides a second redaction floor for URL credentials, Bearer/Basic tokens, credential-like assignments, and control characters. CLI output suppresses rawsubtask_errorwarnings when a manifest is present. Existing session checkpoint and conversation persistence behavior is unchanged. - Persistence errors surface.
Finalize/WriteSessionEndreturn errors up the stack across all exit paths—the no-files path, theloadDiffs-failure path, the normal dispatch path, and the scan path. On the normal path, dispatch and persistence errors are reported viaerrors.Join. A persistence failure does not rewrite the frozen manifest; it surfaces as a delivery error with a non-zero exit code. - Resume preserves lineage, not copied input. A child run records its own currently resolved input and links the direct parent through
parent_run_id; immutable-ref drift rejection is unchanged and remains out of scope.
Terminal state
| State | Condition |
|---|---|
complete |
selected non-empty, failed empty, no run_failure |
partial |
0 < failed < selected, no run_failure |
failed |
all selected failed, or run_failure present |
skipped |
selected empty, no run_failure |
waived items count as covered, so a run containing only completed / reused / waived items is complete. Findings count never affects the state.
scan is unchanged and continues to emit the legacy status values; the two commands do not yet share the same status contract.
Compatibility
ocr review --format jsonintentionally migrates top-levelstatusfrom the legacysuccess/completed_with_errors/completed_with_warningsvalues (and #508'sbudget_exceeded) to the manifest terminal statescomplete/partial/failed/skipped.- Budget-aware consumers should read
summary.budget_exceededor inspectmanifest.coverage.failed[].classification == "budget"; the terminal state remains coverage-derived instead of being overwritten by the budget flag. - A budget stop exits 0 when any selected item was covered (
partial), and exits non-zero when every selected item failed (failed).scanretains its legacy output contract.
Upstream integration
This branch is synchronized through upstream/main@c391892 and preserves the upstream behavior merged while #367 was in progress:
- #508 aggregate token budget: keeps the flag, dispatch guardrail, usage summary, warnings, and
BudgetExceeded()signal; its formerstatus=budget_exceededoutput is adapted to the manifest terminal-state contract described above. - #582 per-file completion semantics: only
task_done(status=DONE)marks an item completed;FAILED, provider errors, missing completion, and structuredMainLoopStopreasons keep the item failed and flow into manifest coverage. - Merge conflicts in CLI output, agent scheduling/budget handling, llmloop termination, and scan call sites were reconciled to retain both upstream behavior and the manifest's single-source-of-truth invariants.
How to test
# 1. Run a review; inspect the manifest in JSON output.
ocr review --from main --to feature --format json | jq .manifest
# 2. A mixed-success run shows terminal_state=partial and lists failed items.
# Text mode no longer prints "Looks good to me." for partial/failed.
# 3. Resume records parent_run_id and marks checkpoint hits as reused.
ocr review --from main --to feature --resume <session-id> --format json | jq .manifest.parent_run_id
ocr review --from main --to feature --resume <session-id> --format json | jq .manifest.coverage.reused
# 4. session list/show and viewer prefer session_end.run_manifest.
ocr session list
ocr session show <session-id>
ocr viewer
Checklist
- [x]
go test -race -count=1 ./...green - [x]
go vet ./...clean - [x]
gofmt -landgo mod tidyproduce no diff - [x]
go build ./...succeeds; CLI smoke checks pass - [x] GitHub Actions and CLA checks are green
- [x] Tests cover the implemented v1 verification matrix: full success, zero findings, mixed failures, all-failed, aggregate-budget partial/all-failed exit boundaries, run-level failure (
input/internal), per-item timeout/budget/panic, skipped, resume (parent_run_id+ reused), provider transition,task_donecompletion semantics, structured main-loop stops (max_rounds/empty_rounds/compression), cancellation contract,SealSelectedlifecycle, failed-finalize rollback, conflicting/idempotent transitions, invalid failure class, empty waiver reason, cross-exit manifest consistency, malformed/legacy/aborted session display, large JSONL/non-EOF reader behavior, and security redaction - [x] On successful persistence, CLI JSON
manifestandsession_end.run_manifestserialize the same frozen manifest value - [x] Manifest fields and review CLI JSON do not expose raw provider errors, credentials, diff/prompt/response bodies, or provider tokens
Out of scope (deliberately)
scanis not wired to the v1 manifest (Non-Goal; it passes a nil manifest andemitRunResultis nil-safe) and keeps its legacystatusvalues.- Waiver user entry is deferred to a follow-up; this release only ships the
waivedoutput semantics. cancelledand run-leveltimeouthave contract coverage but no live source in this release—no new SIGINT handler or global deadline is added. Normal aggregate budget exhaustion is live through--max-tokens-budgetand is represented as per-itemfailed(budget)coverage;run_failure.classification=budgetis reserved for a separate run-level counter/scheduler anomaly and has no live trigger.- Resume matching and checkpoint persistence are unchanged. A resumed child records its own currently resolved input and links the direct parent through
parent_run_id; ref-drift rejection and "diff by immutable SHA" are deferred. - Old sessions are displayed as legacy, never faked as v1
complete.
🔍 OpenCodeReview found 7 issue(s) in this PR.
- ✅ Successfully posted inline: 7 comment(s)