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
86pub(crate) fn check_json_payload(src: &Path, schema_only: bool, strict: bool) -> Value {
87    let report = validate::validate(src);
88    let loaded = repo::load_from_path(src).ok();
89    let (method_report, graph_report) = if schema_only {
90        (None, None)
91    } else if let Some(frontier) = loaded.as_ref() {
92        (
93            Some(lint::lint(frontier, None, None)),
94            Some(lint::lint_frontier(frontier)),
95        )
96    } else {
97        (None, None)
98    };
99    let source_hash = hash_path(src).unwrap_or_else(|_| "unavailable".to_string());
100    let mut diagnostics = Vec::new();
101    diagnostics.extend(report.errors.iter().map(|e| {
102        json!({
103            "severity": "error",
104            "rule_id": "schema",
105            "finding_id": null,
106            "file": &e.file,
107            "field_path": null,
108            "message": &e.error,
109            "suggestion": schema_error_suggestion(&e.error),
110            "fixable": schema_error_fix(&e.error),
111            "normalize_action": schema_error_action(&e.error),
112        })
113    }));
114    for (check_id, lint_report) in [
115        ("methodology", method_report.as_ref()),
116        ("frontier_graph", graph_report.as_ref()),
117    ] {
118        if let Some(lint_report) = lint_report {
119            diagnostics.extend(lint_report.diagnostics.iter().map(|d| {
120                json!({
121                    "severity": d.severity.to_string(),
122                    "rule_id": &d.rule_id,
123                    "check": check_id,
124                    "finding_id": &d.finding_id,
125                    "field_path": null,
126                    "message": &d.message,
127                    "suggestion": &d.suggestion,
128                    "fixable": false,
129                    "normalize_action": null,
130                })
131            }));
132        }
133    }
134    let method_errors = method_report.as_ref().map_or(0, |r| r.errors);
135    let method_warnings = method_report.as_ref().map_or(0, |r| r.warnings);
136    let method_infos = method_report.as_ref().map_or(0, |r| r.infos);
137    let graph_errors = graph_report.as_ref().map_or(0, |r| r.errors);
138    let graph_warnings = graph_report.as_ref().map_or(0, |r| r.warnings);
139    let graph_infos = graph_report.as_ref().map_or(0, |r| r.infos);
140    let replay_report = loaded.as_ref().map(events::replay_report);
141    let state_integrity_report = if schema_only {
142        loaded.as_ref().map(state_integrity::analyze)
143    } else {
144        state_integrity::analyze_path(src).ok()
145    };
146    if let Some(replay) = replay_report.as_ref()
147        && !replay.ok
148    {
149        diagnostics.extend(replay.conflicts.iter().map(|conflict| {
150            json!({
151                "severity": "error",
152                "rule_id": "event_replay",
153                "check": "events",
154                "finding_id": null,
155                "field_path": null,
156                "message": conflict,
157                "suggestion": "Inspect canonical state events and repair the frontier event log before proof export.",
158                "fixable": false,
159                "normalize_action": null,
160            })
161        }));
162    }
163    // Review-decision parity: a stored proposal status with no signed,
164    // replayable decision event behind it is a tamper-evidence failure.
165    let parity_conflicts: Vec<String> = loaded
166        .as_ref()
167        .map(vela_protocol::proposals::verify_proposal_decision_parity)
168        .unwrap_or_default();
169    if !parity_conflicts.is_empty() {
170        diagnostics.extend(parity_conflicts.iter().map(|conflict| {
171            json!({
172                "severity": "error",
173                "rule_id": "review_decision_parity",
174                "check": "proposals",
175                "finding_id": null,
176                "field_path": null,
177                "message": conflict,
178                "suggestion": "Every decided proposal must have a signed review.* event (or, for accepts, its domain event). Re-issue the decision through `vela sign`.",
179                "fixable": false,
180                "normalize_action": null,
181            })
182        }));
183    }
184    let withdrawal_conflicts: Vec<String> = loaded
185        .as_ref()
186        .map(|frontier| {
187            vela_protocol::proposals::verify_proposal_withdrawals(
188                frontier_dir_for_source(src),
189                frontier,
190            )
191        })
192        .unwrap_or_default();
193    diagnostics.extend(withdrawal_conflicts.iter().map(|conflict| {
194        json!({
195            "severity": "error",
196            "rule_id": "invalid_proposal_withdrawal",
197            "check": "proposals",
198            "finding_id": null,
199            "field_path": null,
200            "message": conflict,
201            "suggestion": "Treat the proposal as pending and restore the exact Receipt-bound signed withdrawal bytes.",
202            "fixable": false,
203            "normalize_action": null,
204        })
205    }));
206    // Active-pair integrity and current Permit readiness are assessed once.
207    // Historical admissions remain the separate strict `policy_lane` check.
208    let frontier_dir = frontier_dir_for_source(src);
209    let active_policy_result = if !schema_only && loaded.is_some() {
210        Some(active_policy_pair_snapshot(src))
211    } else {
212        None
213    };
214    let observed_at = chrono::Utc::now().to_rfc3339();
215    let active_policy_assessment =
216        active_policy_result
217            .as_ref()
218            .zip(loaded.as_ref())
219            .map(|(result, frontier)| {
220                vela_protocol::proposals::policy_accept::assess_policy_readiness(
221                    frontier,
222                    result.as_ref().map_err(String::as_str),
223                    &observed_at,
224                )
225            });
226    let active_policy_errors = active_policy_result
227        .as_ref()
228        .and_then(|result| result.as_ref().err())
229        .cloned()
230        .into_iter()
231        .collect::<Vec<_>>();
232    let policy_readiness_errors = active_policy_assessment
233        .as_ref()
234        .filter(|assessment| {
235            assessment.state() != vela_protocol::proposals::policy_accept::PolicyState::Broken
236                && assessment.permit_readiness()
237                    == vela_protocol::proposals::policy_accept::PermitReadiness::Blocked
238        })
239        .map(|assessment| {
240            assessment
241                .detail()
242                .unwrap_or("policy readiness assessment is blocked")
243                .to_string()
244        })
245        .into_iter()
246        .collect::<Vec<_>>();
247    diagnostics.extend(active_policy_errors.iter().map(|error| {
248        json!({
249            "severity": "error",
250            "rule_id": "active_policy_integrity",
251            "check": "active_policy",
252            "finding_id": null,
253            "field_path": ".vela/policies/{active.json,active.sig.json}",
254            "message": error,
255            "suggestion": "Restore the exact active-policy pair or retire legacy bytes through the signed human governance ceremony; invalid policy bytes never fail open.",
256            "fixable": false,
257            "normalize_action": null,
258        })
259    }));
260    diagnostics.extend(policy_readiness_errors.iter().map(|error| {
261        json!({
262            "severity": "error",
263            "rule_id": "policy_head_integrity",
264            "check": "policy_readiness",
265            "finding_id": null,
266            "field_path": "events[governance.policy_head]",
267            "message": error,
268            "suggestion": "Repair the signed policy-head chain through the human governance ceremony; malformed authority history never fails open.",
269            "fixable": false,
270            "normalize_action": null,
271        })
272    }));
273    let policy_lane_errors = if strict && !schema_only {
274        loaded
275            .as_ref()
276            .map(|frontier| {
277                vela_protocol::proposals::policy_accept::verify_policy_lane_events(
278                    frontier,
279                    frontier_dir,
280                )
281            })
282            .unwrap_or_default()
283    } else {
284        Vec::new()
285    };
286    diagnostics.extend(policy_lane_errors.iter().map(|conflict| {
287        json!({
288            "severity": "error",
289            "rule_id": "policy_lane_replay",
290            "check": "policy_lane",
291            "finding_id": null,
292            "field_path": "events[].payload.policy_lane",
293            "message": conflict,
294            "suggestion": "Restore the exact retained receipt, review material, signed policy snapshot, and causal policy-lane event; do not hand-edit accepted state.",
295            "fixable": false,
296            "normalize_action": null,
297        })
298    }));
299    // Activity/state boundary: an activity-plane id (vac_/vrr_) in a
300    // lineage-bearing position of accepted state is a soundness break (activity
301    // is non-authoritative). Counted as a hard error, strict or not.
302    let activity_leaks: Vec<(String, String)> = loaded
303        .as_ref()
304        .map(|f| {
305            vela_protocol::activity::activity_ids_in_lineage(&f.findings, &f.verifier_attachments)
306        })
307        .unwrap_or_default();
308    diagnostics.extend(activity_leaks.iter().map(|(holder, atom)| {
309        json!({
310            "severity": "error",
311            "rule_id": "activity_state_boundary",
312            "check": "lineage",
313            "finding_id": holder,
314            "field_path": null,
315            "message": format!(
316                "{holder} references activity-plane id {atom} in a lineage-bearing position; activity is non-authoritative and cannot enter accepted lineage"
317            ),
318            "suggestion": "Remove the activity id from the finding link / verifier attachment; reference the trace by content address in the activity plane instead.",
319            "fixable": false,
320            "normalize_action": null,
321        })
322    }));
323    let activity_leak_errors = activity_leaks.len();
324    let event_errors = replay_report
325        .as_ref()
326        .map_or(0, |replay| usize::from(!replay.ok))
327        + usize::from(!parity_conflicts.is_empty())
328        + policy_lane_errors.len();
329    let state_integrity_errors = state_integrity_report
330        .as_ref()
331        .map_or(0, |report| report.structural_errors.len());
332    let (source_registry, evidence_atoms, conditions, proposal_summary, proof_state) = loaded
333        .as_ref()
334        .map(|frontier| {
335            (
336                sources::source_summary(frontier),
337                sources::evidence_summary(frontier),
338                sources::condition_summary(frontier),
339                proposals::summary(frontier),
340                proposals::proof_state_json(&frontier.proof_state),
341            )
342        })
343        .unwrap_or_else(|| {
344            (
345                sources::SourceRegistrySummary::default(),
346                sources::EvidenceAtomSummary::default(),
347                sources::ConditionSummary::default(),
348                proposals::ProposalSummary::default(),
349                Value::Null,
350            )
351        });
352    if let Some(frontier) = loaded.as_ref()
353        && !schema_only
354    {
355        let projection = sources::derive_projection(frontier);
356        let existing_sources = frontier
357            .sources
358            .iter()
359            .map(|source| source.id.as_str())
360            .collect::<std::collections::BTreeSet<_>>();
361        let existing_atoms = frontier
362            .evidence_atoms
363            .iter()
364            .map(|atom| atom.id.as_str())
365            .collect::<std::collections::BTreeSet<_>>();
366        let existing_conditions = frontier
367            .condition_records
368            .iter()
369            .map(|record| record.id.as_str())
370            .collect::<std::collections::BTreeSet<_>>();
371        for source in projection
372            .sources
373            .iter()
374            .filter(|source| !existing_sources.contains(source.id.as_str()))
375        {
376            diagnostics.push(json!({
377                "severity": "warning",
378                "rule_id": "missing_source_record",
379                "check": "source_registry",
380                "finding_id": source.finding_ids.first(),
381                "field_path": "sources",
382                "message": format!("Source record {} is derivable but not materialized in frontier state.", source.id),
383                "suggestion": "Run `vela frontier materialize` to regenerate derived views before proof export.",
384                "fixable": true,
385                "normalize_action": "materialize_source_record",
386            }));
387        }
388        for atom in projection
389            .evidence_atoms
390            .iter()
391            .filter(|atom| !existing_atoms.contains(atom.id.as_str()))
392        {
393            diagnostics.push(json!({
394                "severity": "warning",
395                "rule_id": "missing_evidence_atom",
396                "check": "evidence_atoms",
397                "finding_id": atom.finding_id,
398                "field_path": "evidence_atoms",
399                "message": format!("Evidence atom {} is derivable but not materialized in frontier state.", atom.id),
400                "suggestion": "Run `vela frontier materialize .` to rebuild evidence atoms before proof export.",
401                "fixable": true,
402                "normalize_action": "materialize_evidence_atom",
403            }));
404        }
405        for condition in projection
406            .condition_records
407            .iter()
408            .filter(|condition| !existing_conditions.contains(condition.id.as_str()))
409        {
410            diagnostics.push(json!({
411                "severity": "warning",
412                "rule_id": "condition_record_missing",
413                "check": "conditions",
414                "finding_id": condition.finding_id,
415                "field_path": "condition_records",
416                "message": format!("Condition record {} is derivable but not materialized in frontier state.", condition.id),
417                "suggestion": "Run `vela frontier materialize .` to rebuild condition boundaries before proof export.",
418                "fixable": true,
419                "normalize_action": "materialize_condition_record",
420            }));
421        }
422        for proposal in frontier.proposals.iter().filter(|proposal| {
423            matches!(proposal.status.as_str(), "accepted" | "applied")
424                && proposal
425                    .reviewed_by
426                    .as_deref()
427                    .is_none_or(proposals::is_placeholder_reviewer)
428        }) {
429            diagnostics.push(json!({
430                "severity": "error",
431                "rule_id": "reviewer_identity_missing",
432                "check": "proposals",
433                "finding_id": proposal.target.id,
434                "field_path": "proposals[].reviewed_by",
435                "message": format!("Accepted or applied proposal {} uses a missing or placeholder reviewer identity.", proposal.id),
436                "suggestion": "Accept the proposal with a stable named reviewer id before strict proof use.",
437                "fixable": false,
438                "normalize_action": null,
439            }));
440        }
441    }
442    let signal_report = loaded
443        .as_ref()
444        .map(|frontier| {
445            signals::analyze_at(frontier, &diagnostics, Some(frontier_dir_for_source(src)))
446        })
447        .unwrap_or_else(empty_signal_report);
448    let errors = report.errors.len()
449        + method_errors
450        + graph_errors
451        + event_errors
452        + state_integrity_errors
453        + active_policy_errors.len()
454        + policy_readiness_errors.len()
455        + activity_leak_errors;
456    let warnings = method_warnings + graph_warnings + signal_report.proof_readiness.warnings;
457    let infos = method_infos + graph_infos;
458    let strict_blockers = signal_report
459        .signals
460        .iter()
461        .filter(|signal| signal.blocks.iter().any(|block| block == "strict_check"))
462        .count();
463    let fixable = diagnostics
464        .iter()
465        .filter(|d| d.get("fixable").and_then(Value::as_bool).unwrap_or(false))
466        .count();
467    let ok = errors == 0 && (!strict || (warnings == 0 && strict_blockers == 0));
468
469    json!({
470        "ok": ok,
471        "command": "check",
472        "schema_version": project::VELA_SCHEMA_VERSION,
473        "source": {
474            "path": src.display().to_string(),
475            "hash": format!("sha256:{source_hash}"),
476        },
477        "summary": {
478            "status": if ok { "pass" } else { "fail" },
479            "checked_findings": report.total_files,
480            "valid_findings": report.valid,
481            "invalid_findings": report.invalid,
482            "errors": errors,
483            "warnings": warnings,
484            "info": infos,
485            "fixable": fixable,
486            "strict": strict,
487            "schema_only": schema_only,
488        },
489        "checks": [
490            {
491                "id": "schema",
492                "status": if report.invalid == 0 { "pass" } else { "fail" },
493                "checked": report.total_files,
494                "failed": report.invalid,
495                "errors": report.errors.iter().map(|e| json!({
496                    "file": e.file,
497                    "message": e.error,
498                })).collect::<Vec<_>>(),
499            },
500            {
501                "id": "methodology",
502                "status": if method_errors == 0 { "pass" } else { "fail" },
503                "checked": method_report.as_ref().map_or(0, |r| r.findings_checked),
504                "failed": method_errors,
505                "warnings": method_warnings,
506                "info": method_infos,
507                "skipped": schema_only,
508            },
509            {
510                "id": "frontier_graph",
511                "status": if graph_errors == 0 { "pass" } else { "fail" },
512                "checked": graph_report.as_ref().map_or(0, |r| r.findings_checked),
513                "failed": graph_errors,
514                "warnings": graph_warnings,
515                "info": graph_infos,
516                "skipped": schema_only,
517            },
518            {
519                "id": "signals",
520                "status": if strict_blockers == 0 { "pass" } else { "fail" },
521                "checked": signal_report.signals.len(),
522                "failed": strict_blockers,
523                "warnings": signal_report.proof_readiness.warnings,
524                "skipped": loaded.is_none(),
525                "blockers": signal_report.signals.iter()
526                    .filter(|s| s.blocks.iter().any(|b| b == "strict_check"))
527                    .map(|s| json!({
528                        "id": s.id,
529                        "kind": s.kind,
530                        "severity": s.severity,
531                        "reason": s.reason,
532                    }))
533                    .collect::<Vec<_>>(),
534            },
535            {
536                "id": "events",
537                "status": if replay_report.as_ref().is_none_or(|replay| replay.ok) { "pass" } else { "fail" },
538                "checked": replay_report.as_ref().map_or(0, |replay| replay.event_log.count),
539                "failed": event_errors,
540                "skipped": schema_only || loaded.is_none(),
541            },
542            {
543                "id": "state_integrity",
544                "status": if state_integrity_report.as_ref().is_none_or(|report| report.status != "fail") { "pass" } else { "fail" },
545                "checked": state_integrity_report.as_ref().map_or(0, |report| report.summary.get("events").copied().unwrap_or_default()),
546                "failed": state_integrity_errors,
547                "skipped": schema_only || loaded.is_none(),
548            },
549            {
550                "id": "active_policy",
551                "status": if active_policy_errors.is_empty() { "pass" } else { "fail" },
552                "checked": usize::from(active_policy_result.is_some()),
553                "failed": active_policy_errors.len(),
554                "errors": active_policy_errors,
555                "state": active_policy_assessment.as_ref().map(|assessment| assessment.state().as_str()),
556                "permit_readiness": active_policy_assessment.as_ref().map(|assessment| assessment.permit_readiness().as_str()),
557                "reason_codes": active_policy_assessment.as_ref().map(|assessment| assessment.reason_codes()).unwrap_or_default(),
558                "skipped": active_policy_result.is_none(),
559            },
560            {
561                "id": "policy_readiness",
562                "status": if policy_readiness_errors.is_empty() { "pass" } else { "fail" },
563                "checked": usize::from(active_policy_assessment.is_some()),
564                "failed": policy_readiness_errors.len(),
565                "errors": policy_readiness_errors,
566                "state": active_policy_assessment.as_ref().map(|assessment| assessment.state().as_str()),
567                "permit_readiness": active_policy_assessment.as_ref().map(|assessment| assessment.permit_readiness().as_str()),
568                "reason_codes": active_policy_assessment.as_ref().map(|assessment| assessment.reason_codes()).unwrap_or_default(),
569                "skipped": active_policy_assessment.as_ref().is_none_or(|assessment| assessment.state()
570                    == vela_protocol::proposals::policy_accept::PolicyState::Broken),
571            },
572            {
573                "id": "policy_lane",
574                "status": if policy_lane_errors.is_empty() { "pass" } else { "fail" },
575                "checked": loaded.as_ref().map_or(0, |frontier| frontier.events.iter()
576                    .filter(|event| event.payload.get(vela_protocol::proposals::policy_accept::POLICY_LANE_PAYLOAD_KEY).is_some())
577                    .count()),
578                "failed": policy_lane_errors.len(),
579                "errors": policy_lane_errors,
580                "skipped": !strict || schema_only || loaded.is_none(),
581            }
582        ],
583        "event_log": replay_report.as_ref().map(|replay| &replay.event_log),
584        "replay": replay_report,
585        "state_integrity": state_integrity_report,
586        "source_registry": source_registry,
587        "evidence_atoms": evidence_atoms,
588        "conditions": conditions,
589        "proposals": proposal_summary,
590        "proof_state": proof_state,
591        "diagnostics": diagnostics,
592        "signals": signal_report.signals,
593        "review_queue": signal_report.review_queue,
594        "proof_readiness": signal_report.proof_readiness,
595        "repair_plan": build_repair_plan(&diagnostics),
596    })
597}
598
599pub(crate) fn save_recorded_proof_state(
600    frontier: &Path,
601    loaded: &project::Project,
602) -> Result<(), String> {
603    // For a split `.vela` repo, the canonical proof state lives in
604    // .vela/proof-state.json — what `load` and Evidence CI's `proof.freshness`
605    // read. `proof_load_path` resolves a repo to its compatibility
606    // `frontier.json`, so a naive file-patch here would record the proof state
607    // into that snapshot only and leave the canonical .vela state stale (the
608    // observed three-source divergence). When the target is a repo dir, or a
609    // `frontier.json` sitting inside one, save through the canonical repo path
610    // so .vela/proof-state.json and the regenerated lock both reflect the
611    // export.
612    let repo_dir = if frontier.is_dir() && frontier.join(".vela").is_dir() {
613        Some(frontier.to_path_buf())
614    } else if frontier.is_file()
615        && frontier.file_name().is_some_and(|n| n == "frontier.json")
616        && frontier.parent().is_some_and(|p| p.join(".vela").is_dir())
617    {
618        frontier.parent().map(Path::to_path_buf)
619    } else {
620        None
621    };
622    if let Some(dir) = repo_dir {
623        return repo::save_to_path(&dir, loaded);
624    }
625
626    if !frontier.is_file() {
627        return repo::save_to_path(frontier, loaded);
628    }
629
630    let raw = std::fs::read_to_string(frontier)
631        .map_err(|e| format!("Failed to read frontier '{}': {e}", frontier.display()))?;
632    let proof_state = serde_json::to_value(&loaded.proof_state)
633        .map_err(|e| format!("serialize proof_state: {e}"))?;
634    let stats = serde_json::to_value(&loaded.stats).map_err(|e| format!("serialize stats: {e}"))?;
635    let updated = replace_top_level_json_field(&raw, "proof_state", &proof_state)
636        .and_then(|next| replace_top_level_json_field(&next, "stats", &stats))?;
637    let rendered = if updated.ends_with('\n') {
638        updated
639    } else {
640        format!("{updated}\n")
641    };
642    std::fs::write(frontier, rendered)
643        .map_err(|e| format!("Failed to write frontier '{}': {e}", frontier.display()))
644}
645
646pub(crate) fn hash_path(path: &Path) -> Result<String, String> {
647    let mut hasher = Sha256::new();
648    if path.is_file() {
649        let bytes = std::fs::read(path)
650            .map_err(|e| format!("Failed to read {} for hashing: {e}", path.display()))?;
651        hasher.update(&bytes);
652    } else if path.is_dir() {
653        let mut files = Vec::new();
654        collect_hash_files(path, path, &mut files)?;
655        files.sort();
656        for rel in files {
657            hasher.update(rel.to_string_lossy().as_bytes());
658            let bytes = std::fs::read(path.join(&rel))
659                .map_err(|e| format!("Failed to read {} for hashing: {e}", rel.display()))?;
660            hasher.update(bytes);
661        }
662    } else {
663        return Err(format!("Cannot hash missing path {}", path.display()));
664    }
665    Ok(format!("{:x}", hasher.finalize()))
666}
667
668pub(crate) fn load_frontier_or_fail(path: &Path) -> project::Project {
669    repo::load_from_path(path).unwrap_or_else(|e| {
670        fail_return(&format!(
671            "Failed to load frontier '{}': {e}",
672            path.display()
673        ))
674    })
675}
676
677pub(crate) fn hash_path_or_fail(path: &Path) -> String {
678    hash_path(path).unwrap_or_else(|e| {
679        fail_return(&format!(
680            "Failed to hash frontier '{}': {e}",
681            path.display()
682        ))
683    })
684}
685
686fn collect_hash_files(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
687    for entry in
688        std::fs::read_dir(dir).map_err(|e| format!("Failed to read {}: {e}", dir.display()))?
689    {
690        let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
691        let path = entry.path();
692        if path.is_dir() {
693            collect_hash_files(root, &path, files)?;
694        } else if path.is_file() {
695            files.push(
696                path.strip_prefix(root)
697                    .map_err(|e| e.to_string())?
698                    .to_path_buf(),
699            );
700        }
701    }
702    Ok(())
703}
704
705fn schema_error_suggestion(error: &str) -> &'static str {
706    if schema_error_action(error).is_some() {
707        "Run `vela frontier materialize .` to rebuild deterministic frontier state."
708    } else {
709        "Inspect and correct the referenced frontier field."
710    }
711}
712
713fn schema_error_fix(error: &str) -> bool {
714    schema_error_action(error).is_some()
715}
716
717fn schema_error_action(error: &str) -> Option<&'static str> {
718    if error.contains("stats.findings")
719        || error.contains("stats.links")
720        || error.contains("Invalid compiler")
721        || error.contains("Invalid vela_version")
722        || error.contains("Invalid schema")
723    {
724        Some("normalize_metadata_and_stats")
725    } else if error.contains("does not match content-address") {
726        Some("rewrite_ids")
727    } else {
728        None
729    }
730}
731
732fn build_repair_plan(diagnostics: &[Value]) -> Vec<Value> {
733    let mut actions = std::collections::BTreeMap::<String, usize>::new();
734    for diagnostic in diagnostics {
735        if let Some(action) = diagnostic.get("normalize_action").and_then(Value::as_str) {
736            *actions.entry(action.to_string()).or_default() += 1;
737        }
738    }
739    actions
740        .into_iter()
741        .map(|(action, count)| {
742            let command = if action == "rewrite_ids" {
743                "vela normalize <frontier> --write --rewrite-ids --id-map id-map.json"
744            } else {
745                "vela normalize <frontier> --write"
746            };
747            json!({
748                "action": action,
749                "count": count,
750                "command": command,
751            })
752        })
753        .collect()
754}
755
756fn empty_signal_report() -> signals::SignalReport {
757    signals::SignalReport {
758        schema: "vela.signals.v0".to_string(),
759        frontier: "unavailable".to_string(),
760        signals: Vec::new(),
761        review_queue: Vec::new(),
762        proof_readiness: signals::ProofReadiness {
763            status: "unavailable".to_string(),
764            blockers: 0,
765            warnings: 0,
766            caveats: vec!["Frontier could not be loaded for signal analysis.".to_string()],
767        },
768    }
769}