Skip to main content

prikk_store/
verify.rs

1//! Repository verification routines.
2//!
3//! Verification is read-only. It checks object identity, object-type placement, envelope decoding,
4//! sealed block references, joint ref publication state, active WAL replay checksums, and retained
5//! active-publication cleanup state. Mutation belongs to narrow doctor or signer-backed seal paths.
6//!
7//! **A check's own code being present does not establish that a defect actually reaches it.** Earlier
8//! gates in this module's pipeline can intercept a malformed input before a specific, later check ever
9//! sees it -- so a check existing, and even a fixture that constructs the shape that check is meant to
10//! reject, are not proof the check is exercised. Two independent instances (DC-95 Stage 1 rounds 10 and
11//! 11): `ref_publication::require_retained_evidence` reclassifies several `refs/verify.rs` codes before
12//! they're returned, so a raw pointer/log-shape fixture can silently land on a different code than the
13//! one under test; `crate::format::validate_read_schema`, called from `Wal::replay()` itself, already
14//! rejects a malformed-shape signature under `RepositoryFormat::CurrentV6` before
15//! `rollback_verify::verify_rollback_draft_wal_records` is ever reached, so the same defect is reachable
16//! only under `RepositoryFormat::LegacyV1`. Building a fixture for a specific check in this module means
17//! tracing its actual call path from `verify_repository`, not just constructing input shaped to match
18//! the check's own condition.
19//!
20//! **Do not report a result derived from a step that may not have run.** The general form of a rule
21//! found three times, from three directions, across DC-95 Stage 1 and Stage 2 (`stage-2-level-1-sweep-
22//! ruling-v1.md` §4): a check's presence in the source is not proof a defect reaches it (above); an
23//! empty accumulator is not "none found" if its producer did not run to completion; a partial count is
24//! not "this many verified" if the stage computing it stopped partway through. All three are the same
25//! error seen from different angles -- inferring a result from the absence of evidence when the
26//! evidence-gathering step itself may not have happened. `require_retained_evidence`'s own `trust_is_
27//! valid` (see [`VerificationStage::PublicationReclassification`] below) is the concrete instance the
28//! second form was caught in: `trust_verifier.issues.is_empty()` alone reads `true` when the `Objects`
29//! stage failed before checking a single Block or RefState, which is not the same fact as "every
30//! relevant object was checked and found trustworthy." It is `issues.is_empty() && objects_evaluated`
31//! for exactly this reason. The third form is why `RepositoryVerification`'s per-stage counts
32//! (`checked_objects` and its siblings) are `Option<usize>`, `None` rather than a partial number, when
33//! their producing stage did not evaluate to completion -- a partial count is a completeness claim in
34//! miniature, and `verify_objects`'s own topological pass over the whole object store means a partial
35//! per-type count says nothing about whether the objects it did see are individually sound.
36//!
37//! # DC-95 Stage 2, Level 1: scope containment
38//!
39//! `verify_repository`'s pipeline is thirteen stages (see [`VerificationStage`]), each a `?`-propagating
40//! call in the pre-Stage-2 source. Stage 1 (above) proved which checks inside those stages are load-
41//! bearing; Stage 2 Level 1 changed what happens when one fails. **Before:** the first hard error
42//! anywhere aborted `verify_repository` entirely -- every later stage silently never ran, and
43//! `print_verify_report` never printed anything but the one error string. **After:** each stage's own
44//! `?` is caught at the boundary and recorded as a [`StageOutcome`] rather than propagated; the
45//! pipeline continues to the remaining stages regardless. A `Failed` stage's own error becomes its
46//! `StageOutcome`'s message; a stage that could not run because a real dependency ([`StageStatus::
47//! NotEvaluated`], naming that dependency) is blocking on the same footing -- an incomplete
48//! verification is not a passing one, so `RepositoryVerification::has_stage_failure` covers both, plus
49//! a third state, [`StageStatus::Halted`], for `--stop-on-first-error`: a stage that was never attempted
50//! because an *unrelated* earlier stage's failure already stopped the walk. `Halted` is kept distinct
51//! from `NotEvaluated` because `blocked_by` is a dependency-graph claim -- reporting `NotEvaluated {
52//! blocked_by: Objects }` for `LifecycleCache`, which does not depend on `Objects` at all, would assert
53//! an edge that does not exist (implementation review v1 §4). The distinction only matters under
54//! `--stop-on-first-error`; in the default full-accumulation walk, every `NotEvaluated` names a real
55//! dependency and `Halted` never appears.
56//!
57//! **The Stage 1 classification table below is unchanged by this**: which checks are load-bearing,
58//! downstream-redundant, excluded, or unreachable is a fact about the checks themselves, not about how
59//! their failures propagate out of `verify_repository`. What changed is the shape a reader (or
60//! `doctor_repository`, or `prikk verify`'s own exit-code chain) sees a failing check through: a
61//! `StageOutcome` against the owning stage, not a bare `Result::Err` from the whole function. Checks
62//! were not rewritten, moved, or deleted to get here -- only the thirteen top-level boundaries around
63//! them.
64//!
65//! # RFC 103: format-1 retirement, and its effect on the table below
66//!
67//! `RepositoryFormat::LegacyV1` is deleted; a format-1 repository is now rejected at
68//! `RepositoryLayout::open`, before `verify_repository` (or anything else) can run against it. Three
69//! rows in the table below changed status as a direct consequence, all still classified, none left to
70//! drift: `LEGACY-LOG-LEADS` and `LEGACY-TIMESTAMP` (both format-1-gated branches that can now never
71//! execute, since the format they branched on no longer exists) are deleted outright rather than kept
72//! as unreachable, since deleting the dead branch was possible and cheaper than documenting it;
73//! rollback AUTHOR signature wrong-length moves from load-bearing to unreachable, since round 11 had
74//! already established format-1 as its only reachable path (`rollback_verify.rs` carries the argument
75//! at the check site, per round 6's ruling on unreachable checks). `legacy_state_roots_unverifiable`
76//! (a precondition fact, not a table row) is deleted with it. The three-row figure matches RFC 103's
77//! own accounting, corrected once during that RFC's own prerequisite investigation:
78//! `LEGACY-TIMESTAMP`'s status change was found only by re-reading this table, not carried in the
79//! RFC's original draft.
80//!
81//! # RFC 102 Stage 2: isolate-and-continue reading, and its effect on the table below
82//!
83//! A mid-stream checksum mismatch in the active WAL or a ref log no longer aborts the whole read: the
84//! frame at that offset is recorded as a failed item (`wal::WalRecordOutcome` /
85//! `refs::log::RefLogRecordOutcome`) and a byte-wise resync finds the next candidate frame, so every
86//! sound record after the damaged one is still read (RFC 102 §3, `wal.rs`'s `decode_records` and
87//! `refs/log.rs`'s `decode_log_records`). **The two rows this changes stay Load-bearing** -- disabling
88//! either check still lets a defective repository pass with no trace, exactly the property this table
89//! tracks -- but the failure they produce is now item-level (`RepositoryVerification::has_item_failure`,
90//! via the new `wal_record_outcomes` field), not a `WalReplay` stage failure, the same shift DC-95 Stage
91//! 2 Level 2 already made for `verify_objects` and `verify_refs`. `Wal::replay()`'s own post-decode
92//! `validate_read_schema` call is deliberately untouched -- a schema-shape defect is a different concern
93//! from physical corruption and stays a hard stage failure, out of this stage's scope (`stage-2-
94//! implementation-handoff-v1.md` §2's own boundary). Ref-log record corruption is exposed at file
95//! granularity (`refs::RefFileStatus::Failed` in `log_outcomes`, unchanged shape), not per-record like
96//! the WAL's `wal_record_outcomes` -- a deliberate, narrower scope decision for this round, recorded in
97//! the implementation's own review submission. **Every mutation-authorizing caller of `Wal::replay`/
98//! `RefStore::replay_log` that read `records`/`trailing_partial_bytes` without also checking the new
99//! `has_item_failure()` was audited and fixed in the same increment** -- the same discipline DC-95 Stage
100//! 2's ref-item-containment round established for `ensure_no_incomplete_publication`, applied here to a
101//! substantially larger caller set (`wal.rs`, `active.rs`, `rollback_draft.rs`,
102//! `worktree_patch/node_authoring.rs`, `seal.rs`, `branch.rs`, `refs/evidence.rs`, `rollback_verify.rs`,
103//! `refs/publication.rs`, `refs.rs`, `patch_replay.rs`, `seal/support.rs`,
104//! `verify/ref_publication.rs`).
105//!
106//! # RFC 102 Stage 3: container/index storage, and its effect on the table below
107//!
108//! Persisted-object storage moved from one loose file per object to per-type append-only containers
109//! plus one append-only index (design-v1.md §2/§4/§5); `verify_objects` (`verify/objects.rs`) now
110//! scans containers instead of listing directories. **Every check inside `verify_object_record` itself
111//! is untouched** -- schema validation, signature-envelope classification, publication trust, and
112//! `verify_block_payload` all still run on the same decoded `ObjectEnvelope`, just fed from a container
113//! record instead of a loose-file read. Rows whose check reads an object only through
114//! `FileObjectStore`'s public API (`ObjectReader`/`ObjectWriter`) are unaffected: that API's behavior
115//! toward callers is unchanged (task 129 of this stage confirmed this directly, not assumed from the
116//! type signature alone) -- only its internal storage moved. Three rows are not covered by that blanket
117//! statement, because their own mechanism is specifically about object *storage structure*, not about
118//! what a decoded envelope contains:
119//!
120//! - **Envelope type mismatch** (half of the row above) moved, and in moving exposed a real gap: a
121//!   container's magic constrains which container a frame's bytes live in, but nothing already
122//!   enforced that the frame's own decoded `envelope.object_type` agreed with it -- a well-formed,
123//!   correctly checksummed Blob-container frame could hold a validly encoded Patch envelope
124//!   undetected. Found and fixed during this stage's own test migration (not assumed correct from the
125//!   design alone), at the one place every container reader passes through:
126//!   `container::parse_frame_at`. **Stays Load-bearing** -- proven at the container level
127//!   (`container::tests::envelope_type_disagreeing_with_its_own_containers_type_is_rejected`) and end
128//!   to end (`verify_repository_rejects_envelope_type_mismatch`, `assert_object_item_failed(&report,
129//!   "is under type")`).
130//! - **Object id mismatch** (the other half) is now enforced in two places instead of one: ordinary
131//!   reads (`FileObjectStore::read_object`, unchanged in shape -- still a lazy, per-id check) and,
132//!   newly, `verify_objects`'s own proactive full-scan cross-validation of every index entry against
133//!   what its own claimed location actually decodes to (design §12/§10.2's "the bytes found are
134//!   validated by recomputing the content hash... `verify` does the full scan" ruling, read as
135//!   including index-to-container consistency, not just container enumeration in isolation). A decode
136//!   *failure* at an entry's location is deliberately not escalated by this new check -- it is already
137//!   an item-level `Failed` outcome from the per-record container scan (Stage 2's own containment) --
138//!   only "decodes fine but to the wrong id" is, and that is treated as a genuine index-integrity
139//!   defect, propagated as a stage-level `Err`, not an isolable item defect (an index that lies about
140//!   content is corruption at a different scale than one damaged record). **This is a new row, not
141//!   merely this stage's proof of the old one: Load-bearing**, proven end to end by
142//!   `verify_repository_detects_index_entry_resolving_to_a_different_object`.
143//! - **Directory/file shape structural errors** keeps its exact code, unmoved and unchanged
144//!   (`scan_loose_file_temp_debris`, design-v1.md §12.3 item 3's ruling: the loose-file tree's
145//!   temp-debris scan is kept, dormant, since retiring diagnostic surface is an RFC-level act, not a
146//!   stage side effect) -- but that tree is no longer written by anything under format-3, so the row's
147//!   own downstream-redundant partners (`list_directory`'s own directory-vs-file rejection;
148//!   `object_id_from_path`'s own extension check) are reachable today only by a fixture that plants the
149//!   stray entry directly, never as a byproduct of an ordinary write. **Classification unchanged**
150//!   (still Downstream-redundant, both sub-arms -- the redundant partners are generic filesystem-safety
151//!   checks, not specific to which tree is live), re-confirmed passing unmodified:
152//!   `verify_repository_detects_every_directory_shape_violation` already used `FileObjectStore::
153//!   write_object` only to produce a real object elsewhere in the fixture, and planted its two stray
154//!   entries directly at the loose-file paths either way, so this row needed no test change at all.
155//!
156//! # DC-95 Stage 1: end-to-end coverage, by cluster
157//!
158//! Every check `verify_repository` performs, classified by whether disabling it lets a defective
159//! repository pass through `verify_repository` as `Ok` with no trace -- **Load-bearing** (the check is
160//! the last line of defence; some are load-bearing only via a non-blocking-sibling mechanism, named
161//! where that applies); **Downstream-redundant** (something else independently catches the same defect,
162//! blocking, under a different code); **Excluded** (non-blocking finding, out of mandatory scope);
163//! **Unreachable** (provably impossible to construct -- kept, untested, ruled on explicitly, not merely
164//! unattempted). Full reasoning for each row lives in the test file cited, not duplicated here; this
165//! table is the current-state index, not the round-by-round record (that's
166//! `DC-95-VERIFY-COVERAGE-AND-FINDING-ACCUMULATION.md`'s own handoff trail).
167//!
168//! **Scope limit**: this enumerates checks `verify` *has*, not checks it *should have* -- a gap of a
169//! different kind this method cannot surface. One known instance: the received-ref index
170//! (`received_index.rs`, RFC 102 Stage 5 -- formerly `refs/received/`) is never read by
171//! `verify_repository` at all (RFC 101 §5.2's independently-derived transition trace); registered in
172//! reported in the review result, not a row here, since there is no existing check to classify.
173//!
174//! ## `verify/objects.rs` + `block_state.rs` (`verify/tests.rs`)
175//!
176//! | Check | Classification |
177//! |---|---|
178//! | Block parent-block existence | Downstream-redundant (`validate_v2_lineage`) |
179//! | Block patch existence | Downstream-redundant (lifecycle-replay layer's own read) |
180//! | Block snapshot-blob existence | Load-bearing |
181//! | Block format-2 shape validation (8 arms) | Load-bearing, all 8 |
182//! | Topological cycle detection | Unreachable (needs a SHA-256 fixed point; unit-level substitute in `block_state/tests.rs`) |
183//! | Envelope type mismatch / object id mismatch | Load-bearing, both -- RFC 102 Stage 3 moved the type-mismatch half into `container::parse_frame_at`; see the section above |
184//! | Index entry resolves to the wrong object (RFC 102 Stage 3) | Load-bearing -- new this stage; see the section above |
185//! | `validate_read_schema` strict-signature-shape | Load-bearing, via non-blocking-sibling mechanism |
186//! | Publication-trust failure (Block/RefState) | Demonstrated via trusted/untrusted contrast |
187//! | Directory/file shape structural errors | Downstream-redundant, both sub-arms -- RFC 102 Stage 3 made the tree it scans dormant; see the section above |
188//!
189//! ## `refs/verify.rs` + `refs/verify/scan.rs` (`verify/tests/ref_cluster.rs`)
190//!
191//! **RFC 102 Stage 4 (design-v1.md §13.12-§13.15) moved ref publication state from one loose file
192//! per pointer/log to two shared containers** (a ref-pointer index, a ref-log container), the shape
193//! Stage 3 established for objects. Two of this cluster's sixteen original checks had no per-file
194//! path left to be non-canonical or wrong-shaped, and are genuinely retired -- not merely renamed --
195//! confirmed by grepping the rewritten `scan.rs`/`container.rs` for their own diagnostic strings and
196//! finding neither. A third pair (duplicate identity) describes a scenario the new "last entry wins"
197//! model makes structurally impossible to even attempt, not merely astronomically unlikely. All three
198//! retirements are marked below rather than silently dropped -- **the sixteen are still all sixteen,
199//! four now retired with a named reason and, where one exists, a named replacement**, not twelve.
200//!
201//! - **Non-canonical ref pointer path** and **`ensure_ref_path_shape`** (`by-id/`, `logs/`, both
202//!   sub-arms) retired: there is no per-ref file and no per-entry path under the shared-container
203//!   model to be non-canonical or wrong-shaped -- entries are located by offset within one shared
204//!   file, discovered by replaying it, never by listing a directory and checking a filename.
205//!   **Replaced, not merely removed**: `read_one_pointer_entry`'s `ref_name_key_bytes(&entry.ref_name)
206//!   != entry.ref_name_key` check and `validate_log_replay`'s identical check on the log-container
207//!   side are the direct successors -- header/key-vs-content coherence replacing filename-vs-content
208//!   coherence, the same underlying property ("this record's own claimed identity disagrees with what
209//!   it actually contains") through the new storage shape. Both new rows below.
210//! - **Duplicate pointer identity / duplicate ref-log identity** retired: under "last entry wins,"
211//!   multiple entries sharing a `ref_name_key` are the ordinary republish mechanism, not a collision
212//!   to detect -- there is no "second insert into a name-keyed map" operation left to collide, so the
213//!   scenario these two rows described cannot be attempted at all under the current design, not merely
214//!   requiring a SHA-256 collision to reach as before.
215//!
216//! | Check | Classification |
217//! |---|---|
218//! | Incomplete log tail without pointer lead | Load-bearing (unchanged mechanism, container-based replay) |
219//! | Catch-all "unexplained pointer/log divergence" | Load-bearing (unchanged mechanism) |
220//! | `created_at == 0` | Load-bearing -- **now enforced at write time too** (`container::append_ref_container_record`, design-v1.md §13.15), not only at read time; a real production gap in the Stage 4 rewrite, found and closed |
221//! | `CANDIDATE-DEBRIS` | Non-blocking -- **now reachable only via a directly-planted fixture, never a real crash** (the candidate-write mechanism it detected is gone entirely); a dormant mutation wedge (design-v1.md §13.14), not fixed here |
222//! | Duplicate pointer identity / duplicate ref-log identity | **Retired** (design-v1.md §13.12-13.13) -- see prose above |
223//! | Non-canonical ref pointer path | **Retired**, replaced by "Pointer-index entry key mismatch" below |
224//! | RefState name mismatches pointer | Downstream-redundant (`classify_ref_state`'s own coherence arm), unchanged |
225//! | Pointer-index entry key mismatch (new, RFC 102 Stage 4) | Load-bearing (`refs/pointer_index.rs::read_one_pointer_entry`), design-v1.md §13.13 -- was untested before this stage's own checkpoint review found it, not merely newly added |
226//! | Log-container record key mismatch (new, RFC 102 Stage 4) | Load-bearing (`refs/verify/scan.rs::validate_log_replay`) |
227//! | Pointer index fails closed on any damaged entry (new, RFC 102 Stage 4) | Load-bearing -- deliberately asymmetric with the log container's own item-contained isolation: "last entry wins" makes silently skipping a damaged *latest* entry dangerous (an older entry for the same ref could resolve as current instead), so `read_pointers` refuses the whole read rather than isolating the damage. Design-v1.md §13.14 accepts this for Stage 4 but registers the wider blast radius (one bad entry now blocks every ref, not just its own) as a known regression against amended constraint 5, not a design choice -- not to be changed inside this stage |
228//! | `ensure_ref_target_valid` (dangling Branch/Tag target) | Load-bearing, unchanged |
229//! | Ref-log chain/sequence divergence | Load-bearing -- `expected_seq` now computed from a record's position within its own ref's *filtered subsequence* of the shared container (design-v1.md §13.1), not the container's raw physical position; re-proven directly against a physically reordered, individually-valid pair of records (Stage 4 acceptance criterion 3), not assumed carried over |
230//! | Ref-log checksum mismatch | Load-bearing -- mechanism moved from the retired `refs/log.rs::read_one_log` to `refs/container.rs`'s own frame decode (`parse_frame_at`) plus `refs/verify/scan.rs::read_logs`; same classification, new code |
231//! | `verify_update` RefState/RefUpdate coherence | Load-bearing, unchanged |
232//! | RefState unsigned | Downstream-redundant (`PublicationTrustVerifier`), unchanged |
233//! | `ensure_ref_path_shape` (`by-id/`, `logs/`) | **Retired**, both sub-arms -- see prose above; the log-container half's coverage is subsumed by `container/tests.rs`'s own corruption-isolation tests, the pointer-index half's by the fail-closed row above and `pointer_index/tests.rs`'s new corruption-isolation tests (a genuine coverage gap this stage's checkpoint review found and closed, design-v1.md §13.13, not merely a redundancy claim carried over) |
234//! | Signature-envelope issues, `RefLog` source | Excluded (see `signature_envelope_issues` caveat below), unchanged |
235//!
236//! ## `verify/ref_publication.rs`
237//!
238//! `mark_unproved` reclassification and `ACTIVE-CLEANUP-PENDING` were both already end-to-end covered
239//! before DC-95 started; not part of Stage 1's gap-closing scope.
240//!
241//! ## `wal.rs` / `verify_wal_persistence` / `rollback_verify.rs` (`verify/tests/wal_cluster.rs`)
242//!
243//! | Check | Classification |
244//! |---|---|
245//! | `Wal::replay()` checksum mismatch | Load-bearing; RFC 102 Stage 2 made the failure item-level (`wal_record_outcomes`) rather than a whole-`WalReplay`-stage abort -- see the RFC 102 Stage 2 section above |
246//! | `verify_wal_persistence` type mismatch | Load-bearing |
247//! | Rollback WAL envelope type | Unreachable (`is_rollback_draft_envelope` already guarantees Patch type before this check runs) |
248//! | Rollback WAL decode (op_seq contiguity) | Load-bearing |
249//! | Rollback WAL apply-support (`DeleteNode(symlink)`) | Load-bearing |
250//! | Rollback WAL empty-ops | Unreachable (`decode_patch_operations` already errors before returning empty) |
251//! | Rollback AUTHOR signature: missing | Load-bearing |
252//! | Rollback AUTHOR signature: wrong algorithm | Unreachable (`SignatureAlgorithm` has exactly one variant) |
253//! | Rollback AUTHOR signature: legacy marker key id | Load-bearing |
254//! | Rollback AUTHOR signature: wrong length | Unreachable (RFC 103: was reachable only under format-1, now retired; kept, untested, argument recorded in `rollback_verify.rs`) |
255//! | Signature-envelope issues, `ActiveWal` source | Excluded (see caveat below) |
256//!
257//! ## Active-WAL metadata status + WAL ordering (DC-66, `verify/tests.rs`)
258//!
259//! | Check | Classification |
260//! |---|---|
261//! | `MissingForEmptyWal` / `ValidForEmptyWal` | Excluded, non-blocking, both |
262//! | `InvalidForNonEmptyWal` | Load-bearing |
263//! | Active-WAL ordering violations | Load-bearing |
264//!
265//! ## `verify/trust.rs` / `trust.rs` (`verify/tests/trust.rs`)
266//!
267//! | Check | Classification |
268//! |---|---|
269//! | `PRIKK-TRUST-POLICY-INVALID` (missing/malformed policy) | Load-bearing |
270//! | `PRIKK-TRUST-PUBLICATION-UNTRUSTED` | Load-bearing |
271//!
272//! ## `commit_index.rs` (DC-56) / `lifecycle_cache/incremental.rs` (DC-64) (`crates/prikk-cli/tests/dc64_baseline_cache.rs`)
273//!
274//! | Check | Classification |
275//! |---|---|
276//! | Commit-index content divergence | Load-bearing |
277//! | Lifecycle-cache content-disagrees divergence | Load-bearing |
278//! | Lifecycle-cache "could not be independently verified" | Load-bearing (horizon-anchored replay vs. `block_state.rs`'s non-horizon-anchored one -- the one genuine asymmetry between two otherwise-equivalent replay paths) |
279//!
280//! ## Standing caveat: `signature_envelope_issues`
281//!
282//! `signature_envelope_issues` (one `Vec` on [`RepositoryVerification`], populated from every
283//! `SignatureEnvelopeSource`) backs no `has_*` blocking predicate, for any source -- an open question,
284//! not a settled design: should the `MALFORMED` variant be wired into a blocking predicate? Every
285//! "Excluded" row above that names this caveat, plus every "Load-bearing, via non-blocking-sibling
286//! mechanism" row, depends on this staying `false`. If it's ever answered the other way, those rows
287//! reopen.
288//!
289//! **RFC 103 note, not a status change:** `signature_diagnostics.rs::classify_signature_envelope`'s
290//! own doc records that its non-empty-result path is now provably unreachable through
291//! `verify_repository` at all (every call site runs it immediately after a `validate_read_schema`
292//! call that already hard-errors on the same three conditions, once format-1's lenient read branch is
293//! gone). This does not reopen anything above: every row this caveat covers was already "Excluded" --
294//! never blocking, for any source -- so a diagnostic layer becoming unreachable removes no coverage
295//! `verify` depended on.
296
297use std::path::PathBuf;
298
299mod objects;
300mod ref_publication;
301mod trust;
302
303use prikk_error::{PrikkError, Result};
304use prikk_object::{BlockPayload, ObjectId, ObjectType, RefKind, RefStatePayload};
305
306use crate::active::{ActiveRefMetadata, read_active_ref_metadata};
307use crate::block_state::{BlockStateOutcome, BlockStateStatus};
308use crate::commit_index::{CommitIndexDivergence, verify_divergence};
309use crate::layout::{RepositoryFormat, RepositoryLayout};
310use crate::lifecycle_cache::incremental::{
311    LifecycleCacheDivergence, verify_divergence as verify_lifecycle_cache_divergence,
312};
313use crate::object_store::{ObjectReadSnapshot, ObjectReader};
314use crate::received::list_received_pointers;
315use crate::refs::{RefItemOutcome, RefItemStatus, RefStore, ensure_ref_target_valid, verify_refs};
316use crate::rollback_verify::{verify_rollback_draft_wal_records, verify_rollback_patch_envelope};
317use crate::signature_diagnostics::{
318    SignatureEnvelopeIssue, SignatureEnvelopeSource, classify_signature_envelope,
319};
320use crate::trust::PublicationTrustIssue;
321use crate::wal::Wal;
322
323use objects::verify_objects;
324pub use objects::{ObjectItemOutcome, ObjectItemStatus};
325use trust::PublicationTrustVerifier;
326
327/// Verification summary for a single persisted object.
328#[derive(Debug, Clone, PartialEq, Eq)]
329pub struct ObjectVerification {
330    /// The object ID parsed from the object filename.
331    pub object_id: ObjectId,
332    /// The object type implied by the directory being scanned.
333    pub object_type: ObjectType,
334    /// The object file path that was checked.
335    pub path: PathBuf,
336    /// Rollback-marked Patch references verified for this object when it is a Block.
337    pub rollback_patch_count: usize,
338    /// For a Block or RefState, the adopted MAINTAINER key id whose signature was trusted (DC-78
339    /// §D3). `None` for other object types, or when publication trust could not be established.
340    pub sealed_by_key_id: Option<String>,
341    /// For a Patch, the outcome of checking its AUTHOR signature against recorded key material
342    /// (DC-53 Stage 1). `None` for other object types, or when the Patch carries no AUTHOR-role
343    /// signature at all (out of this increment's scope). A signature that does not verify against
344    /// *recorded* material never reaches this field -- it fails this object's own item check
345    /// instead, the same as any other authorship-integrity defect.
346    pub author_verification: Option<AuthorSignatureVerification>,
347}
348
349/// The result of checking one Patch's AUTHOR signature (DC-53 Stage 1, D3's first two rows --
350/// there is no `Fails` variant here because that outcome is a genuine item-level failure,
351/// propagated as an `Err` the same way every other authorship-integrity defect in this pipeline is,
352/// not a value this type carries).
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub enum AuthorSignatureVerification {
355    /// The signature verifies against key material recorded for this `key_id`.
356    Sound {
357        /// The AUTHOR key id the signature named and verified against.
358        key_id: String,
359    },
360    /// No key material has ever been recorded for this `key_id` -- authored before this
361    /// increment, or by a signer whose material this repository never observed. **Not a
362    /// failure**: `verify` still passes, but this must be visible, not silent (DC-53 Stage 1 D3's
363    /// second row).
364    Unverifiable {
365        /// The AUTHOR key id named, for which no key material is on file.
366        key_id: String,
367    },
368}
369
370/// Which adopted MAINTAINER key sealed a given Block (DC-78 §D3). Reporting only: the sealer's key
371/// id already lives, non-strippably, inside the block's own signature.
372#[derive(Debug, Clone, PartialEq, Eq)]
373pub struct BlockSealVerification {
374    /// The sealed Block's object id.
375    pub block_id: ObjectId,
376    /// The MAINTAINER key id whose trusted signature matched this Block.
377    pub sealed_by_key_id: String,
378}
379
380/// One of the fourteen top-level scopes `verify_repository`'s pipeline is organized into (DC-95 Stage 2
381/// Level 1: scope containment). Named in pipeline order; the order itself is load-bearing for
382/// `NotEvaluated` naming (`StageStatus::NotEvaluated`'s `blocked_by` is always an earlier stage).
383#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
384pub enum VerificationStage {
385    /// Persisted-object scan: identity, placement, envelope decoding, sealed block references,
386    /// publication trust for Block/RefState (shares `PublicationTrustVerifier` with
387    /// `RefUpdateSchemaTrust`).
388    Objects,
389    /// Joint ref pointer/log verification: structural shape, publication-state classification.
390    Refs,
391    /// Per-`RefUpdate`-envelope format-read-schema validation and publication trust (shares
392    /// `PublicationTrustVerifier` with `Objects`).
393    RefUpdateSchemaTrust,
394    /// Active-WAL replay: framing, checksums, envelope decoding.
395    WalReplay,
396    /// Active-WAL patch persistence cross-check against the object store.
397    WalPersistence,
398    /// Active-WAL rollback-draft classification and structural validation.
399    RollbackDrafts,
400    /// Per-active-WAL-record format-read-schema validation and signature-envelope classification.
401    WalRecordSchema,
402    /// Active-WAL ref-ownership metadata classification.
403    ActiveWalMetadata,
404    /// Retained-evidence reclassification of interrupted-publication ref issues.
405    PublicationReclassification,
406    /// DC-56 commit-index cache divergence check.
407    CommitIndex,
408    /// DC-64 incremental lifecycle-state cache divergence check.
409    LifecycleCache,
410    /// DC-66 active-WAL queue-ordering check.
411    WalOrdering,
412    /// RFC 115 Stage 3 §6: received (`remotes/*`) ref target validation -- the same kind-aware
413    /// two-hop check local refs already get, applied to the received namespace, which nothing
414    /// scanned before this stage existed.
415    ReceivedRefs,
416    /// DC-78 verify-local-tag-publication-trust (v2 amendment): a locally-published Tag's own
417    /// MAINTAINER signature, checked against the repository-local trust policy (shares
418    /// `PublicationTrustVerifier` with `Objects` and `RefUpdateSchemaTrust`). Enumerates local tag
419    /// refs independently via `RefStore::list_ref_pointers` rather than reading `Refs`' own output --
420    /// deliberately not threaded through `verify_refs`, which `ensure_no_incomplete_publication`
421    /// (a pre-mutation guard, not `prikk verify`) also calls. A received, not-yet-adopted tag is
422    /// never reached here: `list_ref_pointers` never enumerates the received namespace.
423    LocalTagTrust,
424}
425
426impl VerificationStage {
427    /// Stable, lowercase-hyphenated scope name for diagnostics and CLI output.
428    #[must_use]
429    pub const fn label(self) -> &'static str {
430        match self {
431            Self::Objects => "objects",
432            Self::Refs => "refs",
433            Self::RefUpdateSchemaTrust => "ref-update-schema-trust",
434            Self::WalReplay => "wal-replay",
435            Self::WalPersistence => "wal-persistence",
436            Self::RollbackDrafts => "rollback-drafts",
437            Self::WalRecordSchema => "wal-record-schema",
438            Self::ActiveWalMetadata => "active-wal-metadata",
439            Self::PublicationReclassification => "publication-reclassification",
440            Self::CommitIndex => "commit-index",
441            Self::LifecycleCache => "lifecycle-cache",
442            Self::WalOrdering => "wal-ordering",
443            Self::ReceivedRefs => "received-refs",
444            Self::LocalTagTrust => "local-tag-trust",
445        }
446    }
447}
448
449impl std::fmt::Display for VerificationStage {
450    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
451        f.write_str(self.label())
452    }
453}
454
455/// Outcome of attempting to evaluate one verification stage (DC-95 Stage 2 Level 1). **No stage may be
456/// silently absent from a report.** A stage's own check raising an error is recorded as a blocking
457/// finding against its scope rather than aborting the rest of verification (`Failed`); a stage that
458/// could not run because a real dependency did not evaluate is itself blocking, not silently skipped
459/// (`NotEvaluated`); a stage that could have run on its own terms but was preempted by an operator-
460/// requested early stop is also blocking, but for a different reason it must not be confused with
461/// (`Halted`) — a repository whose verification is incomplete is not verified, regardless of which of
462/// the three non-`Evaluated` states explains the gap.
463#[derive(Debug, Clone, PartialEq, Eq)]
464pub enum StageStatus {
465    /// The stage ran to completion; its findings and counts are authoritative.
466    Evaluated,
467    /// The stage's own check raised an error.
468    Failed {
469        /// The error the stage raised.
470        message: String,
471    },
472    /// The stage could not run because a *real* dependency did not evaluate — `blocked_by` names a
473    /// stage this one's own logic actually reads output from. This is a dependency-graph claim, and
474    /// must remain true of the graph even when `--stop-on-first-error` is in effect; see `Halted` for
475    /// the case where a stage merely followed an unrelated earlier stop.
476    NotEvaluated {
477        /// The earlier stage whose own non-evaluation is why this one could not run.
478        blocked_by: VerificationStage,
479    },
480    /// The stage was never attempted because an earlier, *unrelated* stage's failure already stopped
481    /// the walk under `--stop-on-first-error` (DC-95 Stage 2 Level 1 implementation review v1 §4) —
482    /// `after` names the stage whose failure triggered the stop, not a dependency of this stage. Kept
483    /// distinct from `NotEvaluated` because `blocked_by` is a dependency-graph claim: reporting
484    /// `NotEvaluated { blocked_by: Objects }` for a stage that does not actually depend on `Objects`
485    /// (e.g. `LifecycleCache`) would assert an edge that does not exist.
486    Halted {
487        /// The stage whose failure caused the walk to stop before this stage was reached.
488        after: VerificationStage,
489    },
490}
491
492impl StageStatus {
493    /// Return true for any status other than a clean, completed evaluation. `NotEvaluated` and
494    /// `Halted` are both blocking on the same footing as `Failed` — an incomplete verification is not
495    /// a passing one, whichever of the three explains the gap.
496    #[must_use]
497    pub const fn is_blocking(&self) -> bool {
498        !matches!(self, Self::Evaluated)
499    }
500}
501
502/// One stage's resolved outcome.
503#[derive(Debug, Clone, PartialEq, Eq)]
504pub struct StageOutcome {
505    /// Which of the thirteen stages this outcome is for.
506    pub stage: VerificationStage,
507    /// How that stage resolved.
508    pub status: StageStatus,
509}
510
511/// Repository verification summary.
512#[derive(Debug, Clone, PartialEq, Eq)]
513pub struct RepositoryVerification {
514    /// Outcome of each of the thirteen verification stages (DC-95 Stage 2 Level 1), in pipeline order.
515    /// Always exactly thirteen entries — no stage may be silently absent.
516    pub stage_outcomes: Vec<StageOutcome>,
517    /// Phase A: one outcome per persisted object file scanned, in scan order (DC-95 Stage 2 Level 2).
518    /// Empty when the `Objects` stage itself did not evaluate (a structural directory-shape error) —
519    /// nothing was attempted, distinct from a non-empty set where every entry happens to be `Failed`.
520    pub object_outcomes: Vec<ObjectItemOutcome>,
521    /// Phase B: one outcome per `CurrentV6` Block whose Phase A check succeeded, in the
522    /// state-dependency order `verify_blocks_topological` resolved them — not scan order (DC-92
523    /// §4.2). Empty when the `Objects` stage did not evaluate, or when no `CurrentV6` Block passed
524    /// Phase A at all.
525    pub block_state_outcomes: Vec<BlockStateOutcome>,
526    /// Number of persisted object files whose own Phase A checks ran to completion (DC-95 Stage 2
527    /// Level 2). `None` only when the `Objects` stage itself did not evaluate (a structural
528    /// directory-shape error) — under item containment this is no longer the same claim as "every
529    /// object in the store is individually sound": some entries in `object_outcomes` may themselves
530    /// be `Failed` while this count still reflects how many succeeded. Never a partial claim about
531    /// state-root soundness, which `block_state_outcomes` is the only source of truth for (Level 2
532    /// handoff §7 Q3 — `checked_blocks` below keeps its pre-Level-2 meaning unchanged).
533    pub checked_objects: Option<usize>,
534    /// Number of active WAL records replayed successfully. `None` when the WAL-replay stage did not
535    /// evaluate to completion.
536    pub checked_wal_records: Option<usize>,
537    /// One outcome per attempted WAL record frame, in scan order (RFC 102 Stage 2: isolate-and-
538    /// continue reading). Empty when the `WalReplay` stage itself did not evaluate.
539    pub wal_record_outcomes: Vec<crate::wal::WalRecordOutcome>,
540    /// Number of persisted Block objects whose references (parent, patch, snapshot existence, merge
541    /// baseline) were checked successfully — a Phase A claim only, never a claim about state-root
542    /// soundness (see `block_state_outcomes`). `None` only when the `Objects` stage itself did not
543    /// evaluate. This field's meaning is unchanged by Level 2 (handoff §7 Q3) — only *when* it is
544    /// `None` changed, from "the whole stage failed" to "the whole stage did not evaluate at all."
545    pub checked_blocks: Option<usize>,
546    /// Number of persisted Block objects classified as rollback blocks, among those whose Phase A
547    /// check succeeded. `None` only when the `Objects` stage itself did not evaluate.
548    pub checked_rollback_blocks: Option<usize>,
549    /// Number of sealed rollback-marked Patch objects referenced by Blocks whose Phase A check
550    /// succeeded. `None` only when the `Objects` stage itself did not evaluate.
551    pub checked_sealed_rollback_patches: Option<usize>,
552    /// Number of active WAL patch records that already exist as persisted patch objects. `None` when
553    /// the WAL-persistence stage did not evaluate to completion.
554    pub persisted_wal_patches: Option<usize>,
555    /// Number of ref pointer files whose own Phase-A-equivalent read succeeded (DC-95 Stage 2
556    /// Level 2). `None` only when the `Refs` stage itself did not evaluate.
557    pub checked_refs: Option<usize>,
558    /// Number of inline ref-log records read successfully. `None` only when the `Refs` stage
559    /// itself did not evaluate.
560    pub checked_ref_log_records: Option<usize>,
561    /// Interrupted ref-publication and candidate-debris conditions found by joint verification. Stays
562    /// a plain `Vec` under stage containment: entries already pushed by a stage that later failed
563    /// remain real findings; only the count/emptiness-as-proof reasoning needed a stage-aware guard
564    /// (see `require_retained_evidence`'s own `trust_is_valid` computation).
565    pub ref_publication_issues: Vec<crate::refs::RefPublicationIssue>,
566    /// One outcome per ref pointer file scanned, in scan order (DC-95 Stage 2 Level 2). Empty when
567    /// the `Refs` stage itself did not evaluate.
568    pub pointer_outcomes: Vec<crate::refs::RefFileOutcome>,
569    /// One outcome per ref log file scanned, in scan order. Empty when the `Refs` stage itself did
570    /// not evaluate.
571    pub log_outcomes: Vec<crate::refs::RefFileOutcome>,
572    /// One outcome per ref name reached via a successfully-read pointer or log. Empty when the
573    /// `Refs` stage itself did not evaluate.
574    pub ref_item_outcomes: Vec<crate::refs::RefItemOutcome>,
575    /// Warning-level format-1 signature-envelope compatibility findings in deterministic order.
576    pub signature_envelope_issues: Vec<SignatureEnvelopeIssue>,
577    /// Number of active WAL records classified and decoded as rollback drafts. `None` when the
578    /// rollback-drafts stage did not evaluate to completion.
579    pub checked_rollback_draft_records: Option<usize>,
580    /// Number of publication envelopes checked against repository-local trust. `None` unless *both*
581    /// the objects stage and the ref-update schema/trust stage evaluated to completion — this count is
582    /// contributed to by both, sharing one `PublicationTrustVerifier` instance across them.
583    pub checked_publication_trust_records: Option<usize>,
584    /// Publication-trust issues found while structural verification succeeded. Stays a plain `Vec` —
585    /// entries genuinely found before an interrupting failure remain real findings.
586    pub publication_trust_issues: Vec<PublicationTrustIssue>,
587    /// Recognized non-authoritative object publication temps left for explicit maintenance.
588    pub object_temp_paths: Vec<PathBuf>,
589    /// Number of trailing bytes in the active WAL that look like an incomplete final record. `None`
590    /// when the WAL-replay stage did not evaluate to completion.
591    pub trailing_partial_wal_bytes: Option<usize>,
592    /// Active-WAL ref metadata status relative to the replayed WAL. `None` when the active-WAL-metadata
593    /// stage did not evaluate to completion.
594    pub active_wal_metadata_status: Option<ActiveWalMetadataStatus>,
595    /// DC-56 commit-index entries whose recorded content hash disagrees with the worktree's actual
596    /// current content despite a matching stat — a stale-but-trusted cache entry, reported per the
597    /// cache-validity specification §6 rather than silently trusted by a future commit.
598    pub commit_index_divergences: Vec<CommitIndexDivergence>,
599    /// DC-64 incremental lifecycle-state cache entries whose contents disagree with an independent
600    /// full replay of the block they claim to represent — reported per the design document §6
601    /// rather than silently trusted by a future commit.
602    pub lifecycle_cache_divergences: Vec<LifecycleCacheDivergence>,
603    /// DC-66: active WAL queue-ordering violations — a record whose sequence does not strictly
604    /// increase over its predecessor. Adversarial-only under normal operation (`Wal::append_patch`
605    /// always assigns the next sequence), but a queue of N gives ordering a meaning ("patches seal in
606    /// append order") worth verifying explicitly rather than assuming from decode success alone.
607    pub active_wal_ordering_issues: Vec<ActiveWalOrderingIssue>,
608    /// DC-75: `Merge` blocks whose recorded `merge_baseline_block_id` is not, in fact, a common
609    /// ancestor of both parents — independently re-derived, not trusted, per
610    /// `baseline-recording-answer-v1.md` §3 ("record it, then check it, unconditionally"). A recorded
611    /// baseline that legitimate merge execution ever produced always passes this; a false claim (data
612    /// corruption or tampering) does not.
613    pub merge_baseline_divergences: Vec<MergeBaselineDivergence>,
614    /// Which adopted MAINTAINER key sealed each checked Block (DC-78 §D3), in on-disk scan order.
615    /// Reporting only — surfaces provenance that was already intrinsic to each block's own
616    /// signature, so an auditor can ask "which parts of this history did I seal" and get an answer.
617    pub block_seals: Vec<BlockSealVerification>,
618    /// RFC 115 Stage 3 §6: one outcome per received (`remotes/*`) pointer, in
619    /// `list_received_pointers`' sorted-by-name order — the same kind-aware two-hop target check
620    /// local refs already get, applied here for the first time. Empty when the `ReceivedRefs` stage
621    /// itself did not evaluate. A repository with a genuinely dangling received ref (its target
622    /// object was never shipped) now reports an item failure here where nothing reported anything
623    /// before this stage existed — see the stage's own module note for what that means for a
624    /// repository that already holds one.
625    pub received_ref_item_outcomes: Vec<RefItemOutcome>,
626}
627
628/// A `Merge` block (DC-75) whose recorded `merge_baseline_block_id` is not a common ancestor of its
629/// two parents. Precision note: this checks *validity* (is the claim even a common ancestor), not
630/// *nearest-ness* (is it the single nearest one) — a merge legitimately sealed against an older-than-
631/// necessary common ancestor is unusual but not what this finding is for; a baseline that is not a
632/// common ancestor at all can only arise from a forged or corrupted field.
633#[derive(Debug, Clone, PartialEq, Eq)]
634pub struct MergeBaselineDivergence {
635    /// The `Merge` block whose recorded baseline failed re-derivation.
636    pub block_id: ObjectId,
637    /// The recorded (claimed) baseline.
638    pub recorded_baseline: ObjectId,
639    /// The block's mainline parent.
640    pub mainline_parent_id: ObjectId,
641    /// The block's secondary parent.
642    pub secondary_parent_id: ObjectId,
643}
644
645/// One active-WAL record whose sequence did not strictly increase over the previous record.
646#[derive(Debug, Clone, PartialEq, Eq)]
647pub struct ActiveWalOrderingIssue {
648    /// Zero-based position of the offending record within the replayed WAL.
649    pub index: usize,
650    /// Sequence of the previous record.
651    pub previous_seq: u64,
652    /// Sequence of the offending record (not greater than `previous_seq`).
653    pub seq: u64,
654}
655
656impl RepositoryVerification {
657    /// Return true when any of the thirteen verification stages did not evaluate cleanly — either its
658    /// own check raised an error (`Failed`) or a dependency's non-evaluation prevented it from running
659    /// at all (`NotEvaluated`). A repository whose verification did not run to completion is not
660    /// verified, regardless of what the stages that did run found. Checked first, ahead of every
661    /// finding-specific predicate below: those predicates' own backing data can itself be incomplete
662    /// precisely because a stage failed, so this is the more fundamental question.
663    ///
664    /// **Does not, by itself, cover item-level defects (DC-95 Stage 2 Level 2)** — the `Objects`
665    /// stage evaluates cleanly (`Evaluated`) even when one of its items individually failed, since
666    /// item containment means a bad object no longer aborts the whole stage. See
667    /// [`Self::has_item_failure`] for that question, and [`Self::has_blocking_defect`] for the
668    /// combined check almost every caller actually wants.
669    #[must_use]
670    pub fn has_stage_failure(&self) -> bool {
671        self.stage_outcomes
672            .iter()
673            .any(|outcome| outcome.status.is_blocking())
674    }
675
676    /// Return true when any individual item did not evaluate cleanly (DC-95 Stage 2 Level 2) — a
677    /// Phase A object whose own check failed, a Phase B `CurrentV6` Block whose state-root check
678    /// failed or could not be attempted because its own state-derivation parent did not evaluate,
679    /// or a ref (its pointer file, log file, or classification) that failed. Item containment means
680    /// these no longer make [`Self::has_stage_failure`] true: the owning stage itself completed, so
681    /// this is a genuinely separate question, not a more detailed view of the same one. The backing
682    /// `Vec`s are empty (not merely all-`Evaluated`) when their owning stage itself did not
683    /// evaluate — this method reads that case as `false`, same as every other item-backed predicate
684    /// in this type; `has_stage_failure` is what is already true for it.
685    #[must_use]
686    pub fn has_item_failure(&self) -> bool {
687        self.object_outcomes
688            .iter()
689            .any(|outcome| matches!(outcome.status, ObjectItemStatus::Failed { .. }))
690            || self
691                .block_state_outcomes
692                .iter()
693                .any(|outcome| !matches!(outcome.status, BlockStateStatus::Verified))
694            || self
695                .pointer_outcomes
696                .iter()
697                .any(|outcome| matches!(outcome.status, crate::refs::RefFileStatus::Failed { .. }))
698            || self
699                .log_outcomes
700                .iter()
701                .any(|outcome| matches!(outcome.status, crate::refs::RefFileStatus::Failed { .. }))
702            || self
703                .ref_item_outcomes
704                .iter()
705                .any(|outcome| matches!(outcome.status, crate::refs::RefItemStatus::Failed { .. }))
706            || self
707                .wal_record_outcomes
708                .iter()
709                .any(|outcome| matches!(outcome.status, crate::wal::WalRecordStatus::Failed { .. }))
710            || self
711                .received_ref_item_outcomes
712                .iter()
713                .any(|outcome| matches!(outcome.status, RefItemStatus::Failed { .. }))
714    }
715
716    /// Return true when this repository's verification found any blocking reason to refuse it --
717    /// stage-level (`has_stage_failure`) or item-level (`has_item_failure`). A convenience predicate
718    /// for a caller that only wants "is this repository verified at all" and does not care which
719    /// half of that question failed.
720    ///
721    /// **Not currently called by this crate's own production code.** `doctor_repository`'s refusal
722    /// gate is preserved by its own per-stage and per-item `DoctorIssue::error` loops feeding
723    /// `is_healthy()`, not by calling this directly; `prikk verify`'s exit-code chain
724    /// (`main.rs`) calls `has_stage_failure()` and `has_item_failure()` as two separate arms
725    /// precisely so it can report *which* kind of failure occurred, rather than one generic
726    /// message -- collapsing them here would lose that. Kept as public API for an external caller
727    /// that only wants the yes/no answer.
728    #[must_use]
729    pub fn has_blocking_defect(&self) -> bool {
730        self.has_stage_failure() || self.has_item_failure()
731    }
732
733    /// Return true if the active WAL contained an incomplete trailing record. `None` (the WAL-replay
734    /// stage did not evaluate) reads as false here — that condition is already surfaced, more
735    /// precisely, by `has_stage_failure`.
736    #[must_use]
737    pub fn has_trailing_partial_wal(&self) -> bool {
738        self.trailing_partial_wal_bytes.is_some_and(|n| n != 0)
739    }
740
741    /// Return true when all structurally verified publication objects also passed trust checks.
742    #[must_use]
743    pub fn has_publication_trust_issues(&self) -> bool {
744        !self.publication_trust_issues.is_empty()
745    }
746
747    /// Return true when pointer/log state requires signer-backed recovery or manual intervention.
748    #[must_use]
749    pub fn has_blocking_ref_publication_issues(&self) -> bool {
750        self.ref_publication_issues
751            .iter()
752            .any(|issue| issue.blocking)
753    }
754
755    /// Return true when a non-empty active WAL lacks valid ownership metadata. `None` (the
756    /// active-WAL-metadata stage did not evaluate) reads as false here — see `has_trailing_partial_wal`.
757    #[must_use]
758    pub fn has_active_wal_metadata_integrity_issue(&self) -> bool {
759        self.active_wal_metadata_status
760            .as_ref()
761            .is_some_and(ActiveWalMetadataStatus::has_integrity_issue)
762    }
763
764    /// Return true when an empty active WAL has stale local metadata debris. `None` reads as false —
765    /// see `has_trailing_partial_wal`.
766    #[must_use]
767    pub fn has_active_wal_metadata_warning(&self) -> bool {
768        self.active_wal_metadata_status
769            .as_ref()
770            .is_some_and(ActiveWalMetadataStatus::has_local_debris_warning)
771    }
772
773    /// Return true when the commit-index cache disagrees with the worktree for at least one path.
774    #[must_use]
775    pub fn has_commit_index_divergence(&self) -> bool {
776        !self.commit_index_divergences.is_empty()
777    }
778
779    /// Return true when the incremental lifecycle-state cache disagrees with an independent replay.
780    #[must_use]
781    pub fn has_lifecycle_cache_divergence(&self) -> bool {
782        !self.lifecycle_cache_divergences.is_empty()
783    }
784
785    /// Return true when the active WAL contains an out-of-order or duplicate sequence.
786    #[must_use]
787    pub fn has_active_wal_ordering_issue(&self) -> bool {
788        !self.active_wal_ordering_issues.is_empty()
789    }
790
791    /// Return true when a `Merge` block's recorded baseline is not a common ancestor of its parents
792    /// (DC-75) — a false claim, from data corruption or tampering.
793    #[must_use]
794    pub fn has_merge_baseline_divergence(&self) -> bool {
795        !self.merge_baseline_divergences.is_empty()
796    }
797}
798
799/// Active-WAL ref metadata status derived during repository verification.
800#[derive(Debug, Clone, PartialEq, Eq)]
801pub enum ActiveWalMetadataStatus {
802    /// Empty active WAL and no metadata.
803    MissingForEmptyWal,
804    /// Empty active WAL with stale but valid local metadata.
805    ValidForEmptyWal {
806        /// Ref recorded in the stale metadata.
807        ref_name: String,
808    },
809    /// Empty active WAL with malformed local metadata.
810    InvalidForEmptyWal {
811        /// Parse or validation failure.
812        reason: String,
813    },
814    /// Non-empty active WAL with valid ownership metadata.
815    ValidForNonEmptyWal {
816        /// Ref recorded in the active metadata.
817        ref_name: String,
818    },
819    /// Non-empty active WAL missing required ownership metadata.
820    MissingForNonEmptyWal,
821    /// Non-empty active WAL with malformed ownership metadata.
822    InvalidForNonEmptyWal {
823        /// Parse or validation failure.
824        reason: String,
825    },
826}
827
828impl ActiveWalMetadataStatus {
829    /// Return true when the status represents a repository-integrity issue.
830    #[must_use]
831    pub const fn has_integrity_issue(&self) -> bool {
832        matches!(
833            self,
834            Self::MissingForNonEmptyWal | Self::InvalidForNonEmptyWal { .. }
835        )
836    }
837
838    /// Return true when the status represents local debris on an otherwise empty active WAL.
839    #[must_use]
840    pub const fn has_local_debris_warning(&self) -> bool {
841        matches!(
842            self,
843            Self::ValidForEmptyWal { .. } | Self::InvalidForEmptyWal { .. }
844        )
845    }
846}
847
848/// Threads stage outcomes, and (optionally) an early-halt decision, through `verify_repository`'s
849/// pipeline (DC-95 Stage 2 Level 1's `--stop-on-first-error`, design §7 and §12.3).
850struct StagePipeline {
851    outcomes: Vec<StageOutcome>,
852    stop_on_first_error: bool,
853    halted_by: Option<VerificationStage>,
854}
855
856impl StagePipeline {
857    fn new(stop_on_first_error: bool) -> Self {
858        Self {
859            outcomes: Vec::with_capacity(12),
860            stop_on_first_error,
861            halted_by: None,
862        }
863    }
864
865    /// Attempt a stage with no real dependency beyond a possible earlier halt. Returns the value on
866    /// success; `None` on failure, or if an earlier stage already halted the walk. A stage reached
867    /// through `run` never has a real declared dependency (a stage that does is gated behind an
868    /// `if`/`else` at its call site and reaches `not_evaluated` instead when ungated) -- so an
869    /// already-halted walk is always reported as `Halted`, never a fabricated `NotEvaluated`.
870    fn run<T>(&mut self, stage: VerificationStage, result: Result<T>) -> Option<T> {
871        if let Some(halted_by) = self.halted_by {
872            self.outcomes.push(StageOutcome {
873                stage,
874                status: StageStatus::Halted { after: halted_by },
875            });
876            return None;
877        }
878        match result {
879            Ok(value) => {
880                self.outcomes.push(StageOutcome {
881                    stage,
882                    status: StageStatus::Evaluated,
883                });
884                Some(value)
885            }
886            Err(err) => {
887                self.outcomes.push(StageOutcome {
888                    stage,
889                    status: StageStatus::Failed {
890                        message: err.to_string(),
891                    },
892                });
893                if self.stop_on_first_error {
894                    self.halted_by = Some(stage);
895                }
896                None
897            }
898        }
899    }
900
901    /// Record a stage that cannot run because `blocked_by` -- a real dependency -- did not evaluate.
902    /// Always reports `blocked_by` as given, never substituted: a caller only reaches this method when
903    /// `blocked_by`'s own stage failed to produce a usable value (DC-95 Stage 2 Level 1 implementation
904    /// review v1 §4), so the claim is true of the dependency graph regardless of *why* `blocked_by`
905    /// itself did not evaluate -- including when `blocked_by` was itself `Halted`, in which case this
906    /// stage is transitively halted too, discoverable by following the chain rather than by this call
907    /// reaching past its own real dependency to name an unrelated stage. `--stop-on-first-error` never
908    /// originates a fresh halt here: every halt traces back to a `Failed` outcome from `run`, which
909    /// already recorded it.
910    fn not_evaluated(&mut self, stage: VerificationStage, blocked_by: VerificationStage) {
911        self.outcomes.push(StageOutcome {
912            stage,
913            status: StageStatus::NotEvaluated { blocked_by },
914        });
915    }
916
917    /// Record a stage whose own check cannot fail (a pure function, or one that already converts
918    /// errors into findings) -- still subject to an earlier halt. Returns whether the stage should
919    /// actually run its own work. Never a real dependency (see `run`), so an already-halted walk is
920    /// `Halted`, not `NotEvaluated`.
921    fn run_infallible(&mut self, stage: VerificationStage) -> bool {
922        if let Some(halted_by) = self.halted_by {
923            self.outcomes.push(StageOutcome {
924                stage,
925                status: StageStatus::Halted { after: halted_by },
926            });
927            false
928        } else {
929            self.outcomes.push(StageOutcome {
930                stage,
931                status: StageStatus::Evaluated,
932            });
933            true
934        }
935    }
936}
937
938/// Options controlling how `verify_repository` walks its thirteen stages (DC-95 Stage 2 Level 1).
939#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
940pub struct VerifyOptions {
941    /// When true, stop at the first stage that fails or cannot evaluate, leaving every later stage
942    /// `NotEvaluated` (naming the first halting stage) rather than continuing to accumulate.
943    /// Preserves the pre-Stage-2 bounded-walk behavior for a large, badly-damaged repository where a
944    /// full accumulating scan would be costly (design §7) -- unbounded growth is concentrated in the
945    /// `Objects` stage's whole-store scan. Default `false` (full accumulation).
946    pub stop_on_first_error: bool,
947}
948
949/// Verify a repository layout without modifying it, with the default options (full accumulation
950/// across all thirteen stages). See [`verify_repository_with_options`] for `--stop-on-first-error`.
951pub fn verify_repository(layout: &RepositoryLayout) -> Result<RepositoryVerification> {
952    verify_repository_with_options(layout, VerifyOptions::default())
953}
954
955/// Verify a repository layout without modifying it.
956pub fn verify_repository_with_options(
957    layout: &RepositoryLayout,
958    options: VerifyOptions,
959) -> Result<RepositoryVerification> {
960    // RFC 111 §6.1: `verify` is read-only end to end (never calls `write_object` anywhere in its own
961    // call graph, confirmed by RFC 111 Q1's inventory), so it takes one decoded index snapshot here,
962    // once, instead of the O(N) per-object-read decode `FileObjectStore` used to pay.
963    let object_store = ObjectReadSnapshot::open(layout)?;
964    let mut trust_verifier = PublicationTrustVerifier::new(layout);
965    let mut pipeline = StagePipeline::new(options.stop_on_first_error);
966
967    // Stage: Objects. No upstream stage dependency. `trust_verifier` is mutated by reference and its
968    // state survives a `Failed` outcome here, since it lives in this function's own frame rather than
969    // inside `verify_objects` -- reused safely by RefUpdateSchemaTrust and PublicationReclassification
970    // below (DC-95 Stage 2 Step 0 §3: `PublicationTrustVerifier` cannot manufacture a false "trusted"
971    // result from partial evaluation).
972    let object_summary = pipeline.run(
973        VerificationStage::Objects,
974        verify_objects(layout, &object_store, &mut trust_verifier),
975    );
976    let objects_evaluated = object_summary.is_some();
977    let (
978        object_outcomes,
979        block_state_outcomes,
980        checked_objects,
981        checked_blocks,
982        checked_rollback_blocks,
983        checked_sealed_rollback_patches,
984        object_temp_paths,
985        merge_baseline_divergences,
986        block_seals,
987        mut signature_envelope_issues,
988    ) = match object_summary {
989        Some(summary) => {
990            let counts = phase_a_counts(&summary.item_outcomes)?;
991            (
992                summary.item_outcomes,
993                summary.topological_outcomes,
994                Some(counts.objects),
995                Some(counts.blocks),
996                Some(counts.rollback_blocks),
997                Some(counts.rollback_patches),
998                summary.temp_paths,
999                summary.merge_baseline_divergences,
1000                summary.block_seals,
1001                summary.signature_issues,
1002            )
1003        }
1004        None => (
1005            Vec::new(),
1006            Vec::new(),
1007            None,
1008            None,
1009            None,
1010            None,
1011            Vec::new(),
1012            Vec::new(),
1013            Vec::new(),
1014            Vec::new(),
1015        ),
1016    };
1017
1018    // Stage: Refs. No upstream stage dependency.
1019    let ref_verification = pipeline.run(VerificationStage::Refs, verify_refs(layout));
1020
1021    // Stage: ReceivedRefs (RFC 115 Stage 3 §6). No upstream stage dependency -- reads the received
1022    // index and the object store directly, the same footing `Refs` has.
1023    let received_ref_item_outcomes = pipeline
1024        .run(
1025            VerificationStage::ReceivedRefs,
1026            verify_received_refs(layout, &object_store),
1027        )
1028        .unwrap_or_default();
1029
1030    // Stage: LocalTagTrust (DC-78 verify-local-tag-publication-trust v2 amendment). No upstream stage
1031    // dependency -- same footing as ReceivedRefs above: enumerates local tag refs directly via
1032    // `RefStore::list_ref_pointers` instead of reading `Refs`' own output, so `verify_refs` never sees
1033    // `trust_verifier` (the escalation this stage exists to resolve found a caller of `verify_refs`,
1034    // `ensure_no_incomplete_publication`, that is not `prikk verify` and must not pay for this).
1035    // Shares `trust_verifier` with `Objects`/`RefUpdateSchemaTrust`, so an untrusted local Tag surfaces
1036    // through the identical `publication_trust_issues` path those two already report through.
1037    let local_tag_trust_evaluated = pipeline
1038        .run(
1039            VerificationStage::LocalTagTrust,
1040            verify_local_tag_publication_trust(layout, &object_store, &mut trust_verifier),
1041        )
1042        .is_some();
1043
1044    // Stage: RefUpdateSchemaTrust. Depends on Refs for the envelope list.
1045    let ref_update_schema_trust_evaluated = if let Some(rv) = &ref_verification {
1046        pipeline
1047            .run(
1048                VerificationStage::RefUpdateSchemaTrust,
1049                (|| -> Result<()> {
1050                    for envelope in &rv.ref_update_envelopes {
1051                        crate::format::validate_read_schema(layout.format(), envelope)?;
1052                        trust_verifier.verify(envelope)?;
1053                    }
1054                    Ok(())
1055                })(),
1056            )
1057            .is_some()
1058    } else {
1059        pipeline.not_evaluated(
1060            VerificationStage::RefUpdateSchemaTrust,
1061            VerificationStage::Refs,
1062        );
1063        false
1064    };
1065
1066    let refs_evaluated = ref_verification.is_some();
1067    let (
1068        checked_refs,
1069        checked_ref_log_records,
1070        mut ref_publication_issues,
1071        refs_signature_envelope_issues,
1072        pointer_outcomes,
1073        log_outcomes,
1074        ref_item_outcomes,
1075    ) = match ref_verification {
1076        Some(rv) => (
1077            Some(rv.pointer_count),
1078            Some(rv.log_record_count),
1079            rv.publication_issues,
1080            rv.signature_envelope_issues,
1081            rv.pointer_outcomes,
1082            rv.log_outcomes,
1083            rv.ref_item_outcomes,
1084        ),
1085        None => (
1086            None,
1087            None,
1088            Vec::new(),
1089            Vec::new(),
1090            Vec::new(),
1091            Vec::new(),
1092            Vec::new(),
1093        ),
1094    };
1095
1096    // Stage: WalReplay. No upstream stage dependency.
1097    let wal = Wal::for_layout(layout);
1098    let replay = pipeline.run(VerificationStage::WalReplay, wal.replay());
1099
1100    // Stage: WalPersistence. Depends on WalReplay.
1101    let persisted_wal_patches = if let Some(replay) = &replay {
1102        pipeline.run(
1103            VerificationStage::WalPersistence,
1104            verify_wal_persistence(&object_store, &replay.records),
1105        )
1106    } else {
1107        pipeline.not_evaluated(
1108            VerificationStage::WalPersistence,
1109            VerificationStage::WalReplay,
1110        );
1111        None
1112    };
1113
1114    // Stage: RollbackDrafts. Depends on WalReplay.
1115    let checked_rollback_draft_records = if let Some(replay) = &replay {
1116        pipeline.run(
1117            VerificationStage::RollbackDrafts,
1118            verify_rollback_draft_wal_records(&replay.records),
1119        )
1120    } else {
1121        pipeline.not_evaluated(
1122            VerificationStage::RollbackDrafts,
1123            VerificationStage::WalReplay,
1124        );
1125        None
1126    };
1127
1128    // Stage: WalRecordSchema. Depends on WalReplay.
1129    if let Some(replay) = &replay {
1130        pipeline.run(
1131            VerificationStage::WalRecordSchema,
1132            (|| -> Result<()> {
1133                for record in &replay.records {
1134                    crate::format::validate_read_schema(layout.format(), &record.envelope)?;
1135                    signature_envelope_issues.extend(classify_signature_envelope(
1136                        &record.envelope,
1137                        SignatureEnvelopeSource::ActiveWal {
1138                            sequence: record.seq,
1139                            object_id: record.envelope.object_id(),
1140                        },
1141                    )?);
1142                }
1143                Ok(())
1144            })(),
1145        );
1146        // Matches the pre-Level-1 merge order (Objects, then WAL, then Refs) -- deferred until here,
1147        // after the WAL per-record loop's own contributions, rather than appended immediately after
1148        // the Refs stage above, purely to preserve that existing, asserted-on order.
1149        signature_envelope_issues.extend(refs_signature_envelope_issues);
1150    } else {
1151        pipeline.not_evaluated(
1152            VerificationStage::WalRecordSchema,
1153            VerificationStage::WalReplay,
1154        );
1155        signature_envelope_issues.extend(refs_signature_envelope_issues);
1156    }
1157
1158    // Stage: ActiveWalMetadata. Depends on WalReplay.
1159    let active_wal_metadata_status = if let Some(replay) = &replay {
1160        pipeline.run(
1161            VerificationStage::ActiveWalMetadata,
1162            classify_active_wal_metadata(layout, replay.records.is_empty()),
1163        )
1164    } else {
1165        pipeline.not_evaluated(
1166            VerificationStage::ActiveWalMetadata,
1167            VerificationStage::WalReplay,
1168        );
1169        None
1170    };
1171
1172    // Stage: PublicationReclassification. Cannot run at all without Refs (needs `issues` to mutate),
1173    // WalReplay (needs `records`), or ActiveWalMetadata (needs `metadata`) -- `NotEvaluated`, naming
1174    // whichever of those three failed first, if any. Objects failing does *not* block this stage from
1175    // running: it only degrades `trust_is_valid` to a safe `false` (DC-95 Stage 2 Step 0 ruling §2-§3
1176    // -- an accumulator's emptiness means "none found" only if its producer ran to completion; reading
1177    // `trust_verifier.issues.is_empty()` alone would silently claim "proved" from an unrun check).
1178    match (&replay, refs_evaluated, &active_wal_metadata_status) {
1179        (Some(replay), true, Some(metadata)) => {
1180            let trust_is_valid = objects_evaluated && trust_verifier.issues.is_empty();
1181            pipeline.run(
1182                VerificationStage::PublicationReclassification,
1183                ref_publication::require_retained_evidence(
1184                    layout,
1185                    &replay.records,
1186                    metadata,
1187                    trust_is_valid,
1188                    &mut ref_publication_issues,
1189                ),
1190            );
1191        }
1192        _ => {
1193            let blocked_by = if replay.is_none() {
1194                VerificationStage::WalReplay
1195            } else if !refs_evaluated {
1196                VerificationStage::Refs
1197            } else {
1198                VerificationStage::ActiveWalMetadata
1199            };
1200            pipeline.not_evaluated(VerificationStage::PublicationReclassification, blocked_by);
1201        }
1202    }
1203
1204    // Stage: CommitIndex. No upstream stage dependency; contained like any other fallible stage --
1205    // `commit_index::verify_divergence` does return `Result`, unlike `LifecycleCache`'s. An empty
1206    // `Vec` on `Failed`/`NotEvaluated` is safe here (unlike a count): the stage's own outcome above
1207    // already says whether "no divergences" was actually established.
1208    let commit_index_divergences = pipeline
1209        .run(VerificationStage::CommitIndex, verify_divergence(layout))
1210        .unwrap_or_default();
1211
1212    // Stage: LifecycleCache. No upstream stage dependency; cannot fail by construction -- a replay
1213    // error is itself converted into a divergence entry rather than propagated (DC-95 Stage 1 round
1214    // 12). Still subject to an earlier halt under `--stop-on-first-error`.
1215    let lifecycle_cache_divergences = if pipeline.run_infallible(VerificationStage::LifecycleCache)
1216    {
1217        verify_lifecycle_cache_divergence(&object_store, layout)
1218    } else {
1219        Vec::new()
1220    };
1221
1222    // Stage: WalOrdering. Depends on WalReplay; the check itself cannot fail (a pure function).
1223    let active_wal_ordering_issues = if let Some(replay) = &replay {
1224        if pipeline.run_infallible(VerificationStage::WalOrdering) {
1225            check_active_wal_ordering(&replay.records)
1226        } else {
1227            Vec::new()
1228        }
1229    } else {
1230        pipeline.not_evaluated(VerificationStage::WalOrdering, VerificationStage::WalReplay);
1231        Vec::new()
1232    };
1233
1234    let checked_publication_trust_records =
1235        (objects_evaluated && ref_update_schema_trust_evaluated && local_tag_trust_evaluated)
1236            .then_some(trust_verifier.checked_records);
1237
1238    Ok(RepositoryVerification {
1239        stage_outcomes: pipeline.outcomes,
1240        object_outcomes,
1241        block_state_outcomes,
1242        checked_objects,
1243        checked_wal_records: replay.as_ref().map(|replay| replay.records.len()),
1244        wal_record_outcomes: replay
1245            .as_ref()
1246            .map(|replay| replay.record_outcomes.clone())
1247            .unwrap_or_default(),
1248        checked_blocks,
1249        checked_rollback_blocks,
1250        checked_sealed_rollback_patches,
1251        persisted_wal_patches,
1252        checked_refs,
1253        checked_ref_log_records,
1254        ref_publication_issues,
1255        pointer_outcomes,
1256        log_outcomes,
1257        ref_item_outcomes,
1258        signature_envelope_issues,
1259        checked_rollback_draft_records,
1260        checked_publication_trust_records,
1261        publication_trust_issues: trust_verifier.issues,
1262        object_temp_paths,
1263        trailing_partial_wal_bytes: replay.as_ref().map(|replay| replay.trailing_partial_bytes),
1264        active_wal_metadata_status,
1265        commit_index_divergences,
1266        lifecycle_cache_divergences,
1267        active_wal_ordering_issues,
1268        merge_baseline_divergences,
1269        block_seals,
1270        received_ref_item_outcomes,
1271    })
1272}
1273
1274/// Aggregate counts derived from Phase A's per-item outcomes (DC-95 Stage 2 Level 2). Each field
1275/// counts only `Evaluated` entries -- a `Failed` object contributes to none of them, same as it never
1276/// contributed to the pre-Level-2 running totals a whole-stage failure would have zeroed out entirely.
1277struct PhaseACounts {
1278    objects: usize,
1279    blocks: usize,
1280    rollback_blocks: usize,
1281    rollback_patches: usize,
1282}
1283
1284fn phase_a_counts(object_outcomes: &[ObjectItemOutcome]) -> Result<PhaseACounts> {
1285    let mut objects = 0_usize;
1286    let mut blocks = 0_usize;
1287    let mut rollback_blocks = 0_usize;
1288    let mut rollback_patches = 0_usize;
1289    for outcome in object_outcomes {
1290        // RFC 102 Stage 3: an `Unindexed` object is just as real and sound as an `Evaluated` one --
1291        // design-v1.md §12/§10.2's ruling that it is not a failure means it belongs in every count a
1292        // healthy object contributes to, not only in `has_item_failure()`'s exclusion.
1293        let verification = match &outcome.status {
1294            ObjectItemStatus::Evaluated(verification)
1295            | ObjectItemStatus::Unindexed(verification) => verification,
1296            ObjectItemStatus::Failed { .. } => continue,
1297        };
1298        objects = objects.checked_add(1).ok_or_else(|| {
1299            PrikkError::Integrity("object verification count overflow".to_string())
1300        })?;
1301        if verification.object_type == ObjectType::Block {
1302            blocks = blocks.checked_add(1).ok_or_else(|| {
1303                PrikkError::Integrity("block verification count overflow".to_string())
1304            })?;
1305            if verification.rollback_patch_count != 0 {
1306                rollback_blocks = rollback_blocks.checked_add(1).ok_or_else(|| {
1307                    PrikkError::Integrity("rollback block count overflow".to_string())
1308                })?;
1309                rollback_patches = rollback_patches
1310                    .checked_add(verification.rollback_patch_count)
1311                    .ok_or_else(|| {
1312                        PrikkError::Integrity("rollback patch count overflow".to_string())
1313                    })?;
1314            }
1315        }
1316    }
1317    Ok(PhaseACounts {
1318        objects,
1319        blocks,
1320        rollback_blocks,
1321        rollback_patches,
1322    })
1323}
1324
1325/// Check that active WAL record sequences strictly increase in replay (append) order. Reachable only
1326/// under direct file tampering — `Wal::append_patch` always assigns `previous.seq + 1` — but a queue
1327/// of N gives "ordering" its own meaning worth verifying explicitly (RFC criterion 6), not merely
1328/// assumed from successful structural decode.
1329fn check_active_wal_ordering(records: &[crate::wal::WalRecord]) -> Vec<ActiveWalOrderingIssue> {
1330    records
1331        .iter()
1332        .zip(records.iter().skip(1))
1333        .enumerate()
1334        .filter(|(_, (previous, current))| current.seq <= previous.seq)
1335        .map(|(index, (previous, current))| ActiveWalOrderingIssue {
1336            index: index + 1,
1337            previous_seq: previous.seq,
1338            seq: current.seq,
1339        })
1340        .collect()
1341}
1342
1343/// RFC 115 Stage 3 §6: the received-namespace verification gap, closed. `verify_repository` never
1344/// scanned `remotes/*` before this stage — `ReceivedIndex` appeared nowhere in this file or in
1345/// `refs/verify/scan.rs`, so a received ref whose target object was never shipped dangled
1346/// invisibly, on both the sender's and receiver's side, discovered while reviewing the DC-78
1347/// bundle-export tag-ref gap (`DC-78-bundle-tag-gap-implementation-review-v1.md` §5).
1348///
1349/// Reuses `ensure_ref_target_valid` as-is — the exact kind-aware, two-hop-for-tags check local refs
1350/// already get (`refs/verify/scan.rs`) — applied here for the first time to the received namespace.
1351/// This is wiring, not new logic: no new validation rule is introduced, only a new place the
1352/// existing one now runs.
1353fn verify_received_refs(
1354    layout: &RepositoryLayout,
1355    object_store: &impl ObjectReader,
1356) -> Result<Vec<RefItemOutcome>> {
1357    let pointers = list_received_pointers(layout)?;
1358    let mut outcomes = Vec::with_capacity(pointers.len());
1359    for pointer in pointers {
1360        let outcome = (|| -> Result<()> {
1361            let envelope = object_store
1362                .read_typed(pointer.ref_state_id, ObjectType::RefState)?
1363                .ok_or_else(|| {
1364                    PrikkError::Integrity(format!(
1365                        "received pointer {} names missing RefState {}",
1366                        pointer.ref_name, pointer.ref_state_id
1367                    ))
1368                })?;
1369            let payload = RefStatePayload::decode_canonical(
1370                &envelope.canonical_payload,
1371                envelope.schema_version,
1372            )?;
1373            ensure_ref_target_valid(
1374                object_store,
1375                payload.kind,
1376                payload.target_object_id,
1377                pointer.ref_state_id,
1378            )
1379        })();
1380        outcomes.push(RefItemOutcome {
1381            ref_name: pointer.ref_name,
1382            status: match outcome {
1383                Ok(()) => RefItemStatus::Evaluated,
1384                Err(error) => RefItemStatus::Failed {
1385                    message: error.to_string(),
1386                },
1387            },
1388        });
1389    }
1390    Ok(outcomes)
1391}
1392
1393/// DC-78 verify-local-tag-publication-trust (v2 amendment, ruling on
1394/// `verify-local-tag-publication-trust-escalation-v1.md`): a locally-published Tag's own MAINTAINER
1395/// signature gets the same publication-trust expectation `Block`/`RefState`/`RefUpdate` already carry
1396/// -- `053e442` gates both `prikk tag create` and `sync adopt-tag` on this same trust policy, so a
1397/// local tag's trust is re-derivable offline, exactly what `verify` exists to do.
1398///
1399/// Deliberately **not** wired through `verify_refs`: the escalation this amends found `verify_refs` has
1400/// a caller `ensure_ref_target_valid`'s own four-caller sweep never named --
1401/// `ensure_no_incomplete_publication`, a pre-mutation structural guard reached from eight sites
1402/// (`add_trusted_maintainer`, `seal_from_accepted`, `ActiveLock::acquire`, rollback draft, worktree
1403/// commit authoring, `doctor`), none of them `prikk verify`. Threading a trust verifier through
1404/// `verify_refs` would have put a trust-policy read and an Ed25519 verification per local tag on all
1405/// eight. This function enumerates independently instead, exactly like `verify_received_refs` above
1406/// sits alongside `Refs` rather than reading its output.
1407///
1408/// `RefPointerSummary` does not itself carry `RefKind` -- each pointer's `RefState` is read and decoded
1409/// here to find out, a second, independent read of the same envelope `ensure_ref_target_valid` already
1410/// reads (and discards) inside the ordinary ref scan. The ruling accepted this as the cost of not
1411/// contaminating a shared function: "`verify` is an audit, tags are few."
1412///
1413/// A received (not-yet-adopted) tag is never reached here: `list_ref_pointers` enumerates only the
1414/// local pointer index (`refs/by-id`), never the received namespace (`remotes/*`) -- the provenance
1415/// principle (a Tag's trust expectation follows *how it arrived*, not its type) holds structurally,
1416/// not by a flag threaded through a shared check.
1417fn verify_local_tag_publication_trust(
1418    layout: &RepositoryLayout,
1419    object_store: &impl ObjectReader,
1420    trust_verifier: &mut PublicationTrustVerifier<'_>,
1421) -> Result<()> {
1422    let ref_store = RefStore::new(layout.clone());
1423    for summary in ref_store.list_ref_pointers()? {
1424        let ref_state_envelope = object_store
1425            .read_typed(summary.ref_state_id, ObjectType::RefState)?
1426            .ok_or_else(|| {
1427                PrikkError::Integrity(format!(
1428                    "ref {} names missing RefState {}",
1429                    summary.ref_name, summary.ref_state_id
1430                ))
1431            })?;
1432        let ref_state_payload = RefStatePayload::decode_canonical(
1433            &ref_state_envelope.canonical_payload,
1434            ref_state_envelope.schema_version,
1435        )?;
1436        if ref_state_payload.kind != RefKind::Tag {
1437            continue;
1438        }
1439        let tag_envelope = object_store
1440            .read_typed(ref_state_payload.target_object_id, ObjectType::Tag)?
1441            .ok_or_else(|| {
1442                PrikkError::Integrity(format!(
1443                    "ref {} targets missing tag {}",
1444                    summary.ref_name, ref_state_payload.target_object_id
1445                ))
1446            })?;
1447        trust_verifier.verify(&tag_envelope)?;
1448    }
1449    Ok(())
1450}
1451
1452fn classify_active_wal_metadata(
1453    layout: &RepositoryLayout,
1454    wal_is_empty: bool,
1455) -> Result<ActiveWalMetadataStatus> {
1456    match (wal_is_empty, read_active_ref_metadata(layout)?) {
1457        (true, ActiveRefMetadata::Missing) => Ok(ActiveWalMetadataStatus::MissingForEmptyWal),
1458        (true, ActiveRefMetadata::Valid(ref_name)) => {
1459            Ok(ActiveWalMetadataStatus::ValidForEmptyWal { ref_name })
1460        }
1461        (true, ActiveRefMetadata::Invalid(reason)) => {
1462            Ok(ActiveWalMetadataStatus::InvalidForEmptyWal { reason })
1463        }
1464        (false, ActiveRefMetadata::Missing) => Ok(ActiveWalMetadataStatus::MissingForNonEmptyWal),
1465        (false, ActiveRefMetadata::Valid(ref_name)) => {
1466            Ok(ActiveWalMetadataStatus::ValidForNonEmptyWal { ref_name })
1467        }
1468        (false, ActiveRefMetadata::Invalid(reason)) => {
1469            Ok(ActiveWalMetadataStatus::InvalidForNonEmptyWal { reason })
1470        }
1471    }
1472}
1473
1474/// Phase A (DC-92 §4.2): every check that does not depend on lineage-state derivation order —
1475/// existence of referenced objects, rollback-patch counting, and (independent of the shared memo)
1476/// the merge-baseline re-derivation. A `CurrentV6` block's own state-root verification is
1477/// deliberately **not** done here; it is deferred to a batch, dependency-ordered pass
1478/// (`crate::block_state::verify_blocks_topological`) run once after every object type has been
1479/// scanned, so `pending_v3_blocks` collects this block's already-decoded payload rather than
1480/// discarding it. See that function's own doc for why deferring is what bounds
1481/// `LineageStateMemo`'s memory instead of merely avoiding redundant re-derivation.
1482fn verify_block_payload(
1483    object_store: &impl ObjectReader,
1484    block_id: ObjectId,
1485    format: RepositoryFormat,
1486    canonical_payload: &[u8],
1487    pending_v3_blocks: &mut Vec<(ObjectId, BlockPayload)>,
1488) -> Result<(usize, Option<MergeBaselineDivergence>)> {
1489    let payload = BlockPayload::decode_canonical(canonical_payload)?;
1490    for parent in &payload.parent_block_ids {
1491        ensure_object_exists(
1492            object_store,
1493            ObjectType::Block,
1494            *parent,
1495            "parent block",
1496            block_id,
1497        )?;
1498    }
1499    let mut rollback_patch_count = 0_usize;
1500    for patch in &payload.patch_ids {
1501        let Some(envelope) = object_store.read_typed(*patch, ObjectType::Patch)? else {
1502            return Err(PrikkError::Integrity(format!(
1503                "object {block_id} references missing block patch {patch}"
1504            )));
1505        };
1506        let context = format!("sealed Block {block_id} Patch {patch}");
1507        if verify_rollback_patch_envelope(&envelope, &context)? {
1508            rollback_patch_count = rollback_patch_count.checked_add(1).ok_or_else(|| {
1509                PrikkError::Integrity("sealed rollback patch count overflow".to_string())
1510            })?;
1511        }
1512    }
1513    if let Some(snapshot) = payload.snapshot_blob_ref {
1514        ensure_object_exists(
1515            object_store,
1516            ObjectType::Blob,
1517            snapshot,
1518            "snapshot blob",
1519            block_id,
1520        )?;
1521    }
1522    let merge_baseline_divergence = if format == RepositoryFormat::CurrentV6 {
1523        verify_merge_baseline(object_store, block_id, &payload)?
1524    } else {
1525        None
1526    };
1527    if format == RepositoryFormat::CurrentV6 {
1528        pending_v3_blocks.push((block_id, payload));
1529    }
1530    Ok((rollback_patch_count, merge_baseline_divergence))
1531}
1532
1533/// DC-75: for a `Merge` block, independently re-derive whether the recorded
1534/// `merge_baseline_block_id` is a common ancestor of both parents — a claim, not trusted. Shape
1535/// (kind, parent count, mainline/baseline presence) is already guaranteed by
1536/// `verify_block_v2_state`'s `validate_block_v2_shape` call above, so this only checks the claim's
1537/// content. Cost is the same full-parent reachability walk measured linear in
1538/// `baseline-recording-answer-v1.md` §1 — unconditional, not a gated "deep verify" mode.
1539fn verify_merge_baseline(
1540    object_store: &impl ObjectReader,
1541    block_id: ObjectId,
1542    payload: &BlockPayload,
1543) -> Result<Option<MergeBaselineDivergence>> {
1544    if payload.kind != prikk_object::BlockKind::Merge {
1545        return Ok(None);
1546    }
1547    let (Some(mainline_parent_id), Some(recorded_baseline)) =
1548        (payload.mainline_parent_id, payload.merge_baseline_block_id)
1549    else {
1550        // Malformed shape already failed closed above via `validate_block_v2_shape`.
1551        return Ok(None);
1552    };
1553    let Some(&secondary_parent_id) = payload
1554        .parent_block_ids
1555        .iter()
1556        .find(|&&id| id != mainline_parent_id)
1557    else {
1558        return Ok(None);
1559    };
1560    let mainline_ancestors =
1561        crate::merge_evidence::ancestors_inclusive(object_store, mainline_parent_id)?;
1562    let secondary_ancestors =
1563        crate::merge_evidence::ancestors_inclusive(object_store, secondary_parent_id)?;
1564    let is_common_ancestor = mainline_ancestors.contains_key(&recorded_baseline)
1565        && secondary_ancestors.contains_key(&recorded_baseline);
1566    if is_common_ancestor {
1567        Ok(None)
1568    } else {
1569        Ok(Some(MergeBaselineDivergence {
1570            block_id,
1571            recorded_baseline,
1572            mainline_parent_id,
1573            secondary_parent_id,
1574        }))
1575    }
1576}
1577
1578fn ensure_object_exists(
1579    object_store: &impl ObjectReader,
1580    object_type: ObjectType,
1581    object_id: ObjectId,
1582    role: &str,
1583    owner: ObjectId,
1584) -> Result<()> {
1585    let exists = object_store.read_typed(object_id, object_type)?.is_some();
1586    if exists {
1587        return Ok(());
1588    }
1589    Err(PrikkError::Integrity(format!(
1590        "object {owner} references missing {role} {object_id}"
1591    )))
1592}
1593
1594fn verify_wal_persistence(
1595    object_store: &impl ObjectReader,
1596    records: &[crate::WalRecord],
1597) -> Result<usize> {
1598    let mut persisted = 0_usize;
1599    for record in records {
1600        if record.envelope.object_type != ObjectType::Patch {
1601            return Err(PrikkError::Integrity(format!(
1602                "active WAL record {} contains {}, expected patch",
1603                record.seq, record.envelope.object_type
1604            )));
1605        }
1606        // `FileObjectStore::contains_object`'s exact existing semantics, reproduced generically:
1607        // "does this exist, as this type" -- and, matching its own silent-on-error tolerance, any
1608        // read error here means "not found," not a propagated failure. `contains_object` itself is
1609        // inherent, not on `ObjectReader`, so a generic reader uses `read_object` directly instead.
1610        if object_store
1611            .read_object(record.envelope.object_id())
1612            .ok()
1613            .flatten()
1614            .is_some_and(|envelope| envelope.object_type == ObjectType::Patch)
1615        {
1616            persisted = persisted.checked_add(1).ok_or_else(|| {
1617                PrikkError::Integrity("persisted WAL patch count overflow".to_string())
1618            })?;
1619        }
1620    }
1621    Ok(persisted)
1622}
1623
1624#[cfg(test)]
1625mod tests;