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 mut 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    // A verified pinned boundary may retain proposal IDs created under an
434    // older logical-ID preimage. The repository write gate has already proved
435    // that every such conflict existed at the exact Git anchor, that the
436    // conflicted proposal bytes remain unchanged, and that no new conflict was
437    // introduced. Report that historical debt explicitly, but do not run the
438    // context-free parity rule a second time and misclassify it as current
439    // tampering. Native Profile v1, legacy v0.1, and every invalid boundary
440    // retain the ordinary blocking behavior.
441    let preserved_legacy_parity = !parity_conflicts.is_empty()
442        && repository_context.get("valid").and_then(Value::as_bool) == Some(true)
443        && repository_context.get("generation").and_then(Value::as_str) == Some("profile_v1")
444        && repository_context
445            .get("identity_mode")
446            .and_then(Value::as_str)
447            == Some("pinned_boundary");
448    if preserved_legacy_parity {
449        repository_context["legacy_proposal_identity_debt"] = json!({
450            "classification": "anchored_immutable_unauthenticated",
451            "count": parity_conflicts.len(),
452        });
453    }
454    if !parity_conflicts.is_empty() {
455        diagnostics.extend(parity_conflicts.iter().map(|conflict| {
456            if preserved_legacy_parity {
457                json!({
458                    "severity": "info",
459                    "rule_id": "anchored_legacy_proposal_identity",
460                    "check": "proposals",
461                    "finding_id": null,
462                    "field_path": ".vela/proposals",
463                    "message": conflict,
464                    "suggestion": "Retain the exact anchored proposal bytes. The historical ID is readable but unauthenticated by the current logical-ID rule; changing it or adding another conflict fails closed.",
465                    "fixable": false,
466                    "normalize_action": null,
467                })
468            } else {
469                json!({
470                    "severity": "error",
471                    "rule_id": "review_decision_parity",
472                    "check": "proposals",
473                    "finding_id": null,
474                    "field_path": null,
475                    "message": conflict,
476                    "suggestion": "Every decided proposal must have a signed review.* event (or, for accepts, its domain event). Re-issue the decision through `vela sign`.",
477                    "fixable": false,
478                    "normalize_action": null,
479                })
480            }
481        }));
482    }
483    let withdrawal_conflicts: Vec<String> = loaded
484        .as_ref()
485        .map(|frontier| {
486            vela_protocol::proposals::verify_proposal_withdrawals(
487                frontier_dir_for_source(src),
488                frontier,
489            )
490        })
491        .unwrap_or_default();
492    diagnostics.extend(withdrawal_conflicts.iter().map(|conflict| {
493        json!({
494            "severity": "error",
495            "rule_id": "invalid_proposal_withdrawal",
496            "check": "proposals",
497            "finding_id": null,
498            "field_path": null,
499            "message": conflict,
500            "suggestion": "Treat the proposal as pending and restore the exact Receipt-bound signed withdrawal bytes.",
501            "fixable": false,
502            "normalize_action": null,
503        })
504    }));
505    if repository_context.get("valid").and_then(Value::as_bool) == Some(false) {
506        let code = repository_context
507            .get("code")
508            .and_then(Value::as_str)
509            .unwrap_or("repository_boundary_invalid");
510        let message = repository_context
511            .get("error")
512            .and_then(Value::as_str)
513            .unwrap_or("Profile v1 repository context did not validate");
514        diagnostics.push(json!({
515            "severity": "warning",
516            "rule_id": code,
517            "check": REPOSITORY_CONTEXT_CHECK_ID,
518            "finding_id": null,
519            "field_path": "frontier.yaml|events[frontier.repository_bound]|git|<os-account-home>/.vela/trust/frontiers",
520            "message": message,
521            "suggestion": repository_context_suggestion(code),
522            "fixable": false,
523            "normalize_action": null,
524        }));
525    }
526    // Active-pair integrity and current Permit readiness are assessed once.
527    // Historical admissions remain the separate strict `policy_lane` check.
528    let frontier_dir = frontier_dir_for_source(src);
529    let active_policy_result = if !schema_only && loaded.is_some() {
530        Some(active_policy_pair_snapshot(src))
531    } else {
532        None
533    };
534    let observed_at = chrono::Utc::now().to_rfc3339();
535    let active_policy_assessment =
536        active_policy_result
537            .as_ref()
538            .zip(loaded.as_ref())
539            .map(|(result, frontier)| {
540                vela_protocol::proposals::policy_accept::assess_policy_readiness(
541                    frontier,
542                    result.as_ref().map_err(String::as_str),
543                    &observed_at,
544                )
545            });
546    let active_policy_errors = active_policy_result
547        .as_ref()
548        .and_then(|result| result.as_ref().err())
549        .cloned()
550        .into_iter()
551        .collect::<Vec<_>>();
552    let policy_readiness_errors = active_policy_assessment
553        .as_ref()
554        .filter(|assessment| {
555            assessment.state() != vela_protocol::proposals::policy_accept::PolicyState::Broken
556                && assessment.permit_readiness()
557                    == vela_protocol::proposals::policy_accept::PermitReadiness::Blocked
558        })
559        .map(|assessment| {
560            assessment
561                .detail()
562                .unwrap_or("policy readiness assessment is blocked")
563                .to_string()
564        })
565        .into_iter()
566        .collect::<Vec<_>>();
567    diagnostics.extend(active_policy_errors.iter().map(|error| {
568        json!({
569            "severity": "error",
570            "rule_id": "active_policy_integrity",
571            "check": "active_policy",
572            "finding_id": null,
573            "field_path": ".vela/policies/{active.json,active.sig.json}",
574            "message": error,
575            "suggestion": "Restore the exact active-policy pair or retire legacy bytes through the signed human governance ceremony; invalid policy bytes never fail open.",
576            "fixable": false,
577            "normalize_action": null,
578        })
579    }));
580    diagnostics.extend(policy_readiness_errors.iter().map(|error| {
581        json!({
582            "severity": "error",
583            "rule_id": "policy_head_integrity",
584            "check": "policy_readiness",
585            "finding_id": null,
586            "field_path": "events[governance.policy_head]",
587            "message": error,
588            "suggestion": "Repair the signed policy-head chain through the human governance ceremony; malformed authority history never fails open.",
589            "fixable": false,
590            "normalize_action": null,
591        })
592    }));
593    let policy_lane_errors = if strict && !schema_only {
594        loaded
595            .as_ref()
596            .map(|frontier| {
597                vela_protocol::proposals::policy_accept::verify_policy_lane_events(
598                    frontier,
599                    frontier_dir,
600                )
601            })
602            .unwrap_or_default()
603    } else {
604        Vec::new()
605    };
606    diagnostics.extend(policy_lane_errors.iter().map(|conflict| {
607        json!({
608            "severity": "error",
609            "rule_id": "policy_lane_replay",
610            "check": "policy_lane",
611            "finding_id": null,
612            "field_path": "events[].payload.policy_lane",
613            "message": conflict,
614            "suggestion": "Restore the exact retained receipt, review material, signed policy snapshot, and causal policy-lane event; do not hand-edit accepted state.",
615            "fixable": false,
616            "normalize_action": null,
617        })
618    }));
619    // Activity/state boundary: an activity-plane id (vac_/vrr_) in a
620    // lineage-bearing position of accepted state is a soundness break (activity
621    // is non-authoritative). Counted as a hard error, strict or not.
622    let activity_leaks: Vec<(String, String)> = loaded
623        .as_ref()
624        .map(|f| {
625            vela_protocol::activity::activity_ids_in_lineage(&f.findings, &f.verifier_attachments)
626        })
627        .unwrap_or_default();
628    diagnostics.extend(activity_leaks.iter().map(|(holder, atom)| {
629        json!({
630            "severity": "error",
631            "rule_id": "activity_state_boundary",
632            "check": "lineage",
633            "finding_id": holder,
634            "field_path": null,
635            "message": format!(
636                "{holder} references activity-plane id {atom} in a lineage-bearing position; activity is non-authoritative and cannot enter accepted lineage"
637            ),
638            "suggestion": "Remove the activity id from the finding link / verifier attachment; reference the trace by content address in the activity plane instead.",
639            "fixable": false,
640            "normalize_action": null,
641        })
642    }));
643    let activity_leak_errors = activity_leaks.len();
644    let event_errors = replay_report
645        .as_ref()
646        .map_or(0, |replay| usize::from(!replay.ok))
647        + usize::from(!parity_conflicts.is_empty() && !preserved_legacy_parity)
648        + policy_lane_errors.len();
649    let state_integrity_errors = state_integrity_report
650        .as_ref()
651        .map_or(0, |report| report.structural_errors.len());
652    let (source_registry, evidence_atoms, conditions, proposal_summary, proof_state) = loaded
653        .as_ref()
654        .map(|frontier| {
655            (
656                sources::source_summary(frontier),
657                sources::evidence_summary(frontier),
658                sources::condition_summary(frontier),
659                proposals::summary(frontier),
660                proposals::proof_state_json(&frontier.proof_state),
661            )
662        })
663        .unwrap_or_else(|| {
664            (
665                sources::SourceRegistrySummary::default(),
666                sources::EvidenceAtomSummary::default(),
667                sources::ConditionSummary::default(),
668                proposals::ProposalSummary::default(),
669                Value::Null,
670            )
671        });
672    if let Some(frontier) = loaded.as_ref()
673        && !schema_only
674    {
675        let projection = sources::derive_projection(frontier);
676        let existing_sources = frontier
677            .sources
678            .iter()
679            .map(|source| source.id.as_str())
680            .collect::<std::collections::BTreeSet<_>>();
681        let existing_atoms = frontier
682            .evidence_atoms
683            .iter()
684            .map(|atom| atom.id.as_str())
685            .collect::<std::collections::BTreeSet<_>>();
686        let existing_conditions = frontier
687            .condition_records
688            .iter()
689            .map(|record| record.id.as_str())
690            .collect::<std::collections::BTreeSet<_>>();
691        for source in projection
692            .sources
693            .iter()
694            .filter(|source| !existing_sources.contains(source.id.as_str()))
695        {
696            diagnostics.push(json!({
697                "severity": "warning",
698                "rule_id": "missing_source_record",
699                "check": "source_registry",
700                "finding_id": source.finding_ids.first(),
701                "field_path": "sources",
702                "message": format!("Source record {} is derivable but not materialized in frontier state.", source.id),
703                "suggestion": "Run `vela frontier materialize` to regenerate derived views before proof export.",
704                "fixable": true,
705                "normalize_action": "materialize_source_record",
706            }));
707        }
708        for atom in projection
709            .evidence_atoms
710            .iter()
711            .filter(|atom| !existing_atoms.contains(atom.id.as_str()))
712        {
713            diagnostics.push(json!({
714                "severity": "warning",
715                "rule_id": "missing_evidence_atom",
716                "check": "evidence_atoms",
717                "finding_id": atom.finding_id,
718                "field_path": "evidence_atoms",
719                "message": format!("Evidence atom {} is derivable but not materialized in frontier state.", atom.id),
720                "suggestion": "Run `vela frontier materialize .` to rebuild evidence atoms before proof export.",
721                "fixable": true,
722                "normalize_action": "materialize_evidence_atom",
723            }));
724        }
725        for condition in projection
726            .condition_records
727            .iter()
728            .filter(|condition| !existing_conditions.contains(condition.id.as_str()))
729        {
730            diagnostics.push(json!({
731                "severity": "warning",
732                "rule_id": "condition_record_missing",
733                "check": "conditions",
734                "finding_id": condition.finding_id,
735                "field_path": "condition_records",
736                "message": format!("Condition record {} is derivable but not materialized in frontier state.", condition.id),
737                "suggestion": "Run `vela frontier materialize .` to rebuild condition boundaries before proof export.",
738                "fixable": true,
739                "normalize_action": "materialize_condition_record",
740            }));
741        }
742        for proposal in frontier.proposals.iter().filter(|proposal| {
743            matches!(proposal.status.as_str(), "accepted" | "applied")
744                && proposal
745                    .reviewed_by
746                    .as_deref()
747                    .is_none_or(proposals::is_placeholder_reviewer)
748        }) {
749            diagnostics.push(json!({
750                "severity": "error",
751                "rule_id": "reviewer_identity_missing",
752                "check": "proposals",
753                "finding_id": proposal.target.id,
754                "field_path": "proposals[].reviewed_by",
755                "message": format!("Accepted or applied proposal {} uses a missing or placeholder reviewer identity.", proposal.id),
756                "suggestion": "Accept the proposal with a stable named reviewer id before strict proof use.",
757                "fixable": false,
758                "normalize_action": null,
759            }));
760        }
761    }
762    let signal_report = loaded
763        .as_ref()
764        .map(|frontier| {
765            signals::analyze_at(frontier, &diagnostics, Some(frontier_dir_for_source(src)))
766        })
767        .unwrap_or_else(empty_signal_report);
768    let errors = report.errors.len()
769        + method_errors
770        + graph_errors
771        + event_errors
772        + state_integrity_errors
773        + active_policy_errors.len()
774        + policy_readiness_errors.len()
775        + activity_leak_errors;
776    let warnings = method_warnings + graph_warnings + signal_report.proof_readiness.warnings;
777    let infos = method_infos + graph_infos;
778    let strict_blockers = signal_report
779        .signals
780        .iter()
781        .filter(|signal| signal.blocks.iter().any(|block| block == "strict_check"))
782        .count();
783    let fixable = diagnostics
784        .iter()
785        .filter(|d| d.get("fixable").and_then(Value::as_bool).unwrap_or(false))
786        .count();
787    let ok = errors == 0 && (!strict || (warnings == 0 && strict_blockers == 0));
788
789    json!({
790        "ok": ok,
791        "command": "check",
792        "schema_version": project::VELA_SCHEMA_VERSION,
793        "source": {
794            "path": src.display().to_string(),
795            "hash": format!("sha256:{source_hash}"),
796        },
797        "summary": {
798            "status": if ok { "pass" } else { "fail" },
799            "checked_findings": report.total_files,
800            "valid_findings": report.valid,
801            "invalid_findings": report.invalid,
802            "errors": errors,
803            "warnings": warnings,
804            "info": infos,
805            "fixable": fixable,
806            "strict": strict,
807            "schema_only": schema_only,
808        },
809        "checks": [
810            {
811                "id": "schema",
812                "status": if report.invalid == 0 { "pass" } else { "fail" },
813                "checked": report.total_files,
814                "failed": report.invalid,
815                "errors": report.errors.iter().map(|e| json!({
816                    "file": e.file,
817                    "message": e.error,
818                })).collect::<Vec<_>>(),
819            },
820            {
821                "id": "methodology",
822                "status": if method_errors == 0 { "pass" } else { "fail" },
823                "checked": method_report.as_ref().map_or(0, |r| r.findings_checked),
824                "failed": method_errors,
825                "warnings": method_warnings,
826                "info": method_infos,
827                "skipped": schema_only,
828            },
829            {
830                "id": "frontier_graph",
831                "status": if graph_errors == 0 { "pass" } else { "fail" },
832                "checked": graph_report.as_ref().map_or(0, |r| r.findings_checked),
833                "failed": graph_errors,
834                "warnings": graph_warnings,
835                "info": graph_infos,
836                "skipped": schema_only,
837            },
838            {
839                "id": "signals",
840                "status": if strict_blockers == 0 { "pass" } else { "fail" },
841                "checked": signal_report.signals.len(),
842                "failed": strict_blockers,
843                "warnings": signal_report.proof_readiness.warnings,
844                "skipped": loaded.is_none(),
845                "blockers": signal_report.signals.iter()
846                    .filter(|s| s.blocks.iter().any(|b| b == "strict_check"))
847                    .map(|s| json!({
848                        "id": s.id,
849                        "kind": s.kind,
850                        "severity": s.severity,
851                        "reason": s.reason,
852                    }))
853                    .collect::<Vec<_>>(),
854            },
855            {
856                "id": "events",
857                "status": if replay_report.as_ref().is_none_or(|replay| replay.ok) { "pass" } else { "fail" },
858                "checked": replay_report.as_ref().map_or(0, |replay| replay.event_log.count),
859                "failed": event_errors,
860                "skipped": schema_only || loaded.is_none(),
861            },
862            {
863                "id": "state_integrity",
864                "status": if state_integrity_report.as_ref().is_none_or(|report| report.status != "fail") { "pass" } else { "fail" },
865                "checked": state_integrity_report.as_ref().map_or(0, |report| report.summary.get("events").copied().unwrap_or_default()),
866                "failed": state_integrity_errors,
867                "skipped": schema_only || loaded.is_none(),
868            },
869            {
870                "id": "active_policy",
871                "status": if active_policy_errors.is_empty() { "pass" } else { "fail" },
872                "checked": usize::from(active_policy_result.is_some()),
873                "failed": active_policy_errors.len(),
874                "errors": active_policy_errors,
875                "state": active_policy_assessment.as_ref().map(|assessment| assessment.state().as_str()),
876                "permit_readiness": active_policy_assessment.as_ref().map(|assessment| assessment.permit_readiness().as_str()),
877                "reason_codes": active_policy_assessment.as_ref().map(|assessment| assessment.reason_codes()).unwrap_or_default(),
878                "skipped": active_policy_result.is_none(),
879            },
880            {
881                "id": "policy_readiness",
882                "status": if policy_readiness_errors.is_empty() { "pass" } else { "fail" },
883                "checked": usize::from(active_policy_assessment.is_some()),
884                "failed": policy_readiness_errors.len(),
885                "errors": policy_readiness_errors,
886                "state": active_policy_assessment.as_ref().map(|assessment| assessment.state().as_str()),
887                "permit_readiness": active_policy_assessment.as_ref().map(|assessment| assessment.permit_readiness().as_str()),
888                "reason_codes": active_policy_assessment.as_ref().map(|assessment| assessment.reason_codes()).unwrap_or_default(),
889                "skipped": active_policy_assessment.as_ref().is_none_or(|assessment| assessment.state()
890                    == vela_protocol::proposals::policy_accept::PolicyState::Broken),
891            },
892            {
893                "id": "policy_lane",
894                "status": if policy_lane_errors.is_empty() { "pass" } else { "fail" },
895                "checked": loaded.as_ref().map_or(0, |frontier| frontier.events.iter()
896                    .filter(|event| event.payload.get(vela_protocol::proposals::policy_accept::POLICY_LANE_PAYLOAD_KEY).is_some())
897                    .count()),
898                "failed": policy_lane_errors.len(),
899                "errors": policy_lane_errors,
900                "skipped": !strict || schema_only || loaded.is_none(),
901            },
902            repository_context.clone(),
903        ],
904        "event_log": replay_report.as_ref().map(|replay| &replay.event_log),
905        "replay": replay_report,
906        "state_integrity": state_integrity_report,
907        "source_registry": source_registry,
908        "evidence_atoms": evidence_atoms,
909        "conditions": conditions,
910        "proposals": proposal_summary,
911        "proof_state": proof_state,
912        "repository_context": repository_context,
913        "diagnostics": diagnostics,
914        "signals": signal_report.signals,
915        "review_queue": signal_report.review_queue,
916        "proof_readiness": signal_report.proof_readiness,
917        "repair_plan": build_repair_plan(&diagnostics),
918    })
919}
920
921pub(crate) fn save_recorded_proof_state(
922    frontier: &Path,
923    loaded: &project::Project,
924) -> Result<(), String> {
925    // For a split `.vela` repo, the canonical proof state lives in
926    // .vela/proof-state.json — what `load` and Evidence CI's `proof.freshness`
927    // read. `proof_load_path` resolves a repo to its compatibility
928    // `frontier.json`, so a naive file-patch here would record the proof state
929    // into that snapshot only and leave the canonical .vela state stale (the
930    // observed three-source divergence). When the target is a repo dir, or a
931    // `frontier.json` sitting inside one, save through the canonical repo path
932    // so .vela/proof-state.json and the regenerated lock both reflect the
933    // export.
934    let repo_dir = if frontier.is_dir() && frontier.join(".vela").is_dir() {
935        Some(frontier.to_path_buf())
936    } else if frontier.is_file()
937        && frontier.file_name().is_some_and(|n| n == "frontier.json")
938        && frontier.parent().is_some_and(|p| p.join(".vela").is_dir())
939    {
940        frontier.parent().map(Path::to_path_buf)
941    } else {
942        None
943    };
944    if let Some(dir) = repo_dir {
945        let journal_dir = crate::workflow::frontier_transaction_journal_dir(&dir)?;
946        let write_barrier = crate::workflow::acquire_canonical_write_barrier(&dir, &journal_dir)
947            .map_err(|error| error.to_string())?;
948        let managed = repo::render_vela_repo_files(&dir, loaded)?;
949        let writes = crate::frontier_txn::PlannedWrite::from_managed_files(managed)
950            .map_err(|error| error.to_string())?;
951        let request = vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
952            "schema": "vela.proof-state-recording.internal.v1",
953            "frontier_id": loaded.frontier_id(),
954            "proof_state": &loaded.proof_state,
955        }))?;
956        crate::frontier_txn::execute_no_event_transaction(
957            write_barrier,
958            &dir,
959            "proof-state-recording",
960            crate::frontier_txn::ContentDigest::hash(request),
961            &chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, true),
962            loaded,
963            writes,
964            Vec::new(),
965            serde_json::json!({
966                "schema": "vela.proof-state-recording-result.internal.v1",
967            }),
968        )
969        .map_err(|error| error.to_string())?;
970        return Ok(());
971    }
972
973    if !frontier.is_file() {
974        let journal_dir = crate::workflow::frontier_transaction_journal_dir(frontier)?;
975        let write_barrier =
976            crate::workflow::acquire_canonical_write_barrier(frontier, &journal_dir)
977                .map_err(|error| error.to_string())?;
978        let managed = repo::render_vela_repo_files(frontier, loaded)?;
979        let writes = crate::frontier_txn::PlannedWrite::from_managed_files(managed)
980            .map_err(|error| error.to_string())?;
981        let request = vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
982            "schema": "vela.proof-state-recording.internal.v1",
983            "frontier_id": loaded.frontier_id(),
984            "proof_state": &loaded.proof_state,
985        }))?;
986        crate::frontier_txn::execute_no_event_transaction(
987            write_barrier,
988            frontier,
989            "proof-state-recording",
990            crate::frontier_txn::ContentDigest::hash(request),
991            &chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, true),
992            loaded,
993            writes,
994            Vec::new(),
995            serde_json::json!({
996                "schema": "vela.proof-state-recording-result.internal.v1",
997            }),
998        )
999        .map_err(|error| error.to_string())?;
1000        return Ok(());
1001    }
1002
1003    Err(format!(
1004        "frontier_profile_upgrade_required: proof-state recording cannot rewrite legacy standalone snapshot '{}'; migrate it to a Profile v1 repository first",
1005        frontier.display()
1006    ))
1007}
1008
1009pub(crate) fn hash_path(path: &Path) -> Result<String, String> {
1010    let mut hasher = Sha256::new();
1011    if path.is_file() {
1012        let bytes = std::fs::read(path)
1013            .map_err(|e| format!("Failed to read {} for hashing: {e}", path.display()))?;
1014        hasher.update(&bytes);
1015    } else if path.is_dir() {
1016        let mut files = Vec::new();
1017        collect_hash_files(path, path, &mut files)?;
1018        files.sort();
1019        for rel in files {
1020            hasher.update(rel.to_string_lossy().as_bytes());
1021            let bytes = std::fs::read(path.join(&rel))
1022                .map_err(|e| format!("Failed to read {} for hashing: {e}", rel.display()))?;
1023            hasher.update(bytes);
1024        }
1025    } else {
1026        return Err(format!("Cannot hash missing path {}", path.display()));
1027    }
1028    Ok(format!("{:x}", hasher.finalize()))
1029}
1030
1031pub(crate) fn load_frontier_or_fail(path: &Path) -> project::Project {
1032    repo::load_from_path(path).unwrap_or_else(|e| {
1033        fail_return(&format!(
1034            "Failed to load frontier '{}': {e}",
1035            path.display()
1036        ))
1037    })
1038}
1039
1040pub(crate) fn hash_path_or_fail(path: &Path) -> String {
1041    hash_path(path).unwrap_or_else(|e| {
1042        fail_return(&format!(
1043            "Failed to hash frontier '{}': {e}",
1044            path.display()
1045        ))
1046    })
1047}
1048
1049fn collect_hash_files(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
1050    for entry in
1051        std::fs::read_dir(dir).map_err(|e| format!("Failed to read {}: {e}", dir.display()))?
1052    {
1053        let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
1054        let path = entry.path();
1055        if path.is_dir() {
1056            collect_hash_files(root, &path, files)?;
1057        } else if path.is_file() {
1058            files.push(
1059                path.strip_prefix(root)
1060                    .map_err(|e| e.to_string())?
1061                    .to_path_buf(),
1062            );
1063        }
1064    }
1065    Ok(())
1066}
1067
1068fn schema_error_suggestion(error: &str) -> &'static str {
1069    if schema_error_action(error).is_some() {
1070        "Run `vela frontier materialize .` to rebuild deterministic frontier state."
1071    } else {
1072        "Inspect and correct the referenced frontier field."
1073    }
1074}
1075
1076fn schema_error_fix(error: &str) -> bool {
1077    schema_error_action(error).is_some()
1078}
1079
1080fn schema_error_action(error: &str) -> Option<&'static str> {
1081    if error.contains("stats.findings")
1082        || error.contains("stats.links")
1083        || error.contains("Invalid compiler")
1084        || error.contains("Invalid vela_version")
1085        || error.contains("Invalid schema")
1086    {
1087        Some("normalize_metadata_and_stats")
1088    } else if error.contains("does not match content-address") {
1089        Some("rewrite_ids")
1090    } else {
1091        None
1092    }
1093}
1094
1095fn build_repair_plan(diagnostics: &[Value]) -> Vec<Value> {
1096    let mut actions = std::collections::BTreeMap::<String, usize>::new();
1097    for diagnostic in diagnostics {
1098        if let Some(action) = diagnostic.get("normalize_action").and_then(Value::as_str) {
1099            *actions.entry(action.to_string()).or_default() += 1;
1100        }
1101    }
1102    actions
1103        .into_iter()
1104        .map(|(action, count)| {
1105            let command = if action == "rewrite_ids" {
1106                "vela normalize <frontier> --write --rewrite-ids --id-map id-map.json"
1107            } else {
1108                "vela normalize <frontier> --write"
1109            };
1110            json!({
1111                "action": action,
1112                "count": count,
1113                "command": command,
1114            })
1115        })
1116        .collect()
1117}
1118
1119fn empty_signal_report() -> signals::SignalReport {
1120    signals::SignalReport {
1121        schema: "vela.signals.v0".to_string(),
1122        frontier: "unavailable".to_string(),
1123        signals: Vec::new(),
1124        review_queue: Vec::new(),
1125        proof_readiness: signals::ProofReadiness {
1126            status: "unavailable".to_string(),
1127            blockers: 0,
1128            warnings: 0,
1129            caveats: vec!["Frontier could not be loaded for signal analysis.".to_string()],
1130        },
1131    }
1132}
1133
1134#[cfg(test)]
1135mod write_gate_tests {
1136    use super::*;
1137
1138    #[test]
1139    fn legacy_standalone_proof_state_save_requires_profile_upgrade_without_writes() {
1140        let temp = tempfile::tempdir().unwrap();
1141        let path = temp.path().join("frontier.json");
1142        let project = project::assemble("legacy proof fixture", Vec::new(), 0, 0, "fixture");
1143        let mut bytes = serde_json::to_vec_pretty(&project).unwrap();
1144        bytes.push(b'\n');
1145        std::fs::write(&path, &bytes).unwrap();
1146
1147        let error = save_recorded_proof_state(&path, &project).unwrap_err();
1148        assert!(
1149            error.contains("frontier_profile_upgrade_required"),
1150            "{error}"
1151        );
1152        assert_eq!(std::fs::read(&path).unwrap(), bytes);
1153    }
1154}
1155
1156#[cfg(test)]
1157mod repository_context_tests {
1158    use super::*;
1159    use ed25519_dalek::SigningKey;
1160    use std::collections::BTreeMap;
1161    use vela_edge::repository_write::{
1162        REPOSITORY_TRUST_ANCHOR_SCHEMA_V1, RepositoryTrustAnchorV1,
1163        install_repository_trust_anchor_from_home,
1164    };
1165    use vela_protocol::frontier_profile::FrontierProfileV1;
1166    use vela_protocol::frontier_repo::{
1167        FrontierProfileFile, ProfileV1InitOptions, initialize_profile_v1_minimal,
1168        read_repository_profile,
1169    };
1170    use vela_protocol::frontier_repository::{
1171        FRONTIER_REPOSITORY_BOUNDARY_SCHEMA, FrontierIdentityV1, FrontierRepositoryBoundaryMode,
1172        FrontierRepositoryBoundaryPayloadV1, FrontierRepositoryTrustMode, GitObjectFormat,
1173        exact_dependency_root, new_repository_boundary_event,
1174        repository_boundary_event_content_root, repository_boundary_payload_from_event_shape,
1175        repository_identity_event_content_root,
1176    };
1177    use vela_protocol::sign::{ActorRecord, pubkey_hex, sign_event};
1178
1179    #[derive(Clone, Copy)]
1180    enum AnchorCase {
1181        Valid,
1182        WrongTree,
1183        NonAncestor,
1184    }
1185
1186    struct BoundRepositoryFixture {
1187        repo: tempfile::TempDir,
1188        home: tempfile::TempDir,
1189        anchor: RepositoryTrustAnchorV1,
1190    }
1191
1192    fn git(repo: &Path, args: &[&str]) -> String {
1193        let output = std::process::Command::new("git")
1194            .arg("-C")
1195            .arg(repo)
1196            .args(args)
1197            .output()
1198            .unwrap();
1199        assert!(
1200            output.status.success(),
1201            "git {}: {}",
1202            args.join(" "),
1203            String::from_utf8_lossy(&output.stderr)
1204        );
1205        String::from_utf8_lossy(&output.stdout).trim().to_string()
1206    }
1207
1208    fn profile(repository: &Path) -> FrontierProfileV1 {
1209        match read_repository_profile(repository).unwrap().unwrap() {
1210            FrontierProfileFile::V1(profile) => profile,
1211            FrontierProfileFile::LegacyV0_1(_) => panic!("expected Profile v1"),
1212        }
1213    }
1214
1215    fn bound_repository_with_legacy_parity(
1216        case: AnchorCase,
1217        preserve_legacy_parity: bool,
1218    ) -> BoundRepositoryFixture {
1219        let repo = tempfile::tempdir().unwrap();
1220        let home = tempfile::tempdir().unwrap();
1221        initialize_profile_v1_minimal(
1222            repo.path(),
1223            ProfileV1InitOptions {
1224                name: "Read context fixture",
1225                scope: "Does read-side verification fail closed over repository context?",
1226                initialize_git: false,
1227            },
1228        )
1229        .unwrap();
1230        let mut project = repo::load_from_path(repo.path()).unwrap();
1231        let genesis = project.events.first().unwrap().clone();
1232        let identity = FrontierIdentityV1::from_genesis_event(&genesis).unwrap();
1233        let key = SigningKey::from_bytes(&[73; 32]);
1234        let actor = ActorRecord {
1235            id: "reviewer:repository-administrator".to_string(),
1236            public_key: pubkey_hex(&key),
1237            algorithm: "ed25519".to_string(),
1238            created_at: "2026-07-23T00:00:00Z".to_string(),
1239            tier: None,
1240            orcid: None,
1241            access_clearance: None,
1242            revoked_at: None,
1243            revoked_reason: None,
1244        };
1245        project.actors = vec![actor.clone()];
1246        if preserve_legacy_parity {
1247            let mut proposal = vela_protocol::proposals::new_proposal_at(
1248                "finding.note",
1249                vela_protocol::events::StateTarget {
1250                    r#type: "frontier".to_string(),
1251                    id: project.frontier_id(),
1252                },
1253                "agent:legacy",
1254                "agent",
1255                "retain exact legacy proposal identity",
1256                json!({"note": "legacy logical-id preimage"}),
1257                vec!["src:legacy".to_string()],
1258                vec!["historical identity is unauthenticated".to_string()],
1259                "2026-07-22T00:00:30Z",
1260            );
1261            proposal.id = "vpr_legacy000000001".to_string();
1262            project.proposals.push(proposal);
1263        }
1264        repo::save_to_path(repo.path(), &project).unwrap();
1265
1266        git(repo.path(), &["init", "-q", "-b", "main"]);
1267        git(repo.path(), &["config", "user.name", "Vela Test"]);
1268        git(
1269            repo.path(),
1270            &["config", "user.email", "vela@example.invalid"],
1271        );
1272        git(repo.path(), &["add", "."]);
1273        git(repo.path(), &["commit", "-qm", "repository anchor"]);
1274        let main_commit = git(repo.path(), &["rev-parse", "HEAD^{commit}"]);
1275        let anchor_commit = if matches!(case, AnchorCase::NonAncestor) {
1276            git(repo.path(), &["checkout", "-qb", "fork"]);
1277            git(
1278                repo.path(),
1279                &["commit", "--allow-empty", "-qm", "fork-only anchor"],
1280            );
1281            let fork = git(repo.path(), &["rev-parse", "HEAD^{commit}"]);
1282            git(repo.path(), &["checkout", "-q", "main"]);
1283            fork
1284        } else {
1285            main_commit
1286        };
1287        let facts = vela_edge::frontier_repository::derive_repository_anchor_facts(
1288            repo.path(),
1289            &anchor_commit,
1290        )
1291        .unwrap();
1292        let mut anchor_tree = facts.git_tree;
1293        if matches!(case, AnchorCase::WrongTree) {
1294            anchor_tree = if facts.git_object_format == GitObjectFormat::Sha1 {
1295                "0".repeat(40)
1296            } else {
1297                "0".repeat(64)
1298            };
1299        }
1300        let mut boundary = new_repository_boundary_event(
1301            FrontierRepositoryBoundaryPayloadV1 {
1302                schema: FRONTIER_REPOSITORY_BOUNDARY_SCHEMA.to_string(),
1303                mode: FrontierRepositoryBoundaryMode::UpdateDependencies,
1304                frontier_id: identity.frontier_id.clone(),
1305                identity_root: identity.root().unwrap(),
1306                observed_profile_root: profile(repo.path()).profile_root().unwrap(),
1307                dependency_root: exact_dependency_root(&[]).unwrap(),
1308                dependencies: Vec::new(),
1309                previous_identity_event_root: Some(
1310                    repository_identity_event_content_root(&genesis).unwrap(),
1311                ),
1312                legacy_identity_preimage_root: None,
1313                administrator_actor_id: actor.id,
1314                administrator_public_key: actor.public_key,
1315                administrator_algorithm: actor.algorithm,
1316                trust_mode: FrontierRepositoryTrustMode::Genesis,
1317                git_object_format: facts.git_object_format,
1318                anchor_git_commit: facts.git_commit,
1319                anchor_git_tree: anchor_tree,
1320                anchor_event_log_root: facts.event_log_root,
1321                anchor_event_count: facts.event_count,
1322                anchor_snapshot_root: facts.snapshot_root,
1323                anchor_snapshot_schema: facts.snapshot_schema,
1324                anchor_proposal_root: facts.proposal_root,
1325                anchor_actor_registry_root: facts.actor_registry_root,
1326                anchor_artifact_registry_root: facts.artifact_registry_root,
1327                anchor_canonical_store_root: facts.canonical_store_root,
1328            },
1329            "bind exact repository context",
1330            "2026-07-23T00:01:00Z",
1331        )
1332        .unwrap();
1333        boundary.signature = Some(sign_event(&boundary, &key).unwrap());
1334        let payload = repository_boundary_payload_from_event_shape(&boundary).unwrap();
1335        let anchor = RepositoryTrustAnchorV1 {
1336            schema: REPOSITORY_TRUST_ANCHOR_SCHEMA_V1.to_string(),
1337            frontier_id: payload.frontier_id,
1338            identity_root: payload.identity_root,
1339            boundary_content_root: repository_boundary_event_content_root(&boundary).unwrap(),
1340            administrator_actor_id: payload.administrator_actor_id,
1341            administrator_public_key: payload.administrator_public_key,
1342        };
1343        project.events.push(boundary);
1344        repo::save_to_path(repo.path(), &project).unwrap();
1345        vela_protocol::frontier_repo::materialize(repo.path()).unwrap();
1346        git(repo.path(), &["add", "."]);
1347        git(
1348            repo.path(),
1349            &[
1350                "commit",
1351                "-qm",
1352                "bind repository and materialize exact views",
1353            ],
1354        );
1355
1356        BoundRepositoryFixture { repo, home, anchor }
1357    }
1358
1359    fn bound_repository(case: AnchorCase) -> BoundRepositoryFixture {
1360        bound_repository_with_legacy_parity(case, false)
1361    }
1362
1363    fn snapshot_without_git(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
1364        fn visit(root: &Path, current: &Path, files: &mut BTreeMap<PathBuf, Vec<u8>>) {
1365            for entry in std::fs::read_dir(current).unwrap() {
1366                let path = entry.unwrap().path();
1367                if path.file_name().is_some_and(|name| name == ".git") {
1368                    continue;
1369                }
1370                if path.is_dir() {
1371                    visit(root, &path, files);
1372                } else if path.is_file() {
1373                    files.insert(
1374                        path.strip_prefix(root).unwrap().to_path_buf(),
1375                        std::fs::read(&path).unwrap(),
1376                    );
1377                }
1378            }
1379        }
1380        let mut files = BTreeMap::new();
1381        visit(root, root, &mut files);
1382        files
1383    }
1384
1385    fn repository_signal(payload: &Value, kind: &str) -> Option<Value> {
1386        payload
1387            .get("signals")
1388            .and_then(Value::as_array)
1389            .and_then(|signals| {
1390                signals
1391                    .iter()
1392                    .find(|signal| signal.get("kind").and_then(Value::as_str) == Some(kind))
1393            })
1394            .cloned()
1395    }
1396
1397    #[test]
1398    fn strict_nonstrict_invalid_boundary_no_exemption() {
1399        let fixture = bound_repository(AnchorCase::WrongTree);
1400        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1401        let repository_before = snapshot_without_git(fixture.repo.path());
1402        let trust_before = snapshot_without_git(fixture.home.path());
1403
1404        let non_strict = check_json_payload_with_home(
1405            fixture.repo.path(),
1406            false,
1407            false,
1408            Some(fixture.home.path()),
1409        );
1410        assert_eq!(
1411            non_strict
1412                .pointer("/summary/strict")
1413                .and_then(Value::as_bool),
1414            Some(false)
1415        );
1416        assert_eq!(
1417            non_strict
1418                .pointer("/repository_context/status")
1419                .and_then(Value::as_str),
1420            Some("fail")
1421        );
1422        assert_eq!(
1423            non_strict
1424                .pointer("/repository_context/valid")
1425                .and_then(Value::as_bool),
1426            Some(false)
1427        );
1428        assert!(
1429            non_strict
1430                .pointer("/repository_context/error")
1431                .and_then(Value::as_str)
1432                .is_some_and(|error| error.contains("anchor_git_tree mismatch")),
1433            "{}",
1434            non_strict
1435        );
1436        let signal = repository_signal(&non_strict, "repository_boundary_invalid").unwrap();
1437        assert!(
1438            signal
1439                .get("blocks")
1440                .and_then(Value::as_array)
1441                .is_some_and(|blocks| blocks.iter().any(|block| block == "strict_check"))
1442        );
1443        assert!(
1444            signal
1445                .get("caveats")
1446                .and_then(Value::as_array)
1447                .is_some_and(|caveats| caveats.iter().any(|caveat| caveat
1448                    .as_str()
1449                    .is_some_and(|text| text.contains("grants no identity"))))
1450        );
1451
1452        let strict = check_json_payload_with_home(
1453            fixture.repo.path(),
1454            false,
1455            true,
1456            Some(fixture.home.path()),
1457        );
1458        assert_eq!(strict.get("ok").and_then(Value::as_bool), Some(false));
1459        assert_eq!(
1460            strict
1461                .pointer("/repository_context/valid")
1462                .and_then(Value::as_bool),
1463            Some(false)
1464        );
1465        assert!(repository_signal(&strict, "repository_boundary_invalid").is_some());
1466        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1467        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1468    }
1469
1470    #[test]
1471    fn repository_context_rejects_nonancestor_anchor() {
1472        let fixture = bound_repository(AnchorCase::NonAncestor);
1473        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1474        let repository_before = snapshot_without_git(fixture.repo.path());
1475        let trust_before = snapshot_without_git(fixture.home.path());
1476        let checked =
1477            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1478        assert_eq!(
1479            checked.get("code").and_then(Value::as_str),
1480            Some("repository_boundary_invalid")
1481        );
1482        assert!(
1483            checked
1484                .get("error")
1485                .and_then(Value::as_str)
1486                .is_some_and(|error| error.contains("not an ancestor")),
1487            "{checked}"
1488        );
1489        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1490        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1491    }
1492
1493    #[test]
1494    fn repository_context_requires_and_matches_external_pin() {
1495        let fixture = bound_repository(AnchorCase::Valid);
1496        let repository_before = snapshot_without_git(fixture.repo.path());
1497        let empty_home = snapshot_without_git(fixture.home.path());
1498        let missing =
1499            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1500        assert_eq!(
1501            missing.get("code").and_then(Value::as_str),
1502            Some("repository_trust_anchor_required")
1503        );
1504        let missing_payload = check_json_payload_with_home(
1505            fixture.repo.path(),
1506            false,
1507            false,
1508            Some(fixture.home.path()),
1509        );
1510        assert!(repository_signal(&missing_payload, "repository_trust_anchor_required").is_some());
1511        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1512        assert_eq!(snapshot_without_git(fixture.home.path()), empty_home);
1513
1514        let mut mismatched = fixture.anchor.clone();
1515        mismatched.boundary_content_root = format!("sha256:{}", "f".repeat(64));
1516        install_repository_trust_anchor_from_home(fixture.home.path(), &mismatched).unwrap();
1517        let mismatched_home = snapshot_without_git(fixture.home.path());
1518        let mismatch =
1519            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1520        assert_eq!(
1521            mismatch.get("code").and_then(Value::as_str),
1522            Some("repository_trust_anchor_invalid")
1523        );
1524        assert_eq!(mismatch.get("valid").and_then(Value::as_bool), Some(false));
1525        let mismatch_payload = check_json_payload_with_home(
1526            fixture.repo.path(),
1527            false,
1528            false,
1529            Some(fixture.home.path()),
1530        );
1531        assert!(repository_signal(&mismatch_payload, "repository_trust_anchor_invalid").is_some());
1532        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1533        assert_eq!(snapshot_without_git(fixture.home.path()), mismatched_home);
1534    }
1535
1536    #[test]
1537    fn repository_context_accepts_the_exact_external_pin_without_writes() {
1538        let fixture = bound_repository(AnchorCase::Valid);
1539        let installed =
1540            install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor)
1541                .unwrap();
1542        let repository_before = snapshot_without_git(fixture.repo.path());
1543        let trust_before = snapshot_without_git(fixture.home.path());
1544
1545        let checked =
1546            repository_context_check_with_home(fixture.repo.path(), Some(fixture.home.path()));
1547        assert_eq!(checked.get("status").and_then(Value::as_str), Some("pass"));
1548        assert_eq!(checked.get("valid").and_then(Value::as_bool), Some(true));
1549        assert_eq!(
1550            checked.get("identity_mode").and_then(Value::as_str),
1551            Some("pinned_boundary")
1552        );
1553        assert_eq!(
1554            checked.get("trust_anchor_root").and_then(Value::as_str),
1555            Some(installed.root.as_str())
1556        );
1557        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1558        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1559    }
1560
1561    #[test]
1562    fn github_action_profile_v1_strict_check_uses_exact_pin_without_frontier_writes() {
1563        let fixture = bound_repository(AnchorCase::Valid);
1564        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1565        let repository_before = snapshot_without_git(fixture.repo.path());
1566        let trust_before = snapshot_without_git(fixture.home.path());
1567
1568        let checked = check_json_payload_with_home(
1569            fixture.repo.path(),
1570            false,
1571            true,
1572            Some(fixture.home.path()),
1573        );
1574        assert_eq!(
1575            checked.get("ok").and_then(Value::as_bool),
1576            Some(true),
1577            "{checked}"
1578        );
1579        assert_eq!(
1580            checked
1581                .pointer("/repository_context/identity_mode")
1582                .and_then(Value::as_str),
1583            Some("pinned_boundary")
1584        );
1585        assert_eq!(
1586            checked
1587                .pointer("/repository_context/valid")
1588                .and_then(Value::as_bool),
1589            Some(true)
1590        );
1591        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1592        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1593    }
1594
1595    #[test]
1596    fn strict_check_reports_exact_anchored_legacy_proposal_identity_without_blocking() {
1597        let fixture = bound_repository_with_legacy_parity(AnchorCase::Valid, true);
1598        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1599        let repository_before = snapshot_without_git(fixture.repo.path());
1600        let trust_before = snapshot_without_git(fixture.home.path());
1601
1602        let checked = check_json_payload_with_home(
1603            fixture.repo.path(),
1604            false,
1605            true,
1606            Some(fixture.home.path()),
1607        );
1608        assert_eq!(
1609            checked.get("ok").and_then(Value::as_bool),
1610            Some(true),
1611            "{checked}"
1612        );
1613        assert_eq!(
1614            checked
1615                .pointer("/repository_context/legacy_proposal_identity_debt/classification")
1616                .and_then(Value::as_str),
1617            Some("anchored_immutable_unauthenticated")
1618        );
1619        assert_eq!(
1620            checked
1621                .pointer("/repository_context/legacy_proposal_identity_debt/count")
1622                .and_then(Value::as_u64),
1623            Some(1)
1624        );
1625        assert!(
1626            checked
1627                .get("diagnostics")
1628                .and_then(Value::as_array)
1629                .is_some_and(|diagnostics| diagnostics.iter().any(|diagnostic| {
1630                    diagnostic.get("rule_id").and_then(Value::as_str)
1631                        == Some("anchored_legacy_proposal_identity")
1632                        && diagnostic.get("severity").and_then(Value::as_str) == Some("info")
1633                })),
1634            "{checked}"
1635        );
1636        assert!(
1637            checked
1638                .get("signals")
1639                .and_then(Value::as_array)
1640                .is_some_and(|signals| signals.iter().all(|signal| {
1641                    signal
1642                        .get("kind")
1643                        .and_then(Value::as_str)
1644                        .is_none_or(|kind| kind != "check_error")
1645                })),
1646            "{checked}"
1647        );
1648        assert_eq!(snapshot_without_git(fixture.repo.path()), repository_before);
1649        assert_eq!(snapshot_without_git(fixture.home.path()), trust_before);
1650    }
1651
1652    #[test]
1653    fn strict_check_grants_no_legacy_proposal_exemption_after_tampering() {
1654        let fixture = bound_repository_with_legacy_parity(AnchorCase::Valid, true);
1655        install_repository_trust_anchor_from_home(fixture.home.path(), &fixture.anchor).unwrap();
1656        let mut project = repo::load_from_path(fixture.repo.path()).unwrap();
1657        project.proposals[0].reason = "tampered after the signed anchor".to_string();
1658        repo::save_to_path(fixture.repo.path(), &project).unwrap();
1659
1660        let checked = check_json_payload_with_home(
1661            fixture.repo.path(),
1662            false,
1663            true,
1664            Some(fixture.home.path()),
1665        );
1666        assert_eq!(checked.get("ok").and_then(Value::as_bool), Some(false));
1667        assert_eq!(
1668            checked
1669                .pointer("/repository_context/valid")
1670                .and_then(Value::as_bool),
1671            Some(false)
1672        );
1673        assert!(
1674            checked
1675                .pointer("/repository_context/error")
1676                .and_then(Value::as_str)
1677                .is_some_and(|error| {
1678                    error.contains(
1679                        "introduced parity failures absent from the exact repository anchor",
1680                    )
1681                }),
1682            "{checked}"
1683        );
1684        assert!(
1685            checked
1686                .get("diagnostics")
1687                .and_then(Value::as_array)
1688                .is_some_and(|diagnostics| diagnostics.iter().any(|diagnostic| {
1689                    diagnostic.get("rule_id").and_then(Value::as_str)
1690                        == Some("review_decision_parity")
1691                        && diagnostic.get("severity").and_then(Value::as_str) == Some("error")
1692                })),
1693            "{checked}"
1694        );
1695        assert!(
1696            checked
1697                .pointer("/repository_context/legacy_proposal_identity_debt")
1698                .is_none()
1699        );
1700    }
1701
1702    #[test]
1703    fn github_action_profile_v1_genesis_strict_check_needs_no_pin() {
1704        let repository = tempfile::tempdir().unwrap();
1705        let home = tempfile::tempdir().unwrap();
1706        initialize_profile_v1_minimal(
1707            repository.path(),
1708            ProfileV1InitOptions {
1709                name: "Action genesis fixture",
1710                scope: "Can strict CI verify structural genesis without inventing an administrator?",
1711                initialize_git: true,
1712            },
1713        )
1714        .unwrap();
1715        vela_protocol::frontier_repo::materialize(repository.path()).unwrap();
1716        let repository_before = snapshot_without_git(repository.path());
1717        let home_before = snapshot_without_git(home.path());
1718
1719        let checked =
1720            check_json_payload_with_home(repository.path(), false, true, Some(home.path()));
1721        assert_eq!(
1722            checked.get("ok").and_then(Value::as_bool),
1723            Some(true),
1724            "{checked}"
1725        );
1726        assert_eq!(
1727            checked
1728                .pointer("/repository_context/identity_mode")
1729                .and_then(Value::as_str),
1730            Some("genesis")
1731        );
1732        assert_eq!(snapshot_without_git(repository.path()), repository_before);
1733        assert_eq!(snapshot_without_git(home.path()), home_before);
1734    }
1735
1736    #[test]
1737    fn compact_status_fails_closed_for_missing_or_wrong_pin_and_projects_with_exact_pin() {
1738        let fixture = bound_repository(AnchorCase::Valid);
1739        let observed_at = "2026-07-23T00:02:00Z";
1740
1741        let missing = crate::cli_read::compact_status_payload_with_home(
1742            fixture.repo.path(),
1743            observed_at,
1744            Some(fixture.home.path()),
1745        )
1746        .unwrap();
1747        assert_eq!(missing.get("ok").and_then(Value::as_bool), Some(false));
1748        assert_eq!(
1749            missing.pointer("/integrity/strict").and_then(Value::as_str),
1750            Some("blocked")
1751        );
1752        assert_eq!(
1753            missing
1754                .pointer("/integrity/blockers_by_code/repository_trust_anchor_required")
1755                .and_then(Value::as_u64),
1756            Some(1)
1757        );
1758        assert_eq!(
1759            missing
1760                .pointer("/integrity/repository_context/code")
1761                .and_then(Value::as_str),
1762            Some("repository_trust_anchor_required")
1763        );
1764        assert_eq!(
1765            missing.pointer("/counts/open_work").and_then(Value::as_u64),
1766            Some(0),
1767            "unverified repository context must not grant a Target Index projection"
1768        );
1769
1770        let wrong_home = tempfile::tempdir().unwrap();
1771        let mut wrong = fixture.anchor.clone();
1772        wrong.boundary_content_root = format!("sha256:{}", "f".repeat(64));
1773        install_repository_trust_anchor_from_home(wrong_home.path(), &wrong).unwrap();
1774        let mismatched = crate::cli_read::compact_status_payload_with_home(
1775            fixture.repo.path(),
1776            observed_at,
1777            Some(wrong_home.path()),
1778        )
1779        .unwrap();
1780        assert_eq!(mismatched.get("ok").and_then(Value::as_bool), Some(false));
1781        assert_eq!(
1782            mismatched
1783                .pointer("/integrity/blockers_by_code/repository_trust_anchor_invalid")
1784                .and_then(Value::as_u64),
1785            Some(1)
1786        );
1787        assert_eq!(
1788            mismatched
1789                .pointer("/integrity/repository_context/code")
1790                .and_then(Value::as_str),
1791            Some("repository_trust_anchor_invalid")
1792        );
1793
1794        let valid_home = tempfile::tempdir().unwrap();
1795        install_repository_trust_anchor_from_home(valid_home.path(), &fixture.anchor).unwrap();
1796        let valid = crate::cli_read::compact_status_payload_with_home(
1797            fixture.repo.path(),
1798            observed_at,
1799            Some(valid_home.path()),
1800        )
1801        .unwrap();
1802        assert_eq!(valid.get("ok").and_then(Value::as_bool), Some(true));
1803        assert_eq!(
1804            valid
1805                .pointer("/integrity/repository_context/identity_mode")
1806                .and_then(Value::as_str),
1807            Some("pinned_boundary")
1808        );
1809        assert_eq!(
1810            valid
1811                .pointer("/integrity/repository_context/valid")
1812                .and_then(Value::as_bool),
1813            Some(true)
1814        );
1815        assert_eq!(
1816            valid
1817                .pointer("/roots/scientific_state_root")
1818                .and_then(Value::as_str),
1819            valid
1820                .pointer("/integrity/repository_context/scientific_state_root")
1821                .and_then(Value::as_str)
1822        );
1823        assert!(
1824            valid
1825                .pointer("/roots/legacy_snapshot_root")
1826                .and_then(Value::as_str)
1827                .is_some_and(|root| root.starts_with("sha256:"))
1828        );
1829        assert!(valid.pointer("/roots/snapshot").is_none());
1830        assert_eq!(
1831            valid.pointer("/counts/open_work").and_then(Value::as_u64),
1832            Some(1),
1833            "the exact external pin must reach the Target Index projection"
1834        );
1835    }
1836
1837    #[test]
1838    fn legacy_v0_1_read_replay_remains_compatible() {
1839        let repository = tempfile::tempdir().unwrap();
1840        vela_protocol::frontier_repo::initialize_minimal(
1841            repository.path(),
1842            vela_protocol::frontier_repo::InitOptions {
1843                name: "legacy read fixture",
1844                initialize_git: false,
1845            },
1846        )
1847        .unwrap();
1848        let checked = repository_context_check_with_home(repository.path(), None);
1849        assert_eq!(checked.get("status").and_then(Value::as_str), Some("pass"));
1850        assert_eq!(
1851            checked.get("generation").and_then(Value::as_str),
1852            Some("legacy_v0_1")
1853        );
1854        assert_eq!(
1855            checked.get("compatibility").and_then(Value::as_str),
1856            Some("read_only_replay")
1857        );
1858
1859        let status = crate::cli_read::compact_status_payload_with_home(
1860            repository.path(),
1861            "2026-07-23T00:02:00Z",
1862            None,
1863        )
1864        .unwrap();
1865        assert_eq!(
1866            status
1867                .pointer("/frontier/profile_generation")
1868                .and_then(Value::as_str),
1869            Some("legacy_v0_1")
1870        );
1871        assert_eq!(
1872            status.pointer("/roots/scientific_state_root"),
1873            Some(&Value::Null)
1874        );
1875        assert!(
1876            status
1877                .pointer("/roots/legacy_snapshot_root")
1878                .and_then(Value::as_str)
1879                .is_some_and(|root| root.starts_with("sha256:"))
1880        );
1881        assert!(status.pointer("/roots/snapshot").is_none());
1882    }
1883}