1use std::collections::BTreeMap;
8use std::fs;
9use std::path::{Component, Path};
10
11use chrono::{SecondsFormat, Utc};
12use serde::{Deserialize, Serialize};
13use serde_json::json;
14use sha2::{Digest, Sha256};
15
16use crate::events;
17use crate::frontier_profile::{
18 FRONTIER_PROFILE_SCHEMA_V1, FrontierProfileLicenseV1, FrontierProfileScopeV1, FrontierProfileV1,
19};
20use crate::frontier_settings::{FRONTIER_SETTINGS_SCHEMA, FrontierSettingsV1};
21use crate::project::{self, Project, ProjectDependency};
22use crate::proposals;
23
24pub const FRONTIER_REPO_LAYOUT: &str = "vela.frontier_repo.v0.1";
25pub const FRONTIER_REPO_LAYOUT_V1: &str = "vela.frontier_repo.v1";
26pub const FRONTIER_MANIFEST_SCHEMA: &str = "vela.frontier_manifest.v0.1";
27pub const FRONTIER_LOCK_SCHEMA: &str = "vela.frontier_lock.v0.1";
28pub const FRONTIER_LOCK_SCHEMA_V1: &str = "vela.frontier_lock.v1";
29pub const FRONTIER_INIT_SCHEMA: &str = "vela.frontier_repo_init.v0.1";
30pub const FRONTIER_INIT_SCHEMA_V1: &str = "vela.frontier_repo_init.v1";
31pub const FRONTIER_MATERIALIZE_SCHEMA: &str = "vela.frontier_materialize.v0.1";
32pub const FRONTIER_REPO_STATUS_SCHEMA: &str = "vela.frontier_repo_status.v0.1";
33pub const FRONTIER_REPO_DOCTOR_SCHEMA: &str = "vela.frontier_repo_doctor.v0.1";
34pub const FRONTIER_PROOF_VERIFY_SCHEMA: &str = "vela.frontier_proof_verify.v0.1";
35const VELA_ACTION_REPOSITORY: &str = "vela-science/vela";
36
37fn current_vela_release() -> String {
38 format!("v{}", env!("CARGO_PKG_VERSION"))
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42#[serde(deny_unknown_fields)]
43pub struct FrontierManifest {
44 pub schema: String,
45 pub layout: String,
46 #[serde(default = "default_split_mode")]
47 pub mode: String,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub frontier_id: Option<String>,
50 pub name: String,
51 #[serde(default)]
52 pub description: String,
53 #[serde(default = "default_visibility")]
54 pub visibility: String,
55 #[serde(default)]
56 pub scope: FrontierScope,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub carina: Option<LegacyCarinaManifest>,
62 pub vela: VelaManifest,
63 pub paths: FrontierPaths,
64 #[serde(default, skip_serializing_if = "Vec::is_empty")]
65 pub maintainers: Vec<ManifestMaintainer>,
66 #[serde(default)]
67 pub policies: ManifestPolicies,
68 #[serde(default)]
69 pub license: ManifestLicense,
70 #[serde(default)]
71 pub dependencies: ManifestDependencies,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
75#[serde(deny_unknown_fields)]
76pub struct LegacyCarinaManifest {
77 pub kernel: String,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum FrontierProfileFile {
87 LegacyV0_1(FrontierManifest),
88 V1(FrontierProfileV1),
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
92pub struct VelaManifest {
93 pub reducer: String,
94}
95
96#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
97pub struct FrontierScope {
98 #[serde(default)]
99 pub question: String,
100 #[serde(default)]
101 pub includes: Vec<String>,
102 #[serde(default)]
103 pub excludes: Vec<String>,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
107pub struct FrontierPaths {
108 pub state: String,
109 pub sources: String,
110 pub artifacts: String,
111 pub review: String,
112 pub proof: String,
113 pub exports: String,
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
117pub struct ManifestMaintainer {
118 pub id: String,
119 pub role: String,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
123pub struct ManifestPolicies {
124 pub review: String,
125 pub proof: String,
126 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
127 pub frontier: BTreeMap<String, String>,
128}
129
130impl Default for ManifestPolicies {
131 fn default() -> Self {
132 Self {
133 review: "review/policy.yaml".to_string(),
134 proof: "proof/policy.yaml".to_string(),
135 frontier: BTreeMap::new(),
136 }
137 }
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
141pub struct ManifestLicense {
142 pub content: String,
143 pub code: String,
144 pub data: String,
145}
146
147impl Default for ManifestLicense {
148 fn default() -> Self {
149 Self {
150 content: "CC-BY-4.0".to_string(),
151 code: "Apache-2.0".to_string(),
152 data: "varies".to_string(),
153 }
154 }
155}
156
157#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
158pub struct ManifestDependencies {
159 #[serde(default)]
160 pub frontiers: Vec<String>,
161 #[serde(default)]
162 pub packages: Vec<String>,
163 #[serde(default)]
164 pub adapters: Vec<String>,
165 #[serde(default, skip_serializing_if = "Vec::is_empty")]
172 pub frontiers_v2: Vec<ProjectDependency>,
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
176#[serde(deny_unknown_fields)]
177pub struct FrontierLock {
178 pub schema: String,
179 pub generated_at: String,
180 pub vela_version: String,
181 pub frontier_id: String,
182 #[serde(default)]
183 pub canonicalization: LockCanonicalization,
184 #[serde(default)]
185 pub reducer: LockPackage,
186 #[serde(default)]
187 pub verifiers: LockVerifiers,
188 pub snapshot_hash: String,
189 pub event_log_hash: String,
190 pub proposal_state_hash: String,
191 #[serde(default)]
192 pub sources_hash: String,
193 #[serde(default)]
194 pub artifacts_hash: String,
195 #[serde(default)]
196 pub review_hash: String,
197 pub proof_freshness: String,
198 #[serde(default)]
199 pub proof: LockProof,
200 pub paths: LockPaths,
201 #[serde(default, skip_serializing_if = "Vec::is_empty")]
212 pub dependencies: Vec<LockedDependency>,
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
222#[serde(deny_unknown_fields)]
223pub struct FrontierLockV1 {
224 pub schema: String,
225 pub generated_at: String,
226 pub vela_version: String,
227 pub frontier_id: String,
228 pub profile_root: String,
229 pub identity_root: String,
230 pub dependency_root: String,
231 pub scientific_state_root: String,
232 pub legacy_snapshot_root: String,
233 pub event_log_root: String,
234 pub event_count: u64,
235 pub proposal_root: String,
236 pub canonicalization: LockCanonicalization,
237 pub reducer: LockPackage,
238 pub verifiers: LockVerifiers,
239 pub sources_hash: String,
240 pub artifacts_hash: String,
241 pub review_hash: String,
242 pub proof_freshness: String,
243 pub proof: LockProof,
244 pub paths: LockPaths,
245 pub dependencies: Vec<crate::frontier_repository::ExactFrontierDependencyV1>,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum FrontierLockFile {
250 LegacyV0_1(FrontierLock),
251 V1(FrontierLockV1),
252}
253
254#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
260pub struct LockedDependency {
261 #[serde(default, skip_serializing_if = "String::is_empty")]
264 pub name: String,
265 pub source: String,
268 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub vfr_id: Option<String>,
271 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub locator: Option<String>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub pinned_snapshot_hash: Option<String>,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
282pub struct LockCanonicalization {
283 pub json: String,
284 pub yaml: String,
285}
286
287impl Default for LockCanonicalization {
288 fn default() -> Self {
289 Self {
290 json: "vela-canonical-json-v0.1".to_string(),
291 yaml: "vela-yaml-v0.1".to_string(),
292 }
293 }
294}
295
296#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
297pub struct LockPackage {
298 pub package: String,
299 pub digest: String,
300}
301
302#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
310pub struct LockVerifiers {
311 pub package: String,
312 pub digest: String,
313 #[serde(default, skip_serializing_if = "Vec::is_empty")]
314 pub kinds: Vec<String>,
315}
316
317#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
318pub struct LockProof {
319 pub latest: String,
320 pub digest: String,
321 pub freshness: String,
322 pub events_manifest: String,
323 pub replay_trace: String,
324}
325
326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
327pub struct LockPaths {
328 pub frontier: String,
329 pub events: String,
330}
331
332#[derive(Debug, Clone)]
333struct ProofWrite {
334 digest: String,
335 freshness: String,
336 latest: String,
337 events_manifest: String,
338 replay_trace: String,
339}
340
341pub type VisibleRepoFiles = BTreeMap<String, Vec<u8>>;
345
346#[derive(Debug, Clone)]
347struct RenderedProof {
348 files: VisibleRepoFiles,
349 proof: ProofWrite,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct RepoLayoutIssue {
354 pub rule_id: String,
355 pub message: String,
356}
357
358#[derive(Debug, Clone)]
359pub struct InitOptions<'a> {
360 pub name: &'a str,
361 pub initialize_git: bool,
362}
363
364#[derive(Debug, Clone)]
369pub struct ProfileV1InitOptions<'a> {
370 pub name: &'a str,
371 pub scope: &'a str,
372 pub initialize_git: bool,
373}
374
375pub fn initialize(path: &Path, options: InitOptions<'_>) -> Result<serde_json::Value, String> {
376 if path.exists() && !path.is_dir() {
377 return Err(format!("{} exists and is not a directory", path.display()));
378 }
379 fs::create_dir_all(path).map_err(|e| {
380 format!(
381 "Failed to create frontier directory '{}': {e}",
382 path.display()
383 )
384 })?;
385
386 let now = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true);
387 let project = empty_project(options.name, "", &now);
388 crate::repo::init_repo(path, &project)?;
389 write_frontier_card(path, options.name)?;
390 write_scope(path, options.name)?;
391 write_git_native_scaffold(path, options.name, true)?;
392 initialize_git_repository(path, options.initialize_git)?;
393
394 let payload = json!({
395 "schema": FRONTIER_INIT_SCHEMA,
396 "ok": true,
397 "layout": FRONTIER_REPO_LAYOUT,
398 "path": path.display().to_string(),
399 "name": options.name,
400 "wrote": [
401 "README.md",
402 "SCOPE.md",
403 "frontier.yaml",
404 "frontier.json",
405 "vela.lock",
406 ".gitignore",
407 ".gitattributes",
408 ".github/workflows/vela-frontier.yml",
409 "VELA.md",
410 ".mcp.json"
411 ],
412 "next_commands": init_next_commands(path)
413 });
414 Ok(payload)
415}
416
417pub fn initialize_minimal(
421 path: &Path,
422 options: InitOptions<'_>,
423) -> Result<serde_json::Value, String> {
424 let name = options.name.to_string();
425 let mut payload = initialize(path, options)?;
426 for relative in [".mcp.json", ".github/workflows/vela-frontier.yml"] {
427 let candidate = path.join(relative);
428 if candidate.is_file() {
429 fs::remove_file(&candidate)
430 .map_err(|error| format!("remove {}: {error}", candidate.display()))?;
431 }
432 }
433 let proof_dir = path.join("proof");
434 if proof_dir.exists() {
435 fs::remove_dir_all(&proof_dir)
436 .map_err(|error| format!("remove {}: {error}", proof_dir.display()))?;
437 }
438 let project = crate::repo::load_from_path(path)?;
439 let generated_at = materialization_generated_at(path, &project);
440 let empty_proof = ProofWrite {
441 digest: directory_hash(&proof_dir),
442 freshness: "not_materialized".to_string(),
443 latest: String::new(),
444 events_manifest: String::new(),
445 replay_trace: String::new(),
446 };
447 write_lock(path, &project, &empty_proof, &generated_at)?;
448 payload["name"] = json!(name);
449 payload["wrote"] = json!([
450 "README.md",
451 "SCOPE.md",
452 "frontier.yaml",
453 "frontier.json",
454 "vela.lock",
455 ".gitignore",
456 ".gitattributes",
457 "VELA.md"
458 ]);
459 payload["next_commands"] = json!([
460 format!(
461 "vela doctor {} --json",
462 posix_shell_arg(&path.display().to_string())
463 ),
464 format!(
465 "vela status {} --json",
466 posix_shell_arg(&path.display().to_string())
467 ),
468 format!(
469 "vela next {} --json",
470 posix_shell_arg(&path.display().to_string())
471 )
472 ]);
473 Ok(payload)
474}
475
476pub fn initialize_profile_v1_minimal(
481 path: &Path,
482 options: ProfileV1InitOptions<'_>,
483) -> Result<serde_json::Value, String> {
484 let name = options.name.trim();
485 let scope = options.scope.trim();
486 if name.is_empty() {
487 return Err("Profile v1 initialization requires a non-empty name".to_string());
488 }
489 if scope.is_empty() {
490 return Err("Profile v1 initialization requires a non-empty bounded scope".to_string());
491 }
492
493 let target_existed = match fs::symlink_metadata(path) {
494 Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
495 return Err(format!(
496 "{} must be a real directory or an absent path",
497 path.display()
498 ));
499 }
500 Ok(_) => {
501 let mut entries = fs::read_dir(path)
502 .map_err(|error| format!("inspect init target '{}': {error}", path.display()))?;
503 if entries
504 .next()
505 .transpose()
506 .map_err(|error| format!("inspect init target '{}': {error}", path.display()))?
507 .is_some()
508 {
509 return Err(format!(
510 "refusing to initialize non-empty directory {}; adopt an existing repository through the explicit migration path",
511 path.display()
512 ));
513 }
514 true
515 }
516 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
517 fs::create_dir_all(path).map_err(|error| {
518 format!(
519 "Failed to create frontier directory '{}': {error}",
520 path.display()
521 )
522 })?;
523 false
524 }
525 Err(error) => {
526 return Err(format!("inspect init target '{}': {error}", path.display()));
527 }
528 };
529
530 let staging = tempfile::Builder::new()
534 .prefix(".vela-init-")
535 .tempdir_in(path)
536 .map_err(|error| format!("create initialization staging directory: {error}"))?;
537 let staged = initialize_profile_v1_minimal_in_place(staging.path(), &options);
538 let mut payload = match staged {
539 Ok(payload) => payload,
540 Err(error) => {
541 drop(staging);
542 if !target_existed {
543 let _ = fs::remove_dir(path);
544 }
545 return Err(error);
546 }
547 };
548
549 let mut entries = fs::read_dir(staging.path())
550 .map_err(|error| format!("read initialization staging directory: {error}"))?
551 .collect::<Result<Vec<_>, _>>()
552 .map_err(|error| format!("read initialization staging entry: {error}"))?;
553 entries.sort_by_key(fs::DirEntry::file_name);
554 let mut installed = Vec::new();
555 for entry in entries {
556 let destination = path.join(entry.file_name());
557 if fs::symlink_metadata(&destination).is_ok() {
558 for (source, destination) in installed.iter().rev() {
559 let _ = fs::rename(destination, source);
560 }
561 drop(staging);
562 if !target_existed {
563 let _ = fs::remove_dir(path);
564 }
565 return Err(format!(
566 "initialization target changed while staging: {}",
567 destination.display()
568 ));
569 }
570 if let Err(error) = fs::rename(entry.path(), &destination) {
571 for (source, destination) in installed.iter().rev() {
572 let _ = fs::rename(destination, source);
573 }
574 drop(staging);
575 if !target_existed {
576 let _ = fs::remove_dir(path);
577 }
578 return Err(format!(
579 "install initialized repository entry '{}': {error}",
580 destination.display()
581 ));
582 }
583 installed.push((entry.path(), destination));
584 }
585 drop(staging);
586
587 payload["path"] = json!(path.display().to_string());
588 payload["next_commands"] = json!([
589 format!(
590 "vela doctor {} --json",
591 posix_shell_arg(&path.display().to_string())
592 ),
593 format!(
594 "vela status {} --json",
595 posix_shell_arg(&path.display().to_string())
596 ),
597 format!(
598 "vela next {} --json",
599 posix_shell_arg(&path.display().to_string())
600 )
601 ]);
602 Ok(payload)
603}
604
605fn initialize_profile_v1_minimal_in_place(
606 path: &Path,
607 options: &ProfileV1InitOptions<'_>,
608) -> Result<serde_json::Value, String> {
609 let name = options.name.trim();
610 let scope = options.scope.trim();
611
612 let project = project::assemble_profile_v1(name, Vec::new(), 0, 0, scope);
613 let frontier_id = project.frontier_id();
614 let profile = FrontierProfileV1 {
615 schema: FRONTIER_PROFILE_SCHEMA_V1.to_string(),
616 frontier_id: frontier_id.clone(),
617 name: name.to_string(),
618 summary: scope.to_string(),
621 scope: FrontierProfileScopeV1 {
622 question: scope.to_string(),
623 includes: Vec::new(),
624 excludes: Vec::new(),
625 },
626 maintainers: Vec::new(),
627 license: FrontierProfileLicenseV1 {
628 content: "CC-BY-4.0".to_string(),
629 code: "Apache-2.0".to_string(),
630 data: "varies".to_string(),
631 },
632 };
633 profile.validate()?;
634 let profile_root = profile.profile_root()?;
635 let dependency_root = crate::frontier_repository::exact_dependency_root(&[])?;
636 let genesis = project
637 .events
638 .first()
639 .ok_or_else(|| "Profile v1 initialization did not produce frontier.created".to_string())?;
640 if project.events.len() != 1 || genesis.kind != "frontier.created" {
641 return Err(
642 "Profile v1 initialization must produce exactly one frontier.created event".to_string(),
643 );
644 }
645
646 let profile_bytes = serde_yaml::to_string(&profile)
647 .map_err(|error| format!("Failed to serialize Profile v1: {error}"))?;
648 fs::write(path.join("frontier.yaml"), profile_bytes)
649 .map_err(|error| format!("Failed to write frontier.yaml: {error}"))?;
650
651 write_profile_v1_canonical_skeleton(path, &project)?;
652 write_visible_state(
653 path,
654 &project,
655 &materialization_generated_at(path, &project),
656 )?;
657
658 let proof_dir = path.join("proof");
661 let generated_at = materialization_generated_at(path, &project);
662 let empty_proof = ProofWrite {
663 digest: directory_hash(&proof_dir),
664 freshness: "not_materialized".to_string(),
665 latest: String::new(),
666 events_manifest: String::new(),
667 replay_trace: String::new(),
668 };
669 let (_, lock_bytes) = render_lock_v1(path, &project, &profile, &empty_proof, &generated_at)?;
670 fs::write(path.join("vela.lock"), lock_bytes)
671 .map_err(|error| format!("Failed to write vela.lock: {error}"))?;
672
673 let settings = FrontierSettingsV1 {
674 schema: FRONTIER_SETTINGS_SCHEMA.to_string(),
675 publish: None,
676 work: None,
677 mcp: None,
678 };
679 fs::write(path.join(".vela/settings.toml"), settings.to_toml()?)
680 .map_err(|error| format!("Failed to write .vela/settings.toml: {error}"))?;
681 write_frontier_card_v1(path, name, scope)?;
682 write_scope_v1(path, scope)?;
683 write_git_native_scaffold(path, name, false)?;
684 initialize_git_repository(path, options.initialize_git)?;
685
686 let event_path = format!(".vela/events/{}.json", genesis.id);
687 Ok(json!({
688 "schema": FRONTIER_INIT_SCHEMA_V1,
689 "ok": true,
690 "layout": FRONTIER_REPO_LAYOUT_V1,
691 "path": path.display().to_string(),
692 "name": name,
693 "scope": scope,
694 "frontier_id": frontier_id,
695 "frontier_created_event_id": genesis.id,
696 "profile_root": profile_root,
697 "dependency_root": dependency_root,
698 "wrote": [
699 "README.md",
700 "SCOPE.md",
701 "frontier.yaml",
702 "frontier.json",
703 "vela.lock",
704 ".gitignore",
705 ".gitattributes",
706 "VELA.md",
707 ".vela/settings.toml",
708 event_path,
709 ".vela/proof-state.json",
710 ".vela/actors.json"
711 ],
712 "next_commands": [
713 format!("vela doctor {} --json", posix_shell_arg(&path.display().to_string())),
714 format!("vela status {} --json", posix_shell_arg(&path.display().to_string())),
715 format!("vela next {} --json", posix_shell_arg(&path.display().to_string()))
716 ]
717 }))
718}
719
720fn write_profile_v1_canonical_skeleton(path: &Path, project: &Project) -> Result<(), String> {
721 let vela_dir = path.join(".vela");
722 for relative in ["findings", "events", "proposals", "artifacts"] {
723 let directory = vela_dir.join(relative);
724 fs::create_dir_all(&directory)
725 .map_err(|error| format!("Failed to create {}: {error}", directory.display()))?;
726 }
727 for event in &project.events {
728 let destination = vela_dir.join("events").join(format!("{}.json", event.id));
729 let bytes = serde_json::to_vec_pretty(event)
730 .map_err(|error| format!("Failed to serialize state event {}: {error}", event.id))?;
731 fs::write(&destination, bytes)
732 .map_err(|error| format!("Failed to write {}: {error}", destination.display()))?;
733 }
734 let proof_state = serde_json::to_vec_pretty(&project.proof_state)
735 .map_err(|error| format!("Failed to serialize proof state: {error}"))?;
736 fs::write(vela_dir.join("proof-state.json"), proof_state)
737 .map_err(|error| format!("Failed to write .vela/proof-state.json: {error}"))?;
738 let actors = serde_json::to_vec_pretty(&project.actors)
739 .map_err(|error| format!("Failed to serialize actors: {error}"))?;
740 fs::write(vela_dir.join("actors.json"), actors)
741 .map_err(|error| format!("Failed to write .vela/actors.json: {error}"))?;
742 Ok(())
743}
744
745fn initialize_git_repository(path: &Path, requested: bool) -> Result<(), String> {
746 if !requested || path.join(".git").exists() {
747 return Ok(());
748 }
749 let output = std::process::Command::new("git")
752 .args(["init", "--quiet", "-b", "main"])
753 .arg(path)
754 .output()
755 .map_err(|error| format!("Failed to run git init: {error}"))?;
756 if !output.status.success() {
757 return Err(format!(
758 "git init failed: {}",
759 String::from_utf8_lossy(&output.stderr).trim()
760 ));
761 }
762 Ok(())
763}
764
765fn init_next_commands(path: &Path) -> Vec<String> {
766 let target = posix_shell_arg(&path.display().to_string());
767 vec![
768 format!("vela agents sync {target} --json"),
769 format!("vela doctor {target} --json"),
770 format!("vela status {target} --json"),
771 format!("vela next {target} --json"),
772 format!("vela check {target} --strict --json"),
773 ]
774}
775
776fn posix_shell_arg(value: &str) -> String {
781 format!("'{}'", value.replace('\'', "'\"'\"'"))
782}
783
784fn write_git_native_scaffold(
799 path: &Path,
800 name: &str,
801 include_optional_integrations: bool,
802) -> Result<(), String> {
803 let write = |rel: &str, contents: String| -> Result<(), String> {
804 let dest = path.join(rel);
805 if dest.exists() {
806 return Ok(()); }
808 if let Some(parent) = dest.parent() {
809 fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
810 }
811 fs::write(&dest, contents).map_err(|e| format!("write {}: {e}", dest.display()))
812 };
813
814 write(
815 ".gitignore",
816 "# A Vela frontier commits the record, not the derivation.\n\
817 # Authority: .vela/events/ (signed log). Pins: vela.lock. Read-entry: frontier.json.\n\
818 \n\
819 # Producer-local scratch (not replayable truth).\n\
820 /packets/\n/activity/\n/exports/\n\
821 /.vela/agents/\n/.vela/keys/\n/.vela/operation-journals/\n/.vela/tasks/\n/.vela/work/\n/.vela/workspaces/\n/.vela/source-inbox/\n/.vela/artifact-blobs/\n\
822 \n\
823 # Tooling scratch\n\
824 /target/\n__pycache__/\n*.pyc\n.venv/\n.pytest_cache/\n.DS_Store\n"
825 .to_string(),
826 )?;
827
828 write(
829 ".gitattributes",
830 "# Ordinary text is normalized across platforms. More specific rules below win.\n\
831 * text=auto eol=lf\n\
832 \n\
833 # Canonical events, proposals, receipts, and public review material are raw Git\n\
834 # blobs. Repository filters, keyword expansion, working-tree encodings, and\n\
835 # semantic merge drivers may not transform them. Vela publication also checks\n\
836 # the effective attributes and raw staged blob before moving a ref, because a\n\
837 # local .git/info/attributes file has higher precedence than this contract.\n\
838 .vela/** -filter -ident -working-tree-encoding -merge -text\n\
839 .vela/events/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
840 .vela/proposals/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
841 .vela/records/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
842 records/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
843 sources/** -filter -ident -working-tree-encoding -merge -text\n\
844 artifacts/** -filter -ident -working-tree-encoding -merge -text\n\
845 review/** -filter -ident -working-tree-encoding -merge -text\n\
846 proof/** -filter -ident -working-tree-encoding -merge -text\n\
847 frontier.yaml -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
848 frontier.json -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
849 vela.lock -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
850 \n\
851 # Witnesses are evidence the frozen verifiers re-check. They can be large, so\n\
852 # they may use Git LFS. The receipt's Vela digest remains content identity; the\n\
853 # LFS object is transport and its absence is an explicit availability failure.\n\
854 witnesses/** filter=lfs diff=lfs merge=lfs -text\n"
855 .to_string(),
856 )?;
857
858 if include_optional_integrations {
859 let vela_release = current_vela_release();
860 let vela_action_ref = format!("{VELA_ACTION_REPOSITORY}@{vela_release}");
861 let workflow = r#"name: Verify the signed frontier
862
863# The git-native gate: every main push and every pull request runs the shared
864# vela-check action. This is deliberately unfiltered: public canonical roots
865# evolve, and a stale path allowlist would let scientific state bypass the gate.
866# The action re-derives the frontier from a clean checkout and proves the
867# working tree IS the signed state (replay + strict check + hash parity).
868# It NEVER signs: acceptance stays a human-keyed event in the repo.
869on:
870 push:
871 branches: [main]
872 pull_request: {}
873 workflow_dispatch: {}
874
875permissions:
876 contents: read
877
878jobs:
879 verify:
880 runs-on: ubuntu-latest
881 steps:
882 - uses: actions/checkout@v5
883 - uses: __VELA_ACTION_REF__
884 with:
885 vela-version: __VELA_RELEASE__
886"#
887 .replace("__VELA_ACTION_REF__", &vela_action_ref)
888 .replace("__VELA_RELEASE__", &vela_release);
889 write(".github/workflows/vela-frontier.yml", workflow)?;
890 }
891
892 write(
893 "VELA.md",
894 format!(
895 r#"# {name} — agent charter
896
897This frontier is driven by `vela` + `git`. The ordinary path is
898`next -> work -> land -> sign`: agents stop after the routed landing; only a
899human key or a previously human-signed Permit policy changes accepted state.
900`vela agents sync` regenerates CLAUDE.md / AGENTS.md / editor adapters from
901this file — edit here, never there.
902
903## Agent rules
904
905Agents may:
906
907- inspect state: `vela status .`, `vela next .`, `vela check .`
908- claim one target: `vela work <target> --as agent:<name> --json`
909- land Receipt v1 work through that session: `vela land --work <target>
910 --claim … --artifact … --caveat … --as agent:<name> --json`
911- import a foreign producer's canonical Receipt v1: `vela land receipt.json
912 --as agent:<name> --json`
913- run the verifiers: `vela reproduce .`, `vela check . --strict`
914- rebuild derived views: `vela frontier materialize .`
915- inspect a supplied proposal first with `vela review show . <vpr_id> --json`;
916 rejected proposal findings are absent from accepted finding views by design
917
918Agents may not:
919
920- run `vela sign`, accept, reject, apply, or finalize a truth-bearing proposal
921- sign with, read, or handle a human's key
922- hand-edit accepted events or derived views such as `frontier.json` and proof
923 packets
924
925## Fast commands
926
927```bash
928vela next . --json # ranked offer
929vela work <target> --as agent:<name> --json # lease + briefing
930vela land --work <target> --claim <claim> \
931 --type computational --replayability exact \
932 --artifact <path>:<kind> --caveat <limit> \
933 --as agent:<name> --json # Receipt v1 + policy route
934vela status . --json # accepted and pending state
935vela review show . <vpr_id> --json # pending or terminal record
936vela check . --strict # replay and parity gate
937vela frontier materialize . # rebuild derived views
938git push # publication; no authority
939```
940"#
941 ),
942 )?;
943
944 if include_optional_integrations {
945 write(
946 ".mcp.json",
947 r#"{
948 "_generated_by": "vela agents sync (from VELA.md) — edit VELA.md, not this file",
949 "mcpServers": {
950 "vela-local": {
951 "args": [
952 "serve",
953 ".",
954 "--profile",
955 "draft"
956 ],
957 "command": "vela"
958 }
959 }
960}
961"#
962 .to_string(),
963 )?;
964 }
965
966 Ok(())
967}
968
969pub fn materialize(path: &Path) -> Result<serde_json::Value, String> {
970 let source = crate::repo::VelaSource::VelaRepo(path.to_path_buf());
971 let project = crate::repo::load(&source)?;
972 let generated_at = materialization_generated_at(path, &project);
976 write_visible_state(path, &project, &generated_at)?;
977 write_manifest(path, &project)?;
978 let proof = write_proof(path, &project, &generated_at)?;
979 if let Some(FrontierProfileFile::V1(profile)) = read_repository_profile(path)? {
980 let (lock, bytes) = render_lock_v1(path, &project, &profile, &proof, &generated_at)?;
981 fs::write(path.join("vela.lock"), bytes)
982 .map_err(|error| format!("Failed to write vela.lock: {error}"))?;
983 return Ok(json!({
984 "schema": FRONTIER_MATERIALIZE_SCHEMA,
985 "ok": true,
986 "path": path.display().to_string(),
987 "wrote_frontier": "frontier.json",
988 "wrote_lock": "vela.lock",
989 "wrote_proof": "proof/latest.json",
990 "wrote_events_manifest": "proof/events.manifest.jsonl",
991 "profile_root": lock.profile_root,
992 "identity_root": lock.identity_root,
993 "dependency_root": lock.dependency_root,
994 "scientific_state_root": lock.scientific_state_root,
995 "legacy_snapshot_root": lock.legacy_snapshot_root,
996 "event_log_root": lock.event_log_root,
997 "proposal_root": lock.proposal_root,
998 }));
999 }
1000 let lock = write_lock(path, &project, &proof, &generated_at)?;
1001 Ok(json!({
1002 "schema": FRONTIER_MATERIALIZE_SCHEMA,
1003 "ok": true,
1004 "path": path.display().to_string(),
1005 "wrote_frontier": "frontier.json",
1006 "wrote_lock": "vela.lock",
1007 "wrote_proof": "proof/latest.json",
1008 "wrote_events_manifest": "proof/events.manifest.jsonl",
1009 "snapshot_hash": lock.snapshot_hash,
1010 "event_log_hash": lock.event_log_hash,
1011 "proposal_state_hash": lock.proposal_state_hash,
1012 }))
1013}
1014
1015pub fn write_visible_repo_files(path: &Path, project: &Project) -> Result<(), String> {
1016 let files = render_visible_repo_files(path, project)?;
1017 for (relative_path, bytes) in files {
1018 let destination = path.join(&relative_path);
1019 if let Some(parent) = destination.parent() {
1020 fs::create_dir_all(parent)
1021 .map_err(|e| format!("Failed to create {}: {e}", parent.display()))?;
1022 }
1023 fs::write(&destination, bytes)
1024 .map_err(|e| format!("Failed to write {}: {e}", destination.display()))?;
1025 }
1026 Ok(())
1027}
1028
1029pub fn render_visible_repo_files(
1033 path: &Path,
1034 project: &Project,
1035) -> Result<VisibleRepoFiles, String> {
1036 render_visible_repo_files_inner(path, project, None)
1037}
1038
1039pub fn render_visible_repo_files_for_profile_migration(
1047 path: &Path,
1048 project: &Project,
1049 profile: &FrontierProfileV1,
1050 profile_bytes: &[u8],
1051) -> Result<VisibleRepoFiles, String> {
1052 profile.validate()?;
1053 profile.assert_frontier_id(&project.frontier_id())?;
1054 let reparsed = std::str::from_utf8(profile_bytes)
1055 .map_err(|error| format!("candidate Profile v1 bytes are not UTF-8: {error}"))
1056 .and_then(FrontierProfileV1::from_yaml_str)?;
1057 if &reparsed != profile {
1058 return Err(
1059 "candidate Profile v1 bytes do not match the parsed migration profile".to_string(),
1060 );
1061 }
1062 render_visible_repo_files_inner(path, project, Some((profile, profile_bytes)))
1063}
1064
1065fn render_visible_repo_files_inner(
1066 path: &Path,
1067 project: &Project,
1068 migration_profile: Option<(&FrontierProfileV1, &[u8])>,
1069) -> Result<VisibleRepoFiles, String> {
1070 let mut projected: Project = serde_json::from_value(
1076 serde_json::to_value(project)
1077 .map_err(|error| format!("clone split-repository projection: {error}"))?,
1078 )
1079 .map_err(|error| format!("clone split-repository projection: {error}"))?;
1080 projected
1081 .findings
1082 .sort_by(|left, right| left.id.cmp(&right.id));
1083 projected
1084 .events
1085 .sort_by(|left, right| left.id.cmp(&right.id));
1086 projected
1087 .proposals
1088 .sort_by(|left, right| left.id.cmp(&right.id));
1089 projected
1090 .artifacts
1091 .sort_by(|left, right| left.id.cmp(&right.id));
1092 let project = &projected;
1093 let generated_at = materialization_generated_at(path, project);
1094 let mut files = VisibleRepoFiles::new();
1095 files.insert(
1096 "frontier.json".to_string(),
1097 render_visible_state(
1098 path,
1099 project,
1100 &generated_at,
1101 migration_profile.map(|(profile, _)| profile),
1102 )?,
1103 );
1104 let manifest = match migration_profile {
1105 Some((_, bytes)) => bytes.to_vec(),
1106 None => match read_repository_profile(path)? {
1107 None => render_manifest(path, project)?,
1108 Some(FrontierProfileFile::LegacyV0_1(_)) => {
1109 render_synced_manifest(path, &project.project.dependencies)?
1115 }
1116 Some(FrontierProfileFile::V1(_)) => fs::read(path.join("frontier.yaml"))
1117 .map_err(|error| format!("Failed to preserve frontier.yaml: {error}"))?,
1118 },
1119 };
1120 files.insert("frontier.yaml".to_string(), manifest);
1121
1122 let rendered_proof = render_proof(
1123 path,
1124 project,
1125 &generated_at,
1126 migration_profile.map(|(profile, _)| profile),
1127 )?;
1128 files.extend(
1129 rendered_proof
1130 .files
1131 .into_iter()
1132 .map(|(relative_path, bytes)| (format!("proof/{relative_path}"), bytes)),
1133 );
1134 let lock_bytes = match migration_profile {
1135 Some((profile, _)) => {
1136 render_lock_v1(path, project, profile, &rendered_proof.proof, &generated_at)?.1
1137 }
1138 None => match read_repository_profile(path)? {
1139 Some(FrontierProfileFile::V1(profile)) => {
1140 render_lock_v1(
1141 path,
1142 project,
1143 &profile,
1144 &rendered_proof.proof,
1145 &generated_at,
1146 )?
1147 .1
1148 }
1149 _ => render_lock(path, project, &rendered_proof.proof, &generated_at)?.1,
1150 },
1151 };
1152 files.insert("vela.lock".to_string(), lock_bytes);
1153 Ok(files)
1154}
1155
1156pub fn read_manifest(path: &Path) -> Result<Option<FrontierManifest>, String> {
1157 match read_repository_profile(path)? {
1158 Some(FrontierProfileFile::LegacyV0_1(manifest)) => Ok(Some(manifest)),
1159 Some(FrontierProfileFile::V1(_)) => Err(
1160 "frontier.yaml is a vela.frontier-profile.v1 document, not a legacy manifest"
1161 .to_string(),
1162 ),
1163 None => Ok(None),
1164 }
1165}
1166
1167pub fn read_repository_profile(path: &Path) -> Result<Option<FrontierProfileFile>, String> {
1169 let profile_path = path.join("frontier.yaml");
1170 let Some(data) =
1171 read_repository_control_text(path, Path::new("frontier.yaml"), "frontier.yaml")?
1172 else {
1173 return Ok(None);
1174 };
1175 let value: serde_yaml::Value = serde_yaml::from_str(&data).map_err(|error| {
1176 format!(
1177 "Failed to parse frontier profile '{}': {error}",
1178 profile_path.display()
1179 )
1180 })?;
1181 let schema = value
1182 .as_mapping()
1183 .and_then(|mapping| mapping.get(serde_yaml::Value::String("schema".to_string())))
1184 .and_then(serde_yaml::Value::as_str)
1185 .ok_or_else(|| "frontier.yaml must contain a string schema field".to_string())?;
1186 match schema {
1187 FRONTIER_MANIFEST_SCHEMA => serde_yaml::from_value::<FrontierManifest>(value)
1188 .map(FrontierProfileFile::LegacyV0_1)
1189 .map(Some)
1190 .map_err(|error| {
1191 format!(
1192 "Failed to parse legacy frontier manifest '{}': {error}",
1193 profile_path.display()
1194 )
1195 }),
1196 FRONTIER_PROFILE_SCHEMA_V1 => FrontierProfileV1::from_yaml_str(&data)
1197 .map(FrontierProfileFile::V1)
1198 .map(Some),
1199 other => Err(format!(
1200 "unsupported frontier.yaml schema `{other}`; expected `{FRONTIER_MANIFEST_SCHEMA}` or `{FRONTIER_PROFILE_SCHEMA_V1}`"
1201 )),
1202 }
1203}
1204
1205pub fn read_repository_control_text(
1211 repository: &Path,
1212 relative: &Path,
1213 label: &str,
1214) -> Result<Option<String>, String> {
1215 let components = relative.components().collect::<Vec<_>>();
1216 if components.is_empty()
1217 || components
1218 .iter()
1219 .any(|component| !matches!(component, Component::Normal(_)))
1220 {
1221 return Err(format!(
1222 "{label} must use a normalized repository-relative path"
1223 ));
1224 }
1225
1226 let mut directories = Vec::with_capacity(components.len());
1227 let mut current = repository.to_path_buf();
1228 directories.push(current.clone());
1229 for component in &components[..components.len() - 1] {
1230 let Component::Normal(name) = component else {
1231 unreachable!("closed component check above")
1232 };
1233 current.push(name);
1234 directories.push(current.clone());
1235 }
1236
1237 let mut pinned = Vec::with_capacity(directories.len());
1238 for directory in &directories {
1239 let metadata = fs::symlink_metadata(directory)
1240 .map_err(|error| format!("Failed to inspect parent of {label}: {error}"))?;
1241 if metadata.file_type().is_symlink() || !metadata.is_dir() {
1242 return Err(format!(
1243 "{label} must be beneath real non-symlink repository directories"
1244 ));
1245 }
1246 pinned.push(
1247 same_file::Handle::from_path(directory)
1248 .map_err(|error| format!("Failed to identify parent of {label}: {error}"))?,
1249 );
1250 }
1251
1252 let value = read_regular_nonsymlink_text(&repository.join(relative), label)?;
1253 for (directory, expected) in directories.iter().zip(&pinned) {
1254 let metadata = fs::symlink_metadata(directory)
1255 .map_err(|error| format!("Failed to reinspect parent of {label}: {error}"))?;
1256 let actual = same_file::Handle::from_path(directory)
1257 .map_err(|error| format!("Failed to reidentify parent of {label}: {error}"))?;
1258 if metadata.file_type().is_symlink() || !metadata.is_dir() || &actual != expected {
1259 return Err(format!(
1260 "repository parent of {label} changed while it was read"
1261 ));
1262 }
1263 }
1264 Ok(value)
1265}
1266
1267pub fn read_regular_nonsymlink_text(path: &Path, label: &str) -> Result<Option<String>, String> {
1272 use std::io::Read;
1273
1274 const MAX_CONTROL_FILE_BYTES: u64 = 16 * 1024 * 1024;
1275
1276 let linked = match fs::symlink_metadata(path) {
1277 Ok(metadata) => metadata,
1278 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1279 Err(error) => return Err(format!("Failed to inspect {label}: {error}")),
1280 };
1281 if linked.file_type().is_symlink() || !linked.is_file() {
1282 return Err(format!("{label} must be a regular non-symlink file"));
1283 }
1284 let inspected = same_file::Handle::from_path(path)
1285 .map_err(|error| format!("Failed to identify {label}: {error}"))?;
1286 let mut file =
1287 fs::File::open(path).map_err(|error| format!("Failed to open {label}: {error}"))?;
1288 let opened = same_file::Handle::from_file(
1289 file.try_clone()
1290 .map_err(|error| format!("Failed to clone the open {label} descriptor: {error}"))?,
1291 )
1292 .map_err(|error| format!("Failed to identify the open {label}: {error}"))?;
1293 if inspected != opened {
1294 return Err(format!("{label} changed while it was opened"));
1295 }
1296 let mut bytes = Vec::new();
1297 file.by_ref()
1298 .take(MAX_CONTROL_FILE_BYTES + 1)
1299 .read_to_end(&mut bytes)
1300 .map_err(|error| format!("Failed to read {label}: {error}"))?;
1301 if bytes.len() as u64 > MAX_CONTROL_FILE_BYTES {
1302 return Err(format!("{label} exceeds the 16 MiB control-file limit"));
1303 }
1304 let data =
1305 String::from_utf8(bytes).map_err(|error| format!("{label} is not UTF-8: {error}"))?;
1306 let final_link = fs::symlink_metadata(path)
1307 .map_err(|error| format!("Failed to reinspect {label}: {error}"))?;
1308 let final_identity = same_file::Handle::from_path(path)
1309 .map_err(|error| format!("Failed to reidentify {label}: {error}"))?;
1310 if final_link.file_type().is_symlink() || !final_link.is_file() || opened != final_identity {
1311 return Err(format!("{label} changed while it was read"));
1312 }
1313 Ok(Some(data))
1314}
1315
1316pub fn read_lock(path: &Path) -> Result<Option<FrontierLock>, String> {
1317 match read_repository_lock(path)? {
1318 Some(FrontierLockFile::LegacyV0_1(lock)) => Ok(Some(lock)),
1319 Some(FrontierLockFile::V1(_)) => {
1320 Err("vela.lock is a vela.frontier_lock.v1 document".to_string())
1321 }
1322 None => Ok(None),
1323 }
1324}
1325
1326pub fn read_repository_lock(path: &Path) -> Result<Option<FrontierLockFile>, String> {
1327 let lock_path = path.join("vela.lock");
1328 if !lock_path.is_file() {
1329 return Ok(None);
1330 }
1331 let data =
1332 fs::read_to_string(&lock_path).map_err(|e| format!("Failed to read vela.lock: {e}"))?;
1333 let value: serde_yaml::Value = serde_yaml::from_str(&data).map_err(|error| {
1334 format!(
1335 "Failed to parse frontier lock '{}': {error}",
1336 lock_path.display()
1337 )
1338 })?;
1339 let schema = value
1340 .as_mapping()
1341 .and_then(|mapping| mapping.get(serde_yaml::Value::String("schema".to_string())))
1342 .and_then(serde_yaml::Value::as_str)
1343 .ok_or_else(|| "vela.lock must contain a string schema field".to_string())?;
1344 match schema {
1345 FRONTIER_LOCK_SCHEMA => serde_yaml::from_value::<FrontierLock>(value)
1346 .map(FrontierLockFile::LegacyV0_1)
1347 .map(Some)
1348 .map_err(|error| {
1349 format!(
1350 "Failed to parse frontier lock '{}': {error}",
1351 lock_path.display()
1352 )
1353 }),
1354 FRONTIER_LOCK_SCHEMA_V1 => serde_yaml::from_value::<FrontierLockV1>(value)
1355 .map(FrontierLockFile::V1)
1356 .map(Some)
1357 .map_err(|error| {
1358 format!(
1359 "Failed to parse frontier lock '{}': {error}",
1360 lock_path.display()
1361 )
1362 }),
1363 other => Err(format!("unsupported vela.lock schema `{other}`")),
1364 }
1365}
1366
1367pub fn layout_issues(path: &Path, project: &Project) -> Vec<RepoLayoutIssue> {
1368 if !path.is_dir() || !path.join(".vela").is_dir() {
1369 return Vec::new();
1370 }
1371 let mut issues = Vec::new();
1372 let profile = match read_repository_profile(path) {
1373 Ok(value) => value,
1374 Err(e) => {
1375 issues.push(issue("invalid_frontier_manifest", e));
1376 None
1377 }
1378 };
1379 let lock_file = match read_repository_lock(path) {
1380 Ok(value) => value,
1381 Err(e) => {
1382 issues.push(issue("invalid_frontier_lock", e));
1383 None
1384 }
1385 };
1386
1387 if profile.is_none() {
1388 issues.push(issue(
1389 "missing_frontier_manifest",
1390 "Split frontier repo is missing frontier.yaml.",
1391 ));
1392 }
1393 let Some(lock_file) = lock_file else {
1394 return issues;
1401 };
1402
1403 match (profile.as_ref(), lock_file) {
1404 (Some(FrontierProfileFile::V1(profile)), FrontierLockFile::V1(lock)) => {
1405 validate_v1_layout(path, project, profile, &lock, &mut issues);
1406 issues
1407 }
1408 (Some(FrontierProfileFile::V1(_)), FrontierLockFile::LegacyV0_1(_))
1409 | (Some(FrontierProfileFile::LegacyV0_1(_)), FrontierLockFile::V1(_)) => {
1410 issues.push(issue(
1411 "frontier_lock_schema_mismatch",
1412 "frontier.yaml and vela.lock use different repository-profile generations.",
1413 ));
1414 issues
1415 }
1416 (_, FrontierLockFile::V1(_)) => {
1417 issues.push(issue(
1418 "frontier_lock_schema_mismatch",
1419 "vela.lock v1 requires a validated Repository Profile v1.",
1420 ));
1421 issues
1422 }
1423 (_, FrontierLockFile::LegacyV0_1(lock)) => {
1424 validate_legacy_layout(path, project, lock, issues)
1425 }
1426 }
1427}
1428
1429fn validate_legacy_layout(
1430 path: &Path,
1431 project: &Project,
1432 lock: FrontierLock,
1433 mut issues: Vec<RepoLayoutIssue>,
1434) -> Vec<RepoLayoutIssue> {
1435 let locked_project = project_with_frontier_id(project);
1436 let hash_project = locked_project.as_ref().unwrap_or(project);
1437 let expected_snapshot = prefixed(events::snapshot_hash(hash_project));
1438 let expected_event_log = prefixed(events::event_log_hash(&hash_project.events));
1439 let expected_proposals = proposal_state_hash(&project.proposals);
1440 let expected_frontier = hash_project.frontier_id();
1441 let expected_sources = directory_hash(&path.join("sources"));
1442 let expected_artifacts = directory_hash(&path.join("artifacts"));
1443 let expected_review = directory_hash(&path.join("review"));
1444 let expected_proof = directory_hash(&path.join("proof"));
1445 if lock.snapshot_hash != expected_snapshot {
1446 issues.push(issue(
1447 "frontier_lock_mismatch",
1448 format!(
1449 "vela.lock snapshot_hash does not match materialized frontier state: lock={}, current={expected_snapshot}",
1450 lock.snapshot_hash
1451 ),
1452 ));
1453 }
1454 if lock.event_log_hash != expected_event_log {
1455 issues.push(issue(
1456 "frontier_lock_mismatch",
1457 format!(
1458 "vela.lock event_log_hash does not match .vela/events: lock={}, current={expected_event_log}",
1459 lock.event_log_hash
1460 ),
1461 ));
1462 }
1463 if lock.proposal_state_hash != expected_proposals {
1464 issues.push(issue(
1465 "frontier_lock_mismatch",
1466 format!(
1467 "vela.lock proposal_state_hash does not match .vela/proposals: lock={}, current={expected_proposals}",
1468 lock.proposal_state_hash
1469 ),
1470 ));
1471 }
1472 if lock.frontier_id != expected_frontier {
1473 issues.push(issue(
1474 "frontier_lock_mismatch",
1475 format!(
1476 "vela.lock frontier_id does not match current frontier: lock={}, current={expected_frontier}",
1477 lock.frontier_id
1478 ),
1479 ));
1480 }
1481 if !lock.sources_hash.is_empty() && lock.sources_hash != expected_sources {
1482 issues.push(issue(
1483 "frontier_lock_mismatch",
1484 format!(
1485 "vela.lock sources_hash does not match sources/: lock={}, current={expected_sources}",
1486 lock.sources_hash
1487 ),
1488 ));
1489 }
1490 if !lock.artifacts_hash.is_empty() && lock.artifacts_hash != expected_artifacts {
1491 issues.push(issue(
1492 "frontier_lock_mismatch",
1493 format!(
1494 "vela.lock artifacts_hash does not match artifacts/: lock={}, current={expected_artifacts}",
1495 lock.artifacts_hash
1496 ),
1497 ));
1498 }
1499 if !lock.review_hash.is_empty() && lock.review_hash != expected_review {
1500 issues.push(issue(
1501 "frontier_lock_mismatch",
1502 format!(
1503 "vela.lock review_hash does not match review/: lock={}, current={expected_review}",
1504 lock.review_hash
1505 ),
1506 ));
1507 }
1508 if !lock.proof.digest.is_empty() && lock.proof.digest != expected_proof {
1509 issues.push(issue(
1510 "frontier_lock_mismatch",
1511 format!(
1512 "vela.lock proof digest does not match proof/: lock={}, current={expected_proof}",
1513 lock.proof.digest
1514 ),
1515 ));
1516 }
1517 if !lock.verifiers.package.is_empty() {
1523 let actual_kinds = collect_verifier_kinds(path);
1524 if lock.verifiers.kinds != actual_kinds {
1525 issues.push(issue(
1526 "frontier_lock_mismatch",
1527 format!(
1528 "vela.lock verifiers.kinds does not match the witnesses on disk: lock={:?}, current={actual_kinds:?} (run `vela frontier materialize`)",
1529 lock.verifiers.kinds
1530 ),
1531 ));
1532 }
1533 }
1534
1535 let visible_path = path.join("frontier.json");
1536 if !visible_path.is_file() {
1537 issues.push(issue(
1538 "missing_materialized_frontier",
1539 "Split frontier repo is missing frontier.json.",
1540 ));
1541 return issues;
1542 }
1543 match crate::repo::load_project_file(&visible_path) {
1544 Ok(visible) => {
1545 let visible_hash = prefixed(events::snapshot_hash(&visible));
1546 if visible_hash != expected_snapshot {
1547 issues.push(issue(
1548 "frontier_lock_mismatch",
1549 format!(
1550 "frontier.json does not match .vela materialized state: visible={visible_hash}, current={expected_snapshot}",
1551 ),
1552 ));
1553 }
1554 }
1555 Err(e) => issues.push(issue("invalid_materialized_frontier", e)),
1556 }
1557
1558 issues
1559}
1560
1561fn validate_v1_layout(
1562 path: &Path,
1563 project: &Project,
1564 profile: &FrontierProfileV1,
1565 lock: &FrontierLockV1,
1566 issues: &mut Vec<RepoLayoutIssue>,
1567) {
1568 let projection = match profile.project(project) {
1569 Ok(projection) => projection,
1570 Err(error) => {
1571 issues.push(issue("invalid_frontier_profile", error));
1572 return;
1573 }
1574 };
1575 let visible = project_with_frontier_id(project);
1576 let hash_project = visible.as_ref().unwrap_or(project);
1577 let expected_legacy_snapshot = prefixed(events::snapshot_hash(hash_project));
1578 let expected_event_log = prefixed(events::event_log_hash(&project.events));
1579 let expected_proposals = proposal_state_hash(&project.proposals);
1580 for (field, actual, expected) in [
1581 (
1582 "frontier_id",
1583 lock.frontier_id.as_str(),
1584 projection.frontier_id.as_str(),
1585 ),
1586 (
1587 "profile_root",
1588 lock.profile_root.as_str(),
1589 projection.profile_root.as_str(),
1590 ),
1591 (
1592 "identity_root",
1593 lock.identity_root.as_str(),
1594 projection.identity_root.as_str(),
1595 ),
1596 (
1597 "dependency_root",
1598 lock.dependency_root.as_str(),
1599 projection.dependency_root.as_str(),
1600 ),
1601 (
1602 "scientific_state_root",
1603 lock.scientific_state_root.as_str(),
1604 projection.scientific_state_root.as_str(),
1605 ),
1606 (
1607 "legacy_snapshot_root",
1608 lock.legacy_snapshot_root.as_str(),
1609 expected_legacy_snapshot.as_str(),
1610 ),
1611 (
1612 "event_log_root",
1613 lock.event_log_root.as_str(),
1614 expected_event_log.as_str(),
1615 ),
1616 (
1617 "proposal_root",
1618 lock.proposal_root.as_str(),
1619 expected_proposals.as_str(),
1620 ),
1621 ] {
1622 if actual != expected {
1623 issues.push(issue(
1624 "frontier_lock_mismatch",
1625 format!("vela.lock {field} does not match derived state: lock={actual}, current={expected}"),
1626 ));
1627 }
1628 }
1629 if lock.event_count != project.events.len() as u64 {
1630 issues.push(issue(
1631 "frontier_lock_mismatch",
1632 format!(
1633 "vela.lock event_count does not match .vela/events: lock={}, current={}",
1634 lock.event_count,
1635 project.events.len()
1636 ),
1637 ));
1638 }
1639 if lock.dependencies != projection.dependencies {
1640 issues.push(issue(
1641 "frontier_lock_mismatch",
1642 "vela.lock dependencies do not match the effective identity-event payload.",
1643 ));
1644 }
1645 for (field, actual, expected) in [
1646 (
1647 "sources_hash",
1648 lock.sources_hash.as_str(),
1649 directory_hash(&path.join("sources")),
1650 ),
1651 (
1652 "artifacts_hash",
1653 lock.artifacts_hash.as_str(),
1654 directory_hash(&path.join("artifacts")),
1655 ),
1656 (
1657 "review_hash",
1658 lock.review_hash.as_str(),
1659 directory_hash(&path.join("review")),
1660 ),
1661 ] {
1662 if actual != expected {
1663 issues.push(issue(
1664 "frontier_lock_mismatch",
1665 format!("vela.lock {field} does not match repository bytes: lock={actual}, current={expected}"),
1666 ));
1667 }
1668 }
1669 if !lock.verifiers.package.is_empty() && lock.verifiers.kinds != collect_verifier_kinds(path) {
1670 issues.push(issue(
1671 "frontier_lock_mismatch",
1672 "vela.lock verifiers.kinds does not match the witnesses on disk.",
1673 ));
1674 }
1675 if !lock.proof.digest.is_empty() && lock.proof.digest != directory_hash(&path.join("proof")) {
1676 issues.push(issue(
1677 "frontier_lock_mismatch",
1678 "vela.lock proof digest does not match proof/.",
1679 ));
1680 }
1681 let visible_path = path.join("frontier.json");
1682 if !visible_path.is_file() {
1683 issues.push(issue(
1684 "missing_materialized_frontier",
1685 "Split frontier repo is missing frontier.json.",
1686 ));
1687 return;
1688 }
1689 let expected_visible = render_visible_state(
1690 path,
1691 project,
1692 &materialization_generated_at(path, project),
1693 None,
1694 );
1695 match (fs::read(&visible_path), expected_visible) {
1696 (Ok(actual), Ok(expected)) if actual == expected => {}
1697 (Ok(_), Ok(_)) => issues.push(issue(
1698 "frontier_lock_mismatch",
1699 "frontier.json does not match the exact Profile v1 read projection.",
1700 )),
1701 (Err(error), _) => issues.push(issue("invalid_materialized_frontier", error.to_string())),
1702 (_, Err(error)) => issues.push(issue("invalid_materialized_frontier", error)),
1703 }
1704}
1705
1706pub fn manifest_overrides(path: &Path) -> Result<Option<FrontierManifest>, String> {
1707 read_manifest(path)
1708}
1709pub fn proof_verify(path: &Path) -> Result<serde_json::Value, String> {
1710 let project = crate::repo::load_from_path(path)?;
1711 let lock = read_repository_lock(path)?;
1712 let proof_path = path.join("proof/latest.json");
1713 let mut issues = layout_issues(path, &project)
1714 .into_iter()
1715 .map(|issue| {
1716 json!({
1717 "rule_id": issue.rule_id,
1718 "message": issue.message,
1719 })
1720 })
1721 .collect::<Vec<_>>();
1722 let locked = project_with_frontier_id(&project)?;
1723 let snapshot_hash = prefixed(events::snapshot_hash(&locked));
1724 let event_log_hash = prefixed(events::event_log_hash(&locked.events));
1725 let mut latest_payload = serde_json::Value::Null;
1726 if !proof_path.is_file() {
1727 issues.push(json!({
1728 "rule_id": "missing_proof_latest",
1729 "message": "proof/latest.json is missing.",
1730 }));
1731 } else {
1732 let data = fs::read_to_string(&proof_path)
1733 .map_err(|e| format!("Failed to read proof/latest.json: {e}"))?;
1734 latest_payload = serde_json::from_str(&data).map_err(|e| {
1735 format!(
1736 "Failed to parse proof/latest.json '{}': {e}",
1737 proof_path.display()
1738 )
1739 })?;
1740 if latest_payload
1741 .get("frontier_hash")
1742 .and_then(|value| value.as_str())
1743 != Some(snapshot_hash.as_str())
1744 {
1745 issues.push(json!({
1746 "rule_id": "proof_snapshot_mismatch",
1747 "message": "proof/latest.json frontier_hash does not match replayed frontier state.",
1748 }));
1749 }
1750 if latest_payload
1751 .get("event_log_hash")
1752 .and_then(|value| value.as_str())
1753 != Some(event_log_hash.as_str())
1754 {
1755 issues.push(json!({
1756 "rule_id": "proof_event_log_mismatch",
1757 "message": "proof/latest.json event_log_hash does not match .vela/events/.",
1758 }));
1759 }
1760 }
1761 let proof_digest = directory_hash(&path.join("proof"));
1762 if let Some(lock) = &lock {
1763 let locked_proof = match lock {
1764 FrontierLockFile::LegacyV0_1(lock) => &lock.proof,
1765 FrontierLockFile::V1(lock) => &lock.proof,
1766 };
1767 if !locked_proof.digest.is_empty() && locked_proof.digest != proof_digest {
1768 issues.push(json!({
1769 "rule_id": "proof_digest_mismatch",
1770 "message": format!("proof/ digest does not match vela.lock: lock={}, current={proof_digest}", locked_proof.digest),
1771 }));
1772 }
1773 } else {
1774 issues.push(json!({
1775 "rule_id": "missing_frontier_lock",
1776 "message": "vela.lock is missing.",
1777 }));
1778 }
1779
1780 Ok(json!({
1781 "schema": FRONTIER_PROOF_VERIFY_SCHEMA,
1782 "ok": issues.is_empty(),
1783 "path": path.display().to_string(),
1784 "frontier_id": locked.frontier_id(),
1785 "snapshot_hash": snapshot_hash,
1786 "event_log_hash": event_log_hash,
1787 "proof_digest": proof_digest,
1788 "proof": latest_payload,
1789 "issues": issues,
1790 }))
1791}
1792
1793pub fn proof_explain(path: &Path) -> Result<String, String> {
1794 let project = crate::repo::load_from_path(path)?;
1795 let report = proof_verify(path)?;
1796 let ok = report.get("ok").and_then(|value| value.as_bool()) == Some(true);
1797 let locked = project_with_frontier_id(&project)?;
1798 let snapshot_hash = prefixed(events::snapshot_hash(&locked));
1799 let event_log_hash = prefixed(events::event_log_hash(&locked.events));
1800 let open_proposals = project
1801 .proposals
1802 .iter()
1803 .filter(|proposal| {
1804 !matches!(
1805 proposal.status.as_str(),
1806 "accepted" | "applied" | "rejected"
1807 )
1808 })
1809 .count();
1810 let status = if ok { "fresh" } else { "stale or invalid" };
1811 Ok(format!(
1812 "vela proof explain\n\nFrontier: {}\nFrontier id: {}\nProof status: {status}\nAccepted events: {}\nOpen proposals: {open_proposals}\nSnapshot hash: {snapshot_hash}\nEvent log hash: {event_log_hash}\n\nAuthority: `.vela/events/` is replayed into `frontier.json`.\nVisible proof: `proof/latest.json`, `proof/events.manifest.jsonl`, and `proof/replay.trace.jsonl`.\nLockfile: `vela.lock` binds the event log, Vela reducer, verifier set, visible state, and proof digest.\n",
1813 project.project.name,
1814 locked.frontier_id(),
1815 project.events.len(),
1816 ))
1817}
1818
1819fn empty_project(name: &str, description: &str, compiled_at: &str) -> Project {
1820 Project {
1821 vela_version: project::VELA_SCHEMA_VERSION.to_string(),
1822 schema: project::VELA_SCHEMA_URL.to_string(),
1823 frontier_id: None,
1824 project: project::ProjectMeta {
1825 name: name.to_string(),
1826 description: description.to_string(),
1827 compiled_at: compiled_at.to_string(),
1828 compiler: project::VELA_COMPILER_VERSION.to_string(),
1829 papers_processed: 0,
1830 errors: 0,
1831 dependencies: Vec::new(),
1832 },
1833 stats: project::ProjectStats::default(),
1834 findings: Vec::new(),
1835 sources: Vec::new(),
1836 evidence_atoms: Vec::new(),
1837 condition_records: Vec::new(),
1838 review_events: Vec::new(),
1839 confidence_updates: Vec::new(),
1840 events: Vec::new(),
1841 proposals: Vec::new(),
1842 proof_state: proposals::ProofState::default(),
1843 signatures: Vec::new(),
1844 actors: Vec::new(),
1845 artifacts: Vec::new(),
1846 released_diff_packs: Vec::new(),
1847 verdict_conflicts: Vec::new(),
1848 contradictions: Vec::new(),
1849 verifier_attachments: Vec::new(),
1850 attempts: Vec::new(),
1851 attempt_resolutions: Vec::new(),
1852 transfers: Vec::new(),
1853 endorsements: Vec::new(),
1854 statement_attestations: Vec::new(),
1855 anchor_links: Vec::new(),
1856 attempt_claims: Vec::new(),
1857 statement_registrations: Vec::new(),
1858 }
1859}
1860
1861fn write_visible_state(path: &Path, project: &Project, generated_at: &str) -> Result<(), String> {
1862 let bytes = render_visible_state(path, project, generated_at, None)?;
1863 fs::write(path.join("frontier.json"), bytes)
1864 .map_err(|e| format!("Failed to write frontier.json: {e}"))
1865}
1866
1867fn render_visible_state(
1868 path: &Path,
1869 project: &Project,
1870 generated_at: &str,
1871 profile_override: Option<&FrontierProfileV1>,
1872) -> Result<Vec<u8>, String> {
1873 let visible = project_with_frontier_id(project)?;
1874 let snapshot_hash = prefixed(events::snapshot_hash(&visible));
1875 let event_log_hash = prefixed(events::event_log_hash(&visible.events));
1876 let mut value = serde_json::to_value(&visible)
1877 .map_err(|e| format!("Failed to prepare frontier.json: {e}"))?;
1878 if let Some(object) = value.as_object_mut() {
1879 object.insert(
1880 "_warning".to_string(),
1881 serde_json::Value::String(
1882 "Generated by Vela. Do not edit frontier.json directly; use Vela's task-first receipt, signing, materialization, and proof commands."
1883 .to_string(),
1884 ),
1885 );
1886 let profile = match profile_override {
1887 Some(profile) => Some(profile.clone()),
1888 None => match read_repository_profile(path)? {
1889 Some(FrontierProfileFile::V1(profile)) => Some(profile),
1890 _ => None,
1891 },
1892 };
1893 let metadata = match profile {
1894 Some(profile) => {
1895 let projection = profile.project(&visible)?;
1896 json!({
1897 "schema": "vela.frontier_state_meta.v1",
1898 "generated_at": generated_at,
1899 "materialized_from": ".vela/events/",
1900 "proof": "proof/latest.json",
1901 "lockfile": "vela.lock",
1902 "events_manifest": "proof/events.manifest.jsonl",
1903 "replay_trace": "proof/replay.trace.jsonl",
1904 "profile_root": projection.profile_root,
1905 "identity_root": projection.identity_root,
1906 "dependency_root": projection.dependency_root,
1907 "scientific_state_root": projection.scientific_state_root,
1908 "legacy_snapshot_root": snapshot_hash,
1909 "event_log_root": event_log_hash,
1910 "vela_reducer": format!("vela@{}", env!("CARGO_PKG_VERSION")),
1911 })
1912 }
1913 _ => json!({
1914 "schema": "vela.frontier_state_meta.v0.1",
1915 "generated_at": generated_at,
1916 "materialized_from": ".vela/events/",
1917 "proof": "proof/latest.json",
1918 "lockfile": "vela.lock",
1919 "events_manifest": "proof/events.manifest.jsonl",
1920 "replay_trace": "proof/replay.trace.jsonl",
1921 "snapshot_hash": snapshot_hash,
1922 "event_log_hash": event_log_hash,
1923 "vela_reducer": format!("vela@{}", env!("CARGO_PKG_VERSION")),
1924 }),
1925 };
1926 object.insert("_meta".to_string(), metadata);
1927 }
1928 serde_json::to_vec_pretty(&value).map_err(|e| format!("Failed to serialize frontier.json: {e}"))
1929}
1930
1931fn render_synced_manifest(path: &Path, deps: &[ProjectDependency]) -> Result<Vec<u8>, String> {
1932 let mut manifest = match read_manifest(path)? {
1933 Some(m) => m,
1934 None => return Err("frontier.yaml disappeared while rendering visible files".to_string()),
1935 };
1936 manifest.dependencies.frontiers_v2 = deps.to_vec();
1937 serde_yaml::to_string(&manifest)
1938 .map(String::into_bytes)
1939 .map_err(|e| format!("Failed to serialize frontier.yaml: {e}"))
1940}
1941
1942fn write_manifest(path: &Path, project: &Project) -> Result<(), String> {
1943 match read_repository_profile(path)? {
1944 Some(FrontierProfileFile::V1(_)) => Ok(()),
1945 _ => {
1946 let yaml = render_manifest(path, project)?;
1947 fs::write(path.join("frontier.yaml"), yaml)
1948 .map_err(|e| format!("Failed to write frontier.yaml: {e}"))
1949 }
1950 }
1951}
1952
1953fn render_manifest(path: &Path, project: &Project) -> Result<Vec<u8>, String> {
1954 let existing = match read_repository_profile(path)? {
1955 Some(FrontierProfileFile::LegacyV0_1(manifest)) => Some(manifest),
1956 Some(FrontierProfileFile::V1(_)) => {
1957 return Err(
1958 "cannot render a legacy frontier manifest over a Profile v1 document".to_string(),
1959 );
1960 }
1961 None => None,
1962 };
1963 let existing_dependencies = existing
1964 .as_ref()
1965 .map(|manifest| manifest.dependencies.clone())
1966 .unwrap_or_default();
1967 let manifest = FrontierManifest {
1968 schema: FRONTIER_MANIFEST_SCHEMA.to_string(),
1969 layout: FRONTIER_REPO_LAYOUT.to_string(),
1970 mode: "split".to_string(),
1971 frontier_id: Some(project.frontier_id()),
1972 name: project.project.name.clone(),
1973 description: existing
1974 .as_ref()
1975 .map(|manifest| manifest.description.clone())
1976 .unwrap_or_else(|| project.project.description.clone()),
1977 visibility: "public".to_string(),
1978 scope: existing
1979 .as_ref()
1980 .map(|manifest| manifest.scope.clone())
1981 .unwrap_or_else(|| FrontierScope {
1982 question: project.project.description.clone(),
1983 includes: Vec::new(),
1984 excludes: Vec::new(),
1985 }),
1986 carina: None,
1987 vela: VelaManifest {
1988 reducer: format!("vela@{}", env!("CARGO_PKG_VERSION")),
1989 },
1990 paths: FrontierPaths {
1991 state: "frontier.json".to_string(),
1992 sources: "sources/".to_string(),
1993 artifacts: "artifacts/".to_string(),
1994 review: "review/".to_string(),
1995 proof: "proof/".to_string(),
1996 exports: "exports/".to_string(),
1997 },
1998 maintainers: existing
1999 .as_ref()
2000 .map(|manifest| manifest.maintainers.clone())
2001 .unwrap_or_default(),
2002 policies: existing
2003 .as_ref()
2004 .map(|manifest| manifest.policies.clone())
2005 .unwrap_or_default(),
2006 license: existing
2007 .as_ref()
2008 .map(|manifest| manifest.license.clone())
2009 .unwrap_or_default(),
2010 dependencies: ManifestDependencies {
2011 frontiers: existing_dependencies.frontiers,
2012 packages: existing_dependencies.packages,
2013 adapters: existing_dependencies.adapters,
2014 frontiers_v2: project.project.dependencies.clone(),
2015 },
2016 };
2017 serde_yaml::to_string(&manifest)
2018 .map(String::into_bytes)
2019 .map_err(|e| format!("Failed to serialize frontier.yaml: {e}"))
2020}
2021
2022fn write_lock(
2023 path: &Path,
2024 project: &Project,
2025 proof: &ProofWrite,
2026 generated_at: &str,
2027) -> Result<FrontierLock, String> {
2028 let (lock, bytes) = render_lock(path, project, proof, generated_at)?;
2029 fs::write(path.join("vela.lock"), bytes)
2030 .map_err(|e| format!("Failed to write vela.lock: {e}"))?;
2031 Ok(lock)
2032}
2033
2034fn render_lock(
2035 path: &Path,
2036 project: &Project,
2037 proof: &ProofWrite,
2038 generated_at: &str,
2039) -> Result<(FrontierLock, Vec<u8>), String> {
2040 let locked = project_with_frontier_id(project)?;
2041 let reducer_package = format!("vela@{}", env!("CARGO_PKG_VERSION"));
2042 let verifier_package = format!("vela-verify@{}", env!("CARGO_PKG_VERSION"));
2043 let lock = FrontierLock {
2044 schema: FRONTIER_LOCK_SCHEMA.to_string(),
2045 generated_at: generated_at.to_string(),
2046 vela_version: env!("CARGO_PKG_VERSION").to_string(),
2047 frontier_id: locked.frontier_id(),
2048 canonicalization: LockCanonicalization::default(),
2049 reducer: LockPackage {
2050 package: reducer_package.clone(),
2051 digest: identity_digest(&reducer_package),
2052 },
2053 verifiers: LockVerifiers {
2054 package: verifier_package.clone(),
2055 digest: identity_digest(&verifier_package),
2056 kinds: collect_verifier_kinds(path),
2057 },
2058 snapshot_hash: prefixed(events::snapshot_hash(&locked)),
2059 event_log_hash: prefixed(events::event_log_hash(&locked.events)),
2060 proposal_state_hash: proposal_state_hash(&locked.proposals),
2061 sources_hash: directory_hash(&path.join("sources")),
2062 artifacts_hash: directory_hash(&path.join("artifacts")),
2063 review_hash: directory_hash(&path.join("review")),
2064 proof_freshness: proof.freshness.clone(),
2065 proof: LockProof {
2066 latest: proof.latest.clone(),
2067 digest: proof.digest.clone(),
2068 freshness: proof.freshness.clone(),
2069 events_manifest: proof.events_manifest.clone(),
2070 replay_trace: proof.replay_trace.clone(),
2071 },
2072 paths: LockPaths {
2073 frontier: "frontier.json".to_string(),
2074 events: ".vela/events/".to_string(),
2075 },
2076 dependencies: locked
2082 .project
2083 .dependencies
2084 .iter()
2085 .map(|d| LockedDependency {
2086 name: d.name.clone(),
2087 source: d.source.clone(),
2088 vfr_id: d.vfr_id.clone(),
2089 locator: d.locator.clone(),
2090 pinned_snapshot_hash: d.pinned_snapshot_hash.clone(),
2091 })
2092 .collect(),
2093 };
2094 let yaml = serde_yaml::to_string(&lock)
2095 .map(String::into_bytes)
2096 .map_err(|e| format!("Failed to serialize vela.lock: {e}"))?;
2097 Ok((lock, yaml))
2098}
2099
2100fn render_lock_v1(
2101 path: &Path,
2102 project: &Project,
2103 profile: &FrontierProfileV1,
2104 proof: &ProofWrite,
2105 generated_at: &str,
2106) -> Result<(FrontierLockV1, Vec<u8>), String> {
2107 let locked = project_with_frontier_id(project)?;
2108 let projection = profile.project(&locked)?;
2109 let reducer_package = format!("vela@{}", env!("CARGO_PKG_VERSION"));
2110 let verifier_package = format!("vela-verify@{}", env!("CARGO_PKG_VERSION"));
2111 let lock = FrontierLockV1 {
2112 schema: FRONTIER_LOCK_SCHEMA_V1.to_string(),
2113 generated_at: generated_at.to_string(),
2114 vela_version: env!("CARGO_PKG_VERSION").to_string(),
2115 frontier_id: projection.frontier_id,
2116 profile_root: projection.profile_root,
2117 identity_root: projection.identity_root,
2118 dependency_root: projection.dependency_root,
2119 scientific_state_root: projection.scientific_state_root,
2120 legacy_snapshot_root: prefixed(events::snapshot_hash(&locked)),
2121 event_log_root: prefixed(events::event_log_hash(&locked.events)),
2122 event_count: locked.events.len() as u64,
2123 proposal_root: proposal_state_hash(&locked.proposals),
2124 canonicalization: LockCanonicalization::default(),
2125 reducer: LockPackage {
2126 package: reducer_package.clone(),
2127 digest: identity_digest(&reducer_package),
2128 },
2129 verifiers: LockVerifiers {
2130 package: verifier_package.clone(),
2131 digest: identity_digest(&verifier_package),
2132 kinds: collect_verifier_kinds(path),
2133 },
2134 sources_hash: directory_hash(&path.join("sources")),
2135 artifacts_hash: directory_hash(&path.join("artifacts")),
2136 review_hash: directory_hash(&path.join("review")),
2137 proof_freshness: proof.freshness.clone(),
2138 proof: LockProof {
2139 latest: proof.latest.clone(),
2140 digest: proof.digest.clone(),
2141 freshness: proof.freshness.clone(),
2142 events_manifest: proof.events_manifest.clone(),
2143 replay_trace: proof.replay_trace.clone(),
2144 },
2145 paths: LockPaths {
2146 frontier: "frontier.json".to_string(),
2147 events: ".vela/events/".to_string(),
2148 },
2149 dependencies: projection.dependencies,
2150 };
2151 let bytes = serde_yaml::to_string(&lock)
2152 .map(String::into_bytes)
2153 .map_err(|error| format!("Failed to serialize vela.lock v1: {error}"))?;
2154 Ok((lock, bytes))
2155}
2156
2157fn collect_verifier_kinds(path: &Path) -> Vec<String> {
2163 let witnesses_dir = path.join("witnesses");
2164 let root = if witnesses_dir.is_dir() {
2165 witnesses_dir
2166 } else {
2167 path.to_path_buf()
2168 };
2169 let mut files = Vec::new();
2170 collect_witness_json(&root, &mut files);
2171 let mut kinds: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
2172 for f in files {
2173 if let Ok(text) = fs::read_to_string(&f)
2174 && let Ok(v) = serde_json::from_str::<serde_json::Value>(&text)
2175 && let Some(k) = v.get("kind").and_then(|k| k.as_str())
2176 {
2177 kinds.insert(k.to_string());
2178 }
2179 }
2180 kinds.into_iter().collect()
2181}
2182
2183fn collect_witness_json(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
2184 let Ok(entries) = fs::read_dir(dir) else {
2185 return;
2186 };
2187 for entry in entries.flatten() {
2188 let p = entry.path();
2189 if p.is_dir() {
2190 if matches!(
2191 p.file_name().and_then(|n| n.to_str()),
2192 Some(".vela") | Some(".git")
2193 ) {
2194 continue;
2195 }
2196 collect_witness_json(&p, out);
2197 } else if p
2198 .file_name()
2199 .and_then(|n| n.to_str())
2200 .is_some_and(|n| n.ends_with(".witness.json"))
2201 {
2202 out.push(p);
2203 }
2204 }
2205}
2206
2207fn materialization_generated_at(_path: &Path, project: &Project) -> String {
2216 project
2217 .events
2218 .iter()
2219 .map(|e| e.timestamp.as_str())
2220 .max()
2221 .map(|s| s.to_string())
2222 .unwrap_or_else(|| "1970-01-01T00:00:00Z".to_string())
2223}
2224
2225fn project_with_frontier_id(project: &Project) -> Result<Project, String> {
2226 let frontier_id = project.frontier_id();
2227 let mut value = serde_json::to_value(project)
2228 .map_err(|e| format!("Failed to prepare frontier state: {e}"))?;
2229 if let Some(object) = value.as_object_mut() {
2230 object.insert(
2231 "frontier_id".to_string(),
2232 serde_json::Value::String(frontier_id),
2233 );
2234 }
2235 serde_json::from_value(value).map_err(|e| format!("Failed to normalize frontier state: {e}"))
2236}
2237
2238fn write_frontier_card(path: &Path, name: &str) -> Result<(), String> {
2239 let text = format!(
2240 "# {name}\n\nThis is a Vela frontier repository. Agents follow `next -> work -> land`; a human uses `sign` for deferred decisions, and Git publishes the resulting bytes.\n\n- State entrypoint: `frontier.json`\n- Manifest: `frontier.yaml`\n- Lockfile: `vela.lock`\n\nRun:\n\n```bash\nvela agents sync . --json\nvela status . --json\nvela next . --json\nvela check . --strict --json\n```\n"
2241 );
2242 fs::write(path.join("README.md"), text).map_err(|e| format!("Failed to write README.md: {e}"))
2243}
2244
2245fn write_frontier_card_v1(path: &Path, name: &str, scope: &str) -> Result<(), String> {
2246 let text = format!(
2247 "# {name}\n\n{scope}\n\nThis repository is a Vela Frontier. Canonical state lives in `.vela/`; `frontier.json` and `vela.lock` are generated read projections.\n\n## Start here\n\n```bash\nvela status . --json\nvela next . --json\nvela check . --strict --json\n```\n\nAgents may produce and land bounded evidence. Only verified policy or an exact protected human decision changes accepted scientific state.\n"
2248 );
2249 fs::write(path.join("README.md"), text).map_err(|error| {
2250 format!(
2251 "Failed to write Profile v1 README.md '{}': {error}",
2252 path.join("README.md").display()
2253 )
2254 })
2255}
2256
2257fn write_scope(path: &Path, name: &str) -> Result<(), String> {
2258 let text = format!(
2259 "# Scope\n\nFrontier: {name}\n\nThis file records boundaries, exclusions, caveats, and review policy for the frontier.\n\nExternal artifacts and agent outputs are source material until reviewed into accepted Vela events.\n"
2260 );
2261 fs::write(path.join("SCOPE.md"), text).map_err(|e| format!("Failed to write SCOPE.md: {e}"))
2262}
2263
2264fn write_scope_v1(path: &Path, scope: &str) -> Result<(), String> {
2265 let text = format!(
2266 "# Scope\n\n## Question\n\n{scope}\n\n## Includes\n\nNo additional inclusions are declared.\n\n## Excludes\n\nNo exclusions are declared.\n"
2267 );
2268 fs::write(path.join("SCOPE.md"), text).map_err(|error| {
2269 format!(
2270 "Failed to write Profile v1 SCOPE.md '{}': {error}",
2271 path.join("SCOPE.md").display()
2272 )
2273 })
2274}
2275
2276fn write_proof(path: &Path, project: &Project, generated_at: &str) -> Result<ProofWrite, String> {
2277 let rendered = render_proof(path, project, generated_at, None)?;
2278 let proof_dir = path.join("proof");
2279 fs::create_dir_all(&proof_dir).map_err(|e| format!("Failed to create proof/: {e}"))?;
2280 for (relative_path, bytes) in &rendered.files {
2281 fs::write(proof_dir.join(relative_path), bytes)
2282 .map_err(|e| format!("Failed to write proof/{relative_path}: {e}"))?;
2283 }
2284 Ok(rendered.proof)
2285}
2286
2287fn render_proof(
2288 path: &Path,
2289 project: &Project,
2290 generated_at: &str,
2291 profile_override: Option<&FrontierProfileV1>,
2292) -> Result<RenderedProof, String> {
2293 let locked = project_with_frontier_id(project)?;
2294 let proof_dir = path.join("proof");
2295
2296 let event_log_hash = prefixed(events::event_log_hash(&locked.events));
2305 let snapshot_hash = prefixed(events::snapshot_hash(&locked));
2306 let profile_projection = match profile_override {
2307 Some(profile) => Some(profile.project(&locked)?),
2308 None => match read_repository_profile(path)? {
2309 Some(FrontierProfileFile::V1(profile)) => Some(profile.project(&locked)?),
2310 _ => None,
2311 },
2312 };
2313 let (event_root_field, state_root_field, state_root) = match &profile_projection {
2314 Some(projection) => (
2315 "event_log_root",
2316 "scientific_state_root",
2317 projection.scientific_state_root.as_str(),
2318 ),
2319 None => ("event_log_hash", "frontier_hash", snapshot_hash.as_str()),
2320 };
2321 if proof_is_current(
2322 &proof_dir,
2323 event_root_field,
2324 &event_log_hash,
2325 state_root_field,
2326 state_root,
2327 ) {
2328 return Ok(RenderedProof {
2329 files: VisibleRepoFiles::new(),
2330 proof: ProofWrite {
2331 digest: directory_hash(&proof_dir),
2332 freshness: "fresh".to_string(),
2333 latest: "proof/latest.json".to_string(),
2334 events_manifest: "proof/events.manifest.jsonl".to_string(),
2335 replay_trace: "proof/replay.trace.jsonl".to_string(),
2336 },
2337 });
2338 }
2339 let proposal_state_hash = proposal_state_hash(&locked.proposals);
2340 let reducer_package = format!("vela@{}", env!("CARGO_PKG_VERSION"));
2341
2342 let common_reducer = json!({
2343 "name": "vela",
2344 "version": env!("CARGO_PKG_VERSION"),
2345 "package": reducer_package,
2346 "digest": identity_digest(&format!("vela@{}", env!("CARGO_PKG_VERSION"))),
2347 });
2348 let common_paths = json!({
2349 "frontier": "frontier.json",
2350 "lockfile": "vela.lock",
2351 "events_authority": ".vela/events/",
2352 "events_manifest": "proof/events.manifest.jsonl",
2353 "replay_trace": "proof/replay.trace.jsonl"
2354 });
2355 let latest = match &profile_projection {
2356 Some(projection) => json!({
2357 "schema": "vela.frontier_repo_proof.v1",
2358 "frontier_id": projection.frontier_id,
2359 "profile_root": projection.profile_root,
2360 "identity_root": projection.identity_root,
2361 "dependency_root": projection.dependency_root,
2362 "scientific_state_root": projection.scientific_state_root,
2363 "legacy_snapshot_root": snapshot_hash,
2364 "event_log_root": event_log_hash,
2365 "proposal_root": proposal_state_hash,
2366 "reducer": common_reducer,
2367 "materialized_at": generated_at,
2368 "freshness": "fresh",
2369 "event_count": locked.events.len(),
2370 "paths": common_paths,
2371 "warning": "Generated integrity evidence. Scientific acceptance remains event-derived."
2372 }),
2373 None => json!({
2374 "schema": "vela.frontier_repo_proof.v0.1",
2375 "frontier_id": locked.frontier_id(),
2376 "frontier_hash": snapshot_hash,
2377 "event_log_hash": event_log_hash,
2378 "proposal_state_hash": proposal_state_hash,
2379 "reducer": common_reducer,
2380 "materialized_at": generated_at,
2381 "freshness": "fresh",
2382 "event_count": locked.events.len(),
2383 "paths": common_paths,
2384 "warning": "Do not edit frontier.json directly. Use Vela's task-first receipt, signing, materialization, and proof commands."
2385 }),
2386 };
2387 let mut files = VisibleRepoFiles::new();
2388 files.insert(
2389 "latest.json".to_string(),
2390 serde_json::to_vec_pretty(&latest)
2391 .map_err(|e| format!("Failed to serialize proof/latest.json: {e}"))?,
2392 );
2393
2394 let mut manifest_lines = String::new();
2395 let mut trace_lines = String::new();
2396 let mut chained_log_hash = String::new();
2404 let mut ordered: Vec<_> = locked.events.iter().collect();
2408 ordered.sort_by(|a, b| a.id.cmp(&b.id));
2409 for (idx, event) in ordered.into_iter().enumerate() {
2410 let event_hash = prefixed(event_hash(event));
2411 let entry = json!({
2412 "schema": "vela.proof_event_manifest_entry.v0.1",
2413 "index": idx + 1,
2414 "id": event.id,
2415 "kind": event.kind,
2416 "target": event.target,
2417 "actor": event.actor,
2418 "timestamp": event.timestamp,
2419 "event_hash": event_hash,
2420 "before_hash": event.before_hash,
2421 "after_hash": event.after_hash,
2422 "caveat_count": event.caveats.len(),
2423 });
2424 manifest_lines.push_str(
2425 &serde_json::to_string(&entry)
2426 .map_err(|e| format!("Failed to serialize event manifest entry: {e}"))?,
2427 );
2428 manifest_lines.push('\n');
2429
2430 chained_log_hash = hex::encode(Sha256::digest(
2431 format!("{chained_log_hash}{event_hash}").as_bytes(),
2432 ));
2433 let trace = json!({
2434 "schema": "vela.replay_trace_entry.v0.2",
2435 "step": idx + 1,
2436 "event": event.id,
2437 "kind": event.kind,
2438 "event_hash": event_hash,
2439 "event_log_hash_after": prefixed(chained_log_hash.clone()),
2440 "target_after_hash": event.after_hash,
2441 });
2442 trace_lines.push_str(
2443 &serde_json::to_string(&trace)
2444 .map_err(|e| format!("Failed to serialize replay trace entry: {e}"))?,
2445 );
2446 trace_lines.push('\n');
2447 }
2448 files.insert(
2449 "events.manifest.jsonl".to_string(),
2450 manifest_lines.into_bytes(),
2451 );
2452 files.insert("replay.trace.jsonl".to_string(), trace_lines.into_bytes());
2453 let state_label = if profile_projection.is_some() {
2454 "Scientific-state root"
2455 } else {
2456 "Snapshot hash"
2457 };
2458 files.insert(
2459 "freshness.md".to_string(),
2460 format!(
2461 "# Freshness\n\nCurrent proof status: fresh\n\n`frontier.json` was materialized from `.vela/events/` at {generated_at}.\n\nAccepted events: {}\nEvent log root: `{event_log_hash}`\n{state_label}: `{state_root}`\n\nRun:\n\n```bash\nvela check . --strict --json\nvela proof verify . --json\n```\n",
2462 locked.events.len()
2463 )
2464 .into_bytes(),
2465 );
2466
2467 let hashes = match &profile_projection {
2468 Some(projection) => json!({
2469 "schema": "vela.frontier_repo_hashes.v1",
2470 "frontier_id": projection.frontier_id,
2471 "profile_root": projection.profile_root,
2472 "identity_root": projection.identity_root,
2473 "dependency_root": projection.dependency_root,
2474 "scientific_state_root": projection.scientific_state_root,
2475 "legacy_snapshot_root": snapshot_hash,
2476 "event_log_root": event_log_hash,
2477 "proposal_root": proposal_state_hash,
2478 "sources_hash": directory_hash(&path.join("sources")),
2479 "artifacts_hash": directory_hash(&path.join("artifacts")),
2480 "review_hash": directory_hash(&path.join("review")),
2481 }),
2482 None => json!({
2483 "schema": "vela.frontier_repo_hashes.v0.1",
2484 "frontier_id": locked.frontier_id(),
2485 "snapshot_hash": snapshot_hash,
2486 "event_log_hash": event_log_hash,
2487 "proposal_state_hash": proposal_state_hash,
2488 "sources_hash": directory_hash(&path.join("sources")),
2489 "artifacts_hash": directory_hash(&path.join("artifacts")),
2490 "review_hash": directory_hash(&path.join("review")),
2491 }),
2492 };
2493 files.insert(
2494 "hashes.json".to_string(),
2495 serde_json::to_vec_pretty(&hashes)
2496 .map_err(|e| format!("Failed to serialize proof/hashes.json: {e}"))?,
2497 );
2498 let digest = directory_hash_with_replacements(&proof_dir, &files);
2499
2500 Ok(RenderedProof {
2501 files,
2502 proof: ProofWrite {
2503 digest,
2504 freshness: "fresh".to_string(),
2505 latest: "proof/latest.json".to_string(),
2506 events_manifest: "proof/events.manifest.jsonl".to_string(),
2507 replay_trace: "proof/replay.trace.jsonl".to_string(),
2508 },
2509 })
2510}
2511
2512fn proof_is_current(
2517 proof_dir: &Path,
2518 event_root_field: &str,
2519 event_log_root: &str,
2520 state_root_field: &str,
2521 state_root: &str,
2522) -> bool {
2523 let Ok(text) = fs::read_to_string(proof_dir.join("latest.json")) else {
2524 return false;
2525 };
2526 let Ok(latest) = serde_json::from_str::<serde_json::Value>(&text) else {
2527 return false;
2528 };
2529 let same_log = latest.get(event_root_field).and_then(|v| v.as_str()) == Some(event_log_root);
2530 let same_snapshot = latest.get(state_root_field).and_then(|v| v.as_str()) == Some(state_root);
2531 let same_reducer = latest.pointer("/reducer/version").and_then(|v| v.as_str())
2532 == Some(env!("CARGO_PKG_VERSION"));
2533 same_log
2534 && same_snapshot
2535 && same_reducer
2536 && proof_dir.join("events.manifest.jsonl").is_file()
2537 && proof_dir.join("replay.trace.jsonl").is_file()
2538 && proof_dir.join("hashes.json").is_file()
2539}
2540
2541fn proposal_state_hash(proposals: &[crate::proposals::StateProposal]) -> String {
2542 let bytes = crate::canonical::to_canonical_bytes(proposals).unwrap_or_default();
2543 prefixed(hex::encode(Sha256::digest(bytes)))
2544}
2545
2546fn directory_hash(path: &Path) -> String {
2547 let mut entries = Vec::new();
2548 if path.is_dir() {
2549 collect_file_entries(path, path, &mut entries);
2550 }
2551 entries.sort_by(|a, b| a.0.cmp(&b.0));
2552 let bytes = crate::canonical::to_canonical_bytes(&entries).unwrap_or_default();
2553 prefixed(hex::encode(Sha256::digest(bytes)))
2554}
2555
2556fn directory_hash_with_replacements(path: &Path, replacements: &VisibleRepoFiles) -> String {
2557 let mut entries = Vec::new();
2558 if path.is_dir() {
2559 collect_file_entries(path, path, &mut entries);
2560 }
2561 let mut entries = entries.into_iter().collect::<BTreeMap<_, _>>();
2562 for (relative_path, bytes) in replacements {
2563 entries.insert(
2564 relative_path.clone(),
2565 prefixed(hex::encode(Sha256::digest(bytes))),
2566 );
2567 }
2568 let entries = entries.into_iter().collect::<Vec<_>>();
2569 let bytes = crate::canonical::to_canonical_bytes(&entries).unwrap_or_default();
2570 prefixed(hex::encode(Sha256::digest(bytes)))
2571}
2572
2573fn collect_file_entries(root: &Path, path: &Path, entries: &mut Vec<(String, String)>) {
2574 let Ok(read_dir) = fs::read_dir(path) else {
2575 return;
2576 };
2577 for entry in read_dir.flatten() {
2578 let entry_path = entry.path();
2579 let Some(name) = entry_path.file_name().and_then(|s| s.to_str()) else {
2580 continue;
2581 };
2582 if name == ".DS_Store" {
2583 continue;
2584 }
2585 if entry_path.is_dir() {
2586 collect_file_entries(root, &entry_path, entries);
2587 } else if entry_path.is_file() {
2588 let rel = entry_path
2589 .strip_prefix(root)
2590 .unwrap_or(&entry_path)
2591 .to_string_lossy()
2592 .replace('\\', "/");
2593 let digest = fs::read(&entry_path)
2594 .map(|bytes| prefixed(hex::encode(Sha256::digest(bytes))))
2595 .unwrap_or_else(|_| "sha256:unreadable".to_string());
2596 entries.push((rel, digest));
2597 }
2598 }
2599}
2600
2601fn event_hash(event: &crate::events::StateEvent) -> String {
2602 let bytes = crate::canonical::to_canonical_bytes(event).unwrap_or_default();
2603 hex::encode(Sha256::digest(bytes))
2604}
2605
2606fn identity_digest(value: &str) -> String {
2607 prefixed(hex::encode(Sha256::digest(value.as_bytes())))
2608}
2609
2610fn prefixed(hash: String) -> String {
2611 if hash.starts_with("sha256:") {
2612 hash
2613 } else {
2614 format!("sha256:{hash}")
2615 }
2616}
2617
2618fn issue(rule_id: &str, message: impl Into<String>) -> RepoLayoutIssue {
2619 RepoLayoutIssue {
2620 rule_id: rule_id.to_string(),
2621 message: message.into(),
2622 }
2623}
2624
2625fn default_split_mode() -> String {
2626 "split".to_string()
2627}
2628
2629fn default_visibility() -> String {
2630 "public".to_string()
2631}
2632
2633#[cfg(test)]
2634mod tests {
2635 use super::*;
2636
2637 #[test]
2638 fn retired_carina_field_is_readable_only_in_legacy_manifests() {
2639 let tmp = tempfile::tempdir().expect("tempdir");
2640 fs::write(
2641 tmp.path().join("frontier.yaml"),
2642 r#"schema: vela.frontier_manifest.v0.1
2643layout: vela.frontier_repo.v0.1
2644mode: split
2645name: Historical formal frontier
2646carina:
2647 kernel: carina@0.1.0
2648vela:
2649 reducer: vela@0.757.4
2650paths:
2651 state: frontier.json
2652 sources: sources/
2653 artifacts: artifacts/
2654 review: review/
2655 proof: proof/
2656 exports: exports/
2657"#,
2658 )
2659 .expect("write historical manifest");
2660
2661 let Some(FrontierProfileFile::LegacyV0_1(manifest)) =
2662 read_repository_profile(tmp.path()).expect("parse historical manifest")
2663 else {
2664 panic!("expected legacy manifest");
2665 };
2666 assert_eq!(
2667 manifest.carina,
2668 Some(LegacyCarinaManifest {
2669 kernel: "carina@0.1.0".to_string()
2670 })
2671 );
2672
2673 let project = empty_project(
2674 "Historical formal frontier",
2675 "Legacy rendering drops retired integration metadata.",
2676 "2026-07-23T00:00:00Z",
2677 );
2678 let rendered = String::from_utf8(
2679 render_manifest(tmp.path(), &project).expect("render migrated legacy manifest"),
2680 )
2681 .expect("rendered manifest is UTF-8");
2682 assert!(
2683 !rendered.contains("carina:") && !rendered.contains("carina@0.1.0"),
2684 "legacy re-rendering must drop retired carina metadata:\n{rendered}"
2685 );
2686 let rendered_manifest: FrontierManifest =
2687 serde_yaml::from_str(&rendered).expect("parse rendered legacy manifest");
2688 assert_eq!(rendered_manifest.carina, None);
2689
2690 let profile_v1_with_carina = r#"schema: vela.frontier-profile.v1
2691frontier_id: vfr_0123456789abcdef
2692name: Closed profile
2693summary: Profile v1 rejects retired integration metadata.
2694scope:
2695 question: Which exact result does this Frontier maintain?
2696 includes:
2697 - Rooted evidence
2698 excludes:
2699 - Unbounded discovery
2700maintainers:
2701 - maintainer:example
2702license:
2703 content: CC-BY-4.0
2704 code: Apache-2.0
2705 data: CC0-1.0
2706carina:
2707 kernel: carina@0.1.0
2708"#;
2709 let error = FrontierProfileV1::from_yaml_str(profile_v1_with_carina)
2710 .expect_err("Profile v1 must reject the retired carina field");
2711 assert!(
2712 error.contains("unknown field `carina`"),
2713 "unexpected closed Profile v1 error: {error}"
2714 );
2715 }
2716
2717 #[test]
2718 fn visible_repo_render_is_read_only_and_byte_equivalent_to_write() {
2719 let tmp = tempfile::tempdir().expect("tempdir");
2720 initialize(
2721 tmp.path(),
2722 InitOptions {
2723 name: "Rendered frontier",
2724 initialize_git: false,
2725 },
2726 )
2727 .expect("initialize frontier");
2728 let source = crate::repo::VelaSource::VelaRepo(tmp.path().to_path_buf());
2729 let mut project = crate::repo::load(&source).expect("load frontier");
2730 project.project.description = "rendered without a frontier write".to_string();
2731 let original_frontier = fs::read(tmp.path().join("frontier.json")).unwrap();
2732
2733 let rendered = render_visible_repo_files(tmp.path(), &project).expect("render files");
2734
2735 assert_eq!(
2736 fs::read(tmp.path().join("frontier.json")).unwrap(),
2737 original_frontier,
2738 "rendering must not modify the frontier"
2739 );
2740 assert!(rendered.contains_key("frontier.json"));
2741 assert!(rendered.contains_key("frontier.yaml"));
2742 assert!(rendered.contains_key("proof/latest.json"));
2743 assert!(rendered.contains_key("vela.lock"));
2744
2745 write_visible_repo_files(tmp.path(), &project).expect("write rendered files");
2746 for (relative_path, expected) in rendered {
2747 assert_eq!(
2748 fs::read(tmp.path().join(&relative_path)).unwrap(),
2749 expected,
2750 "rendered bytes differ for {relative_path}"
2751 );
2752 }
2753 }
2754
2755 #[test]
2756 fn initialize_writes_unfiltered_frontier_gate_for_every_public_root() {
2757 let tmp = tempfile::tempdir().expect("tempdir");
2758 initialize(
2759 tmp.path(),
2760 InitOptions {
2761 name: "Unskippable frontier gate",
2762 initialize_git: false,
2763 },
2764 )
2765 .expect("initialize frontier");
2766
2767 let workflow = fs::read_to_string(tmp.path().join(".github/workflows/vela-frontier.yml"))
2768 .expect("read generated frontier workflow");
2769 let triggers = workflow
2770 .split_once("\npermissions:")
2771 .map(|(triggers, _)| triggers)
2772 .expect("workflow has permissions boundary after triggers");
2773
2774 assert!(triggers.contains(" push:\n branches: [main]"));
2775 assert!(triggers.contains(" pull_request: {}"));
2776 assert!(triggers.contains(" workflow_dispatch: {}"));
2777 let expected_release = current_vela_release();
2778 assert!(workflow.contains(&format!(
2779 " - uses: {VELA_ACTION_REPOSITORY}@{expected_release}"
2780 )));
2781 assert!(workflow.contains(&format!(" vela-version: {expected_release}")));
2782 assert!(!workflow.contains(" strict:"));
2783 assert!(!workflow.contains("@main"));
2784 assert!(!workflow.contains("constellate-science/vela"));
2785 assert!(!workflow.contains("vela sign"));
2786
2787 let has_path_filter = triggers.lines().any(|line| {
2788 let line = line.trim_start();
2789 !line.starts_with('#') && (line.contains("paths:") || line.contains("paths-ignore:"))
2790 });
2791 let public_canonical_changes = [
2792 ".vela/events/ve_example.json",
2793 "witnesses/vw_example/witness.json",
2794 "records/receipt.json",
2795 "sources/source.pdf",
2796 "artifacts/va_example",
2797 "review/decision-brief.json",
2798 "proof/latest.json",
2799 "frontier.json",
2800 "frontier.yaml",
2801 "vela.lock",
2802 ];
2803 for changed_path in public_canonical_changes {
2804 assert!(
2805 !has_path_filter,
2806 "a direct change to public canonical path {changed_path} must trigger the generated frontier gate"
2807 );
2808 }
2809 }
2810
2811 #[test]
2812 fn init_commands_quote_frontier_paths_as_one_shell_argument() {
2813 let commands = init_next_commands(Path::new("frontier with 'quotes' and spaces"));
2814 assert_eq!(
2815 commands[0],
2816 "vela agents sync 'frontier with '\"'\"'quotes'\"'\"' and spaces' --json"
2817 );
2818 assert!(
2819 commands
2820 .iter()
2821 .all(|command| command.contains("'frontier with '\"'\"'quotes'\"'\"' and spaces'"))
2822 );
2823 }
2824
2825 #[test]
2826 fn initialize_writes_canonical_git_attributes() {
2827 let tmp = tempfile::tempdir().expect("tempdir");
2828 let payload = initialize(
2829 tmp.path(),
2830 InitOptions {
2831 name: "Attribute-safe frontier",
2832 initialize_git: false,
2833 },
2834 )
2835 .expect("initialize frontier");
2836
2837 let attributes = fs::read_to_string(tmp.path().join(".gitattributes"))
2838 .expect("read generated attributes");
2839 assert!(attributes.contains("* text=auto eol=lf"));
2840 assert!(attributes.contains(".vela/** -filter -ident -working-tree-encoding -merge -text"));
2841 assert!(attributes.contains(
2842 ".vela/events/** -filter -ident -working-tree-encoding -merge diff text eol=lf"
2843 ));
2844 assert!(attributes.contains(
2845 "frontier.json -filter -ident -working-tree-encoding -merge diff text eol=lf"
2846 ));
2847 assert!(
2848 attributes.contains("review/** -filter -ident -working-tree-encoding -merge -text")
2849 );
2850 assert!(attributes.contains("witnesses/** filter=lfs diff=lfs merge=lfs -text"));
2851 let ignore =
2852 fs::read_to_string(tmp.path().join(".gitignore")).expect("read generated ignore rules");
2853 assert!(ignore.contains("/.vela/agents/"));
2854 assert!(ignore.contains("/.vela/keys/"));
2855 assert!(ignore.contains("/.vela/operation-journals/"));
2856 assert!(ignore.contains("/.vela/work/"));
2857 assert!(ignore.contains("/.vela/artifact-blobs/"));
2858 assert!(ignore.contains("/exports/"));
2859 assert!(
2860 !ignore.lines().any(|line| line.trim() == "/proof/"),
2861 "materialized proof review bytes must remain clone-visible"
2862 );
2863 assert!(
2864 !ignore.lines().any(|line| line.trim() == "/records/"),
2865 "public compatibility records must survive a clean clone"
2866 );
2867 assert!(
2868 payload["wrote"]
2869 .as_array()
2870 .expect("wrote array")
2871 .iter()
2872 .any(|entry| entry == ".gitattributes")
2873 );
2874 }
2875
2876 #[test]
2877 fn proof_current_requires_matching_snapshot_hash() {
2878 let tmp = tempfile::tempdir().expect("tempdir");
2879 let proof_dir = tmp.path();
2880 fs::write(
2881 proof_dir.join("latest.json"),
2882 serde_json::to_string_pretty(&json!({
2883 "event_log_hash": "sha256:event-log",
2884 "frontier_hash": "sha256:old-snapshot",
2885 "reducer": {
2886 "version": env!("CARGO_PKG_VERSION")
2887 }
2888 }))
2889 .expect("serialize proof latest"),
2890 )
2891 .expect("write proof latest");
2892 fs::write(proof_dir.join("events.manifest.jsonl"), "").expect("write events manifest");
2893 fs::write(proof_dir.join("replay.trace.jsonl"), "").expect("write replay trace");
2894 fs::write(proof_dir.join("hashes.json"), "{}").expect("write hashes");
2895
2896 assert!(!proof_is_current(
2897 proof_dir,
2898 "event_log_hash",
2899 "sha256:event-log",
2900 "frontier_hash",
2901 "sha256:new-snapshot"
2902 ));
2903 }
2904
2905 #[test]
2906 fn collect_verifier_kinds_scans_witnesses_dir_sorted_unique() {
2907 let tmp = tempfile::tempdir().expect("tempdir");
2908 let root = tmp.path();
2909 let wdir = root.join("witnesses");
2910 fs::create_dir_all(&wdir).expect("mkdir witnesses");
2911 fs::write(wdir.join("a.witness.json"), r#"{"kind":"sidon","n":8}"#).unwrap();
2912 fs::write(wdir.join("b.witness.json"), r#"{"kind":"golomb","n":5}"#).unwrap();
2913 fs::write(wdir.join("c.witness.json"), r#"{"kind":"sidon","n":9}"#).unwrap();
2914 fs::write(wdir.join("notes.json"), r#"{"kind":"ignored"}"#).unwrap();
2916 fs::write(root.join("stray.witness.json"), r#"{"kind":"cap"}"#).unwrap();
2919 assert_eq!(
2920 collect_verifier_kinds(root),
2921 vec!["golomb".to_string(), "sidon".to_string()]
2922 );
2923 }
2924
2925 #[test]
2926 fn collect_verifier_kinds_falls_back_to_whole_tree_when_no_witnesses_dir() {
2927 let tmp = tempfile::tempdir().expect("tempdir");
2928 let root = tmp.path();
2929 let nested = root.join("discoveries").join("sweep");
2930 fs::create_dir_all(&nested).expect("mkdir nested");
2931 fs::write(nested.join("x.witness.json"), r#"{"kind":"costas"}"#).unwrap();
2932 let vela = root.join(".vela").join("events");
2934 fs::create_dir_all(&vela).unwrap();
2935 fs::write(vela.join("e.witness.json"), r#"{"kind":"should_skip"}"#).unwrap();
2936 assert_eq!(collect_verifier_kinds(root), vec!["costas".to_string()]);
2937 }
2938}