Skip to main content

vela_cli/cli/
checks.rs

1//! `vela check` payload assembly and hashing plumbing: schema/lint/replay
2//! diagnostics, repair-plan derivation, sensitive-path scanning, and the
3//! frontier hash helpers. Moved verbatim from `cli/mod.rs`.
4
5use super::*;
6
7#[allow(clippy::too_many_arguments)]
8/// v0.113: walk a frontier path and return any files whose names
9/// match shapes commonly associated with secrets: literal extensions
10/// (`*.key`, `*.pem`, `*.p12`) and substring patterns (`private`,
11/// `secret`, `credential`). Skips standard noise (`.git/`, `target/`,
12/// `node_modules/`, `dist/`, `build/`). Used by `vela check --strict`
13/// and by `scripts/test-secret-audit.sh`. Closes part of
14/// THREAT_MODEL.md A17 with active detection on top of the passive
15/// .gitignore exclusion shipped at v0.111.1.
16pub fn scan_for_sensitive_paths(root: &Path) -> Vec<PathBuf> {
17    let mut hits: Vec<PathBuf> = Vec::new();
18    let skip_dirs: &[&str] = &[".git", "target", "node_modules", "dist", "build"];
19    let bad_exts: &[&str] = &["key", "pem", "p12", "pfx"];
20    let bad_substrings: &[&str] = &["private", "secret", "credential"];
21    let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
22    while let Some(dir) = stack.pop() {
23        let Ok(entries) = std::fs::read_dir(&dir) else {
24            continue;
25        };
26        for entry in entries.flatten() {
27            let path = entry.path();
28            let name_os = path.file_name();
29            let Some(name) = name_os.and_then(|n| n.to_str()) else {
30                continue;
31            };
32            let lower = name.to_lowercase();
33            if path.is_dir() {
34                if skip_dirs.contains(&name) {
35                    continue;
36                }
37                stack.push(path);
38                continue;
39            }
40            // .pub and .pubkey files are public-key material; skip.
41            if lower.ends_with(".pub") || lower.ends_with(".pubkey") {
42                continue;
43            }
44            // public.key by name is an Ed25519 PUBLIC key; safe.
45            if lower == "public.key" {
46                continue;
47            }
48            let ext = path
49                .extension()
50                .and_then(|e| e.to_str())
51                .map(str::to_lowercase)
52                .unwrap_or_default();
53            let mut hit = false;
54            if bad_exts.iter().any(|x| ext == *x) {
55                hit = true;
56            }
57            if bad_substrings.iter().any(|s| lower.contains(s)) {
58                hit = true;
59            }
60            if hit {
61                hits.push(path);
62            }
63        }
64    }
65    hits.sort();
66    hits
67}
68
69pub(crate) fn frontier_dir_for_source(source: &Path) -> &Path {
70    if source.is_dir() {
71        source
72    } else {
73        source
74            .parent()
75            .filter(|parent| !parent.as_os_str().is_empty())
76            .unwrap_or_else(|| Path::new("."))
77    }
78}
79
80pub(crate) fn active_policy_pair_snapshot(
81    source: &Path,
82) -> Result<vela_protocol::acceptance_policy::ActivePolicySnapshot, String> {
83    vela_protocol::acceptance_policy::load_active_policy_snapshot(frontier_dir_for_source(source))
84}
85
86const REPOSITORY_CONTEXT_CHECK_ID: &str = "repository_context";
87
88pub(crate) struct RepositoryContextAssessment {
89    pub(crate) payload: Value,
90    /// Independently retained consumer pin, converted to the narrow form
91    /// accepted by read-only Target Index verification. This is populated
92    /// only after the complete repository context has verified successfully;
93    /// repository-controlled bytes can never manufacture it.
94    pub(crate) target_index_trust_anchor:
95        Option<vela_edge::frontier_repository::RepositoryTrustAnchor>,
96}
97
98fn repository_context_not_applicable() -> Value {
99    json!({
100        "id": REPOSITORY_CONTEXT_CHECK_ID,
101        "status": "not_applicable",
102        "valid": null,
103        "generation": null,
104        "checked": 0,
105        "failed": 0,
106        "code": null,
107        "error": null,
108        "trust_anchor_root": null,
109    })
110}
111
112fn repository_context_legacy(generation: &str) -> Value {
113    json!({
114        "id": REPOSITORY_CONTEXT_CHECK_ID,
115        "status": "pass",
116        "valid": true,
117        "generation": generation,
118        "checked": 1,
119        "failed": 0,
120        "code": null,
121        "error": null,
122        "trust_anchor_root": null,
123        "compatibility": "read_only_replay",
124    })
125}
126
127fn repository_context_invalid(code: &str, message: impl Into<String>) -> Value {
128    json!({
129        "id": REPOSITORY_CONTEXT_CHECK_ID,
130        "status": "fail",
131        "valid": false,
132        "generation": "profile_v1",
133        "checked": 1,
134        "failed": 1,
135        "code": code,
136        "error": message.into(),
137        "trust_anchor_root": null,
138    })
139}
140
141fn repository_context_suggestion(code: &str) -> &'static str {
142    match code {
143        "repository_trust_anchor_required" => {
144            "Inspect the exact first administrator boundary, then install its independently reviewed consumer pin with `vela frontier trust pin`; never derive trust from repository bytes alone."
145        }
146        "repository_trust_anchor_invalid" => {
147            "Restore the exact independently reviewed consumer pin or stop using this checkout; an invalid or mismatched pin grants no repository-boundary validity."
148        }
149        "repository_boundary_invalid" => {
150            "Restore complete Git ancestry and the exact anchored repository bytes. Missing, forked, non-ancestor, or root-mismatched boundaries grant no exemption."
151        }
152        "frontier_profile_upgrade_required" => {
153            "Legacy v0.1 remains readable, but Profile v1 identity events require a valid closed frontier.yaml; use the reviewed migration flow instead of hand-editing it."
154        }
155        _ => {
156            "Restore the exact Profile v1 repository, canonical event projection, and independently pinned boundary context before relying on repository identity."
157        }
158    }
159}
160
161/// Inspect the repository-generation and boundary context used by read-side
162/// verification.
163///
164/// This function is deliberately read-only. Profile v0.1 remains replayable.
165/// Profile v1 reuses the canonical write gate's complete profile, settings,
166/// replay, actor/retained-byte, Git-anchor, and external trust-pin validation,
167/// but does not acquire a transaction barrier or create a journal.
168pub(crate) fn repository_context_assessment_with_home(
169    source: &Path,
170    trusted_home: Option<&Path>,
171) -> RepositoryContextAssessment {
172    use vela_edge::frontier_repository::RepositoryTrustAnchor;
173    use vela_edge::repository_write::{
174        RepositoryWriteGateCode, VerifiedRepositoryIdentity,
175        load_repository_trust_anchor_from_home, verify_repository_for_write,
176    };
177    use vela_protocol::events::EVENT_KIND_FRONTIER_REPOSITORY_BOUND;
178    use vela_protocol::frontier_repo::{FrontierProfileFile, read_repository_profile};
179
180    let repository = frontier_dir_for_source(source);
181    if !repository.join(".vela").is_dir() && !repository.join("frontier.yaml").exists() {
182        return RepositoryContextAssessment {
183            payload: repository_context_not_applicable(),
184            target_index_trust_anchor: None,
185        };
186    }
187
188    let profile = match read_repository_profile(repository) {
189        Ok(Some(profile)) => profile,
190        Ok(None) => {
191            return RepositoryContextAssessment {
192                payload: repository_context_invalid(
193                    RepositoryWriteGateCode::FrontierProfileInvalid.as_str(),
194                    "frontier.yaml is missing; repository generation and identity context are unknown",
195                ),
196                target_index_trust_anchor: None,
197            };
198        }
199        Err(error) => {
200            return RepositoryContextAssessment {
201                payload: repository_context_invalid(
202                    RepositoryWriteGateCode::FrontierProfileInvalid.as_str(),
203                    error,
204                ),
205                target_index_trust_anchor: None,
206            };
207        }
208    };
209
210    match profile {
211        FrontierProfileFile::LegacyV0_1(_) => RepositoryContextAssessment {
212            payload: repository_context_legacy("legacy_v0_1"),
213            target_index_trust_anchor: None,
214        },
215        FrontierProfileFile::V1(_) => {
216            let project = match repo::load_from_path(source) {
217                Ok(project) => project,
218                Err(error) => {
219                    return RepositoryContextAssessment {
220                        payload: repository_context_invalid(
221                            RepositoryWriteGateCode::RepositoryIdentityInvalid.as_str(),
222                            format!("load Profile v1 repository for context verification: {error}"),
223                        ),
224                        target_index_trust_anchor: None,
225                    };
226                }
227            };
228            let has_administrator_boundary = project
229                .events
230                .iter()
231                .any(|event| event.kind.as_str() == EVENT_KIND_FRONTIER_REPOSITORY_BOUND);
232            let loaded_anchor = if has_administrator_boundary {
233                let home = match trusted_home {
234                    Some(home) => std::fs::canonicalize(home).map_err(|error| {
235                        format!("resolve operating-system account home for trust store: {error}")
236                    }),
237                    None => crate::frontier_txn::operating_system_account_home()
238                        .map_err(|error| error.to_string())
239                        .and_then(|home| {
240                            std::fs::canonicalize(&home).map_err(|error| {
241                                format!(
242                                    "resolve operating-system account home for trust store: {error}"
243                                )
244                            })
245                        }),
246                };
247                let home = match home {
248                    Ok(home) => home,
249                    Err(error) => {
250                        return RepositoryContextAssessment {
251                            payload: repository_context_invalid(
252                                RepositoryWriteGateCode::RepositoryTrustAnchorInvalid.as_str(),
253                                error,
254                            ),
255                            target_index_trust_anchor: None,
256                        };
257                    }
258                };
259                match load_repository_trust_anchor_from_home(&home, &project.frontier_id()) {
260                    Ok(anchor) => anchor,
261                    Err(error) => {
262                        return RepositoryContextAssessment {
263                            payload: repository_context_invalid(
264                                RepositoryWriteGateCode::RepositoryTrustAnchorInvalid.as_str(),
265                                error,
266                            ),
267                            target_index_trust_anchor: None,
268                        };
269                    }
270                }
271            } else {
272                None
273            };
274            match verify_repository_for_write(
275                repository,
276                &project,
277                loaded_anchor.as_ref().map(|loaded| &loaded.anchor),
278            ) {
279                Ok(context) => {
280                    let target_index_trust_anchor =
281                        loaded_anchor.as_ref().map(|loaded| RepositoryTrustAnchor {
282                            boundary_content_root: loaded.anchor.boundary_content_root.clone(),
283                            administrator_public_key: loaded
284                                .anchor
285                                .administrator_public_key
286                                .clone(),
287                        });
288                    let (identity_mode, trust_anchor_root) = match context.identity {
289                        VerifiedRepositoryIdentity::Genesis { .. } => ("genesis", None),
290                        VerifiedRepositoryIdentity::PinnedBoundary {
291                            trust_anchor_root, ..
292                        } => ("pinned_boundary", Some(trust_anchor_root)),
293                    };
294                    RepositoryContextAssessment {
295                        payload: json!({
296                            "id": REPOSITORY_CONTEXT_CHECK_ID,
297                            "status": "pass",
298                            "valid": true,
299                            "generation": "profile_v1",
300                            "checked": 1,
301                            "failed": 0,
302                            "code": null,
303                            "error": null,
304                            "frontier_id": context.frontier_id,
305                            "profile_root": context.profile.profile_root,
306                            "identity_root": context.profile.identity_root,
307                            "identity_event_root": context.profile.identity_event_root,
308                            "scientific_state_root": context.profile.scientific_state_root,
309                            "identity_mode": identity_mode,
310                            "trust_anchor_root": trust_anchor_root,
311                        }),
312                        target_index_trust_anchor,
313                    }
314                }
315                Err(error) => RepositoryContextAssessment {
316                    payload: repository_context_invalid(error.code.as_str(), error.message),
317                    target_index_trust_anchor: None,
318                },
319            }
320        }
321    }
322}
323
324fn repository_context_check_with_home(source: &Path, trusted_home: Option<&Path>) -> Value {
325    repository_context_assessment_with_home(source, trusted_home).payload
326}
327
328pub(crate) fn repository_context_assessment(source: &Path) -> RepositoryContextAssessment {
329    repository_context_assessment_with_home(source, None)
330}
331
332pub(crate) fn repository_context_check(source: &Path) -> Value {
333    repository_context_assessment(source).payload
334}
335
336pub(crate) fn check_json_payload(src: &Path, schema_only: bool, strict: bool) -> Value {
337    check_json_payload_with_home(src, schema_only, strict, None)
338}
339
340fn check_json_payload_with_home(
341    src: &Path,
342    schema_only: bool,
343    strict: bool,
344    trusted_home: Option<&Path>,
345) -> Value {
346    let report = validate::validate(src);
347    let loaded = repo::load_from_path(src).ok();
348    let (method_report, graph_report) = if schema_only {
349        (None, None)
350    } else if let Some(frontier) = loaded.as_ref() {
351        (
352            Some(lint::lint(frontier, None, None)),
353            Some(lint::lint_frontier(frontier)),
354        )
355    } else {
356        (None, None)
357    };
358    let source_hash = hash_path(src).unwrap_or_else(|_| "unavailable".to_string());
359    let repository_context = if schema_only {
360        repository_context_not_applicable()
361    } else {
362        repository_context_check_with_home(src, trusted_home)
363    };
364    let mut diagnostics = Vec::new();
365    diagnostics.extend(report.errors.iter().map(|e| {
366        json!({
367            "severity": "error",
368            "rule_id": "schema",
369            "finding_id": null,
370            "file": &e.file,
371            "field_path": null,
372            "message": &e.error,
373            "suggestion": schema_error_suggestion(&e.error),
374            "fixable": schema_error_fix(&e.error),
375            "normalize_action": schema_error_action(&e.error),
376        })
377    }));
378    for (check_id, lint_report) in [
379        ("methodology", method_report.as_ref()),
380        ("frontier_graph", graph_report.as_ref()),
381    ] {
382        if let Some(lint_report) = lint_report {
383            diagnostics.extend(lint_report.diagnostics.iter().map(|d| {
384                json!({
385                    "severity": d.severity.to_string(),
386                    "rule_id": &d.rule_id,
387                    "check": check_id,
388                    "finding_id": &d.finding_id,
389                    "field_path": null,
390                    "message": &d.message,
391                    "suggestion": &d.suggestion,
392                    "fixable": false,
393                    "normalize_action": null,
394                })
395            }));
396        }
397    }
398    let method_errors = method_report.as_ref().map_or(0, |r| r.errors);
399    let method_warnings = method_report.as_ref().map_or(0, |r| r.warnings);
400    let method_infos = method_report.as_ref().map_or(0, |r| r.infos);
401    let graph_errors = graph_report.as_ref().map_or(0, |r| r.errors);
402    let graph_warnings = graph_report.as_ref().map_or(0, |r| r.warnings);
403    let graph_infos = graph_report.as_ref().map_or(0, |r| r.infos);
404    let replay_report = loaded.as_ref().map(events::replay_report);
405    let state_integrity_report = if schema_only {
406        loaded.as_ref().map(state_integrity::analyze)
407    } else {
408        state_integrity::analyze_path(src).ok()
409    };
410    if let Some(replay) = replay_report.as_ref()
411        && !replay.ok
412    {
413        diagnostics.extend(replay.conflicts.iter().map(|conflict| {
414            json!({
415                "severity": "error",
416                "rule_id": "event_replay",
417                "check": "events",
418                "finding_id": null,
419                "field_path": null,
420                "message": conflict,
421                "suggestion": "Inspect canonical state events and repair the frontier event log before proof export.",
422                "fixable": false,
423                "normalize_action": null,
424            })
425        }));
426    }
427    // Review-decision parity: a stored proposal status with no signed,
428    // replayable decision event behind it is a tamper-evidence failure.
429    let parity_conflicts: Vec<String> = loaded
430        .as_ref()
431        .map(vela_protocol::proposals::verify_proposal_decision_parity)
432        .unwrap_or_default();
433    if !parity_conflicts.is_empty() {
434        diagnostics.extend(parity_conflicts.iter().map(|conflict| {
435            json!({
436                "severity": "error",
437                "rule_id": "review_decision_parity",
438                "check": "proposals",
439                "finding_id": null,
440                "field_path": null,
441                "message": conflict,
442                "suggestion": "Every decided proposal must have a signed review.* event (or, for accepts, its domain event). Re-issue the decision through `vela sign`.",
443                "fixable": false,
444                "normalize_action": null,
445            })
446        }));
447    }
448    let withdrawal_conflicts: Vec<String> = loaded
449        .as_ref()
450        .map(|frontier| {
451            vela_protocol::proposals::verify_proposal_withdrawals(
452                frontier_dir_for_source(src),
453                frontier,
454            )
455        })
456        .unwrap_or_default();
457    diagnostics.extend(withdrawal_conflicts.iter().map(|conflict| {
458        json!({
459            "severity": "error",
460            "rule_id": "invalid_proposal_withdrawal",
461            "check": "proposals",
462            "finding_id": null,
463            "field_path": null,
464            "message": conflict,
465            "suggestion": "Treat the proposal as pending and restore the exact Receipt-bound signed withdrawal bytes.",
466            "fixable": false,
467            "normalize_action": null,
468        })
469    }));
470    if repository_context.get("valid").and_then(Value::as_bool) == Some(false) {
471        let code = repository_context
472            .get("code")
473            .and_then(Value::as_str)
474            .unwrap_or("repository_boundary_invalid");
475        let message = repository_context
476            .get("error")
477            .and_then(Value::as_str)
478            .unwrap_or("Profile v1 repository context did not validate");
479        diagnostics.push(json!({
480            "severity": "warning",
481            "rule_id": code,
482            "check": REPOSITORY_CONTEXT_CHECK_ID,
483            "finding_id": null,
484            "field_path": "frontier.yaml|events[frontier.repository_bound]|git|<os-account-home>/.vela/trust/frontiers",
485            "message": message,
486            "suggestion": repository_context_suggestion(code),
487            "fixable": false,
488            "normalize_action": null,
489        }));
490    }
491    // Active-pair integrity and current Permit readiness are assessed once.
492    // Historical admissions remain the separate strict `policy_lane` check.
493    let frontier_dir = frontier_dir_for_source(src);
494    let active_policy_result = if !schema_only && loaded.is_some() {
495        Some(active_policy_pair_snapshot(src))
496    } else {
497        None
498    };
499    let observed_at = chrono::Utc::now().to_rfc3339();
500    let active_policy_assessment =
501        active_policy_result
502            .as_ref()
503            .zip(loaded.as_ref())
504            .map(|(result, frontier)| {
505                vela_protocol::proposals::policy_accept::assess_policy_readiness(
506                    frontier,
507                    result.as_ref().map_err(String::as_str),
508                    &observed_at,
509                )
510            });
511    let active_policy_errors = active_policy_result
512        .as_ref()
513        .and_then(|result| result.as_ref().err())
514        .cloned()
515        .into_iter()
516        .collect::<Vec<_>>();
517    let policy_readiness_errors = active_policy_assessment
518        .as_ref()
519        .filter(|assessment| {
520            assessment.state() != vela_protocol::proposals::policy_accept::PolicyState::Broken
521                && assessment.permit_readiness()
522                    == vela_protocol::proposals::policy_accept::PermitReadiness::Blocked
523        })
524        .map(|assessment| {
525            assessment
526                .detail()
527                .unwrap_or("policy readiness assessment is blocked")
528                .to_string()
529        })
530        .into_iter()
531        .collect::<Vec<_>>();
532    diagnostics.extend(active_policy_errors.iter().map(|error| {
533        json!({
534            "severity": "error",
535            "rule_id": "active_policy_integrity",
536            "check": "active_policy",
537            "finding_id": null,
538            "field_path": ".vela/policies/{active.json,active.sig.json}",
539            "message": error,
540            "suggestion": "Restore the exact active-policy pair or retire legacy bytes through the signed human governance ceremony; invalid policy bytes never fail open.",
541            "fixable": false,
542            "normalize_action": null,
543        })
544    }));
545    diagnostics.extend(policy_readiness_errors.iter().map(|error| {
546        json!({
547            "severity": "error",
548            "rule_id": "policy_head_integrity",
549            "check": "policy_readiness",
550            "finding_id": null,
551            "field_path": "events[governance.policy_head]",
552            "message": error,
553            "suggestion": "Repair the signed policy-head chain through the human governance ceremony; malformed authority history never fails open.",
554            "fixable": false,
555            "normalize_action": null,
556        })
557    }));
558    let policy_lane_errors = if strict && !schema_only {
559        loaded
560            .as_ref()
561            .map(|frontier| {
562                vela_protocol::proposals::policy_accept::verify_policy_lane_events(
563                    frontier,
564                    frontier_dir,
565                )
566            })
567            .unwrap_or_default()
568    } else {
569        Vec::new()
570    };
571    diagnostics.extend(policy_lane_errors.iter().map(|conflict| {
572        json!({
573            "severity": "error",
574            "rule_id": "policy_lane_replay",
575            "check": "policy_lane",
576            "finding_id": null,
577            "field_path": "events[].payload.policy_lane",
578            "message": conflict,
579            "suggestion": "Restore the exact retained receipt, review material, signed policy snapshot, and causal policy-lane event; do not hand-edit accepted state.",
580            "fixable": false,
581            "normalize_action": null,
582        })
583    }));
584    // Activity/state boundary: an activity-plane id (vac_/vrr_) in a
585    // lineage-bearing position of accepted state is a soundness break (activity
586    // is non-authoritative). Counted as a hard error, strict or not.
587    let activity_leaks: Vec<(String, String)> = loaded
588        .as_ref()
589        .map(|f| {
590            vela_protocol::activity::activity_ids_in_lineage(&f.findings, &f.verifier_attachments)
591        })
592        .unwrap_or_default();
593    diagnostics.extend(activity_leaks.iter().map(|(holder, atom)| {
594        json!({
595            "severity": "error",
596            "rule_id": "activity_state_boundary",
597            "check": "lineage",
598            "finding_id": holder,
599            "field_path": null,
600            "message": format!(
601                "{holder} references activity-plane id {atom} in a lineage-bearing position; activity is non-authoritative and cannot enter accepted lineage"
602            ),
603            "suggestion": "Remove the activity id from the finding link / verifier attachment; reference the trace by content address in the activity plane instead.",
604            "fixable": false,
605            "normalize_action": null,
606        })
607    }));
608    let activity_leak_errors = activity_leaks.len();
609    let event_errors = replay_report
610        .as_ref()
611        .map_or(0, |replay| usize::from(!replay.ok))
612        + usize::from(!parity_conflicts.is_empty())
613        + policy_lane_errors.len();
614    let state_integrity_errors = state_integrity_report
615        .as_ref()
616        .map_or(0, |report| report.structural_errors.len());
617    let (source_registry, evidence_atoms, conditions, proposal_summary, proof_state) = loaded
618        .as_ref()
619        .map(|frontier| {
620            (
621                sources::source_summary(frontier),
622                sources::evidence_summary(frontier),
623                sources::condition_summary(frontier),
624                proposals::summary(frontier),
625                proposals::proof_state_json(&frontier.proof_state),
626            )
627        })
628        .unwrap_or_else(|| {
629            (
630                sources::SourceRegistrySummary::default(),
631                sources::EvidenceAtomSummary::default(),
632                sources::ConditionSummary::default(),
633                proposals::ProposalSummary::default(),
634                Value::Null,
635            )
636        });
637    if let Some(frontier) = loaded.as_ref()
638        && !schema_only
639    {
640        let projection = sources::derive_projection(frontier);
641        let existing_sources = frontier
642            .sources
643            .iter()
644            .map(|source| source.id.as_str())
645            .collect::<std::collections::BTreeSet<_>>();
646        let existing_atoms = frontier
647            .evidence_atoms
648            .iter()
649            .map(|atom| atom.id.as_str())
650            .collect::<std::collections::BTreeSet<_>>();
651        let existing_conditions = frontier
652            .condition_records
653            .iter()
654            .map(|record| record.id.as_str())
655            .collect::<std::collections::BTreeSet<_>>();
656        for source in projection
657            .sources
658            .iter()
659            .filter(|source| !existing_sources.contains(source.id.as_str()))
660        {
661            diagnostics.push(json!({
662                "severity": "warning",
663                "rule_id": "missing_source_record",
664                "check": "source_registry",
665                "finding_id": source.finding_ids.first(),
666                "field_path": "sources",
667                "message": format!("Source record {} is derivable but not materialized in frontier state.", source.id),
668                "suggestion": "Run `vela frontier materialize` to regenerate derived views before proof export.",
669                "fixable": true,
670                "normalize_action": "materialize_source_record",
671            }));
672        }
673        for atom in projection
674            .evidence_atoms
675            .iter()
676            .filter(|atom| !existing_atoms.contains(atom.id.as_str()))
677        {
678            diagnostics.push(json!({
679                "severity": "warning",
680                "rule_id": "missing_evidence_atom",
681                "check": "evidence_atoms",
682                "finding_id": atom.finding_id,
683                "field_path": "evidence_atoms",
684                "message": format!("Evidence atom {} is derivable but not materialized in frontier state.", atom.id),
685                "suggestion": "Run `vela frontier materialize .` to rebuild evidence atoms before proof export.",
686                "fixable": true,
687                "normalize_action": "materialize_evidence_atom",
688            }));
689        }
690        for condition in projection
691            .condition_records
692            .iter()
693            .filter(|condition| !existing_conditions.contains(condition.id.as_str()))
694        {
695            diagnostics.push(json!({
696                "severity": "warning",
697                "rule_id": "condition_record_missing",
698                "check": "conditions",
699                "finding_id": condition.finding_id,
700                "field_path": "condition_records",
701                "message": format!("Condition record {} is derivable but not materialized in frontier state.", condition.id),
702                "suggestion": "Run `vela frontier materialize .` to rebuild condition boundaries before proof export.",
703                "fixable": true,
704                "normalize_action": "materialize_condition_record",
705            }));
706        }
707        for proposal in frontier.proposals.iter().filter(|proposal| {
708            matches!(proposal.status.as_str(), "accepted" | "applied")
709                && proposal
710                    .reviewed_by
711                    .as_deref()
712                    .is_none_or(proposals::is_placeholder_reviewer)
713        }) {
714            diagnostics.push(json!({
715                "severity": "error",
716                "rule_id": "reviewer_identity_missing",
717                "check": "proposals",
718                "finding_id": proposal.target.id,
719                "field_path": "proposals[].reviewed_by",
720                "message": format!("Accepted or applied proposal {} uses a missing or placeholder reviewer identity.", proposal.id),
721                "suggestion": "Accept the proposal with a stable named reviewer id before strict proof use.",
722                "fixable": false,
723                "normalize_action": null,
724            }));
725        }
726    }
727    let signal_report = loaded
728        .as_ref()
729        .map(|frontier| {
730            signals::analyze_at(frontier, &diagnostics, Some(frontier_dir_for_source(src)))
731        })
732        .unwrap_or_else(empty_signal_report);
733    let errors = report.errors.len()
734        + method_errors
735        + graph_errors
736        + event_errors
737        + state_integrity_errors
738        + active_policy_errors.len()
739        + policy_readiness_errors.len()
740        + activity_leak_errors;
741    let warnings = method_warnings + graph_warnings + signal_report.proof_readiness.warnings;
742    let infos = method_infos + graph_infos;
743    let strict_blockers = signal_report
744        .signals
745        .iter()
746        .filter(|signal| signal.blocks.iter().any(|block| block == "strict_check"))
747        .count();
748    let fixable = diagnostics
749        .iter()
750        .filter(|d| d.get("fixable").and_then(Value::as_bool).unwrap_or(false))
751        .count();
752    let ok = errors == 0 && (!strict || (warnings == 0 && strict_blockers == 0));
753
754    json!({
755        "ok": ok,
756        "command": "check",
757        "schema_version": project::VELA_SCHEMA_VERSION,
758        "source": {
759            "path": src.display().to_string(),
760            "hash": format!("sha256:{source_hash}"),
761        },
762        "summary": {
763            "status": if ok { "pass" } else { "fail" },
764            "checked_findings": report.total_files,
765            "valid_findings": report.valid,
766            "invalid_findings": report.invalid,
767            "errors": errors,
768            "warnings": warnings,
769            "info": infos,
770            "fixable": fixable,
771            "strict": strict,
772            "schema_only": schema_only,
773        },
774        "checks": [
775            {
776                "id": "schema",
777                "status": if report.invalid == 0 { "pass" } else { "fail" },
778                "checked": report.total_files,
779                "failed": report.invalid,
780                "errors": report.errors.iter().map(|e| json!({
781                    "file": e.file,
782                    "message": e.error,
783                })).collect::<Vec<_>>(),
784            },
785            {
786                "id": "methodology",
787                "status": if method_errors == 0 { "pass" } else { "fail" },
788                "checked": method_report.as_ref().map_or(0, |r| r.findings_checked),
789                "failed": method_errors,
790                "warnings": method_warnings,
791                "info": method_infos,
792                "skipped": schema_only,
793            },
794            {
795                "id": "frontier_graph",
796                "status": if graph_errors == 0 { "pass" } else { "fail" },
797                "checked": graph_report.as_ref().map_or(0, |r| r.findings_checked),
798                "failed": graph_errors,
799                "warnings": graph_warnings,
800                "info": graph_infos,
801                "skipped": schema_only,
802            },
803            {
804                "id": "signals",
805                "status": if strict_blockers == 0 { "pass" } else { "fail" },
806                "checked": signal_report.signals.len(),
807                "failed": strict_blockers,
808                "warnings": signal_report.proof_readiness.warnings,
809                "skipped": loaded.is_none(),
810                "blockers": signal_report.signals.iter()
811                    .filter(|s| s.blocks.iter().any(|b| b == "strict_check"))
812                    .map(|s| json!({
813                        "id": s.id,
814                        "kind": s.kind,
815                        "severity": s.severity,
816                        "reason": s.reason,
817                    }))
818                    .collect::<Vec<_>>(),
819            },
820            {
821                "id": "events",
822                "status": if replay_report.as_ref().is_none_or(|replay| replay.ok) { "pass" } else { "fail" },
823                "checked": replay_report.as_ref().map_or(0, |replay| replay.event_log.count),
824                "failed": event_errors,
825                "skipped": schema_only || loaded.is_none(),
826            },
827            {
828                "id": "state_integrity",
829                "status": if state_integrity_report.as_ref().is_none_or(|report| report.status != "fail") { "pass" } else { "fail" },
830                "checked": state_integrity_report.as_ref().map_or(0, |report| report.summary.get("events").copied().unwrap_or_default()),
831                "failed": state_integrity_errors,
832                "skipped": schema_only || loaded.is_none(),
833            },
834            {
835                "id": "active_policy",
836                "status": if active_policy_errors.is_empty() { "pass" } else { "fail" },
837                "checked": usize::from(active_policy_result.is_some()),
838                "failed": active_policy_errors.len(),
839                "errors": active_policy_errors,
840                "state": active_policy_assessment.as_ref().map(|assessment| assessment.state().as_str()),
841                "permit_readiness": active_policy_assessment.as_ref().map(|assessment| assessment.permit_readiness().as_str()),
842                "reason_codes": active_policy_assessment.as_ref().map(|assessment| assessment.reason_codes()).unwrap_or_default(),
843                "skipped": active_policy_result.is_none(),
844            },
845            {
846                "id": "policy_readiness",
847                "status": if policy_readiness_errors.is_empty() { "pass" } else { "fail" },
848                "checked": usize::from(active_policy_assessment.is_some()),
849                "failed": policy_readiness_errors.len(),
850                "errors": policy_readiness_errors,
851                "state": active_policy_assessment.as_ref().map(|assessment| assessment.state().as_str()),
852                "permit_readiness": active_policy_assessment.as_ref().map(|assessment| assessment.permit_readiness().as_str()),
853                "reason_codes": active_policy_assessment.as_ref().map(|assessment| assessment.reason_codes()).unwrap_or_default(),
854                "skipped": active_policy_assessment.as_ref().is_none_or(|assessment| assessment.state()
855                    == vela_protocol::proposals::policy_accept::PolicyState::Broken),
856            },
857            {
858                "id": "policy_lane",
859                "status": if policy_lane_errors.is_empty() { "pass" } else { "fail" },
860                "checked": loaded.as_ref().map_or(0, |frontier| frontier.events.iter()
861                    .filter(|event| event.payload.get(vela_protocol::proposals::policy_accept::POLICY_LANE_PAYLOAD_KEY).is_some())
862                    .count()),
863                "failed": policy_lane_errors.len(),
864                "errors": policy_lane_errors,
865                "skipped": !strict || schema_only || loaded.is_none(),
866            },
867            repository_context.clone(),
868        ],
869        "event_log": replay_report.as_ref().map(|replay| &replay.event_log),
870        "replay": replay_report,
871        "state_integrity": state_integrity_report,
872        "source_registry": source_registry,
873        "evidence_atoms": evidence_atoms,
874        "conditions": conditions,
875        "proposals": proposal_summary,
876        "proof_state": proof_state,
877        "repository_context": repository_context,
878        "diagnostics": diagnostics,
879        "signals": signal_report.signals,
880        "review_queue": signal_report.review_queue,
881        "proof_readiness": signal_report.proof_readiness,
882        "repair_plan": build_repair_plan(&diagnostics),
883    })
884}
885
886pub(crate) fn save_recorded_proof_state(
887    frontier: &Path,
888    loaded: &project::Project,
889) -> Result<(), String> {
890    // For a split `.vela` repo, the canonical proof state lives in
891    // .vela/proof-state.json — what `load` and Evidence CI's `proof.freshness`
892    // read. `proof_load_path` resolves a repo to its compatibility
893    // `frontier.json`, so a naive file-patch here would record the proof state
894    // into that snapshot only and leave the canonical .vela state stale (the
895    // observed three-source divergence). When the target is a repo dir, or a
896    // `frontier.json` sitting inside one, save through the canonical repo path
897    // so .vela/proof-state.json and the regenerated lock both reflect the
898    // export.
899    let repo_dir = if frontier.is_dir() && frontier.join(".vela").is_dir() {
900        Some(frontier.to_path_buf())
901    } else if frontier.is_file()
902        && frontier.file_name().is_some_and(|n| n == "frontier.json")
903        && frontier.parent().is_some_and(|p| p.join(".vela").is_dir())
904    {
905        frontier.parent().map(Path::to_path_buf)
906    } else {
907        None
908    };
909    if let Some(dir) = repo_dir {
910        let journal_dir = crate::workflow::frontier_transaction_journal_dir(&dir)?;
911        let write_barrier = crate::workflow::acquire_canonical_write_barrier(&dir, &journal_dir)
912            .map_err(|error| error.to_string())?;
913        let managed = repo::render_vela_repo_files(&dir, loaded)?;
914        let writes = crate::frontier_txn::PlannedWrite::from_managed_files(managed)
915            .map_err(|error| error.to_string())?;
916        let request = vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
917            "schema": "vela.proof-state-recording.internal.v1",
918            "frontier_id": loaded.frontier_id(),
919            "proof_state": &loaded.proof_state,
920        }))?;
921        crate::frontier_txn::execute_no_event_transaction(
922            write_barrier,
923            &dir,
924            "proof-state-recording",
925            crate::frontier_txn::ContentDigest::hash(request),
926            &chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, true),
927            loaded,
928            writes,
929            Vec::new(),
930            serde_json::json!({
931                "schema": "vela.proof-state-recording-result.internal.v1",
932            }),
933        )
934        .map_err(|error| error.to_string())?;
935        return Ok(());
936    }
937
938    if !frontier.is_file() {
939        let journal_dir = crate::workflow::frontier_transaction_journal_dir(frontier)?;
940        let write_barrier =
941            crate::workflow::acquire_canonical_write_barrier(frontier, &journal_dir)
942                .map_err(|error| error.to_string())?;
943        let managed = repo::render_vela_repo_files(frontier, loaded)?;
944        let writes = crate::frontier_txn::PlannedWrite::from_managed_files(managed)
945            .map_err(|error| error.to_string())?;
946        let request = vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
947            "schema": "vela.proof-state-recording.internal.v1",
948            "frontier_id": loaded.frontier_id(),
949            "proof_state": &loaded.proof_state,
950        }))?;
951        crate::frontier_txn::execute_no_event_transaction(
952            write_barrier,
953            frontier,
954            "proof-state-recording",
955            crate::frontier_txn::ContentDigest::hash(request),
956            &chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, true),
957            loaded,
958            writes,
959            Vec::new(),
960            serde_json::json!({
961                "schema": "vela.proof-state-recording-result.internal.v1",
962            }),
963        )
964        .map_err(|error| error.to_string())?;
965        return Ok(());
966    }
967
968    Err(format!(
969        "frontier_profile_upgrade_required: proof-state recording cannot rewrite legacy standalone snapshot '{}'; migrate it to a Profile v1 repository first",
970        frontier.display()
971    ))
972}
973
974pub(crate) fn hash_path(path: &Path) -> Result<String, String> {
975    let mut hasher = Sha256::new();
976    if path.is_file() {
977        let bytes = std::fs::read(path)
978            .map_err(|e| format!("Failed to read {} for hashing: {e}", path.display()))?;
979        hasher.update(&bytes);
980    } else if path.is_dir() {
981        let mut files = Vec::new();
982        collect_hash_files(path, path, &mut files)?;
983        files.sort();
984        for rel in files {
985            hasher.update(rel.to_string_lossy().as_bytes());
986            let bytes = std::fs::read(path.join(&rel))
987                .map_err(|e| format!("Failed to read {} for hashing: {e}", rel.display()))?;
988            hasher.update(bytes);
989        }
990    } else {
991        return Err(format!("Cannot hash missing path {}", path.display()));
992    }
993    Ok(format!("{:x}", hasher.finalize()))
994}
995
996pub(crate) fn load_frontier_or_fail(path: &Path) -> project::Project {
997    repo::load_from_path(path).unwrap_or_else(|e| {
998        fail_return(&format!(
999            "Failed to load frontier '{}': {e}",
1000            path.display()
1001        ))
1002    })
1003}
1004
1005pub(crate) fn hash_path_or_fail(path: &Path) -> String {
1006    hash_path(path).unwrap_or_else(|e| {
1007        fail_return(&format!(
1008            "Failed to hash frontier '{}': {e}",
1009            path.display()
1010        ))
1011    })
1012}
1013
1014fn collect_hash_files(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
1015    for entry in
1016        std::fs::read_dir(dir).map_err(|e| format!("Failed to read {}: {e}", dir.display()))?
1017    {
1018        let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
1019        let path = entry.path();
1020        if path.is_dir() {
1021            collect_hash_files(root, &path, files)?;
1022        } else if path.is_file() {
1023            files.push(
1024                path.strip_prefix(root)
1025                    .map_err(|e| e.to_string())?
1026                    .to_path_buf(),
1027            );
1028        }
1029    }
1030    Ok(())
1031}
1032
1033fn schema_error_suggestion(error: &str) -> &'static str {
1034    if schema_error_action(error).is_some() {
1035        "Run `vela frontier materialize .` to rebuild deterministic frontier state."
1036    } else {
1037        "Inspect and correct the referenced frontier field."
1038    }
1039}
1040
1041fn schema_error_fix(error: &str) -> bool {
1042    schema_error_action(error).is_some()
1043}
1044
1045fn schema_error_action(error: &str) -> Option<&'static str> {
1046    if error.contains("stats.findings")
1047        || error.contains("stats.links")
1048        || error.contains("Invalid compiler")
1049        || error.contains("Invalid vela_version")
1050        || error.contains("Invalid schema")
1051    {
1052        Some("normalize_metadata_and_stats")
1053    } else if error.contains("does not match content-address") {
1054        Some("rewrite_ids")
1055    } else {
1056        None
1057    }
1058}
1059
1060fn build_repair_plan(diagnostics: &[Value]) -> Vec<Value> {
1061    let mut actions = std::collections::BTreeMap::<String, usize>::new();
1062    for diagnostic in diagnostics {
1063        if let Some(action) = diagnostic.get("normalize_action").and_then(Value::as_str) {
1064            *actions.entry(action.to_string()).or_default() += 1;
1065        }
1066    }
1067    actions
1068        .into_iter()
1069        .map(|(action, count)| {
1070            let command = if action == "rewrite_ids" {
1071                "vela normalize <frontier> --write --rewrite-ids --id-map id-map.json"
1072            } else {
1073                "vela normalize <frontier> --write"
1074            };
1075            json!({
1076                "action": action,
1077                "count": count,
1078                "command": command,
1079            })
1080        })
1081        .collect()
1082}
1083
1084fn empty_signal_report() -> signals::SignalReport {
1085    signals::SignalReport {
1086        schema: "vela.signals.v0".to_string(),
1087        frontier: "unavailable".to_string(),
1088        signals: Vec::new(),
1089        review_queue: Vec::new(),
1090        proof_readiness: signals::ProofReadiness {
1091            status: "unavailable".to_string(),
1092            blockers: 0,
1093            warnings: 0,
1094            caveats: vec!["Frontier could not be loaded for signal analysis.".to_string()],
1095        },
1096    }
1097}
1098
1099#[cfg(test)]
1100mod write_gate_tests {
1101    use super::*;
1102
1103    #[test]
1104    fn legacy_standalone_proof_state_save_requires_profile_upgrade_without_writes() {
1105        let temp = tempfile::tempdir().unwrap();
1106        let path = temp.path().join("frontier.json");
1107        let project = project::assemble("legacy proof fixture", Vec::new(), 0, 0, "fixture");
1108        let mut bytes = serde_json::to_vec_pretty(&project).unwrap();
1109        bytes.push(b'\n');
1110        std::fs::write(&path, &bytes).unwrap();
1111
1112        let error = save_recorded_proof_state(&path, &project).unwrap_err();
1113        assert!(
1114            error.contains("frontier_profile_upgrade_required"),
1115            "{error}"
1116        );
1117        assert_eq!(std::fs::read(&path).unwrap(), bytes);
1118    }
1119}
1120
1121#[cfg(test)]
1122mod repository_context_tests {
1123    use super::*;
1124    use ed25519_dalek::SigningKey;
1125    use std::collections::BTreeMap;
1126    use vela_edge::repository_write::{
1127        REPOSITORY_TRUST_ANCHOR_SCHEMA_V1, RepositoryTrustAnchorV1,
1128        install_repository_trust_anchor_from_home,
1129    };
1130    use vela_protocol::frontier_profile::FrontierProfileV1;
1131    use vela_protocol::frontier_repo::{
1132        FrontierProfileFile, ProfileV1InitOptions, initialize_profile_v1_minimal,
1133        read_repository_profile,
1134    };
1135    use vela_protocol::frontier_repository::{
1136        FRONTIER_REPOSITORY_BOUNDARY_SCHEMA, FrontierIdentityV1, FrontierRepositoryBoundaryMode,
1137        FrontierRepositoryBoundaryPayloadV1, FrontierRepositoryTrustMode, GitObjectFormat,
1138        exact_dependency_root, new_repository_boundary_event,
1139        repository_boundary_event_content_root, repository_boundary_payload_from_event_shape,
1140        repository_identity_event_content_root,
1141    };
1142    use vela_protocol::sign::{ActorRecord, pubkey_hex, sign_event};
1143
1144    #[derive(Clone, Copy)]
1145    enum AnchorCase {
1146        Valid,
1147        WrongTree,
1148        NonAncestor,
1149    }
1150
1151    struct BoundRepositoryFixture {
1152        repo: tempfile::TempDir,
1153        home: tempfile::TempDir,
1154        anchor: RepositoryTrustAnchorV1,
1155    }
1156
1157    fn git(repo: &Path, args: &[&str]) -> String {
1158        let output = std::process::Command::new("git")
1159            .arg("-C")
1160            .arg(repo)
1161            .args(args)
1162            .output()
1163            .unwrap();
1164        assert!(
1165            output.status.success(),
1166            "git {}: {}",
1167            args.join(" "),
1168            String::from_utf8_lossy(&output.stderr)
1169        );
1170        String::from_utf8_lossy(&output.stdout).trim().to_string()
1171    }
1172
1173    fn profile(repository: &Path) -> FrontierProfileV1 {
1174        match read_repository_profile(repository).unwrap().unwrap() {
1175            FrontierProfileFile::V1(profile) => profile,
1176            FrontierProfileFile::LegacyV0_1(_) => panic!("expected Profile v1"),
1177        }
1178    }
1179
1180    fn bound_repository(case: AnchorCase) -> BoundRepositoryFixture {
1181        let repo = tempfile::tempdir().unwrap();
1182        let home = tempfile::tempdir().unwrap();
1183        initialize_profile_v1_minimal(
1184            repo.path(),
1185            ProfileV1InitOptions {
1186                name: "Read context fixture",
1187                scope: "Does read-side verification fail closed over repository context?",
1188                initialize_git: false,
1189            },
1190        )
1191        .unwrap();
1192        let mut project = repo::load_from_path(repo.path()).unwrap();
1193        let genesis = project.events.first().unwrap().clone();
1194        let identity = FrontierIdentityV1::from_genesis_event(&genesis).unwrap();
1195        let key = SigningKey::from_bytes(&[73; 32]);
1196        let actor = ActorRecord {
1197            id: "reviewer:repository-administrator".to_string(),
1198            public_key: pubkey_hex(&key),
1199            algorithm: "ed25519".to_string(),
1200            created_at: "2026-07-23T00:00:00Z".to_string(),
1201            tier: None,
1202            orcid: None,
1203            access_clearance: None,
1204            revoked_at: None,
1205            revoked_reason: None,
1206        };
1207        project.actors = vec![actor.clone()];
1208        repo::save_to_path(repo.path(), &project).unwrap();
1209
1210        git(repo.path(), &["init", "-q", "-b", "main"]);
1211        git(repo.path(), &["config", "user.name", "Vela Test"]);
1212        git(
1213            repo.path(),
1214            &["config", "user.email", "vela@example.invalid"],
1215        );
1216        git(repo.path(), &["add", "."]);
1217        git(repo.path(), &["commit", "-qm", "repository anchor"]);
1218        let main_commit = git(repo.path(), &["rev-parse", "HEAD^{commit}"]);
1219        let anchor_commit = if matches!(case, AnchorCase::NonAncestor) {
1220            git(repo.path(), &["checkout", "-qb", "fork"]);
1221            git(
1222                repo.path(),
1223                &["commit", "--allow-empty", "-qm", "fork-only anchor"],
1224            );
1225            let fork = git(repo.path(), &["rev-parse", "HEAD^{commit}"]);
1226            git(repo.path(), &["checkout", "-q", "main"]);
1227            fork
1228        } else {
1229            main_commit
1230        };
1231        let facts = vela_edge::frontier_repository::derive_repository_anchor_facts(
1232            repo.path(),
1233            &anchor_commit,
1234        )
1235        .unwrap();
1236        let mut anchor_tree = facts.git_tree;
1237        if matches!(case, AnchorCase::WrongTree) {
1238            anchor_tree = if facts.git_object_format == GitObjectFormat::Sha1 {
1239                "0".repeat(40)
1240            } else {
1241                "0".repeat(64)
1242            };
1243        }
1244        let mut boundary = new_repository_boundary_event(
1245            FrontierRepositoryBoundaryPayloadV1 {
1246                schema: FRONTIER_REPOSITORY_BOUNDARY_SCHEMA.to_string(),
1247                mode: FrontierRepositoryBoundaryMode::UpdateDependencies,
1248                frontier_id: identity.frontier_id.clone(),
1249                identity_root: identity.root().unwrap(),
1250                observed_profile_root: profile(repo.path()).profile_root().unwrap(),
1251                dependency_root: exact_dependency_root(&[]).unwrap(),
1252                dependencies: Vec::new(),
1253                previous_identity_event_root: Some(
1254                    repository_identity_event_content_root(&genesis).unwrap(),
1255                ),
1256                legacy_identity_preimage_root: None,
1257                administrator_actor_id: actor.id,
1258                administrator_public_key: actor.public_key,
1259                administrator_algorithm: actor.algorithm,
1260                trust_mode: FrontierRepositoryTrustMode::Genesis,
1261                git_object_format: facts.git_object_format,
1262                anchor_git_commit: facts.git_commit,
1263                anchor_git_tree: anchor_tree,
1264                anchor_event_log_root: facts.event_log_root,
1265                anchor_event_count: facts.event_count,
1266                anchor_snapshot_root: facts.snapshot_root,
1267                anchor_snapshot_schema: facts.snapshot_schema,
1268                anchor_proposal_root: facts.proposal_root,
1269                anchor_actor_registry_root: facts.actor_registry_root,
1270                anchor_artifact_registry_root: facts.artifact_registry_root,
1271                anchor_canonical_store_root: facts.canonical_store_root,
1272            },
1273            "bind exact repository context",
1274            "2026-07-23T00:01:00Z",
1275        )
1276        .unwrap();
1277        boundary.signature = Some(sign_event(&boundary, &key).unwrap());
1278        let payload = repository_boundary_payload_from_event_shape(&boundary).unwrap();
1279        let anchor = RepositoryTrustAnchorV1 {
1280            schema: REPOSITORY_TRUST_ANCHOR_SCHEMA_V1.to_string(),
1281            frontier_id: payload.frontier_id,
1282            identity_root: payload.identity_root,
1283            boundary_content_root: repository_boundary_event_content_root(&boundary).unwrap(),
1284            administrator_actor_id: payload.administrator_actor_id,
1285            administrator_public_key: payload.administrator_public_key,
1286        };
1287        project.events.push(boundary);
1288        repo::save_to_path(repo.path(), &project).unwrap();
1289        vela_protocol::frontier_repo::materialize(repo.path()).unwrap();
1290        git(repo.path(), &["add", "."]);
1291        git(
1292            repo.path(),
1293            &[
1294                "commit",
1295                "-qm",
1296                "bind repository and materialize exact views",
1297            ],
1298        );
1299
1300        BoundRepositoryFixture { repo, home, anchor }
1301    }
1302
1303    fn snapshot_without_git(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
1304        fn visit(root: &Path, current: &Path, files: &mut BTreeMap<PathBuf, Vec<u8>>) {
1305            for entry in std::fs::read_dir(current).unwrap() {
1306                let path = entry.unwrap().path();
1307                if path.file_name().is_some_and(|name| name == ".git") {
1308                    continue;
1309                }
1310                if path.is_dir() {
1311                    visit(root, &path, files);
1312                } else if path.is_file() {
1313                    files.insert(
1314                        path.strip_prefix(root).unwrap().to_path_buf(),
1315                        std::fs::read(&path).unwrap(),
1316                    );
1317                }
1318            }
1319        }
1320        let mut files = BTreeMap::new();
1321        visit(root, root, &mut files);
1322        files
1323    }
1324
1325    fn repository_signal(payload: &Value, kind: &str) -> Option<Value> {
1326        payload
1327            .get("signals")
1328            .and_then(Value::as_array)
1329            .and_then(|signals| {
1330                signals
1331                    .iter()
1332                    .find(|signal| signal.get("kind").and_then(Value::as_str) == Some(kind))
1333            })
1334            .cloned()
1335    }
1336
1337    #[test]
1338    fn strict_nonstrict_invalid_boundary_no_exemption() {
1339        let fixture = bound_repository(AnchorCase::WrongTree);
1340        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1341        let repository_before = snapshot_without_git(fixture.repo.path());
1342        let trust_before = snapshot_without_git(fixture.home.path());
1343
1344        let non_strict = check_json_payload_with_home(
1345            fixture.repo.path(),
1346            false,
1347            false,
1348            Some(fixture.home.path()),
1349        );
1350        assert_eq!(
1351            non_strict
1352                .pointer("/summary/strict")
1353                .and_then(Value::as_bool),
1354            Some(false)
1355        );
1356        assert_eq!(
1357            non_strict
1358                .pointer("/repository_context/status")
1359                .and_then(Value::as_str),
1360            Some("fail")
1361        );
1362        assert_eq!(
1363            non_strict
1364                .pointer("/repository_context/valid")
1365                .and_then(Value::as_bool),
1366            Some(false)
1367        );
1368        assert!(
1369            non_strict
1370                .pointer("/repository_context/error")
1371                .and_then(Value::as_str)
1372                .is_some_and(|error| error.contains("anchor_git_tree mismatch")),
1373            "{}",
1374            non_strict
1375        );
1376        let signal = repository_signal(&non_strict, "repository_boundary_invalid").unwrap();
1377        assert!(
1378            signal
1379                .get("blocks")
1380                .and_then(Value::as_array)
1381                .is_some_and(|blocks| blocks.iter().any(|block| block == "strict_check"))
1382        );
1383        assert!(
1384            signal
1385                .get("caveats")
1386                .and_then(Value::as_array)
1387                .is_some_and(|caveats| caveats.iter().any(|caveat| caveat
1388                    .as_str()
1389                    .is_some_and(|text| text.contains("grants no identity"))))
1390        );
1391
1392        let strict = check_json_payload_with_home(
1393            fixture.repo.path(),
1394            false,
1395            true,
1396            Some(fixture.home.path()),
1397        );
1398        assert_eq!(strict.get("ok").and_then(Value::as_bool), Some(false));
1399        assert_eq!(
1400            strict
1401                .pointer("/repository_context/valid")
1402                .and_then(Value::as_bool),
1403            Some(false)
1404        );
1405        assert!(repository_signal(&strict, "repository_boundary_invalid").is_some());
1406        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1407        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1408    }
1409
1410    #[test]
1411    fn repository_context_rejects_nonancestor_anchor() {
1412        let fixture = bound_repository(AnchorCase::NonAncestor);
1413        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1414        let repository_before = snapshot_without_git(fixture.repo.path());
1415        let trust_before = snapshot_without_git(fixture.home.path());
1416        let checked =
1417            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1418        assert_eq!(
1419            checked.get("code").and_then(Value::as_str),
1420            Some("repository_boundary_invalid")
1421        );
1422        assert!(
1423            checked
1424                .get("error")
1425                .and_then(Value::as_str)
1426                .is_some_and(|error| error.contains("not an ancestor")),
1427            "{checked}"
1428        );
1429        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1430        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1431    }
1432
1433    #[test]
1434    fn repository_context_requires_and_matches_external_pin() {
1435        let fixture = bound_repository(AnchorCase::Valid);
1436        let repository_before = snapshot_without_git(fixture.repo.path());
1437        let empty_home = snapshot_without_git(fixture.home.path());
1438        let missing =
1439            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1440        assert_eq!(
1441            missing.get("code").and_then(Value::as_str),
1442            Some("repository_trust_anchor_required")
1443        );
1444        let missing_payload = check_json_payload_with_home(
1445            fixture.repo.path(),
1446            false,
1447            false,
1448            Some(fixture.home.path()),
1449        );
1450        assert!(repository_signal(&missing_payload, "repository_trust_anchor_required").is_some());
1451        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1452        assert_eq!(snapshot_without_git(fixture.home.path()), empty_home);
1453
1454        let mut mismatched = fixture.anchor.clone();
1455        mismatched.boundary_content_root = format!("sha256:{}", "f".repeat(64));
1456        install_repository_trust_anchor_from_home(fixture.home.path(), &mismatched).unwrap();
1457        let mismatched_home = snapshot_without_git(fixture.home.path());
1458        let mismatch =
1459            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1460        assert_eq!(
1461            mismatch.get("code").and_then(Value::as_str),
1462            Some("repository_trust_anchor_invalid")
1463        );
1464        assert_eq!(mismatch.get("valid").and_then(Value::as_bool), Some(false));
1465        let mismatch_payload = check_json_payload_with_home(
1466            fixture.repo.path(),
1467            false,
1468            false,
1469            Some(fixture.home.path()),
1470        );
1471        assert!(repository_signal(&mismatch_payload, "repository_trust_anchor_invalid").is_some());
1472        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1473        assert_eq!(snapshot_without_git(fixture.home.path()), mismatched_home);
1474    }
1475
1476    #[test]
1477    fn repository_context_accepts_the_exact_external_pin_without_writes() {
1478        let fixture = bound_repository(AnchorCase::Valid);
1479        let installed =
1480            install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor)
1481                .unwrap();
1482        let repository_before = snapshot_without_git(fixture.repo.path());
1483        let trust_before = snapshot_without_git(fixture.home.path());
1484
1485        let checked =
1486            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1487        assert_eq!(checked.get("status").and_then(Value::as_str), Some("pass"));
1488        assert_eq!(checked.get("valid").and_then(Value::as_bool), Some(true));
1489        assert_eq!(
1490            checked.get("identity_mode").and_then(Value::as_str),
1491            Some("pinned_boundary")
1492        );
1493        assert_eq!(
1494            checked.get("trust_anchor_root").and_then(Value::as_str),
1495            Some(installed.root.as_str())
1496        );
1497        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1498        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1499    }
1500
1501    #[test]
1502    fn github_action_profile_v1_strict_check_uses_exact_pin_without_frontier_writes() {
1503        let fixture = bound_repository(AnchorCase::Valid);
1504        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1505        let repository_before = snapshot_without_git(fixture.repo.path());
1506        let trust_before = snapshot_without_git(fixture.home.path());
1507
1508        let checked = check_json_payload_with_home(
1509            fixture.repo.path(),
1510            false,
1511            true,
1512            Some(fixture.home.path()),
1513        );
1514        assert_eq!(
1515            checked.get("ok").and_then(Value::as_bool),
1516            Some(true),
1517            "{checked}"
1518        );
1519        assert_eq!(
1520            checked
1521                .pointer("/repository_context/identity_mode")
1522                .and_then(Value::as_str),
1523            Some("pinned_boundary")
1524        );
1525        assert_eq!(
1526            checked
1527                .pointer("/repository_context/valid")
1528                .and_then(Value::as_bool),
1529            Some(true)
1530        );
1531        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1532        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1533    }
1534
1535    #[test]
1536    fn github_action_profile_v1_genesis_strict_check_needs_no_pin() {
1537        let repository = tempfile::tempdir().unwrap();
1538        let home = tempfile::tempdir().unwrap();
1539        initialize_profile_v1_minimal(
1540            repository.path(),
1541            ProfileV1InitOptions {
1542                name: "Action genesis fixture",
1543                scope: "Can strict CI verify structural genesis without inventing an administrator?",
1544                initialize_git: true,
1545            },
1546        )
1547        .unwrap();
1548        vela_protocol::frontier_repo::materialize(repository.path()).unwrap();
1549        let repository_before = snapshot_without_git(repository.path());
1550        let home_before = snapshot_without_git(home.path());
1551
1552        let checked =
1553            check_json_payload_with_home(repository.path(), false, true, Some(home.path()));
1554        assert_eq!(
1555            checked.get("ok").and_then(Value::as_bool),
1556            Some(true),
1557            "{checked}"
1558        );
1559        assert_eq!(
1560            checked
1561                .pointer("/repository_context/identity_mode")
1562                .and_then(Value::as_str),
1563            Some("genesis")
1564        );
1565        assert_eq!(snapshot_without_git(repository.path()), repository_before);
1566        assert_eq!(snapshot_without_git(home.path()), home_before);
1567    }
1568
1569    #[test]
1570    fn compact_status_fails_closed_for_missing_or_wrong_pin_and_projects_with_exact_pin() {
1571        let fixture = bound_repository(AnchorCase::Valid);
1572        let observed_at = "2026-07-23T00:02:00Z";
1573
1574        let missing = crate::cli_read::compact_status_payload_with_home(
1575            fixture.repo.path(),
1576            observed_at,
1577            Some(fixture.home.path()),
1578        )
1579        .unwrap();
1580        assert_eq!(missing.get("ok").and_then(Value::as_bool), Some(false));
1581        assert_eq!(
1582            missing.pointer("/integrity/strict").and_then(Value::as_str),
1583            Some("blocked")
1584        );
1585        assert_eq!(
1586            missing
1587                .pointer("/integrity/blockers_by_code/repository_trust_anchor_required")
1588                .and_then(Value::as_u64),
1589            Some(1)
1590        );
1591        assert_eq!(
1592            missing
1593                .pointer("/integrity/repository_context/code")
1594                .and_then(Value::as_str),
1595            Some("repository_trust_anchor_required")
1596        );
1597        assert_eq!(
1598            missing.pointer("/counts/open_work").and_then(Value::as_u64),
1599            Some(0),
1600            "unverified repository context must not grant a Target Index projection"
1601        );
1602
1603        let wrong_home = tempfile::tempdir().unwrap();
1604        let mut wrong = fixture.anchor.clone();
1605        wrong.boundary_content_root = format!("sha256:{}", "f".repeat(64));
1606        install_repository_trust_anchor_from_home(wrong_home.path(), &wrong).unwrap();
1607        let mismatched = crate::cli_read::compact_status_payload_with_home(
1608            fixture.repo.path(),
1609            observed_at,
1610            Some(wrong_home.path()),
1611        )
1612        .unwrap();
1613        assert_eq!(mismatched.get("ok").and_then(Value::as_bool), Some(false));
1614        assert_eq!(
1615            mismatched
1616                .pointer("/integrity/blockers_by_code/repository_trust_anchor_invalid")
1617                .and_then(Value::as_u64),
1618            Some(1)
1619        );
1620        assert_eq!(
1621            mismatched
1622                .pointer("/integrity/repository_context/code")
1623                .and_then(Value::as_str),
1624            Some("repository_trust_anchor_invalid")
1625        );
1626
1627        let valid_home = tempfile::tempdir().unwrap();
1628        install_repository_trust_anchor_from_home(valid_home.path(), &fixture.anchor).unwrap();
1629        let valid = crate::cli_read::compact_status_payload_with_home(
1630            fixture.repo.path(),
1631            observed_at,
1632            Some(valid_home.path()),
1633        )
1634        .unwrap();
1635        assert_eq!(valid.get("ok").and_then(Value::as_bool), Some(true));
1636        assert_eq!(
1637            valid
1638                .pointer("/integrity/repository_context/identity_mode")
1639                .and_then(Value::as_str),
1640            Some("pinned_boundary")
1641        );
1642        assert_eq!(
1643            valid
1644                .pointer("/integrity/repository_context/valid")
1645                .and_then(Value::as_bool),
1646            Some(true)
1647        );
1648        assert_eq!(
1649            valid
1650                .pointer("/roots/scientific_state_root")
1651                .and_then(Value::as_str),
1652            valid
1653                .pointer("/integrity/repository_context/scientific_state_root")
1654                .and_then(Value::as_str)
1655        );
1656        assert!(
1657            valid
1658                .pointer("/roots/legacy_snapshot_root")
1659                .and_then(Value::as_str)
1660                .is_some_and(|root| root.starts_with("sha256:"))
1661        );
1662        assert!(valid.pointer("/roots/snapshot").is_none());
1663        assert_eq!(
1664            valid.pointer("/counts/open_work").and_then(Value::as_u64),
1665            Some(1),
1666            "the exact external pin must reach the Target Index projection"
1667        );
1668    }
1669
1670    #[test]
1671    fn legacy_v0_1_read_replay_remains_compatible() {
1672        let repository = tempfile::tempdir().unwrap();
1673        vela_protocol::frontier_repo::initialize_minimal(
1674            repository.path(),
1675            vela_protocol::frontier_repo::InitOptions {
1676                name: "legacy read fixture",
1677                initialize_git: false,
1678            },
1679        )
1680        .unwrap();
1681        let checked = repository_context_check_with_home(repository.path(), None);
1682        assert_eq!(checked.get("status").and_then(Value::as_str), Some("pass"));
1683        assert_eq!(
1684            checked.get("generation").and_then(Value::as_str),
1685            Some("legacy_v0_1")
1686        );
1687        assert_eq!(
1688            checked.get("compatibility").and_then(Value::as_str),
1689            Some("read_only_replay")
1690        );
1691
1692        let status = crate::cli_read::compact_status_payload_with_home(
1693            repository.path(),
1694            "2026-07-23T00:02:00Z",
1695            None,
1696        )
1697        .unwrap();
1698        assert_eq!(
1699            status
1700                .pointer("/frontier/profile_generation")
1701                .and_then(Value::as_str),
1702            Some("legacy_v0_1")
1703        );
1704        assert_eq!(
1705            status.pointer("/roots/scientific_state_root"),
1706            Some(&Value::Null)
1707        );
1708        assert!(
1709            status
1710                .pointer("/roots/legacy_snapshot_root")
1711                .and_then(Value::as_str)
1712                .is_some_and(|root| root.starts_with("sha256:"))
1713        );
1714        assert!(status.pointer("/roots/snapshot").is_none());
1715    }
1716}