Skip to main content

vela_protocol/analysis/
scientific_diff.rs

1//! v0.193: Scientific Diff Pack (`vsd_*`).
2//!
3//! A proposal diff captures the change a single proposal would induce on
4//! frontier state. A Scientific
5//! Diff Pack sits one level up: it bundles N proposals into one
6//! reviewable change-set so a reviewer sees a coherent unit
7//! ("BBB-shared sister findings reconciled") rather than 12
8//! individual events.
9//!
10//! Substrate-honest framing: the Pack is purely an aggregator. It
11//! does NOT introduce new event semantics; applying the pack is
12//! exactly equivalent to applying its member proposals in canonical
13//! order through the existing reducer. The pack id is content-
14//! addressed over the (frontier_id, ordered proposals,
15//! aggregate_kind, summary, created_at) tuple and pinned by Lean
16//! Theorem 23 (Scientific Diff Pack id injectivity).
17//!
18//! Composition with later cycles:
19//!   - v0.195 vaa_*: Pack carries optional `agent_run: vaa_*` so
20//!     a pack produced by an LLM agent links to its signed
21//!     attestation envelope.
22//!   - v0.200 ver_*: an Evaluation Record can target a `vsd_*`,
23//!     letting "this pack was replicated by Lab X" be a first-
24//!     class statement.
25//!   - v0.201 diff_pack.released: a canonical event arm that turns
26//!     a signed pack into a released record across hubs.
27
28use ed25519_dalek::SigningKey;
29use serde::{Deserialize, Serialize};
30use sha2::{Digest, Sha256};
31use std::collections::{BTreeMap, BTreeSet};
32use std::path::Path;
33
34use crate::{frontier_policy, proposals, repo};
35
36pub const SCIENTIFIC_DIFF_SCHEMA: &str = "vela.scientific_diff.v0.1";
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
39pub struct ScientificDiffPack {
40    pub schema: String,
41    pub pack_id: String,
42    pub frontier_id: String,
43    pub created_at: String,
44    pub summary: String,
45    pub proposals: Vec<String>,
46    pub aggregate_kind: String,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub agent_run: Option<String>,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub parent_pack: Option<String>,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub applied_event_id: Option<String>,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub signature: Option<String>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub signer_pubkey_hex: Option<String>,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60pub struct DiffPackOperationPreview {
61    pub proposal_id: String,
62    pub kind: String,
63    pub operation_class: String,
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub target_type: Option<String>,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub target_id: Option<String>,
68    pub summary: String,
69    #[serde(default)]
70    pub source_or_evidence_refs: Vec<String>,
71    #[serde(default)]
72    pub downstream_affected_findings: Vec<String>,
73    #[serde(default)]
74    pub review_requirements: Vec<String>,
75    #[serde(default)]
76    pub review_class: String,
77    #[serde(default)]
78    pub required_reviewer_count: usize,
79    #[serde(default)]
80    pub required_reviewer_roles: Vec<String>,
81    #[serde(default)]
82    pub required_reason_fields: Vec<String>,
83    #[serde(default)]
84    pub allowed_agent_actions: Vec<String>,
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub confidence_reason: Option<String>,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub preview_counts: Option<DiffPackPreviewCounts>,
89}
90
91#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
92pub struct DiffPackPreviewCounts {
93    pub findings_before: usize,
94    pub findings_after: usize,
95    pub findings_delta: isize,
96    pub artifacts_before: usize,
97    pub artifacts_after: usize,
98    pub artifacts_delta: isize,
99    pub events_before: usize,
100    pub events_after: usize,
101    pub events_delta: isize,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
105pub struct DiffPackReviewSummary {
106    pub pack_id: String,
107    pub frontier_id: String,
108    pub summary: String,
109    pub aggregate_kind: String,
110    pub members: usize,
111    pub source_artifacts: Vec<String>,
112    pub proposed_operations: Vec<DiffPackOperationPreview>,
113    pub operation_counts: BTreeMap<String, usize>,
114    pub preview_counts: DiffPackPreviewCounts,
115    pub proof_freshness_impact: bool,
116    pub affected_findings: Vec<String>,
117    pub evidence_deltas: Vec<String>,
118    pub confidence_deltas: Vec<String>,
119    pub contradiction_effects: Vec<String>,
120    pub downstream_impacts: Vec<String>,
121    pub validation_results: Vec<String>,
122    pub evidence_ci_summary: DiffPackEvidenceCiSummary,
123    pub required_reviewers: Vec<String>,
124    pub cli_equivalents: BTreeMap<String, String>,
125    pub review_session_scope: String,
126    pub review_session_commands: BTreeMap<String, String>,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
130pub struct DiffPackEvidenceCiSummary {
131    pub scope: String,
132    pub status: String,
133    pub total: usize,
134    pub passed: usize,
135    pub warnings: usize,
136    pub failed: usize,
137    pub release_blocking_failed: usize,
138    pub command: String,
139    pub caveat: String,
140}
141
142#[derive(Debug, Clone)]
143pub struct PackDraft {
144    pub frontier_id: String,
145    pub created_at: String,
146    pub summary: String,
147    pub proposals: Vec<String>,
148    pub aggregate_kind: String,
149    pub agent_run: Option<String>,
150    pub parent_pack: Option<String>,
151}
152
153impl ScientificDiffPack {
154    /// Build an unsigned pack from a draft. The pack_id is
155    /// content-addressed over canonical bytes; signing is a
156    /// separate step via `sign`.
157    pub fn build(draft: PackDraft) -> Result<Self, String> {
158        validate_draft(&draft)?;
159        let mut pack = Self {
160            schema: SCIENTIFIC_DIFF_SCHEMA.to_string(),
161            pack_id: String::new(),
162            frontier_id: draft.frontier_id,
163            created_at: draft.created_at,
164            summary: draft.summary,
165            proposals: draft.proposals,
166            aggregate_kind: draft.aggregate_kind,
167            agent_run: draft.agent_run,
168            parent_pack: draft.parent_pack,
169            applied_event_id: None,
170            signature: None,
171            signer_pubkey_hex: None,
172        };
173        pack.pack_id = pack.derive_id();
174        Ok(pack)
175    }
176
177    /// Sign the pack with an Ed25519 key. Sets `signature` and
178    /// `signer_pubkey_hex`; does NOT change `pack_id` (the pack
179    /// is content-addressed over its body, not its signature).
180    pub fn sign(&mut self, key: &SigningKey) {
181        let preimage = self.preimage_bytes();
182        self.signature = Some(hex::encode(crate::sign::sign_bytes(key, &preimage)));
183        self.signer_pubkey_hex = Some(hex::encode(key.verifying_key().to_bytes()));
184    }
185
186    /// Canonical bytes over which pack_id is derived AND signatures
187    /// are computed. The order of fields is fixed; any change to
188    /// this method is a breaking schema bump.
189    fn preimage_bytes(&self) -> Vec<u8> {
190        let mut out = Vec::new();
191        out.extend_from_slice(self.frontier_id.as_bytes());
192        out.push(b'|');
193        out.extend_from_slice(self.aggregate_kind.as_bytes());
194        out.push(b'|');
195        out.extend_from_slice(self.summary.as_bytes());
196        out.push(b'|');
197        out.extend_from_slice(self.created_at.as_bytes());
198        out.push(b'|');
199        for (i, vpr) in self.proposals.iter().enumerate() {
200            if i > 0 {
201                out.push(b',');
202            }
203            out.extend_from_slice(vpr.as_bytes());
204        }
205        out.push(b'|');
206        if let Some(parent) = &self.parent_pack {
207            out.extend_from_slice(parent.as_bytes());
208        }
209        out.push(b'|');
210        if let Some(agent) = &self.agent_run {
211            out.extend_from_slice(agent.as_bytes());
212        }
213        out
214    }
215
216    fn derive_id(&self) -> String {
217        let mut hasher = Sha256::new();
218        hasher.update(self.preimage_bytes());
219        format!("vsd_{}", &hex::encode(hasher.finalize())[..16])
220    }
221
222    /// Verify: pack_id matches re-derivation; if a signature is
223    /// present, it verifies under the declared pubkey.
224    pub fn verify(&self) -> Result<(), String> {
225        let rederived = self.derive_id();
226        if rederived != self.pack_id {
227            return Err(format!(
228                "pack_id mismatch: declared {}, rebuilt {}",
229                self.pack_id, rederived
230            ));
231        }
232        if let (Some(sig_hex), Some(pub_hex)) = (&self.signature, &self.signer_pubkey_hex) {
233            if !crate::sign::verify_action_signature(&self.preimage_bytes(), sig_hex, pub_hex)? {
234                return Err(
235                    "scientific_diff signature does not verify under signer_pubkey_hex".to_string(),
236                );
237            }
238        } else if self.signature.is_some() || self.signer_pubkey_hex.is_some() {
239            return Err("signature and signer_pubkey_hex must be set together".to_string());
240        }
241        Ok(())
242    }
243
244    pub fn review_summary(&self, repo_path: &Path) -> DiffPackReviewSummary {
245        let mut source_artifacts = BTreeSet::new();
246        let mut affected_findings = BTreeSet::new();
247        let mut evidence_deltas = BTreeSet::new();
248        let mut confidence_deltas = BTreeSet::new();
249        let mut contradiction_effects = BTreeSet::new();
250        let mut downstream_impacts = BTreeSet::new();
251        let mut proposed_operations = Vec::new();
252        let mut operation_counts = BTreeMap::new();
253        let project = repo::load_from_path(repo_path).ok();
254        let policy = frontier_policy::load_policy_summary(repo_path).ok();
255        let mut preview_counts = project
256            .as_ref()
257            .map(|frontier| DiffPackPreviewCounts {
258                findings_before: frontier.findings.len(),
259                findings_after: frontier.findings.len(),
260                findings_delta: 0,
261                artifacts_before: frontier.artifacts.len(),
262                artifacts_after: frontier.artifacts.len(),
263                artifacts_delta: 0,
264                events_before: frontier.events.len(),
265                events_after: frontier.events.len(),
266                events_delta: 0,
267            })
268            .unwrap_or_default();
269        let mut proof_freshness_impact = false;
270
271        for proposal_id in &self.proposals {
272            let proposal = read_member_proposal(repo_path, proposal_id);
273            let kind = proposal
274                .as_ref()
275                .and_then(|v| string_at(v, &["kind"]))
276                .unwrap_or_else(|| "proposal.reference".to_string());
277            let operation_class = operation_class_for_kind(&kind, proposal.as_ref()).to_string();
278            *operation_counts.entry(operation_class.clone()).or_default() += 1;
279            let target_type = proposal
280                .as_ref()
281                .and_then(|v| string_at(v, &["target", "type"]));
282            let target_id = proposal
283                .as_ref()
284                .and_then(|v| string_at(v, &["target", "id"]))
285                .or_else(|| {
286                    proposal
287                        .as_ref()
288                        .and_then(|v| string_at(v, &["payload", "finding_id"]))
289                })
290                .or_else(|| {
291                    proposal
292                        .as_ref()
293                        .and_then(|v| string_at(v, &["payload", "finding", "id"]))
294                });
295
296            let explicit_reason = proposal
297                .as_ref()
298                .and_then(|v| string_at(v, &["reason"]))
299                .filter(|s| !s.trim().is_empty());
300            let narrative = proposal
301                .as_ref()
302                .and_then(|v| string_at(v, &["payload", "narrative"]));
303            let summary = explicit_reason
304                .clone()
305                .or_else(|| narrative.clone())
306                .unwrap_or_else(|| "Proposal referenced by id only".to_string());
307            let confidence_reason = if operation_class == "revise_confidence" {
308                explicit_reason.clone().or_else(|| {
309                    proposal
310                        .as_ref()
311                        .and_then(|v| string_at(v, &["payload", "reason"]))
312                })
313            } else {
314                None
315            };
316
317            let mut source_or_evidence_refs = collect_source_or_evidence_refs(proposal.as_ref());
318            source_or_evidence_refs.sort();
319            source_or_evidence_refs.dedup();
320
321            if let Some(id) = &target_id
322                && id.starts_with("vf_")
323            {
324                affected_findings.insert(id.clone());
325            }
326            if let Some(tension_with) = proposal
327                .as_ref()
328                .and_then(|v| string_at(v, &["payload", "tension_with"]))
329            {
330                affected_findings.insert(tension_with.clone());
331                downstream_impacts.insert(format!("Review linked finding {tension_with}"));
332            }
333            let mut downstream_affected_findings = collect_downstream_findings(
334                project.as_ref(),
335                proposal.as_ref(),
336                target_id.as_deref(),
337            );
338            for id in &downstream_affected_findings {
339                affected_findings.insert(id.clone());
340                downstream_impacts.insert(format!("{proposal_id}: affects linked finding {id}"));
341            }
342
343            if let Some(source_refs) = proposal.as_ref().and_then(|v| v.get("source_refs"))
344                && let Some(arr) = source_refs.as_array()
345            {
346                for item in arr {
347                    if let Some(s) = item.as_str() {
348                        source_artifacts.insert(s.to_string());
349                    }
350                }
351            }
352            if let Some(pmid) = proposal
353                .as_ref()
354                .and_then(|v| string_at(v, &["payload", "finding", "provenance", "pmid"]))
355            {
356                source_artifacts.insert(format!("pmid:{pmid}"));
357            }
358            if let Some(doi) = proposal
359                .as_ref()
360                .and_then(|v| string_at(v, &["payload", "finding", "provenance", "doi"]))
361            {
362                source_artifacts.insert(format!("doi:{doi}"));
363            }
364            if let Some(title) = proposal
365                .as_ref()
366                .and_then(|v| string_at(v, &["payload", "finding", "provenance", "title"]))
367            {
368                source_artifacts.insert(title);
369            }
370
371            collect_evidence_spans(proposal.as_ref(), &mut evidence_deltas);
372            if kind.contains("evidence") {
373                evidence_deltas.insert(format!("{proposal_id}: evidence-affecting proposal"));
374            }
375            if kind.contains("confidence") {
376                confidence_deltas.insert(format!("{proposal_id}: confidence-affecting proposal"));
377            }
378            if let Some(score) = proposal
379                .as_ref()
380                .and_then(|v| v.pointer("/payload/finding/confidence/score"))
381                .and_then(|v| v.as_f64())
382            {
383                confidence_deltas.insert(format!("{proposal_id}: confidence score {score:.3}"));
384            }
385            if let Some(basis) = proposal
386                .as_ref()
387                .and_then(|v| string_at(v, &["payload", "finding", "confidence", "basis"]))
388            {
389                confidence_deltas.insert(format!("{proposal_id}: {basis}"));
390            }
391
392            if kind.contains("tension") || kind.contains("contradiction") {
393                contradiction_effects.insert(format!(
394                    "{proposal_id}: reviewer-visible tension or contradiction"
395                ));
396            }
397            if let Some(tension_kind) = proposal
398                .as_ref()
399                .and_then(|v| string_at(v, &["payload", "tension_kind"]))
400            {
401                contradiction_effects.insert(format!("{proposal_id}: {tension_kind}"));
402            }
403            if let Some(action) = proposal
404                .as_ref()
405                .and_then(|v| string_at(v, &["payload", "proposed_action"]))
406            {
407                downstream_impacts.insert(format!("{proposal_id}: {action}"));
408            }
409
410            let policy_requirement = frontier_policy::review_requirement_for_operation(
411                policy.as_ref(),
412                &operation_class,
413                &kind,
414                !downstream_affected_findings.is_empty(),
415            );
416            let mut review_requirements = operation_review_requirements(
417                &operation_class,
418                !downstream_affected_findings.is_empty(),
419            );
420            review_requirements.extend(policy_requirement.reviewer_roles.iter().cloned());
421            review_requirements.extend(
422                policy_requirement
423                    .required_reason_fields
424                    .iter()
425                    .map(|field| format!("reason:{field}")),
426            );
427            review_requirements.sort();
428            review_requirements.dedup();
429
430            let op_preview_counts = project.as_ref().and_then(|frontier| {
431                proposals::preview_in_frontier(frontier, proposal_id, "reviewer:diff-pack-preview")
432                    .ok()
433                    .map(|preview| DiffPackPreviewCounts {
434                        findings_before: preview.findings_before,
435                        findings_after: preview.findings_after,
436                        findings_delta: preview.findings_delta,
437                        artifacts_before: preview.artifacts_before,
438                        artifacts_after: preview.artifacts_after,
439                        artifacts_delta: preview.artifacts_delta,
440                        events_before: preview.events_before,
441                        events_after: preview.events_after,
442                        events_delta: preview.events_delta,
443                    })
444            });
445            if let Some(counts) = &op_preview_counts {
446                preview_counts.findings_after = (preview_counts.findings_after as isize
447                    + counts.findings_delta)
448                    .max(0) as usize;
449                preview_counts.findings_delta += counts.findings_delta;
450                preview_counts.artifacts_after = (preview_counts.artifacts_after as isize
451                    + counts.artifacts_delta)
452                    .max(0) as usize;
453                preview_counts.artifacts_delta += counts.artifacts_delta;
454                preview_counts.events_after =
455                    (preview_counts.events_after as isize + counts.events_delta).max(0) as usize;
456                preview_counts.events_delta += counts.events_delta;
457                proof_freshness_impact |= counts.events_delta != 0
458                    || counts.findings_delta != 0
459                    || counts.artifacts_delta != 0;
460            } else if proposal.is_some() {
461                proof_freshness_impact = true;
462            }
463
464            proposed_operations.push(DiffPackOperationPreview {
465                proposal_id: proposal_id.clone(),
466                kind,
467                operation_class,
468                target_type,
469                target_id,
470                summary,
471                source_or_evidence_refs,
472                downstream_affected_findings: {
473                    downstream_affected_findings.sort();
474                    downstream_affected_findings.dedup();
475                    downstream_affected_findings
476                },
477                review_requirements,
478                review_class: policy_requirement.review_class,
479                required_reviewer_count: policy_requirement.required_reviewer_count,
480                required_reviewer_roles: policy_requirement.reviewer_roles,
481                required_reason_fields: policy_requirement.required_reason_fields,
482                allowed_agent_actions: policy_requirement.allowed_agent_actions,
483                confidence_reason,
484                preview_counts: op_preview_counts,
485            });
486        }
487
488        let mut validation_results = Vec::new();
489        validation_results.push("pack id verified from canonical bytes".to_string());
490        if self.signature.is_some() {
491            validation_results.push("signature present and verified".to_string());
492        } else {
493            validation_results.push("unsigned pack".to_string());
494        }
495        validation_results.push(format!(
496            "{} member proposal{} resolved for review",
497            proposed_operations.len(),
498            if proposed_operations.len() == 1 {
499                ""
500            } else {
501                "s"
502            }
503        ));
504        if source_artifacts.is_empty() {
505            validation_results
506                .push("no explicit source artifacts declared by member proposals".to_string());
507        }
508        for op in &proposed_operations {
509            if op.operation_class == "revise_confidence" {
510                if op.source_or_evidence_refs.is_empty() {
511                    validation_results.push(format!(
512                        "{}: confidence operation missing source or evidence reference",
513                        op.proposal_id
514                    ));
515                }
516                if op
517                    .confidence_reason
518                    .as_deref()
519                    .unwrap_or_default()
520                    .trim()
521                    .is_empty()
522                {
523                    validation_results.push(format!(
524                        "{}: confidence operation missing review reason",
525                        op.proposal_id
526                    ));
527                }
528            }
529        }
530
531        let mut required_reviewers = BTreeSet::new();
532        required_reviewers.insert("local_reviewer".to_string());
533        if !confidence_deltas.is_empty() {
534            required_reviewers.insert("domain_reviewer".to_string());
535        }
536        if !contradiction_effects.is_empty() {
537            required_reviewers.insert("method_reviewer".to_string());
538        }
539        for op in &proposed_operations {
540            for role in &op.required_reviewer_roles {
541                required_reviewers.insert(role.clone());
542            }
543        }
544        let evidence_ci_summary = diff_pack_evidence_ci_summary(
545            &self.pack_id,
546            source_artifacts.is_empty(),
547            &proposed_operations,
548        );
549
550        let mut cli_equivalents = BTreeMap::new();
551        cli_equivalents.insert(
552            "decision_brief".to_string(),
553            "vela next <frontier> --json".to_string(),
554        );
555        cli_equivalents.insert(
556            "check".to_string(),
557            "vela check <frontier> --strict --json".to_string(),
558        );
559        cli_equivalents.insert(
560            "decide".to_string(),
561            "vela sign --frontier <frontier>".to_string(),
562        );
563        let review_session_scope = format!("diff_pack:{}", self.pack_id);
564        let mut review_session_commands = BTreeMap::new();
565        review_session_commands.insert(
566            "inspect".to_string(),
567            "vela next <frontier> --json".to_string(),
568        );
569        review_session_commands.insert(
570            "decide".to_string(),
571            "vela sign --frontier <frontier>".to_string(),
572        );
573
574        DiffPackReviewSummary {
575            pack_id: self.pack_id.clone(),
576            frontier_id: self.frontier_id.clone(),
577            summary: self.summary.clone(),
578            aggregate_kind: self.aggregate_kind.clone(),
579            members: self.proposals.len(),
580            source_artifacts: sorted(source_artifacts),
581            proposed_operations,
582            operation_counts,
583            preview_counts,
584            proof_freshness_impact,
585            affected_findings: sorted(affected_findings),
586            evidence_deltas: sorted(evidence_deltas),
587            confidence_deltas: sorted(confidence_deltas),
588            contradiction_effects: sorted(contradiction_effects),
589            downstream_impacts: sorted(downstream_impacts),
590            validation_results,
591            evidence_ci_summary,
592            required_reviewers: sorted(required_reviewers),
593            cli_equivalents,
594            review_session_scope,
595            review_session_commands,
596        }
597    }
598}
599
600fn diff_pack_evidence_ci_summary(
601    pack_id: &str,
602    missing_source_artifacts: bool,
603    operations: &[DiffPackOperationPreview],
604) -> DiffPackEvidenceCiSummary {
605    let mut total = 2;
606    let mut failed = usize::from(missing_source_artifacts);
607
608    for op in operations {
609        total += 1;
610        if op.required_reviewer_count == 0 || op.required_reviewer_roles.is_empty() {
611            failed += 1;
612        }
613        if op.operation_class == "revise_confidence" {
614            total += 2;
615            if op.source_or_evidence_refs.is_empty() {
616                failed += 1;
617            }
618            if op
619                .confidence_reason
620                .as_deref()
621                .unwrap_or_default()
622                .trim()
623                .is_empty()
624            {
625                failed += 1;
626            }
627        }
628    }
629
630    DiffPackEvidenceCiSummary {
631        scope: format!("diff_pack:{pack_id}"),
632        status: if failed == 0 {
633            "ready".to_string()
634        } else {
635            "blocked".to_string()
636        },
637        total,
638        passed: total.saturating_sub(failed),
639        warnings: 0,
640        failed,
641        release_blocking_failed: failed,
642        command: "vela check <frontier> --strict --json".to_string(),
643        caveat: "Evidence CI checks review readiness. It does not accept scientific state."
644            .to_string(),
645    }
646}
647
648fn operation_class_for_kind(kind: &str, proposal: Option<&serde_json::Value>) -> &'static str {
649    let normalized = kind.to_ascii_lowercase();
650    if normalized.contains("contradiction")
651        || normalized.contains("tension")
652        || string_at_optional(proposal, &["payload", "tension_kind"]).is_some()
653        || string_at_optional(proposal, &["payload", "tension_with"]).is_some()
654    {
655        return "mark_contradiction";
656    }
657    if normalized.contains("downstream") || normalized.contains("review_request") {
658        return "request_downstream_review";
659    }
660    if normalized.contains("open_gap")
661        || normalized.contains("gap.open")
662        || proposal
663            .and_then(|p| p.pointer("/payload/finding/flags/gap"))
664            .and_then(|v| v.as_bool())
665            .unwrap_or(false)
666    {
667        return "open_gap";
668    }
669    if normalized.contains("confidence") {
670        return "revise_confidence";
671    }
672    if normalized.contains("caveat") {
673        return "add_caveat";
674    }
675    if normalized.contains("span_repair") || normalized.contains("span.repair") {
676        return "repair_span";
677    }
678    if normalized.contains("locator_repair") || normalized.contains("locator.repair") {
679        return "repair_locator";
680    }
681    if normalized.contains("evidence") {
682        return "add_evidence_atom";
683    }
684    if normalized.contains("link") {
685        return "add_link";
686    }
687    if normalized == "finding.add" || normalized.ends_with(".finding.add") {
688        return "add_finding";
689    }
690    "request_downstream_review"
691}
692
693fn operation_review_requirements(
694    operation_class: &str,
695    has_downstream_impact: bool,
696) -> Vec<String> {
697    let mut out = BTreeSet::new();
698    out.insert("local_reviewer".to_string());
699    match operation_class {
700        "revise_confidence" | "mark_contradiction" => {
701            out.insert("domain_reviewer".to_string());
702            out.insert("method_reviewer".to_string());
703        }
704        "add_evidence_atom" | "repair_locator" | "repair_span" => {
705            out.insert("source_reviewer".to_string());
706        }
707        "open_gap" | "request_downstream_review" => {
708            out.insert("frontier_reviewer".to_string());
709        }
710        _ => {}
711    }
712    if has_downstream_impact {
713        out.insert("frontier_reviewer".to_string());
714    }
715    out.into_iter().collect()
716}
717
718fn sorted(set: BTreeSet<String>) -> Vec<String> {
719    set.into_iter().collect()
720}
721
722fn read_member_proposal(repo_path: &Path, proposal_id: &str) -> Option<serde_json::Value> {
723    for dir in ["agent_proposals", "proposals"] {
724        let path = repo_path
725            .join(".vela")
726            .join(dir)
727            .join(format!("{proposal_id}.json"));
728        if let Ok(body) = std::fs::read_to_string(path)
729            && let Ok(value) = serde_json::from_str::<serde_json::Value>(&body)
730        {
731            return Some(value);
732        }
733    }
734    None
735}
736
737fn string_at(value: &serde_json::Value, path: &[&str]) -> Option<String> {
738    let mut cur = value;
739    for key in path {
740        cur = cur.get(*key)?;
741    }
742    cur.as_str().map(ToString::to_string)
743}
744
745fn string_at_optional(value: Option<&serde_json::Value>, path: &[&str]) -> Option<String> {
746    value.and_then(|v| string_at(v, path))
747}
748
749fn collect_source_or_evidence_refs(proposal: Option<&serde_json::Value>) -> Vec<String> {
750    let mut out = BTreeSet::new();
751    let Some(proposal) = proposal else {
752        return Vec::new();
753    };
754    if let Some(source_refs) = proposal.get("source_refs").and_then(|v| v.as_array()) {
755        for item in source_refs {
756            if let Some(s) = item.as_str()
757                && !s.trim().is_empty()
758            {
759                out.insert(s.to_string());
760            }
761        }
762    }
763    collect_ref_strings_recursive(proposal, &mut out);
764    out.into_iter().collect()
765}
766
767fn collect_ref_strings_recursive(value: &serde_json::Value, out: &mut BTreeSet<String>) {
768    match value {
769        serde_json::Value::Object(map) => {
770            for (key, child) in map {
771                let key_lower = key.to_ascii_lowercase();
772                if (key_lower.contains("source") || key_lower.contains("evidence"))
773                    && key_lower.contains("ref")
774                {
775                    match child {
776                        serde_json::Value::String(s) if !s.trim().is_empty() => {
777                            out.insert(s.to_string());
778                        }
779                        serde_json::Value::Array(arr) => {
780                            for item in arr {
781                                if let Some(s) = item.as_str()
782                                    && !s.trim().is_empty()
783                                {
784                                    out.insert(s.to_string());
785                                }
786                            }
787                        }
788                        _ => {}
789                    }
790                }
791                collect_ref_strings_recursive(child, out);
792            }
793        }
794        serde_json::Value::Array(arr) => {
795            for child in arr {
796                collect_ref_strings_recursive(child, out);
797            }
798        }
799        _ => {}
800    }
801}
802
803fn collect_downstream_findings(
804    project: Option<&crate::project::Project>,
805    proposal: Option<&serde_json::Value>,
806    target_id: Option<&str>,
807) -> Vec<String> {
808    let mut out = BTreeSet::new();
809    for key in [
810        "tension_with",
811        "downstream_finding",
812        "downstream_review",
813        "linked_finding",
814        "linked_findings",
815        "to_finding",
816        "from_finding",
817    ] {
818        collect_payload_finding_refs(proposal, key, &mut out);
819    }
820    if let (Some(project), Some(target_id)) = (project, target_id) {
821        for finding in &project.findings {
822            if finding.id == target_id {
823                for link in &finding.links {
824                    if link.target.starts_with("vf_") {
825                        out.insert(link.target.clone());
826                    }
827                }
828            }
829            for link in &finding.links {
830                if link.target == target_id && finding.id.starts_with("vf_") {
831                    out.insert(finding.id.clone());
832                }
833            }
834        }
835    }
836    out.remove(target_id.unwrap_or_default());
837    out.into_iter().collect()
838}
839
840fn collect_payload_finding_refs(
841    proposal: Option<&serde_json::Value>,
842    key: &str,
843    out: &mut BTreeSet<String>,
844) {
845    let Some(value) = proposal.and_then(|v| v.pointer(&format!("/payload/{key}"))) else {
846        return;
847    };
848    match value {
849        serde_json::Value::String(s) if s.starts_with("vf_") => {
850            out.insert(s.to_string());
851        }
852        serde_json::Value::Array(arr) => {
853            for item in arr {
854                if let Some(s) = item.as_str()
855                    && s.starts_with("vf_")
856                {
857                    out.insert(s.to_string());
858                }
859            }
860        }
861        _ => {}
862    }
863}
864
865fn collect_evidence_spans(proposal: Option<&serde_json::Value>, out: &mut BTreeSet<String>) {
866    let Some(proposal) = proposal else {
867        return;
868    };
869    let Some(spans) = proposal.pointer("/payload/finding/evidence/evidence_spans") else {
870        return;
871    };
872    let Some(arr) = spans.as_array() else {
873        return;
874    };
875    for span in arr {
876        if let Some(text) = span.get("text").and_then(|v| v.as_str()) {
877            let clipped: String = text.chars().take(180).collect();
878            out.insert(clipped);
879        }
880    }
881}
882
883fn validate_draft(d: &PackDraft) -> Result<(), String> {
884    if !d.frontier_id.starts_with("vfr_") {
885        return Err(format!(
886            "frontier_id must start with `vfr_`, got `{}`",
887            d.frontier_id
888        ));
889    }
890    if d.summary.is_empty() {
891        return Err("summary cannot be empty".to_string());
892    }
893    if d.summary.chars().count() > 280 {
894        return Err("summary exceeds 280 chars".to_string());
895    }
896    if d.proposals.is_empty() {
897        return Err("a pack must bundle at least one proposal".to_string());
898    }
899    for vpr in &d.proposals {
900        if !vpr.starts_with("vpr_") {
901            return Err(format!("every member must start with `vpr_`, got `{vpr}`"));
902        }
903    }
904    if d.aggregate_kind.is_empty() {
905        return Err("aggregate_kind cannot be empty".to_string());
906    }
907    if let Some(parent) = &d.parent_pack
908        && !parent.starts_with("vsd_")
909    {
910        return Err(format!(
911            "parent_pack must start with `vsd_`, got `{parent}`"
912        ));
913    }
914    if let Some(agent) = &d.agent_run
915        && !agent.starts_with("vaa_")
916    {
917        return Err(format!("agent_run must start with `vaa_`, got `{agent}`"));
918    }
919    Ok(())
920}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925    use rand::rngs::OsRng;
926
927    fn key() -> SigningKey {
928        SigningKey::generate(&mut OsRng)
929    }
930
931    fn ok_draft() -> PackDraft {
932        PackDraft {
933            frontier_id: "vfr_5076e7b3ff8e6b0f".to_string(),
934            created_at: "2026-05-11T00:00:00Z".to_string(),
935            summary: "Test pack — bundles two proposals.".to_string(),
936            proposals: vec!["vpr_a1".to_string(), "vpr_b2".to_string()],
937            aggregate_kind: "finding.cluster_revision".to_string(),
938            agent_run: None,
939            parent_pack: None,
940        }
941    }
942
943    #[test]
944    fn operation_classifies_scientific_diff_operations() {
945        let cases = [
946            ("finding.add", "add_finding"),
947            ("evidence_atom.add", "add_evidence_atom"),
948            ("finding.locator_repair", "repair_locator"),
949            ("finding.span_repair", "repair_span"),
950            ("link.add", "add_link"),
951            ("finding.caveat", "add_caveat"),
952            ("finding.confidence_revise", "revise_confidence"),
953            ("finding.contradiction", "mark_contradiction"),
954            ("finding.open_gap", "open_gap"),
955            ("finding.downstream_review", "request_downstream_review"),
956        ];
957        for (kind, expected) in cases {
958            assert_eq!(operation_class_for_kind(kind, None), expected);
959        }
960    }
961
962    #[test]
963    fn review_summary_exposes_operation_semantics() {
964        let tmp = tempfile::tempdir().unwrap();
965        let proposals = tmp.path().join(".vela").join("agent_proposals");
966        std::fs::create_dir_all(&proposals).unwrap();
967        std::fs::write(
968            proposals.join("vpr_confidence.json"),
969            r#"{
970              "id":"vpr_confidence",
971              "kind":"finding.confidence_revise",
972              "target":{"type":"finding","id":"vf_claim"},
973              "reason":"confidence moved because source evidence narrowed the claim",
974              "source_refs":["pmid:123"],
975              "payload":{
976                "finding_id":"vf_claim",
977                "score":0.42,
978                "evidence_ref":"evidence:abc",
979                "downstream_review":["vf_child"],
980                "linked_findings":["vf_child"]
981              }
982            }"#,
983        )
984        .unwrap();
985        let pack = ScientificDiffPack::build(PackDraft {
986            frontier_id: "vfr_5076e7b3ff8e6b0f".to_string(),
987            created_at: "2026-05-13T00:00:00Z".to_string(),
988            summary: "Review one confidence-moving operation.".to_string(),
989            proposals: vec!["vpr_confidence".to_string()],
990            aggregate_kind: "confidence.review".to_string(),
991            agent_run: None,
992            parent_pack: None,
993        })
994        .unwrap();
995
996        let summary = pack.review_summary(tmp.path());
997        assert_eq!(summary.operation_counts["revise_confidence"], 1);
998        assert!(summary.proof_freshness_impact);
999        let op = summary.proposed_operations.first().unwrap();
1000        assert_eq!(op.operation_class, "revise_confidence");
1001        assert_eq!(
1002            op.confidence_reason.as_deref(),
1003            Some("confidence moved because source evidence narrowed the claim")
1004        );
1005        assert!(op.source_or_evidence_refs.contains(&"pmid:123".to_string()));
1006        assert!(
1007            op.source_or_evidence_refs
1008                .contains(&"evidence:abc".to_string())
1009        );
1010        assert!(
1011            op.review_requirements
1012                .contains(&"domain_reviewer".to_string())
1013        );
1014        assert!(
1015            op.downstream_affected_findings
1016                .contains(&"vf_child".to_string())
1017        );
1018        assert_eq!(
1019            summary.review_session_scope,
1020            format!("diff_pack:{}", pack.pack_id)
1021        );
1022        assert_eq!(
1023            summary.evidence_ci_summary.scope,
1024            summary.review_session_scope
1025        );
1026        assert!(summary.evidence_ci_summary.total >= summary.proposed_operations.len());
1027        assert!(summary.evidence_ci_summary.command.contains("vela check"));
1028        assert!(
1029            summary
1030                .review_session_commands
1031                .get("inspect")
1032                .unwrap()
1033                .contains("vela next")
1034        );
1035    }
1036
1037    #[test]
1038    fn review_summary_marks_missing_confidence_support() {
1039        let tmp = tempfile::tempdir().unwrap();
1040        let proposals = tmp.path().join(".vela").join("agent_proposals");
1041        std::fs::create_dir_all(&proposals).unwrap();
1042        std::fs::write(
1043            proposals.join("vpr_confidence.json"),
1044            r#"{
1045              "id":"vpr_confidence",
1046              "kind":"finding.confidence_revise",
1047              "target":{"type":"finding","id":"vf_claim"},
1048              "reason":"",
1049              "source_refs":[],
1050              "payload":{"finding_id":"vf_claim"}
1051            }"#,
1052        )
1053        .unwrap();
1054        let pack = ScientificDiffPack::build(PackDraft {
1055            frontier_id: "vfr_5076e7b3ff8e6b0f".to_string(),
1056            created_at: "2026-05-13T00:00:00Z".to_string(),
1057            summary: "Review one incomplete confidence operation.".to_string(),
1058            proposals: vec!["vpr_confidence".to_string()],
1059            aggregate_kind: "confidence.review".to_string(),
1060            agent_run: None,
1061            parent_pack: None,
1062        })
1063        .unwrap();
1064
1065        let summary = pack.review_summary(tmp.path());
1066        assert!(summary.validation_results.iter().any(|line| {
1067            line.contains("vpr_confidence")
1068                && line.contains("confidence operation missing source or evidence reference")
1069        }));
1070        assert!(summary.validation_results.iter().any(|line| {
1071            line.contains("vpr_confidence")
1072                && line.contains("confidence operation missing review reason")
1073        }));
1074    }
1075
1076    #[test]
1077    fn builds_and_id_is_deterministic() {
1078        let p1 = ScientificDiffPack::build(ok_draft()).unwrap();
1079        let p2 = ScientificDiffPack::build(ok_draft()).unwrap();
1080        assert_eq!(p1.pack_id, p2.pack_id);
1081        assert!(p1.pack_id.starts_with("vsd_"));
1082        assert_eq!(p1.pack_id.len(), 4 + 16);
1083    }
1084
1085    #[test]
1086    fn different_proposals_produce_different_ids() {
1087        let p1 = ScientificDiffPack::build(ok_draft()).unwrap();
1088        let mut d2 = ok_draft();
1089        d2.proposals = vec!["vpr_b2".to_string(), "vpr_a1".to_string()];
1090        let p2 = ScientificDiffPack::build(d2).unwrap();
1091        assert_ne!(p1.pack_id, p2.pack_id, "order matters in pack_id");
1092    }
1093
1094    #[test]
1095    fn empty_pack_rejected() {
1096        let mut d = ok_draft();
1097        d.proposals.clear();
1098        assert!(ScientificDiffPack::build(d).is_err());
1099    }
1100
1101    #[test]
1102    fn non_vpr_member_rejected() {
1103        let mut d = ok_draft();
1104        d.proposals[0] = "vsd_not_a_vpr".to_string();
1105        assert!(ScientificDiffPack::build(d).is_err());
1106    }
1107
1108    #[test]
1109    fn summary_length_capped() {
1110        let mut d = ok_draft();
1111        d.summary = "x".repeat(281);
1112        assert!(ScientificDiffPack::build(d).is_err());
1113    }
1114
1115    #[test]
1116    fn sign_then_verify() {
1117        let mut pack = ScientificDiffPack::build(ok_draft()).unwrap();
1118        pack.sign(&key());
1119        pack.verify().expect("verifies after signing");
1120    }
1121
1122    #[test]
1123    fn tampered_body_after_sign_fails_verify() {
1124        let mut pack = ScientificDiffPack::build(ok_draft()).unwrap();
1125        pack.sign(&key());
1126        pack.summary = "different summary".to_string();
1127        // pack_id no longer matches re-derivation.
1128        assert!(pack.verify().is_err());
1129    }
1130
1131    #[test]
1132    fn unsigned_pack_verifies_without_keys() {
1133        let pack = ScientificDiffPack::build(ok_draft()).unwrap();
1134        pack.verify().expect("unsigned pack still verifies its id");
1135    }
1136
1137    #[test]
1138    fn canonical_bytes_pinned_id() {
1139        // The pinned constants below make the canonical-bytes layout an
1140        // implementation-independent fixture. Any encoder drift fails here.
1141        let p = ScientificDiffPack::build(PackDraft {
1142            frontier_id: "vfr_5076e7b3ff8e6b0f".to_string(),
1143            created_at: "2026-05-11T00:00:00Z".to_string(),
1144            summary: "Test pack — bundles two proposals.".to_string(),
1145            proposals: vec!["vpr_a1".to_string(), "vpr_b2".to_string()],
1146            aggregate_kind: "finding.cluster_revision".to_string(),
1147            agent_run: None,
1148            parent_pack: None,
1149        })
1150        .unwrap();
1151        assert_eq!(p.pack_id, "vsd_cd2a0071e7ffbffd");
1152    }
1153
1154    #[test]
1155    fn round_trips_through_json() {
1156        let mut pack = ScientificDiffPack::build(ok_draft()).unwrap();
1157        pack.sign(&key());
1158        let s = serde_json::to_string(&pack).unwrap();
1159        let back: ScientificDiffPack = serde_json::from_str(&s).unwrap();
1160        assert_eq!(pack, back);
1161        back.verify().unwrap();
1162    }
1163}