Skip to main content

vela_protocol/computed/
project.rs

1//! Stage 5: ASSEMBLE — build the project with stats and metadata.
2
3use std::collections::{HashMap, HashSet};
4
5use chrono::Utc;
6use serde::{Deserialize, Serialize};
7
8use crate::bundle::{ConfidenceUpdate, FindingBundle, ReviewEvent};
9use crate::events::StateEvent;
10use crate::proposals::{ProofState, StateProposal};
11use crate::sign::{ActorRecord, SignedEnvelope};
12use crate::sources::{ConditionRecord, EvidenceAtom, SourceRecord};
13
14/// A dependency on another project (like a Cargo dependency for science).
15///
16/// v0.8 extends this with three optional fields that turn it into a
17/// **cross-frontier dependency**: when `vfr_id` is set, the entry pins
18/// a remote frontier by its content-addressed id and a snapshot hash.
19/// `Link.target` values of the form `vf_<id>@vfr_<id>` resolve through
20/// here. Without `vfr_id`, the entry behaves as a pre-v0.8 compile-time
21/// dependency record.
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
23pub struct ProjectDependency {
24    pub name: String,
25    pub source: String,
26    pub version: Option<String>,
27    pub pinned_hash: Option<String>,
28    /// v0.8: content-addressed id of the dependent frontier.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub vfr_id: Option<String>,
31    /// v0.8: where to fetch the dependent frontier file from
32    /// (typically an `https://…` URL pointing at raw JSON).
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub locator: Option<String>,
35    /// v0.8: SHA-256 of the canonical snapshot the dependent commits
36    /// to. Strict pull verifies the fetched dependency's actual
37    /// `snapshot_hash` matches this value before satisfying any link.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub pinned_snapshot_hash: Option<String>,
40}
41
42impl ProjectDependency {
43    /// True if this entry declares a cross-frontier dependency
44    /// (`vfr_id` is set). Pre-v0.8 entries return `false`.
45    pub fn is_cross_frontier(&self) -> bool {
46        self.vfr_id.is_some()
47    }
48}
49
50#[derive(Debug, Serialize, Deserialize)]
51pub struct Project {
52    pub vela_version: String,
53    pub schema: String,
54    /// Stable Vela-addressable frontier ID, derived from a `frontier.created`
55    /// genesis event hash. Optional for backward compatibility with v0.2
56    /// frontiers; new v0.3 frontiers populate it on `assemble()`.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub frontier_id: Option<String>,
59    #[serde(rename = "frontier")]
60    pub project: ProjectMeta,
61    pub stats: ProjectStats,
62    pub findings: Vec<FindingBundle>,
63    /// Source artifacts that produced evidence-bearing units.
64    #[serde(default)]
65    pub sources: Vec<SourceRecord>,
66    /// Materialized source-grounded evidence units linked to findings.
67    #[serde(default)]
68    pub evidence_atoms: Vec<EvidenceAtom>,
69    /// Materialized condition boundaries used to avoid claim overgeneralization.
70    #[serde(default)]
71    pub condition_records: Vec<ConditionRecord>,
72    /// Append-only log of review events (content-addressed).
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub review_events: Vec<ReviewEvent>,
75    /// Append-only log of confidence updates.
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub confidence_updates: Vec<ConfidenceUpdate>,
78    /// Canonical append-only event log for replayable frontier state.
79    #[serde(default)]
80    pub events: Vec<StateEvent>,
81    /// Portable pending/applied proposal records for proposal-first writes.
82    #[serde(default)]
83    pub proposals: Vec<StateProposal>,
84    /// Frontier-local proof freshness projection.
85    #[serde(default)]
86    pub proof_state: ProofState,
87    /// Cryptographic signatures for findings (Ed25519).
88    #[serde(default)]
89    pub signatures: Vec<SignedEnvelope>,
90    /// Registered actor identities, mapping a stable actor.id to an
91    /// Ed25519 public key. Phase M (v0.4): once an actor is registered,
92    /// any canonical event referencing that actor.id under
93    /// `--strict` must carry a verifiable Ed25519 signature.
94    #[serde(default, skip_serializing_if = "Vec::is_empty")]
95    pub actors: Vec<ActorRecord>,
96    /// Generic content-addressed artifacts: protocols, trial registry
97    /// records, supplements, notebooks, source files, and dataset
98    /// manifests that need a durable byte or pointer commitment.
99    #[serde(default, skip_serializing_if = "Vec::is_empty")]
100    pub artifacts: Vec<crate::bundle::Artifact>,
101    /// v0.213: Released Diff Pack tracking — first-class replay
102    /// state for the v0.201 `diff_pack.released` and v0.205
103    /// `diff_pack.reviewed` event arms. Prior cycles left these
104    /// arms metadata-only (Ok(()) returns); v0.213 makes them
105    /// mutate this array so a consumer walking the canonical
106    /// event log can answer "which packs have been released on
107    /// this frontier?" without reading sibling directories.
108    ///
109    /// Replay invariant: the array is append-only on
110    /// `diff_pack.released` events (idempotent on pack_id) and
111    /// updated in place on `diff_pack.reviewed` events. Theorem
112    /// 29 pins the accumulation algebra.
113    #[serde(default, skip_serializing_if = "Vec::is_empty")]
114    pub released_diff_packs: Vec<crate::released_diff_pack::ReleasedDiffPackRecord>,
115    /// v0.218: Verdict-conflict resolutions on this frontier. The
116    /// `verdict_conflict.resolved` reducer arm appends to this
117    /// array (idempotent on conflict_id). Theorem 32 pins the
118    /// accumulation algebra. Audit-trail semantics: every
119    /// resolution stays here, even when a later resolution
120    /// supersedes an earlier one — the substrate is honest about
121    /// the full disagreement history, not just the latest verdict.
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub verdict_conflicts: Vec<crate::verdict_conflict::VerdictConflict>,
124    /// T7: reviewed Contradiction objects (`vcx_`). Holds only
125    /// contradictions a reviewer has acted on (under-review or
126    /// adjudicated) — candidates are derived from the graph on demand
127    /// and are not canonical state. Latest resolution per id wins;
128    /// see `apply_contradiction_resolved`.
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub contradictions: Vec<crate::contradiction::Contradiction>,
131    /// verifier attachments bound to findings (target = `vf_…`). Sidecar
132    /// collection (not a field on FindingBundle) so finding-state replay
133    /// digests are unaffected. Per-finding trust-gate status is DERIVED from
134    /// these on read, never stored. See `verifier_attachment`.
135    #[serde(default, skip_serializing_if = "Vec::is_empty")]
136    pub verifier_attachments: Vec<crate::verifier_attachment::VerifierAttachment>,
137    /// Signed banked attempts (`vat_`). Immutable deposits; the verified
138    /// status is DERIVED from the gate + attempt_resolutions on read, never
139    /// stored. See `apply_attempt_deposited`.
140    #[serde(default, skip_serializing_if = "Vec::is_empty")]
141    pub attempts: Vec<crate::attempt::Attempt>,
142    /// Append-only lifecycle transitions on attempts (`vre_`). Idempotent by
143    /// id; the head per attempt is the latest by `at`. See
144    /// `apply_attempt_resolved` and `Project::head_resolution`.
145    #[serde(default, skip_serializing_if = "Vec::is_empty")]
146    pub attempt_resolutions: Vec<crate::attempt::ResolutionEvent>,
147    /// Signed cross-domain transfers (`vtr_`). Immutable deposits; admission
148    /// (whether the link is sound) is DERIVED via `derive_transfer_status` on
149    /// read, never stored. See `apply_transfer_deposited`.
150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
151    pub transfers: Vec<crate::transfer::Transfer>,
152    /// Signed significance endorsements (`ven_`). Stored as individual records,
153    /// NEVER aggregated into a score — significance is social and uncomputed by
154    /// design. See `apply_endorsement_deposited` and `docs/SIGNIFICANCE_SLOT.md`.
155    #[serde(default, skip_serializing_if = "Vec::is_empty")]
156    pub endorsements: Vec<crate::endorsement::Endorsement>,
157    /// Statement-faithfulness attestations (`vsa_`): signed human
158    /// judgments that a formal statement encodes its informal problem.
159    /// Events-only storage (the replay loader grafts them).
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    pub statement_attestations: Vec<crate::statement_attestation::StatementAttestation>,
162    /// Math-atlas anchor links: signed, retractable `val_` assertions that a
163    /// claim carries an external-catalogue anchor (OEIS / Erdős / mathlib / ...).
164    /// Events-only storage (the replay loader grafts them); the cross-frontier
165    /// identity join reads these. See `crate::anchor`.
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub anchor_links: Vec<crate::anchor::AnchorLink>,
168    /// Active obligation leases (events-only; replay-grafted). Expiry is
169    /// computed at read time from claimed_at + ttl.
170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171    pub attempt_claims: Vec<AttemptClaim>,
172    /// Priority registrations: content-addressed statement hashes with
173    /// their log timestamps (events-only; replay-grafted).
174    #[serde(default, skip_serializing_if = "Vec::is_empty")]
175    pub statement_registrations: Vec<StatementRegistration>,
176}
177
178#[derive(Debug, Serialize, Deserialize)]
179pub struct ProjectMeta {
180    pub name: String,
181    pub description: String,
182    pub compiled_at: String,
183    pub compiler: String,
184    pub papers_processed: usize,
185    pub errors: usize,
186    #[serde(default)]
187    pub dependencies: Vec<ProjectDependency>,
188}
189
190/// serde `skip_serializing_if` predicate: a zero-valued `usize` stat is
191/// omitted so a frontier that predates the field round-trips and
192/// snapshot-hashes byte-identically to the pre-field serialization.
193/// Without this, adding a stat field silently breaks `registry pull`
194/// verification of every frontier published by an older binary.
195fn stat_is_zero(n: &usize) -> bool {
196    *n == 0
197}
198
199#[derive(Debug, Serialize, Deserialize, Default)]
200pub struct ProjectStats {
201    pub findings: usize,
202    pub links: usize,
203    pub replicated: usize,
204    pub unreplicated: usize,
205    pub avg_confidence: f64,
206    pub gaps: usize,
207    pub negative_space: usize,
208    pub contested: usize,
209    pub categories: HashMap<String, usize>,
210    pub link_types: HashMap<String, usize>,
211    pub human_reviewed: usize,
212    /// Findings whose review came from an agent/bot actor, counted
213    /// separately so `human_reviewed` never overstates human review.
214    /// Skipped when zero so frontiers published before this field
215    /// existed snapshot-hash identically (registry-pull back-compat).
216    #[serde(default, skip_serializing_if = "stat_is_zero")]
217    pub agent_reviewed: usize,
218    /// Number of review events in this frontier.
219    #[serde(default)]
220    pub review_event_count: usize,
221    /// Number of confidence updates in this frontier.
222    #[serde(default)]
223    pub confidence_update_count: usize,
224    /// Number of canonical state events in this frontier.
225    #[serde(default)]
226    pub event_count: usize,
227    /// Number of source records in the frontier source registry.
228    #[serde(default)]
229    pub source_count: usize,
230    /// Number of materialized evidence atoms in the frontier.
231    #[serde(default)]
232    pub evidence_atom_count: usize,
233    /// Number of materialized condition records in the frontier.
234    #[serde(default)]
235    pub condition_record_count: usize,
236    /// Number of persisted proposals in the frontier.
237    #[serde(default)]
238    pub proposal_count: usize,
239    pub confidence_distribution: ConfidenceDistribution,
240}
241
242#[derive(Debug, Serialize, Deserialize, Default)]
243pub struct ConfidenceDistribution {
244    pub high_gt_80: usize,
245    pub medium_60_80: usize,
246    pub low_lt_60: usize,
247}
248
249/// Schema and compiler defaults for the current Vela protocol release.
250pub const VELA_SCHEMA_URL: &str = "https://vela.science/schema/finding-bundle/v0.10.0";
251pub const VELA_SCHEMA_VERSION: &str = "0.10.0";
252pub const VELA_COMPILER_VERSION: &str = concat!("vela/", env!("CARGO_PKG_VERSION"));
253
254/// Derive a `vfr_<hash>` frontier ID from frontier metadata. Used as a
255/// fallback for legacy frontiers without a `frontier.created` genesis
256/// event; v0.4+ frontiers derive from the genesis event itself via
257/// `frontier_id_from_genesis`.
258#[must_use]
259pub fn derive_frontier_id_from_meta(meta: &ProjectMeta) -> String {
260    let preimage = serde_json::json!({
261        "name": meta.name,
262        "compiled_at": meta.compiled_at,
263        "compiler": meta.compiler,
264    });
265    let bytes = crate::canonical::to_canonical_bytes(&preimage).unwrap_or_default();
266    use sha2::{Digest, Sha256};
267    format!("vfr_{}", &hex::encode(Sha256::digest(bytes))[..16])
268}
269
270/// Derive a `vfr_<hash>` frontier ID from the canonical hash of the
271/// `frontier.created` genesis event. Returns `None` if `events[0]` is
272/// absent or not a `frontier.created` event (legacy frontiers fall back
273/// to meta-derivation via `derive_frontier_id_from_meta`).
274///
275/// The preimage shape matches `event_id` exactly so the same canonical
276/// rule produces both the event's `vev_…` and the frontier's `vfr_…`
277/// from the same logical content. Doctrine line: a frontier IS what the
278/// `frontier.created` event creates.
279#[must_use]
280pub fn frontier_id_from_genesis(events: &[crate::events::StateEvent]) -> Option<String> {
281    let genesis = events.first()?;
282    if genesis.kind != "frontier.created" {
283        return None;
284    }
285    let preimage = serde_json::json!({
286        "schema": genesis.schema,
287        "kind": genesis.kind,
288        "target": genesis.target,
289        "actor": genesis.actor,
290        "timestamp": genesis.timestamp,
291        "reason": genesis.reason,
292        "before_hash": genesis.before_hash,
293        "after_hash": genesis.after_hash,
294        "payload": genesis.payload,
295        "caveats": genesis.caveats,
296    });
297    let bytes = crate::canonical::to_canonical_bytes(&preimage).ok()?;
298    use sha2::{Digest, Sha256};
299    Some(format!("vfr_{}", &hex::encode(Sha256::digest(bytes))[..16]))
300}
301
302/// Construct the `frontier.created` canonical event for a freshly
303/// compiled frontier. The event becomes `events[0]` and the frontier_id
304/// derives from its canonical hash.
305///
306/// Targets `frontier:<name>` (not `finding:…`) so replay's orphan-target
307/// detection does not flag it; the genesis event carries identity, not a
308/// finding mutation.
309fn build_genesis_event(name: &str, compiled_at: &str, creator: &str) -> crate::events::StateEvent {
310    use crate::events::{EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget};
311    let mut event = StateEvent {
312        schema: EVENT_SCHEMA.to_string(),
313        id: String::new(),
314        kind: "frontier.created".into(),
315        target: StateTarget {
316            r#type: "frontier".to_string(),
317            id: name.to_string(),
318        },
319        actor: StateActor {
320            id: creator.to_string(),
321            r#type: "frontier".to_string(),
322        },
323        timestamp: compiled_at.to_string(),
324        reason: "frontier compiled".to_string(),
325        before_hash: NULL_HASH.to_string(),
326        after_hash: NULL_HASH.to_string(),
327        payload: serde_json::json!({
328            "name": name,
329            "creator": creator,
330            "schema_version": VELA_SCHEMA_VERSION,
331            "compiled_at": compiled_at,
332        }),
333        caveats: vec![],
334        signature: None,
335    };
336    event.id = crate::events::compute_event_id(&event);
337    event
338}
339
340pub fn assemble(
341    name: &str,
342    bundles: Vec<FindingBundle>,
343    papers_processed: usize,
344    errors: usize,
345    description: &str,
346) -> Project {
347    let compiled_at = Utc::now().to_rfc3339();
348    let meta = ProjectMeta {
349        name: name.to_string(),
350        description: description.to_string(),
351        compiled_at: compiled_at.clone(),
352        compiler: VELA_COMPILER_VERSION.to_string(),
353        papers_processed,
354        errors,
355        dependencies: Vec::new(),
356    };
357    // Phase J (v0.4): emit a `frontier.created` canonical event as
358    // events[0] and derive frontier_id from its canonical hash. The
359    // address primitive becomes doctrine-grounded — a frontier IS what
360    // the genesis event creates, not a convenience over its metadata.
361    let genesis = build_genesis_event(name, &compiled_at, VELA_COMPILER_VERSION);
362    let frontier_id = frontier_id_from_genesis(std::slice::from_ref(&genesis));
363    let mut project = Project {
364        vela_version: VELA_SCHEMA_VERSION.to_string(),
365        schema: VELA_SCHEMA_URL.to_string(),
366        frontier_id,
367        project: meta,
368        stats: ProjectStats::default(),
369        findings: bundles,
370        sources: Vec::new(),
371        evidence_atoms: Vec::new(),
372        condition_records: Vec::new(),
373        review_events: Vec::new(),
374        confidence_updates: Vec::new(),
375        events: vec![genesis],
376        proposals: Vec::new(),
377        proof_state: ProofState::default(),
378        signatures: Vec::new(),
379        actors: Vec::new(),
380        artifacts: Vec::new(),
381        released_diff_packs: Vec::new(),
382        verdict_conflicts: Vec::new(),
383        contradictions: Vec::new(),
384        verifier_attachments: Vec::new(),
385        attempts: Vec::new(),
386        attempt_resolutions: Vec::new(),
387        transfers: Vec::new(),
388        endorsements: Vec::new(),
389        statement_attestations: Vec::new(),
390        anchor_links: Vec::new(),
391        attempt_claims: Vec::new(),
392        statement_registrations: Vec::new(),
393    };
394    crate::sources::materialize_project(&mut project);
395    project
396}
397
398impl Project {
399    /// The head (latest by `at`) lifecycle resolution for an attempt, or
400    /// `None` if the attempt is still an unresolved candidate. Computed on
401    /// read from the append-only `attempt_resolutions`, never stored.
402    #[must_use]
403    pub fn head_resolution(&self, attempt_id: &str) -> Option<&crate::attempt::ResolutionEvent> {
404        self.attempt_resolutions
405            .iter()
406            .filter(|r| r.attempt_id == attempt_id)
407            .max_by(|a, b| a.at.cmp(&b.at))
408    }
409
410    /// Return the stable Vela-addressable frontier ID. Prefers the stored
411    /// field; if absent, derives from the `frontier.created` genesis
412    /// event in `events[0]`; if no genesis event is present, falls back
413    /// to meta-derivation (legacy v0.3 frontiers).
414    #[must_use]
415    pub fn frontier_id(&self) -> String {
416        if let Some(id) = self.frontier_id.clone() {
417            return id;
418        }
419        if let Some(id) = frontier_id_from_genesis(&self.events) {
420            return id;
421        }
422        derive_frontier_id_from_meta(&self.project)
423    }
424
425    /// v0.8: iterate the cross-frontier dependencies (those with
426    /// `vfr_id` set). Pre-v0.8 compile-time deps without `vfr_id`
427    /// are filtered out.
428    pub fn cross_frontier_deps(&self) -> impl Iterator<Item = &ProjectDependency> {
429        self.project
430            .dependencies
431            .iter()
432            .filter(|d| d.is_cross_frontier())
433    }
434
435    /// v0.8: look up the dependency record for a specific `vfr_id`.
436    /// Returns `None` if no matching cross-frontier dep is declared.
437    pub fn dep_for_vfr(&self, vfr_id: &str) -> Option<&ProjectDependency> {
438        self.cross_frontier_deps()
439            .find(|d| d.vfr_id.as_deref() == Some(vfr_id))
440    }
441
442    /// v0.49.3: build a reverse-dependency index from the forward
443    /// `links: Vec<Link>` data on each finding. The forward direction
444    /// (which findings does this finding depend on?) is O(1) per
445    /// finding because it's just `f.links`. The reverse direction
446    /// (which findings depend on this finding?) previously required
447    /// scanning every finding for every query — O(N×L). This index
448    /// flips that to O(1) lookup once built.
449    ///
450    /// Cost to build: O(N×L) one-time scan over all findings × links.
451    /// At 48 findings × ~3 links each (the legacy BBB proof fixture),
452    /// that's ~150 hash-insert operations and microseconds. At
453    /// 100K findings × 10 links, it's still well under a second.
454    ///
455    /// Used by retraction-impact queries (serve.rs), cascade
456    /// computation, and any consumer that needs to walk the dependent
457    /// graph rather than the dependency graph. The index is not
458    /// serialized — it's a derived structure that callers build when
459    /// they need it and drop when they don't.
460    #[must_use]
461    pub fn build_reverse_dep_index(&self) -> ReverseDepIndex {
462        let mut map: std::collections::HashMap<String, Vec<String>> =
463            std::collections::HashMap::with_capacity(self.findings.len());
464        for f in &self.findings {
465            for link in &f.links {
466                map.entry(link.target.clone())
467                    .or_default()
468                    .push(f.id.clone());
469            }
470        }
471        // Stable sort each dependent list so two implementations of the
472        // index agree on ordering for any downstream serialization.
473        for v in map.values_mut() {
474            v.sort();
475            v.dedup();
476        }
477        ReverseDepIndex { map }
478    }
479}
480
481/// v0.49.3: reverse-dependency index built from a Project's forward
482/// `links` graph. Maps `finding_id → [dependent_finding_id, …]` so a
483/// "what depends on X?" lookup is O(1) instead of O(N×L).
484///
485/// Construct via `Project::build_reverse_dep_index`. The index is a
486/// snapshot — it does not auto-update if the Project mutates after.
487/// For long-lived consumers that mutate state, rebuild after each
488/// reduce step.
489#[derive(Debug, Clone, Default)]
490pub struct ReverseDepIndex {
491    map: std::collections::HashMap<String, Vec<String>>,
492}
493
494impl ReverseDepIndex {
495    /// Findings whose forward `links` list a target with this id.
496    /// Empty slice if nothing depends on this finding (or if the id
497    /// isn't in the index at all).
498    #[must_use]
499    pub fn dependents_of(&self, finding_id: &str) -> &[String] {
500        self.map
501            .get(finding_id)
502            .map(|v| v.as_slice())
503            .unwrap_or(&[])
504    }
505
506    /// Total number of dependent edges in the index. Useful for
507    /// quick sanity checks and metric reporting.
508    #[must_use]
509    pub fn edge_count(&self) -> usize {
510        self.map.values().map(Vec::len).sum()
511    }
512
513    /// Number of distinct findings that have at least one dependent.
514    #[must_use]
515    pub fn target_count(&self) -> usize {
516        self.map.len()
517    }
518
519    /// Iterate `(target_finding_id, dependents)` pairs. Order is
520    /// HashMap-iteration-order, not stable across runs; sort if a
521    /// consumer needs determinism.
522    pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<String>)> {
523        self.map.iter()
524    }
525}
526
527#[cfg(test)]
528mod cross_frontier_dep_tests {
529    use super::*;
530
531    fn dep_local(name: &str) -> ProjectDependency {
532        ProjectDependency {
533            name: name.into(),
534            source: "local".into(),
535            version: None,
536            pinned_hash: None,
537            vfr_id: None,
538            locator: None,
539            pinned_snapshot_hash: None,
540        }
541    }
542
543    fn dep_cross(vfr: &str) -> ProjectDependency {
544        ProjectDependency {
545            name: "ext".into(),
546            source: "vela.hub".into(),
547            version: None,
548            pinned_hash: None,
549            vfr_id: Some(vfr.into()),
550            locator: Some(format!("https://example.test/{vfr}.json")),
551            pinned_snapshot_hash: Some("a".repeat(64)),
552        }
553    }
554
555    #[test]
556    fn is_cross_frontier_only_when_vfr_id_set() {
557        assert!(!dep_local("x").is_cross_frontier());
558        assert!(dep_cross("vfr_abc").is_cross_frontier());
559    }
560
561    #[test]
562    fn dep_serializes_byte_identical_when_v0_8_fields_absent() {
563        // Backward compat: a pre-v0.8 dep round-trips through serde
564        // without emitting any of the new optional v0.8 fields.
565        let d = dep_local("legacy");
566        let s = serde_json::to_string(&d).unwrap();
567        assert!(!s.contains("vfr_id"));
568        assert!(!s.contains("locator"));
569        assert!(!s.contains("pinned_snapshot_hash"));
570    }
571}
572
573#[cfg(test)]
574pub(crate) mod reverse_dep_index_tests {
575    use super::*;
576    use crate::bundle::{
577        Assertion, Author, Conditions, Confidence, ConfidenceKind, ConfidenceMethod, Evidence,
578        Extraction, FindingBundle, Flags, Link, Provenance,
579    };
580
581    pub(crate) fn synth_finding(idx: usize, links: Vec<Link>) -> FindingBundle {
582        let assertion = Assertion {
583            text: format!("Synthetic finding {idx}"),
584            assertion_type: "mechanism".into(),
585            entities: vec![],
586            relation: None,
587            direction: None,
588            causal_claim: None,
589            causal_evidence_grade: None,
590        };
591        let evidence = Evidence {
592            evidence_type: "experimental".into(),
593            model_system: "test".into(),
594            method: "test".into(),
595            replicated: false,
596            replication_count: None,
597            evidence_spans: vec![],
598        };
599        let conditions = Conditions {
600            text: "test".into(),
601            duration: None,
602        };
603        let confidence = Confidence {
604            kind: ConfidenceKind::FrontierEpistemic,
605            score: 0.5,
606            basis: "test".into(),
607            method: ConfidenceMethod::LlmInitial,
608            extraction_confidence: 0.9,
609        };
610        let provenance = Provenance {
611            source_type: "published_paper".into(),
612            doi: Some(format!("10.0000/reverse-dep-index-test.{idx:04}")),
613            url: None,
614            title: format!("Synthetic test paper {idx}"),
615            authors: vec![Author {
616                name: "T".into(),
617                orcid: None,
618            }],
619            year: None,
620            license: None,
621            publisher: None,
622            funders: vec![],
623            extraction: Extraction::default(),
624            review: None,
625            contributions: Vec::new(),
626        };
627        let flags = Flags::default();
628        let mut bundle = FindingBundle::new(
629            assertion, evidence, conditions, confidence, provenance, flags,
630        );
631        bundle.links = links;
632        bundle
633    }
634
635    pub(crate) fn link_to(target: &str) -> Link {
636        Link {
637            target: target.into(),
638            link_type: "supports".into(),
639            note: "test".into(),
640            inferred_by: "test".into(),
641            created_at: "2026-05-02T00:00:00Z".into(),
642            mechanism: None,
643        }
644    }
645
646    /// Build a chain: 0 → 1 → 2 → 3 (each finding supports the next).
647    /// Then dependents_of(2) should return [1], dependents_of(1) → [0],
648    /// dependents_of(3) → [2], dependents_of(0) → [] (root, nothing
649    /// depends on it).
650    #[test]
651    fn dependents_of_returns_correct_set_for_simple_chain() {
652        let f3 = synth_finding(3, vec![]);
653        let f2 = synth_finding(2, vec![link_to(&f3.id)]);
654        let f1 = synth_finding(1, vec![link_to(&f2.id)]);
655        let f0 = synth_finding(0, vec![link_to(&f1.id)]);
656
657        let mut project = assemble("chain", vec![], 0, 0, "test");
658        project.findings = vec![f0.clone(), f1.clone(), f2.clone(), f3.clone()];
659
660        let idx = project.build_reverse_dep_index();
661        assert_eq!(idx.dependents_of(&f3.id), &[f2.id.clone()]);
662        assert_eq!(idx.dependents_of(&f2.id), &[f1.id.clone()]);
663        assert_eq!(idx.dependents_of(&f1.id), &[f0.id.clone()]);
664        assert!(idx.dependents_of(&f0.id).is_empty());
665        // Edge count = 3 (one per non-root link).
666        assert_eq!(idx.edge_count(), 3);
667        // Target count = 3 (f1, f2, f3 each have a dependent).
668        assert_eq!(idx.target_count(), 3);
669    }
670
671    /// Multiple findings depending on the same target should produce a
672    /// sorted, deduped dependent list.
673    #[test]
674    fn dependents_of_dedups_and_sorts() {
675        let target = synth_finding(99, vec![]);
676        let target_id = target.id.clone();
677        // f1, f2, f3 all link to target. Plus f1 has TWO links to
678        // target (to test dedup).
679        let f1 = synth_finding(1, vec![link_to(&target_id), link_to(&target_id)]);
680        let f2 = synth_finding(2, vec![link_to(&target_id)]);
681        let f3 = synth_finding(3, vec![link_to(&target_id)]);
682
683        let mut project = assemble("multi-dependents", vec![], 0, 0, "test");
684        project.findings = vec![target, f1.clone(), f2.clone(), f3.clone()];
685
686        let idx = project.build_reverse_dep_index();
687        let mut expected = vec![f1.id.clone(), f2.id.clone(), f3.id.clone()];
688        expected.sort();
689        assert_eq!(idx.dependents_of(&target_id), expected.as_slice());
690    }
691
692    /// A finding id with no dependents — and an id that doesn't exist
693    /// in the project at all — both return an empty slice.
694    #[test]
695    fn dependents_of_unknown_or_orphan_returns_empty() {
696        let lonely = synth_finding(7, vec![]);
697        let mut project = assemble("orphan", vec![], 0, 0, "test");
698        project.findings = vec![lonely.clone()];
699
700        let idx = project.build_reverse_dep_index();
701        assert!(idx.dependents_of(&lonely.id).is_empty());
702        assert!(idx.dependents_of("vf_does_not_exist").is_empty());
703    }
704
705    /// Empty project → empty index.
706    #[test]
707    fn empty_project_yields_empty_index() {
708        let project = assemble("empty", vec![], 0, 0, "test");
709        let idx = project.build_reverse_dep_index();
710        assert_eq!(idx.edge_count(), 0);
711        assert_eq!(idx.target_count(), 0);
712    }
713}
714
715/// Recompute derived frontier statistics after mechanical edits.
716pub fn recompute_stats(project: &mut Project) {
717    let total_links: usize = project.findings.iter().map(|b| b.links.len()).sum();
718
719    let mut link_types: HashMap<String, usize> = HashMap::new();
720    for b in &project.findings {
721        for l in &b.links {
722            *link_types.entry(l.link_type.clone()).or_default() += 1;
723        }
724    }
725
726    let mut categories: HashMap<String, usize> = HashMap::new();
727    for b in &project.findings {
728        *categories
729            .entry(b.assertion.assertion_type.clone())
730            .or_default() += 1;
731    }
732
733    // Count findings with a successful replication, read from the
734    // scalar `evidence.replicated` field.
735    let replicated = project
736        .findings
737        .iter()
738        .filter(|b| b.evidence.replicated)
739        .count();
740    let avg_confidence = if project.findings.is_empty() {
741        0.0
742    } else {
743        (project
744            .findings
745            .iter()
746            .map(|b| b.confidence.score)
747            .sum::<f64>()
748            / project.findings.len() as f64
749            * 1000.0)
750            .round()
751            / 1000.0
752    };
753
754    project.stats.findings = project.findings.len();
755    project.stats.links = total_links;
756    project.stats.replicated = replicated;
757    project.stats.unreplicated = project.findings.len().saturating_sub(replicated);
758    project.stats.avg_confidence = avg_confidence;
759    project.stats.gaps = project.findings.iter().filter(|b| b.flags.gap).count();
760    project.stats.negative_space = project
761        .findings
762        .iter()
763        .filter(|b| b.flags.negative_space)
764        .count();
765    project.stats.contested = project
766        .findings
767        .iter()
768        .filter(|b| b.flags.contested)
769        .count();
770    project.stats.categories = categories;
771    project.stats.link_types = link_types;
772    // Provenance honesty: a finding is human-reviewed only if a
773    // human-classified actor reviewed it. Agent/bot review is counted
774    // separately so `human_reviewed` never overstates human review
775    // (an `agent:`/`-bot` reviewer used to inflate this count).
776    let finding_ids: HashSet<&str> = project.findings.iter().map(|b| b.id.as_str()).collect();
777    let mut human_reviewed_ids: HashSet<String> = HashSet::new();
778    let mut agent_reviewed_ids: HashSet<String> = HashSet::new();
779    for b in &project.findings {
780        if let Some(r) = b.provenance.review.as_ref().filter(|r| r.reviewed) {
781            let kind = r
782                .reviewer
783                .as_deref()
784                .map(crate::events::actor_kind)
785                .unwrap_or("human");
786            if kind == "human" {
787                human_reviewed_ids.insert(b.id.clone());
788            } else {
789                agent_reviewed_ids.insert(b.id.clone());
790            }
791        }
792    }
793    for event in project.events.iter().filter(|event| {
794        matches!(
795            event.kind.as_str(),
796            "finding.reviewed"
797                | "finding.noted"
798                | "finding.caveated"
799                | "finding.confidence_revised"
800                | "finding.rejected"
801                | "finding.retracted"
802        ) && finding_ids.contains(event.target.id.as_str())
803    }) {
804        if crate::events::actor_kind(&event.actor.id) == "human" {
805            human_reviewed_ids.insert(event.target.id.clone());
806        } else {
807            agent_reviewed_ids.insert(event.target.id.clone());
808        }
809    }
810    // Disjoint: a finding with any human review is human-reviewed; one
811    // touched only by agents is agent-reviewed.
812    let agent_only = agent_reviewed_ids.difference(&human_reviewed_ids).count();
813    project.stats.human_reviewed = human_reviewed_ids.len();
814    project.stats.agent_reviewed = agent_only;
815    let canonical_review_events = project
816        .events
817        .iter()
818        .filter(|event| {
819            matches!(
820                event.kind.as_str(),
821                "finding.reviewed"
822                    | "finding.noted"
823                    | "finding.caveated"
824                    | "finding.rejected"
825                    | "finding.retracted"
826                    | "finding.asserted"
827                    | "source_text.reviewed"
828            )
829        })
830        .count();
831    project.stats.review_event_count = canonical_review_events + project.review_events.len();
832    project.stats.confidence_update_count = project
833        .events
834        .iter()
835        .filter(|event| event.kind == "finding.confidence_revised")
836        .count()
837        + project.confidence_updates.len();
838    project.stats.event_count = project.events.len();
839    project.stats.source_count = project.sources.len();
840    project.stats.evidence_atom_count = project.evidence_atoms.len();
841    project.stats.condition_record_count = project.condition_records.len();
842    project.stats.proposal_count = project.proposals.len();
843    project.stats.confidence_distribution = ConfidenceDistribution {
844        high_gt_80: project
845            .findings
846            .iter()
847            .filter(|b| b.confidence.score > 0.8)
848            .count(),
849        medium_60_80: project
850            .findings
851            .iter()
852            .filter(|b| (0.6..=0.8).contains(&b.confidence.score))
853            .count(),
854        low_lt_60: project
855            .findings
856            .iter()
857            .filter(|b| b.confidence.score < 0.6)
858            .count(),
859    };
860}
861
862#[cfg(test)]
863mod tests {
864    use super::*;
865    use crate::bundle::*;
866
867    fn make_finding(
868        id: &str,
869        score: f64,
870        assertion_type: &str,
871        replicated: bool,
872        gap: bool,
873    ) -> FindingBundle {
874        FindingBundle {
875            id: id.into(),
876            version: 1,
877            previous_version: None,
878            assertion: Assertion {
879                text: format!("Finding {id}"),
880                assertion_type: assertion_type.into(),
881                entities: vec![],
882                relation: None,
883                direction: None,
884                causal_claim: None,
885                causal_evidence_grade: None,
886            },
887            evidence: Evidence {
888                evidence_type: "experimental".into(),
889                model_system: String::new(),
890                method: String::new(),
891                replicated,
892                replication_count: None,
893                evidence_spans: vec![],
894            },
895            conditions: Conditions {
896                text: String::new(),
897                duration: None,
898            },
899            confidence: Confidence::raw(score, "seeded prior", 0.85),
900            provenance: Provenance {
901                source_type: "published_paper".into(),
902                doi: None,
903                url: None,
904                title: "Test".into(),
905                authors: vec![],
906                year: Some(2024),
907                license: None,
908                publisher: None,
909                funders: vec![],
910                extraction: Extraction::default(),
911                review: None,
912                contributions: Vec::new(),
913            },
914            flags: Flags {
915                gap,
916                negative_space: false,
917                contested: false,
918                retracted: false,
919                declining: false,
920                gravity_well: false,
921                review_state: None,
922                superseded: false,
923                signature_threshold: None,
924                jointly_accepted: false,
925            },
926            links: vec![],
927            annotations: vec![],
928            attachments: vec![],
929            created: String::new(),
930            updated: None,
931
932            access_tier: crate::access_tier::AccessTier::Public,
933        }
934    }
935
936    #[test]
937    fn empty_frontier() {
938        let c = assemble("test", vec![], 0, 0, "empty");
939        assert_eq!(c.stats.findings, 0);
940        assert_eq!(c.stats.links, 0);
941        assert_eq!(c.stats.avg_confidence, 0.0);
942        assert_eq!(c.stats.replicated, 0);
943        assert_eq!(c.stats.unreplicated, 0);
944        assert_eq!(c.project.name, "test");
945        assert_eq!(c.project.description, "empty");
946    }
947
948    #[test]
949    fn findings_count() {
950        let bundles = vec![
951            make_finding("f1", 0.8, "mechanism", false, false),
952            make_finding("f2", 0.6, "therapeutic", true, false),
953            make_finding("f3", 0.9, "mechanism", false, true),
954        ];
955        let c = assemble("test", bundles, 5, 1, "desc");
956        assert_eq!(c.stats.findings, 3);
957        assert_eq!(c.project.papers_processed, 5);
958        assert_eq!(c.project.errors, 1);
959    }
960
961    #[test]
962    fn replicated_unreplicated_counts() {
963        let bundles = vec![
964            make_finding("f1", 0.8, "mechanism", true, false),
965            make_finding("f2", 0.6, "mechanism", true, false),
966            make_finding("f3", 0.9, "mechanism", false, false),
967        ];
968        let c = assemble("test", bundles, 3, 0, "desc");
969        assert_eq!(c.stats.replicated, 2);
970        assert_eq!(c.stats.unreplicated, 1);
971    }
972
973    #[test]
974    fn category_counts() {
975        let bundles = vec![
976            make_finding("f1", 0.8, "mechanism", false, false),
977            make_finding("f2", 0.6, "mechanism", false, false),
978            make_finding("f3", 0.9, "therapeutic", false, false),
979        ];
980        let c = assemble("test", bundles, 3, 0, "desc");
981        assert_eq!(*c.stats.categories.get("mechanism").unwrap(), 2);
982        assert_eq!(*c.stats.categories.get("therapeutic").unwrap(), 1);
983    }
984
985    #[test]
986    fn link_counting() {
987        let mut f1 = make_finding("f1", 0.8, "mechanism", false, false);
988        f1.add_link("f2", "extends", "shared entity");
989        f1.add_link("f3", "contradicts", "opposite direction");
990        let f2 = make_finding("f2", 0.7, "mechanism", false, false);
991        let c = assemble("test", vec![f1, f2], 2, 0, "desc");
992        assert_eq!(c.stats.links, 2);
993        assert_eq!(*c.stats.link_types.get("extends").unwrap(), 1);
994        assert_eq!(*c.stats.link_types.get("contradicts").unwrap(), 1);
995    }
996
997    #[test]
998    fn avg_confidence() {
999        let bundles = vec![
1000            make_finding("f1", 0.8, "mechanism", false, false),
1001            make_finding("f2", 0.6, "mechanism", false, false),
1002        ];
1003        let c = assemble("test", bundles, 2, 0, "desc");
1004        assert!((c.stats.avg_confidence - 0.7).abs() < 0.01);
1005    }
1006
1007    #[test]
1008    fn confidence_distribution_buckets() {
1009        let bundles = vec![
1010            make_finding("f1", 0.9, "mechanism", false, false), // high
1011            make_finding("f2", 0.85, "mechanism", false, false), // high
1012            make_finding("f3", 0.7, "mechanism", false, false), // medium
1013            make_finding("f4", 0.6, "mechanism", false, false), // medium (0.6 is in 0.6..=0.8)
1014            make_finding("f5", 0.4, "mechanism", false, false), // low
1015        ];
1016        let c = assemble("test", bundles, 5, 0, "desc");
1017        assert_eq!(c.stats.confidence_distribution.high_gt_80, 2);
1018        assert_eq!(c.stats.confidence_distribution.medium_60_80, 2);
1019        assert_eq!(c.stats.confidence_distribution.low_lt_60, 1);
1020    }
1021
1022    #[test]
1023    fn gaps_counted() {
1024        let bundles = vec![
1025            make_finding("f1", 0.8, "mechanism", false, true),
1026            make_finding("f2", 0.6, "mechanism", false, false),
1027            make_finding("f3", 0.9, "mechanism", false, true),
1028        ];
1029        let c = assemble("test", bundles, 3, 0, "desc");
1030        assert_eq!(c.stats.gaps, 2);
1031    }
1032
1033    #[test]
1034    fn metadata_preserved() {
1035        let c = assemble("my frontier", vec![], 10, 2, "A description");
1036        assert_eq!(c.project.name, "my frontier");
1037        assert_eq!(c.project.description, "A description");
1038        assert_eq!(c.project.papers_processed, 10);
1039        assert_eq!(c.project.errors, 2);
1040        assert_eq!(c.vela_version, VELA_SCHEMA_VERSION);
1041        assert!(!c.project.compiled_at.is_empty());
1042    }
1043}
1044
1045/// An active (or expired — expiry is a read-time computation) lease on
1046/// an open obligation. One live lease per obligation; the reducer
1047/// rejects a second claim while a prior one is unexpired.
1048#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1049pub struct AttemptClaim {
1050    pub obligation_id: String,
1051    pub claimant_actor: String,
1052    pub claimant_pubkey: String,
1053    pub claimed_at: String,
1054    pub lease_ttl_seconds: u64,
1055    /// The exact signed `attempt.claimed` event that established this
1056    /// derived lease.  Older serialized projections did not retain the event
1057    /// identity, so they continue to deserialize with `None`; replay of the
1058    /// canonical event log fills it mechanically.  Refresh and zero-TTL
1059    /// release updates use this as their compare-and-swap predecessor.
1060    #[serde(default, skip_serializing_if = "Option::is_none")]
1061    pub claim_event_id: Option<String>,
1062}
1063
1064/// A registered statement hash: the priority timestamp primitive.
1065#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1066pub struct StatementRegistration {
1067    pub statement_hash: String,
1068    pub informal_ref: String,
1069    pub registered_by: String,
1070    pub registered_at: String,
1071    /// The canonical finding-to-registration edge (STATE_PLANE_MEMO
1072    /// appendix gap 5): the `vf_` id this registration timestamps, when
1073    /// the registrant declared one. Carried as an optional payload
1074    /// field on the existing `statement.registered` kind — old events
1075    /// (and old serialized state) parse unchanged via the serde
1076    /// default; `None` serializes to nothing, so pre-edge state stays
1077    /// byte-identical.
1078    #[serde(default, skip_serializing_if = "Option::is_none")]
1079    pub finding_id: Option<String>,
1080}