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