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