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
340/// Construct the closed structural genesis used only by Repository Profile v1.
341///
342/// Keeping this separate from [`assemble`] is intentional. The generic
343/// constructor is also used by historical importers and legacy fixtures; if it
344/// emitted this payload, a v0.1 repository could appear to have native v1
345/// identity and incorrectly bypass the signed legacy migration boundary.
346fn build_profile_v1_genesis_event(
347    name: &str,
348    compiled_at: &str,
349    creator: &str,
350) -> crate::events::StateEvent {
351    use crate::events::{
352        EVENT_SCHEMA, FRONTIER_CREATED_SCHEMA_V1, NULL_HASH, StateActor, StateEvent, StateTarget,
353    };
354    let dependency_root = crate::frontier_repository::exact_dependency_root(&[])
355        .expect("the canonical empty dependency list is always valid");
356    let mut event = StateEvent {
357        schema: EVENT_SCHEMA.to_string(),
358        id: String::new(),
359        kind: "frontier.created".into(),
360        target: StateTarget {
361            r#type: "frontier".to_string(),
362            id: name.to_string(),
363        },
364        actor: StateActor {
365            id: creator.to_string(),
366            r#type: "frontier".to_string(),
367        },
368        timestamp: compiled_at.to_string(),
369        reason: "frontier compiled".to_string(),
370        before_hash: NULL_HASH.to_string(),
371        after_hash: NULL_HASH.to_string(),
372        payload: serde_json::json!({
373            "schema": FRONTIER_CREATED_SCHEMA_V1,
374            "name_at_creation": name,
375            "creator": creator,
376            "profile_schema": "vela.frontier-profile.v1",
377            "dependency_root": dependency_root,
378            "created_at": compiled_at,
379        }),
380        caveats: vec![],
381        signature: None,
382    };
383    event.id = crate::events::compute_event_id(&event);
384    event
385}
386
387pub fn assemble(
388    name: &str,
389    bundles: Vec<FindingBundle>,
390    papers_processed: usize,
391    errors: usize,
392    description: &str,
393) -> Project {
394    let compiled_at = Utc::now().to_rfc3339();
395    let genesis = build_genesis_event(name, &compiled_at, VELA_COMPILER_VERSION);
396    assemble_with_genesis(
397        name,
398        bundles,
399        papers_processed,
400        errors,
401        description,
402        compiled_at,
403        genesis,
404    )
405}
406
407/// Assemble a new Repository Profile v1 project with its closed structural
408/// genesis. This is deliberately narrower than [`assemble`]; callers creating
409/// historical fixtures or importing old packet formats must use the legacy
410/// constructor so migration remains representative and fail-closed.
411pub fn assemble_profile_v1(
412    name: &str,
413    bundles: Vec<FindingBundle>,
414    papers_processed: usize,
415    errors: usize,
416    description: &str,
417) -> Project {
418    let compiled_at = Utc::now().to_rfc3339();
419    let genesis = build_profile_v1_genesis_event(name, &compiled_at, VELA_COMPILER_VERSION);
420    assemble_with_genesis(
421        name,
422        bundles,
423        papers_processed,
424        errors,
425        description,
426        compiled_at,
427        genesis,
428    )
429}
430
431fn assemble_with_genesis(
432    name: &str,
433    bundles: Vec<FindingBundle>,
434    papers_processed: usize,
435    errors: usize,
436    description: &str,
437    compiled_at: String,
438    genesis: crate::events::StateEvent,
439) -> Project {
440    let meta = ProjectMeta {
441        name: name.to_string(),
442        description: description.to_string(),
443        compiled_at: compiled_at.clone(),
444        compiler: VELA_COMPILER_VERSION.to_string(),
445        papers_processed,
446        errors,
447        dependencies: Vec::new(),
448    };
449    // Phase J (v0.4): emit a `frontier.created` canonical event as
450    // events[0] and derive frontier_id from its canonical hash. The
451    // address primitive becomes doctrine-grounded — a frontier IS what
452    // the genesis event creates, not a convenience over its metadata.
453    let frontier_id = frontier_id_from_genesis(std::slice::from_ref(&genesis));
454    let mut project = Project {
455        vela_version: VELA_SCHEMA_VERSION.to_string(),
456        schema: VELA_SCHEMA_URL.to_string(),
457        frontier_id,
458        project: meta,
459        stats: ProjectStats::default(),
460        findings: bundles,
461        sources: Vec::new(),
462        evidence_atoms: Vec::new(),
463        condition_records: Vec::new(),
464        review_events: Vec::new(),
465        confidence_updates: Vec::new(),
466        events: vec![genesis],
467        proposals: Vec::new(),
468        proof_state: ProofState::default(),
469        signatures: Vec::new(),
470        actors: Vec::new(),
471        artifacts: Vec::new(),
472        released_diff_packs: Vec::new(),
473        verdict_conflicts: Vec::new(),
474        contradictions: Vec::new(),
475        verifier_attachments: Vec::new(),
476        attempts: Vec::new(),
477        attempt_resolutions: Vec::new(),
478        transfers: Vec::new(),
479        endorsements: Vec::new(),
480        statement_attestations: Vec::new(),
481        anchor_links: Vec::new(),
482        attempt_claims: Vec::new(),
483        statement_registrations: Vec::new(),
484    };
485    crate::sources::materialize_project(&mut project);
486    project
487}
488
489impl Project {
490    /// The head (latest by `at`) lifecycle resolution for an attempt, or
491    /// `None` if the attempt is still an unresolved candidate. Computed on
492    /// read from the append-only `attempt_resolutions`, never stored.
493    #[must_use]
494    pub fn head_resolution(&self, attempt_id: &str) -> Option<&crate::attempt::ResolutionEvent> {
495        self.attempt_resolutions
496            .iter()
497            .filter(|r| r.attempt_id == attempt_id)
498            .max_by(|a, b| a.at.cmp(&b.at))
499    }
500
501    /// Return the stable Vela-addressable frontier ID. Prefers the stored
502    /// field; if absent, derives from the `frontier.created` genesis
503    /// event in `events[0]`; if no genesis event is present, falls back
504    /// to meta-derivation (legacy v0.3 frontiers).
505    #[must_use]
506    pub fn frontier_id(&self) -> String {
507        if let Some(id) = self.frontier_id.clone() {
508            return id;
509        }
510        if let Some(id) = frontier_id_from_genesis(&self.events) {
511            return id;
512        }
513        derive_frontier_id_from_meta(&self.project)
514    }
515
516    /// v0.8: iterate the cross-frontier dependencies (those with
517    /// `vfr_id` set). Pre-v0.8 compile-time deps without `vfr_id`
518    /// are filtered out.
519    pub fn cross_frontier_deps(&self) -> impl Iterator<Item = &ProjectDependency> {
520        self.project
521            .dependencies
522            .iter()
523            .filter(|d| d.is_cross_frontier())
524    }
525
526    /// v0.8: look up the dependency record for a specific `vfr_id`.
527    /// Returns `None` if no matching cross-frontier dep is declared.
528    pub fn dep_for_vfr(&self, vfr_id: &str) -> Option<&ProjectDependency> {
529        self.cross_frontier_deps()
530            .find(|d| d.vfr_id.as_deref() == Some(vfr_id))
531    }
532
533    /// v0.49.3: build a reverse-dependency index from the forward
534    /// `links: Vec<Link>` data on each finding. The forward direction
535    /// (which findings does this finding depend on?) is O(1) per
536    /// finding because it's just `f.links`. The reverse direction
537    /// (which findings depend on this finding?) previously required
538    /// scanning every finding for every query — O(N×L). This index
539    /// flips that to O(1) lookup once built.
540    ///
541    /// Cost to build: O(N×L) one-time scan over all findings × links.
542    /// At 48 findings × ~3 links each (the legacy BBB proof fixture),
543    /// that's ~150 hash-insert operations and microseconds. At
544    /// 100K findings × 10 links, it's still well under a second.
545    ///
546    /// Used by retraction-impact queries (serve.rs), cascade
547    /// computation, and any consumer that needs to walk the dependent
548    /// graph rather than the dependency graph. The index is not
549    /// serialized — it's a derived structure that callers build when
550    /// they need it and drop when they don't.
551    #[must_use]
552    pub fn build_reverse_dep_index(&self) -> ReverseDepIndex {
553        let mut map: std::collections::HashMap<String, Vec<String>> =
554            std::collections::HashMap::with_capacity(self.findings.len());
555        for f in &self.findings {
556            for link in &f.links {
557                map.entry(link.target.clone())
558                    .or_default()
559                    .push(f.id.clone());
560            }
561        }
562        // Stable sort each dependent list so two implementations of the
563        // index agree on ordering for any downstream serialization.
564        for v in map.values_mut() {
565            v.sort();
566            v.dedup();
567        }
568        ReverseDepIndex { map }
569    }
570}
571
572/// v0.49.3: reverse-dependency index built from a Project's forward
573/// `links` graph. Maps `finding_id → [dependent_finding_id, …]` so a
574/// "what depends on X?" lookup is O(1) instead of O(N×L).
575///
576/// Construct via `Project::build_reverse_dep_index`. The index is a
577/// snapshot — it does not auto-update if the Project mutates after.
578/// For long-lived consumers that mutate state, rebuild after each
579/// reduce step.
580#[derive(Debug, Clone, Default)]
581pub struct ReverseDepIndex {
582    map: std::collections::HashMap<String, Vec<String>>,
583}
584
585impl ReverseDepIndex {
586    /// Findings whose forward `links` list a target with this id.
587    /// Empty slice if nothing depends on this finding (or if the id
588    /// isn't in the index at all).
589    #[must_use]
590    pub fn dependents_of(&self, finding_id: &str) -> &[String] {
591        self.map
592            .get(finding_id)
593            .map(|v| v.as_slice())
594            .unwrap_or(&[])
595    }
596
597    /// Total number of dependent edges in the index. Useful for
598    /// quick sanity checks and metric reporting.
599    #[must_use]
600    pub fn edge_count(&self) -> usize {
601        self.map.values().map(Vec::len).sum()
602    }
603
604    /// Number of distinct findings that have at least one dependent.
605    #[must_use]
606    pub fn target_count(&self) -> usize {
607        self.map.len()
608    }
609
610    /// Iterate `(target_finding_id, dependents)` pairs. Order is
611    /// HashMap-iteration-order, not stable across runs; sort if a
612    /// consumer needs determinism.
613    pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<String>)> {
614        self.map.iter()
615    }
616}
617
618#[cfg(test)]
619mod cross_frontier_dep_tests {
620    use super::*;
621
622    fn dep_local(name: &str) -> ProjectDependency {
623        ProjectDependency {
624            name: name.into(),
625            source: "local".into(),
626            version: None,
627            pinned_hash: None,
628            vfr_id: None,
629            locator: None,
630            pinned_snapshot_hash: None,
631        }
632    }
633
634    fn dep_cross(vfr: &str) -> ProjectDependency {
635        ProjectDependency {
636            name: "ext".into(),
637            source: "vela.hub".into(),
638            version: None,
639            pinned_hash: None,
640            vfr_id: Some(vfr.into()),
641            locator: Some(format!("https://example.test/{vfr}.json")),
642            pinned_snapshot_hash: Some("a".repeat(64)),
643        }
644    }
645
646    #[test]
647    fn is_cross_frontier_only_when_vfr_id_set() {
648        assert!(!dep_local("x").is_cross_frontier());
649        assert!(dep_cross("vfr_abc").is_cross_frontier());
650    }
651
652    #[test]
653    fn dep_serializes_byte_identical_when_v0_8_fields_absent() {
654        // Backward compat: a pre-v0.8 dep round-trips through serde
655        // without emitting any of the new optional v0.8 fields.
656        let d = dep_local("legacy");
657        let s = serde_json::to_string(&d).unwrap();
658        assert!(!s.contains("vfr_id"));
659        assert!(!s.contains("locator"));
660        assert!(!s.contains("pinned_snapshot_hash"));
661    }
662}
663
664#[cfg(test)]
665pub(crate) mod reverse_dep_index_tests {
666    use super::*;
667    use crate::bundle::{
668        Assertion, Author, Conditions, Confidence, ConfidenceKind, ConfidenceMethod, Evidence,
669        Extraction, FindingBundle, Flags, Link, Provenance,
670    };
671
672    pub(crate) fn synth_finding(idx: usize, links: Vec<Link>) -> FindingBundle {
673        let assertion = Assertion {
674            text: format!("Synthetic finding {idx}"),
675            assertion_type: "mechanism".into(),
676            entities: vec![],
677            relation: None,
678            direction: None,
679            causal_claim: None,
680            causal_evidence_grade: None,
681        };
682        let evidence = Evidence {
683            evidence_type: "experimental".into(),
684            model_system: "test".into(),
685            method: "test".into(),
686            replicated: false,
687            replication_count: None,
688            evidence_spans: vec![],
689        };
690        let conditions = Conditions {
691            text: "test".into(),
692            duration: None,
693        };
694        let confidence = Confidence {
695            kind: ConfidenceKind::FrontierEpistemic,
696            score: 0.5,
697            basis: "test".into(),
698            method: ConfidenceMethod::LlmInitial,
699            extraction_confidence: 0.9,
700        };
701        let provenance = Provenance {
702            source_type: "published_paper".into(),
703            doi: Some(format!("10.0000/reverse-dep-index-test.{idx:04}")),
704            url: None,
705            title: format!("Synthetic test paper {idx}"),
706            authors: vec![Author {
707                name: "T".into(),
708                orcid: None,
709            }],
710            year: None,
711            license: None,
712            publisher: None,
713            funders: vec![],
714            extraction: Extraction::default(),
715            review: None,
716            contributions: Vec::new(),
717        };
718        let flags = Flags::default();
719        let mut bundle = FindingBundle::new(
720            assertion, evidence, conditions, confidence, provenance, flags,
721        );
722        bundle.links = links;
723        bundle
724    }
725
726    pub(crate) fn link_to(target: &str) -> Link {
727        Link {
728            target: target.into(),
729            link_type: "supports".into(),
730            note: "test".into(),
731            inferred_by: "test".into(),
732            created_at: "2026-05-02T00:00:00Z".into(),
733            mechanism: None,
734        }
735    }
736
737    /// Build a chain: 0 → 1 → 2 → 3 (each finding supports the next).
738    /// Then dependents_of(2) should return [1], dependents_of(1) → [0],
739    /// dependents_of(3) → [2], dependents_of(0) → [] (root, nothing
740    /// depends on it).
741    #[test]
742    fn dependents_of_returns_correct_set_for_simple_chain() {
743        let f3 = synth_finding(3, vec![]);
744        let f2 = synth_finding(2, vec![link_to(&f3.id)]);
745        let f1 = synth_finding(1, vec![link_to(&f2.id)]);
746        let f0 = synth_finding(0, vec![link_to(&f1.id)]);
747
748        let mut project = assemble("chain", vec![], 0, 0, "test");
749        project.findings = vec![f0.clone(), f1.clone(), f2.clone(), f3.clone()];
750
751        let idx = project.build_reverse_dep_index();
752        assert_eq!(idx.dependents_of(&f3.id), &[f2.id.clone()]);
753        assert_eq!(idx.dependents_of(&f2.id), &[f1.id.clone()]);
754        assert_eq!(idx.dependents_of(&f1.id), &[f0.id.clone()]);
755        assert!(idx.dependents_of(&f0.id).is_empty());
756        // Edge count = 3 (one per non-root link).
757        assert_eq!(idx.edge_count(), 3);
758        // Target count = 3 (f1, f2, f3 each have a dependent).
759        assert_eq!(idx.target_count(), 3);
760    }
761
762    /// Multiple findings depending on the same target should produce a
763    /// sorted, deduped dependent list.
764    #[test]
765    fn dependents_of_dedups_and_sorts() {
766        let target = synth_finding(99, vec![]);
767        let target_id = target.id.clone();
768        // f1, f2, f3 all link to target. Plus f1 has TWO links to
769        // target (to test dedup).
770        let f1 = synth_finding(1, vec![link_to(&target_id), link_to(&target_id)]);
771        let f2 = synth_finding(2, vec![link_to(&target_id)]);
772        let f3 = synth_finding(3, vec![link_to(&target_id)]);
773
774        let mut project = assemble("multi-dependents", vec![], 0, 0, "test");
775        project.findings = vec![target, f1.clone(), f2.clone(), f3.clone()];
776
777        let idx = project.build_reverse_dep_index();
778        let mut expected = vec![f1.id.clone(), f2.id.clone(), f3.id.clone()];
779        expected.sort();
780        assert_eq!(idx.dependents_of(&target_id), expected.as_slice());
781    }
782
783    /// A finding id with no dependents — and an id that doesn't exist
784    /// in the project at all — both return an empty slice.
785    #[test]
786    fn dependents_of_unknown_or_orphan_returns_empty() {
787        let lonely = synth_finding(7, vec![]);
788        let mut project = assemble("orphan", vec![], 0, 0, "test");
789        project.findings = vec![lonely.clone()];
790
791        let idx = project.build_reverse_dep_index();
792        assert!(idx.dependents_of(&lonely.id).is_empty());
793        assert!(idx.dependents_of("vf_does_not_exist").is_empty());
794    }
795
796    /// Empty project → empty index.
797    #[test]
798    fn empty_project_yields_empty_index() {
799        let project = assemble("empty", vec![], 0, 0, "test");
800        let idx = project.build_reverse_dep_index();
801        assert_eq!(idx.edge_count(), 0);
802        assert_eq!(idx.target_count(), 0);
803    }
804}
805
806/// Recompute derived frontier statistics after mechanical edits.
807pub fn recompute_stats(project: &mut Project) {
808    let total_links: usize = project.findings.iter().map(|b| b.links.len()).sum();
809
810    let mut link_types: HashMap<String, usize> = HashMap::new();
811    for b in &project.findings {
812        for l in &b.links {
813            *link_types.entry(l.link_type.clone()).or_default() += 1;
814        }
815    }
816
817    let mut categories: HashMap<String, usize> = HashMap::new();
818    for b in &project.findings {
819        *categories
820            .entry(b.assertion.assertion_type.clone())
821            .or_default() += 1;
822    }
823
824    // Count findings with a successful replication, read from the
825    // scalar `evidence.replicated` field.
826    let replicated = project
827        .findings
828        .iter()
829        .filter(|b| b.evidence.replicated)
830        .count();
831    let avg_confidence = if project.findings.is_empty() {
832        0.0
833    } else {
834        (project
835            .findings
836            .iter()
837            .map(|b| b.confidence.score)
838            .sum::<f64>()
839            / project.findings.len() as f64
840            * 1000.0)
841            .round()
842            / 1000.0
843    };
844
845    project.stats.findings = project.findings.len();
846    project.stats.links = total_links;
847    project.stats.replicated = replicated;
848    project.stats.unreplicated = project.findings.len().saturating_sub(replicated);
849    project.stats.avg_confidence = avg_confidence;
850    project.stats.gaps = project.findings.iter().filter(|b| b.flags.gap).count();
851    project.stats.negative_space = project
852        .findings
853        .iter()
854        .filter(|b| b.flags.negative_space)
855        .count();
856    project.stats.contested = project
857        .findings
858        .iter()
859        .filter(|b| b.flags.contested)
860        .count();
861    project.stats.categories = categories;
862    project.stats.link_types = link_types;
863    // Provenance honesty: a finding is human-reviewed only if a
864    // human-classified actor reviewed it. Agent/bot review is counted
865    // separately so `human_reviewed` never overstates human review
866    // (an `agent:`/`-bot` reviewer used to inflate this count).
867    let finding_ids: HashSet<&str> = project.findings.iter().map(|b| b.id.as_str()).collect();
868    let mut human_reviewed_ids: HashSet<String> = HashSet::new();
869    let mut agent_reviewed_ids: HashSet<String> = HashSet::new();
870    for b in &project.findings {
871        if let Some(r) = b.provenance.review.as_ref().filter(|r| r.reviewed) {
872            let kind = r
873                .reviewer
874                .as_deref()
875                .map(crate::events::actor_kind)
876                .unwrap_or("human");
877            if kind == "human" {
878                human_reviewed_ids.insert(b.id.clone());
879            } else {
880                agent_reviewed_ids.insert(b.id.clone());
881            }
882        }
883    }
884    for event in project.events.iter().filter(|event| {
885        matches!(
886            event.kind.as_str(),
887            "finding.reviewed"
888                | "finding.noted"
889                | "finding.caveated"
890                | "finding.confidence_revised"
891                | "finding.rejected"
892                | "finding.retracted"
893        ) && finding_ids.contains(event.target.id.as_str())
894    }) {
895        if crate::events::actor_kind(&event.actor.id) == "human" {
896            human_reviewed_ids.insert(event.target.id.clone());
897        } else {
898            agent_reviewed_ids.insert(event.target.id.clone());
899        }
900    }
901    // Disjoint: a finding with any human review is human-reviewed; one
902    // touched only by agents is agent-reviewed.
903    let agent_only = agent_reviewed_ids.difference(&human_reviewed_ids).count();
904    project.stats.human_reviewed = human_reviewed_ids.len();
905    project.stats.agent_reviewed = agent_only;
906    let canonical_review_events = project
907        .events
908        .iter()
909        .filter(|event| {
910            matches!(
911                event.kind.as_str(),
912                "finding.reviewed"
913                    | "finding.noted"
914                    | "finding.caveated"
915                    | "finding.rejected"
916                    | "finding.retracted"
917                    | "finding.asserted"
918                    | "source_text.reviewed"
919            )
920        })
921        .count();
922    project.stats.review_event_count = canonical_review_events + project.review_events.len();
923    project.stats.confidence_update_count = project
924        .events
925        .iter()
926        .filter(|event| event.kind == "finding.confidence_revised")
927        .count()
928        + project.confidence_updates.len();
929    project.stats.event_count = project.events.len();
930    project.stats.source_count = project.sources.len();
931    project.stats.evidence_atom_count = project.evidence_atoms.len();
932    project.stats.condition_record_count = project.condition_records.len();
933    project.stats.proposal_count = project.proposals.len();
934    project.stats.confidence_distribution = ConfidenceDistribution {
935        high_gt_80: project
936            .findings
937            .iter()
938            .filter(|b| b.confidence.score > 0.8)
939            .count(),
940        medium_60_80: project
941            .findings
942            .iter()
943            .filter(|b| (0.6..=0.8).contains(&b.confidence.score))
944            .count(),
945        low_lt_60: project
946            .findings
947            .iter()
948            .filter(|b| b.confidence.score < 0.6)
949            .count(),
950    };
951}
952
953#[cfg(test)]
954mod tests {
955    use super::*;
956    use crate::bundle::*;
957
958    fn make_finding(
959        id: &str,
960        score: f64,
961        assertion_type: &str,
962        replicated: bool,
963        gap: bool,
964    ) -> FindingBundle {
965        FindingBundle {
966            id: id.into(),
967            version: 1,
968            previous_version: None,
969            assertion: Assertion {
970                text: format!("Finding {id}"),
971                assertion_type: assertion_type.into(),
972                entities: vec![],
973                relation: None,
974                direction: None,
975                causal_claim: None,
976                causal_evidence_grade: None,
977            },
978            evidence: Evidence {
979                evidence_type: "experimental".into(),
980                model_system: String::new(),
981                method: String::new(),
982                replicated,
983                replication_count: None,
984                evidence_spans: vec![],
985            },
986            conditions: Conditions {
987                text: String::new(),
988                duration: None,
989            },
990            confidence: Confidence::raw(score, "seeded prior", 0.85),
991            provenance: Provenance {
992                source_type: "published_paper".into(),
993                doi: None,
994                url: None,
995                title: "Test".into(),
996                authors: vec![],
997                year: Some(2024),
998                license: None,
999                publisher: None,
1000                funders: vec![],
1001                extraction: Extraction::default(),
1002                review: None,
1003                contributions: Vec::new(),
1004            },
1005            flags: Flags {
1006                gap,
1007                negative_space: false,
1008                contested: false,
1009                retracted: false,
1010                declining: false,
1011                gravity_well: false,
1012                review_state: None,
1013                superseded: false,
1014                signature_threshold: None,
1015                jointly_accepted: false,
1016            },
1017            links: vec![],
1018            annotations: vec![],
1019            attachments: vec![],
1020            created: String::new(),
1021            updated: None,
1022
1023            access_tier: crate::access_tier::AccessTier::Public,
1024        }
1025    }
1026
1027    #[test]
1028    fn empty_frontier() {
1029        let c = assemble("test", vec![], 0, 0, "empty");
1030        assert_eq!(c.stats.findings, 0);
1031        assert_eq!(c.stats.links, 0);
1032        assert_eq!(c.stats.avg_confidence, 0.0);
1033        assert_eq!(c.stats.replicated, 0);
1034        assert_eq!(c.stats.unreplicated, 0);
1035        assert_eq!(c.project.name, "test");
1036        assert_eq!(c.project.description, "empty");
1037    }
1038
1039    #[test]
1040    fn findings_count() {
1041        let bundles = vec![
1042            make_finding("f1", 0.8, "mechanism", false, false),
1043            make_finding("f2", 0.6, "therapeutic", true, false),
1044            make_finding("f3", 0.9, "mechanism", false, true),
1045        ];
1046        let c = assemble("test", bundles, 5, 1, "desc");
1047        assert_eq!(c.stats.findings, 3);
1048        assert_eq!(c.project.papers_processed, 5);
1049        assert_eq!(c.project.errors, 1);
1050    }
1051
1052    #[test]
1053    fn replicated_unreplicated_counts() {
1054        let bundles = vec![
1055            make_finding("f1", 0.8, "mechanism", true, false),
1056            make_finding("f2", 0.6, "mechanism", true, false),
1057            make_finding("f3", 0.9, "mechanism", false, false),
1058        ];
1059        let c = assemble("test", bundles, 3, 0, "desc");
1060        assert_eq!(c.stats.replicated, 2);
1061        assert_eq!(c.stats.unreplicated, 1);
1062    }
1063
1064    #[test]
1065    fn category_counts() {
1066        let bundles = vec![
1067            make_finding("f1", 0.8, "mechanism", false, false),
1068            make_finding("f2", 0.6, "mechanism", false, false),
1069            make_finding("f3", 0.9, "therapeutic", false, false),
1070        ];
1071        let c = assemble("test", bundles, 3, 0, "desc");
1072        assert_eq!(*c.stats.categories.get("mechanism").unwrap(), 2);
1073        assert_eq!(*c.stats.categories.get("therapeutic").unwrap(), 1);
1074    }
1075
1076    #[test]
1077    fn link_counting() {
1078        let mut f1 = make_finding("f1", 0.8, "mechanism", false, false);
1079        f1.add_link("f2", "extends", "shared entity");
1080        f1.add_link("f3", "contradicts", "opposite direction");
1081        let f2 = make_finding("f2", 0.7, "mechanism", false, false);
1082        let c = assemble("test", vec![f1, f2], 2, 0, "desc");
1083        assert_eq!(c.stats.links, 2);
1084        assert_eq!(*c.stats.link_types.get("extends").unwrap(), 1);
1085        assert_eq!(*c.stats.link_types.get("contradicts").unwrap(), 1);
1086    }
1087
1088    #[test]
1089    fn avg_confidence() {
1090        let bundles = vec![
1091            make_finding("f1", 0.8, "mechanism", false, false),
1092            make_finding("f2", 0.6, "mechanism", false, false),
1093        ];
1094        let c = assemble("test", bundles, 2, 0, "desc");
1095        assert!((c.stats.avg_confidence - 0.7).abs() < 0.01);
1096    }
1097
1098    #[test]
1099    fn confidence_distribution_buckets() {
1100        let bundles = vec![
1101            make_finding("f1", 0.9, "mechanism", false, false), // high
1102            make_finding("f2", 0.85, "mechanism", false, false), // high
1103            make_finding("f3", 0.7, "mechanism", false, false), // medium
1104            make_finding("f4", 0.6, "mechanism", false, false), // medium (0.6 is in 0.6..=0.8)
1105            make_finding("f5", 0.4, "mechanism", false, false), // low
1106        ];
1107        let c = assemble("test", bundles, 5, 0, "desc");
1108        assert_eq!(c.stats.confidence_distribution.high_gt_80, 2);
1109        assert_eq!(c.stats.confidence_distribution.medium_60_80, 2);
1110        assert_eq!(c.stats.confidence_distribution.low_lt_60, 1);
1111    }
1112
1113    #[test]
1114    fn gaps_counted() {
1115        let bundles = vec![
1116            make_finding("f1", 0.8, "mechanism", false, true),
1117            make_finding("f2", 0.6, "mechanism", false, false),
1118            make_finding("f3", 0.9, "mechanism", false, true),
1119        ];
1120        let c = assemble("test", bundles, 3, 0, "desc");
1121        assert_eq!(c.stats.gaps, 2);
1122    }
1123
1124    #[test]
1125    fn metadata_preserved() {
1126        let c = assemble("my frontier", vec![], 10, 2, "A description");
1127        assert_eq!(c.project.name, "my frontier");
1128        assert_eq!(c.project.description, "A description");
1129        assert_eq!(c.project.papers_processed, 10);
1130        assert_eq!(c.project.errors, 2);
1131        assert_eq!(c.vela_version, VELA_SCHEMA_VERSION);
1132        assert!(!c.project.compiled_at.is_empty());
1133    }
1134}
1135
1136/// An active (or expired — expiry is a read-time computation) lease on
1137/// an open obligation. One live lease per obligation; the reducer
1138/// rejects a second claim while a prior one is unexpired.
1139#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1140pub struct AttemptClaim {
1141    pub obligation_id: String,
1142    pub claimant_actor: String,
1143    pub claimant_pubkey: String,
1144    pub claimed_at: String,
1145    pub lease_ttl_seconds: u64,
1146    /// The exact signed `attempt.claimed` event that established this
1147    /// derived lease.  Older serialized projections did not retain the event
1148    /// identity, so they continue to deserialize with `None`; replay of the
1149    /// canonical event log fills it mechanically.  Refresh and zero-TTL
1150    /// release updates use this as their compare-and-swap predecessor.
1151    #[serde(default, skip_serializing_if = "Option::is_none")]
1152    pub claim_event_id: Option<String>,
1153}
1154
1155/// A registered statement hash: the priority timestamp primitive.
1156#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1157pub struct StatementRegistration {
1158    pub statement_hash: String,
1159    pub informal_ref: String,
1160    pub registered_by: String,
1161    pub registered_at: String,
1162    /// The canonical finding-to-registration edge (STATE_PLANE_MEMO
1163    /// appendix gap 5): the `vf_` id this registration timestamps, when
1164    /// the registrant declared one. Carried as an optional payload
1165    /// field on the existing `statement.registered` kind — old events
1166    /// (and old serialized state) parse unchanged via the serde
1167    /// default; `None` serializes to nothing, so pre-edge state stays
1168    /// byte-identical.
1169    #[serde(default, skip_serializing_if = "Option::is_none")]
1170    pub finding_id: Option<String>,
1171}