1use std::collections::BTreeMap;
8use std::fs;
9use std::path::Path;
10
11use chrono::{SecondsFormat, Utc};
12use serde::{Deserialize, Serialize};
13use serde_json::json;
14use sha2::{Digest, Sha256};
15
16use crate::events;
17use crate::project::{self, Project, ProjectDependency};
18use crate::proposals;
19
20pub const FRONTIER_REPO_LAYOUT: &str = "vela.frontier_repo.v0.1";
21pub const FRONTIER_MANIFEST_SCHEMA: &str = "vela.frontier_manifest.v0.1";
22pub const FRONTIER_LOCK_SCHEMA: &str = "vela.frontier_lock.v0.1";
23pub const FRONTIER_INIT_SCHEMA: &str = "vela.frontier_repo_init.v0.1";
24pub const FRONTIER_MATERIALIZE_SCHEMA: &str = "vela.frontier_materialize.v0.1";
25pub const FRONTIER_REPO_STATUS_SCHEMA: &str = "vela.frontier_repo_status.v0.1";
26pub const FRONTIER_REPO_DOCTOR_SCHEMA: &str = "vela.frontier_repo_doctor.v0.1";
27pub const FRONTIER_PROOF_VERIFY_SCHEMA: &str = "vela.frontier_proof_verify.v0.1";
28const VELA_ACTION_REPOSITORY: &str = "vela-science/vela";
29
30fn current_vela_release() -> String {
31 format!("v{}", env!("CARGO_PKG_VERSION"))
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
35#[serde(deny_unknown_fields)]
36pub struct FrontierManifest {
37 pub schema: String,
38 pub layout: String,
39 #[serde(default = "default_split_mode")]
40 pub mode: String,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub frontier_id: Option<String>,
43 pub name: String,
44 #[serde(default)]
45 pub description: String,
46 #[serde(default = "default_visibility")]
47 pub visibility: String,
48 #[serde(default)]
49 pub scope: FrontierScope,
50 pub vela: VelaManifest,
51 pub paths: FrontierPaths,
52 #[serde(default, skip_serializing_if = "Vec::is_empty")]
53 pub maintainers: Vec<ManifestMaintainer>,
54 #[serde(default)]
55 pub policies: ManifestPolicies,
56 #[serde(default)]
57 pub license: ManifestLicense,
58 #[serde(default)]
59 pub dependencies: ManifestDependencies,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
63pub struct VelaManifest {
64 pub reducer: String,
65}
66
67#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
68pub struct FrontierScope {
69 #[serde(default)]
70 pub question: String,
71 #[serde(default)]
72 pub includes: Vec<String>,
73 #[serde(default)]
74 pub excludes: Vec<String>,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
78pub struct FrontierPaths {
79 pub state: String,
80 pub sources: String,
81 pub artifacts: String,
82 pub review: String,
83 pub proof: String,
84 pub exports: String,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
88pub struct ManifestMaintainer {
89 pub id: String,
90 pub role: String,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
94pub struct ManifestPolicies {
95 pub review: String,
96 pub proof: String,
97 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
98 pub frontier: BTreeMap<String, String>,
99}
100
101impl Default for ManifestPolicies {
102 fn default() -> Self {
103 Self {
104 review: "review/policy.yaml".to_string(),
105 proof: "proof/policy.yaml".to_string(),
106 frontier: BTreeMap::new(),
107 }
108 }
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
112pub struct ManifestLicense {
113 pub content: String,
114 pub code: String,
115 pub data: String,
116}
117
118impl Default for ManifestLicense {
119 fn default() -> Self {
120 Self {
121 content: "CC-BY-4.0".to_string(),
122 code: "Apache-2.0".to_string(),
123 data: "varies".to_string(),
124 }
125 }
126}
127
128#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
129pub struct ManifestDependencies {
130 #[serde(default)]
131 pub frontiers: Vec<String>,
132 #[serde(default)]
133 pub packages: Vec<String>,
134 #[serde(default)]
135 pub adapters: Vec<String>,
136 #[serde(default, skip_serializing_if = "Vec::is_empty")]
143 pub frontiers_v2: Vec<ProjectDependency>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
147#[serde(deny_unknown_fields)]
148pub struct FrontierLock {
149 pub schema: String,
150 pub generated_at: String,
151 pub vela_version: String,
152 pub frontier_id: String,
153 #[serde(default)]
154 pub canonicalization: LockCanonicalization,
155 #[serde(default)]
156 pub reducer: LockPackage,
157 #[serde(default)]
158 pub verifiers: LockVerifiers,
159 pub snapshot_hash: String,
160 pub event_log_hash: String,
161 pub proposal_state_hash: String,
162 #[serde(default)]
163 pub sources_hash: String,
164 #[serde(default)]
165 pub artifacts_hash: String,
166 #[serde(default)]
167 pub review_hash: String,
168 pub proof_freshness: String,
169 #[serde(default)]
170 pub proof: LockProof,
171 pub paths: LockPaths,
172 #[serde(default, skip_serializing_if = "Vec::is_empty")]
183 pub dependencies: Vec<LockedDependency>,
184}
185
186#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
192pub struct LockedDependency {
193 #[serde(default, skip_serializing_if = "String::is_empty")]
196 pub name: String,
197 pub source: String,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub vfr_id: Option<String>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub locator: Option<String>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub pinned_snapshot_hash: Option<String>,
211}
212
213#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
214pub struct LockCanonicalization {
215 pub json: String,
216 pub yaml: String,
217}
218
219impl Default for LockCanonicalization {
220 fn default() -> Self {
221 Self {
222 json: "vela-canonical-json-v0.1".to_string(),
223 yaml: "vela-yaml-v0.1".to_string(),
224 }
225 }
226}
227
228#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
229pub struct LockPackage {
230 pub package: String,
231 pub digest: String,
232}
233
234#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
242pub struct LockVerifiers {
243 pub package: String,
244 pub digest: String,
245 #[serde(default, skip_serializing_if = "Vec::is_empty")]
246 pub kinds: Vec<String>,
247}
248
249#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
250pub struct LockProof {
251 pub latest: String,
252 pub digest: String,
253 pub freshness: String,
254 pub events_manifest: String,
255 pub replay_trace: String,
256}
257
258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
259pub struct LockPaths {
260 pub frontier: String,
261 pub events: String,
262}
263
264#[derive(Debug, Clone)]
265struct ProofWrite {
266 digest: String,
267 freshness: String,
268 latest: String,
269 events_manifest: String,
270 replay_trace: String,
271}
272
273pub type VisibleRepoFiles = BTreeMap<String, Vec<u8>>;
277
278#[derive(Debug, Clone)]
279struct RenderedProof {
280 files: VisibleRepoFiles,
281 proof: ProofWrite,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct RepoLayoutIssue {
286 pub rule_id: String,
287 pub message: String,
288}
289
290#[derive(Debug, Clone)]
291pub struct InitOptions<'a> {
292 pub name: &'a str,
293 pub initialize_git: bool,
294}
295
296pub fn initialize(path: &Path, options: InitOptions<'_>) -> Result<serde_json::Value, String> {
297 if path.exists() && !path.is_dir() {
298 return Err(format!("{} exists and is not a directory", path.display()));
299 }
300 fs::create_dir_all(path).map_err(|e| {
301 format!(
302 "Failed to create frontier directory '{}': {e}",
303 path.display()
304 )
305 })?;
306
307 let now = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true);
308 let project = empty_project(options.name, "", &now);
309 crate::repo::init_repo(path, &project)?;
310 write_frontier_card(path, options.name)?;
311 write_scope(path, options.name)?;
312 write_git_native_scaffold(path, options.name)?;
313 if options.initialize_git && !path.join(".git").exists() {
314 let output = std::process::Command::new("git")
318 .args(["init", "--quiet", "-b", "main"])
319 .arg(path)
320 .output()
321 .map_err(|e| format!("Failed to run git init: {e}"))?;
322 if !output.status.success() {
323 return Err(format!(
324 "git init failed: {}",
325 String::from_utf8_lossy(&output.stderr).trim()
326 ));
327 }
328 }
329
330 let payload = json!({
331 "schema": FRONTIER_INIT_SCHEMA,
332 "ok": true,
333 "layout": FRONTIER_REPO_LAYOUT,
334 "path": path.display().to_string(),
335 "name": options.name,
336 "wrote": [
337 "README.md",
338 "SCOPE.md",
339 "frontier.yaml",
340 "frontier.json",
341 "vela.lock",
342 ".gitignore",
343 ".gitattributes",
344 ".github/workflows/vela-frontier.yml",
345 "VELA.md",
346 ".mcp.json"
347 ],
348 "next_commands": init_next_commands(path)
349 });
350 Ok(payload)
351}
352
353pub fn initialize_minimal(
357 path: &Path,
358 options: InitOptions<'_>,
359) -> Result<serde_json::Value, String> {
360 let name = options.name.to_string();
361 let mut payload = initialize(path, options)?;
362 for relative in [".mcp.json", ".github/workflows/vela-frontier.yml"] {
363 let candidate = path.join(relative);
364 if candidate.is_file() {
365 fs::remove_file(&candidate)
366 .map_err(|error| format!("remove {}: {error}", candidate.display()))?;
367 }
368 }
369 let proof_dir = path.join("proof");
370 if proof_dir.exists() {
371 fs::remove_dir_all(&proof_dir)
372 .map_err(|error| format!("remove {}: {error}", proof_dir.display()))?;
373 }
374 let project = crate::repo::load_from_path(path)?;
375 let generated_at = materialization_generated_at(path, &project);
376 let empty_proof = ProofWrite {
377 digest: directory_hash(&proof_dir),
378 freshness: "not_materialized".to_string(),
379 latest: String::new(),
380 events_manifest: String::new(),
381 replay_trace: String::new(),
382 };
383 write_lock(path, &project, &empty_proof, &generated_at)?;
384 payload["name"] = json!(name);
385 payload["wrote"] = json!([
386 "README.md",
387 "SCOPE.md",
388 "frontier.yaml",
389 "frontier.json",
390 "vela.lock",
391 ".gitignore",
392 ".gitattributes",
393 "VELA.md"
394 ]);
395 payload["next_commands"] = json!([
396 format!(
397 "vela doctor {} --json",
398 posix_shell_arg(&path.display().to_string())
399 ),
400 format!(
401 "vela status {} --json",
402 posix_shell_arg(&path.display().to_string())
403 ),
404 format!(
405 "vela next {} --json",
406 posix_shell_arg(&path.display().to_string())
407 )
408 ]);
409 Ok(payload)
410}
411
412fn init_next_commands(path: &Path) -> Vec<String> {
413 let target = posix_shell_arg(&path.display().to_string());
414 vec![
415 format!("vela agents sync {target} --json"),
416 format!("vela doctor {target} --json"),
417 format!("vela status {target} --json"),
418 format!("vela next {target} --json"),
419 format!("vela check {target} --strict --json"),
420 ]
421}
422
423fn posix_shell_arg(value: &str) -> String {
428 format!("'{}'", value.replace('\'', "'\"'\"'"))
429}
430
431fn write_git_native_scaffold(path: &Path, name: &str) -> Result<(), String> {
446 let write = |rel: &str, contents: String| -> Result<(), String> {
447 let dest = path.join(rel);
448 if dest.exists() {
449 return Ok(()); }
451 if let Some(parent) = dest.parent() {
452 fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
453 }
454 fs::write(&dest, contents).map_err(|e| format!("write {}: {e}", dest.display()))
455 };
456
457 write(
458 ".gitignore",
459 "# A Vela frontier commits the record, not the derivation.\n\
460 # Authority: .vela/events/ (signed log). Pins: vela.lock. Read-entry: frontier.json.\n\
461 \n\
462 # Producer-local scratch (not replayable truth).\n\
463 /packets/\n/activity/\n/exports/\n\
464 /.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\
465 \n\
466 # Tooling scratch\n\
467 /target/\n__pycache__/\n*.pyc\n.venv/\n.pytest_cache/\n.DS_Store\n"
468 .to_string(),
469 )?;
470
471 write(
472 ".gitattributes",
473 "# Ordinary text is normalized across platforms. More specific rules below win.\n\
474 * text=auto eol=lf\n\
475 \n\
476 # Canonical events, proposals, receipts, and public review material are raw Git\n\
477 # blobs. Repository filters, keyword expansion, working-tree encodings, and\n\
478 # semantic merge drivers may not transform them. Vela publication also checks\n\
479 # the effective attributes and raw staged blob before moving a ref, because a\n\
480 # local .git/info/attributes file has higher precedence than this contract.\n\
481 .vela/** -filter -ident -working-tree-encoding -merge -text\n\
482 .vela/events/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
483 .vela/proposals/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
484 .vela/records/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
485 records/** -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
486 sources/** -filter -ident -working-tree-encoding -merge -text\n\
487 artifacts/** -filter -ident -working-tree-encoding -merge -text\n\
488 review/** -filter -ident -working-tree-encoding -merge -text\n\
489 proof/** -filter -ident -working-tree-encoding -merge -text\n\
490 frontier.yaml -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
491 frontier.json -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
492 vela.lock -filter -ident -working-tree-encoding -merge diff text eol=lf\n\
493 \n\
494 # Witnesses are evidence the frozen verifiers re-check. They can be large, so\n\
495 # they may use Git LFS. The receipt's Vela digest remains content identity; the\n\
496 # LFS object is transport and its absence is an explicit availability failure.\n\
497 witnesses/** filter=lfs diff=lfs merge=lfs -text\n"
498 .to_string(),
499 )?;
500
501 let vela_release = current_vela_release();
502 let vela_action_ref = format!("{VELA_ACTION_REPOSITORY}@{vela_release}");
503 let workflow = r#"name: Verify the signed frontier
504
505# The git-native gate: every main push and every pull request runs the shared
506# vela-check action. This is deliberately unfiltered: public canonical roots
507# evolve, and a stale path allowlist would let scientific state bypass the gate.
508# The action re-derives the frontier from a clean checkout and proves the
509# working tree IS the signed state (replay + strict check + hash parity).
510# It NEVER signs: acceptance stays a human-keyed event in the repo.
511on:
512 push:
513 branches: [main]
514 pull_request: {}
515 workflow_dispatch: {}
516
517permissions:
518 contents: read
519
520jobs:
521 verify:
522 runs-on: ubuntu-latest
523 steps:
524 - uses: actions/checkout@v5
525 - uses: __VELA_ACTION_REF__
526 with:
527 vela-version: __VELA_RELEASE__
528"#
529 .replace("__VELA_ACTION_REF__", &vela_action_ref)
530 .replace("__VELA_RELEASE__", &vela_release);
531 write(".github/workflows/vela-frontier.yml", workflow)?;
532
533 write(
534 "VELA.md",
535 format!(
536 r#"# {name} — agent charter
537
538This frontier is driven by `vela` + `git`. The ordinary path is
539`next -> work -> land -> sign`: agents stop after the routed landing; only a
540human key or a previously human-signed Permit policy changes accepted state.
541`vela agents sync` regenerates CLAUDE.md / AGENTS.md / editor adapters from
542this file — edit here, never there.
543
544## Agent rules
545
546Agents may:
547
548- inspect state: `vela status .`, `vela next .`, `vela check .`
549- claim one target: `vela work <target> --as agent:<name> --json`
550- land Receipt v1 work through that session: `vela land --work <target>
551 --claim … --artifact … --caveat … --as agent:<name> --json`
552- import a foreign producer's canonical Receipt v1: `vela land receipt.json
553 --as agent:<name> --json`
554- run the verifiers: `vela reproduce .`, `vela check . --strict`
555- rebuild derived views: `vela frontier materialize .`
556
557Agents may not:
558
559- run `vela sign`, accept, reject, apply, or finalize a truth-bearing proposal
560- sign with, read, or handle a human's key
561- hand-edit accepted events or derived views such as `frontier.json` and proof
562 packets
563
564## Fast commands
565
566```bash
567vela next . --json # ranked offer
568vela work <target> --as agent:<name> --json # lease + briefing
569vela land --work <target> --claim <claim> \
570 --type computational --replayability exact \
571 --artifact <path>:<kind> --caveat <limit> \
572 --as agent:<name> --json # Receipt v1 + policy route
573vela status . --json # accepted and pending state
574vela check . --strict # replay and parity gate
575vela frontier materialize . # rebuild derived views
576git push # publication; no authority
577```
578"#
579 ),
580 )?;
581
582 write(
583 ".mcp.json",
584 r#"{
585 "_generated_by": "vela agents sync (from VELA.md) — edit VELA.md, not this file",
586 "mcpServers": {
587 "vela-local": {
588 "args": [
589 "serve",
590 ".",
591 "--profile",
592 "draft"
593 ],
594 "command": "vela"
595 }
596 }
597}
598"#
599 .to_string(),
600 )?;
601
602 Ok(())
603}
604
605pub fn materialize(path: &Path) -> Result<serde_json::Value, String> {
606 let source = crate::repo::VelaSource::VelaRepo(path.to_path_buf());
607 let project = crate::repo::load(&source)?;
608 let generated_at = materialization_generated_at(path, &project);
612 write_visible_state(path, &project, &generated_at)?;
613 write_manifest(path, &project)?;
614 let proof = write_proof(path, &project, &generated_at)?;
615 let lock = write_lock(path, &project, &proof, &generated_at)?;
616 Ok(json!({
617 "schema": FRONTIER_MATERIALIZE_SCHEMA,
618 "ok": true,
619 "path": path.display().to_string(),
620 "wrote_frontier": "frontier.json",
621 "wrote_lock": "vela.lock",
622 "wrote_proof": "proof/latest.json",
623 "wrote_events_manifest": "proof/events.manifest.jsonl",
624 "snapshot_hash": lock.snapshot_hash,
625 "event_log_hash": lock.event_log_hash,
626 "proposal_state_hash": lock.proposal_state_hash,
627 }))
628}
629
630pub fn write_visible_repo_files(path: &Path, project: &Project) -> Result<(), String> {
631 let files = render_visible_repo_files(path, project)?;
632 for (relative_path, bytes) in files {
633 let destination = path.join(&relative_path);
634 if let Some(parent) = destination.parent() {
635 fs::create_dir_all(parent)
636 .map_err(|e| format!("Failed to create {}: {e}", parent.display()))?;
637 }
638 fs::write(&destination, bytes)
639 .map_err(|e| format!("Failed to write {}: {e}", destination.display()))?;
640 }
641 Ok(())
642}
643
644pub fn render_visible_repo_files(
648 path: &Path,
649 project: &Project,
650) -> Result<VisibleRepoFiles, String> {
651 let generated_at = materialization_generated_at(path, project);
652 let mut files = VisibleRepoFiles::new();
653 files.insert(
654 "frontier.json".to_string(),
655 render_visible_state(project, &generated_at)?,
656 );
657 let manifest = if !path.join("frontier.yaml").is_file() {
658 render_manifest(path, project)?
659 } else {
660 render_synced_manifest(path, &project.project.dependencies)?
666 };
667 files.insert("frontier.yaml".to_string(), manifest);
668
669 let rendered_proof = render_proof(path, project, &generated_at)?;
670 files.extend(
671 rendered_proof
672 .files
673 .into_iter()
674 .map(|(relative_path, bytes)| (format!("proof/{relative_path}"), bytes)),
675 );
676 let (_, lock_bytes) = render_lock(path, project, &rendered_proof.proof, &generated_at)?;
677 files.insert("vela.lock".to_string(), lock_bytes);
678 Ok(files)
679}
680
681pub fn read_manifest(path: &Path) -> Result<Option<FrontierManifest>, String> {
682 let manifest_path = path.join("frontier.yaml");
683 if !manifest_path.is_file() {
684 return Ok(None);
685 }
686 let data = fs::read_to_string(&manifest_path)
687 .map_err(|e| format!("Failed to read frontier.yaml: {e}"))?;
688 serde_yaml::from_str(&data).map(Some).map_err(|e| {
689 format!(
690 "Failed to parse frontier manifest '{}': {e}",
691 manifest_path.display()
692 )
693 })
694}
695
696pub fn read_lock(path: &Path) -> Result<Option<FrontierLock>, String> {
697 let lock_path = path.join("vela.lock");
698 if !lock_path.is_file() {
699 return Ok(None);
700 }
701 let data =
702 fs::read_to_string(&lock_path).map_err(|e| format!("Failed to read vela.lock: {e}"))?;
703 serde_yaml::from_str(&data).map(Some).map_err(|e| {
704 format!(
705 "Failed to parse frontier lock '{}': {e}",
706 lock_path.display()
707 )
708 })
709}
710
711pub fn layout_issues(path: &Path, project: &Project) -> Vec<RepoLayoutIssue> {
712 if !path.is_dir() || !path.join(".vela").is_dir() {
713 return Vec::new();
714 }
715 let mut issues = Vec::new();
716 let manifest = match read_manifest(path) {
717 Ok(value) => value,
718 Err(e) => {
719 issues.push(issue("invalid_frontier_manifest", e));
720 None
721 }
722 };
723 let lock = match read_lock(path) {
724 Ok(value) => value,
725 Err(e) => {
726 issues.push(issue("invalid_frontier_lock", e));
727 None
728 }
729 };
730
731 if manifest.is_none() {
732 issues.push(issue(
733 "missing_frontier_manifest",
734 "Split frontier repo is missing frontier.yaml.",
735 ));
736 }
737 let Some(lock) = lock else {
738 return issues;
745 };
746
747 let locked_project = project_with_frontier_id(project);
748 let hash_project = locked_project.as_ref().unwrap_or(project);
749 let expected_snapshot = prefixed(events::snapshot_hash(hash_project));
750 let expected_event_log = prefixed(events::event_log_hash(&hash_project.events));
751 let expected_proposals = proposal_state_hash(&project.proposals);
752 let expected_frontier = hash_project.frontier_id();
753 let expected_sources = directory_hash(&path.join("sources"));
754 let expected_artifacts = directory_hash(&path.join("artifacts"));
755 let expected_review = directory_hash(&path.join("review"));
756 let expected_proof = directory_hash(&path.join("proof"));
757 if lock.snapshot_hash != expected_snapshot {
758 issues.push(issue(
759 "frontier_lock_mismatch",
760 format!(
761 "vela.lock snapshot_hash does not match materialized frontier state: lock={}, current={expected_snapshot}",
762 lock.snapshot_hash
763 ),
764 ));
765 }
766 if lock.event_log_hash != expected_event_log {
767 issues.push(issue(
768 "frontier_lock_mismatch",
769 format!(
770 "vela.lock event_log_hash does not match .vela/events: lock={}, current={expected_event_log}",
771 lock.event_log_hash
772 ),
773 ));
774 }
775 if lock.proposal_state_hash != expected_proposals {
776 issues.push(issue(
777 "frontier_lock_mismatch",
778 format!(
779 "vela.lock proposal_state_hash does not match .vela/proposals: lock={}, current={expected_proposals}",
780 lock.proposal_state_hash
781 ),
782 ));
783 }
784 if lock.frontier_id != expected_frontier {
785 issues.push(issue(
786 "frontier_lock_mismatch",
787 format!(
788 "vela.lock frontier_id does not match current frontier: lock={}, current={expected_frontier}",
789 lock.frontier_id
790 ),
791 ));
792 }
793 if !lock.sources_hash.is_empty() && lock.sources_hash != expected_sources {
794 issues.push(issue(
795 "frontier_lock_mismatch",
796 format!(
797 "vela.lock sources_hash does not match sources/: lock={}, current={expected_sources}",
798 lock.sources_hash
799 ),
800 ));
801 }
802 if !lock.artifacts_hash.is_empty() && lock.artifacts_hash != expected_artifacts {
803 issues.push(issue(
804 "frontier_lock_mismatch",
805 format!(
806 "vela.lock artifacts_hash does not match artifacts/: lock={}, current={expected_artifacts}",
807 lock.artifacts_hash
808 ),
809 ));
810 }
811 if !lock.review_hash.is_empty() && lock.review_hash != expected_review {
812 issues.push(issue(
813 "frontier_lock_mismatch",
814 format!(
815 "vela.lock review_hash does not match review/: lock={}, current={expected_review}",
816 lock.review_hash
817 ),
818 ));
819 }
820 if !lock.proof.digest.is_empty() && lock.proof.digest != expected_proof {
821 issues.push(issue(
822 "frontier_lock_mismatch",
823 format!(
824 "vela.lock proof digest does not match proof/: lock={}, current={expected_proof}",
825 lock.proof.digest
826 ),
827 ));
828 }
829 if !lock.verifiers.package.is_empty() {
835 let actual_kinds = collect_verifier_kinds(path);
836 if lock.verifiers.kinds != actual_kinds {
837 issues.push(issue(
838 "frontier_lock_mismatch",
839 format!(
840 "vela.lock verifiers.kinds does not match the witnesses on disk: lock={:?}, current={actual_kinds:?} (run `vela frontier materialize`)",
841 lock.verifiers.kinds
842 ),
843 ));
844 }
845 }
846
847 let visible_path = path.join("frontier.json");
848 if !visible_path.is_file() {
849 issues.push(issue(
850 "missing_materialized_frontier",
851 "Split frontier repo is missing frontier.json.",
852 ));
853 return issues;
854 }
855 match crate::repo::load_project_file(&visible_path) {
856 Ok(visible) => {
857 let visible_hash = prefixed(events::snapshot_hash(&visible));
858 if visible_hash != expected_snapshot {
859 issues.push(issue(
860 "frontier_lock_mismatch",
861 format!(
862 "frontier.json does not match .vela materialized state: visible={visible_hash}, current={expected_snapshot}",
863 ),
864 ));
865 }
866 }
867 Err(e) => issues.push(issue("invalid_materialized_frontier", e)),
868 }
869
870 issues
871}
872
873pub fn manifest_overrides(path: &Path) -> Result<Option<FrontierManifest>, String> {
874 read_manifest(path)
875}
876pub fn proof_verify(path: &Path) -> Result<serde_json::Value, String> {
877 let project = crate::repo::load_from_path(path)?;
878 let lock = read_lock(path)?;
879 let proof_path = path.join("proof/latest.json");
880 let mut issues = layout_issues(path, &project)
881 .into_iter()
882 .map(|issue| {
883 json!({
884 "rule_id": issue.rule_id,
885 "message": issue.message,
886 })
887 })
888 .collect::<Vec<_>>();
889 let locked = project_with_frontier_id(&project)?;
890 let snapshot_hash = prefixed(events::snapshot_hash(&locked));
891 let event_log_hash = prefixed(events::event_log_hash(&locked.events));
892 let mut latest_payload = serde_json::Value::Null;
893 if !proof_path.is_file() {
894 issues.push(json!({
895 "rule_id": "missing_proof_latest",
896 "message": "proof/latest.json is missing.",
897 }));
898 } else {
899 let data = fs::read_to_string(&proof_path)
900 .map_err(|e| format!("Failed to read proof/latest.json: {e}"))?;
901 latest_payload = serde_json::from_str(&data).map_err(|e| {
902 format!(
903 "Failed to parse proof/latest.json '{}': {e}",
904 proof_path.display()
905 )
906 })?;
907 if latest_payload
908 .get("frontier_hash")
909 .and_then(|value| value.as_str())
910 != Some(snapshot_hash.as_str())
911 {
912 issues.push(json!({
913 "rule_id": "proof_snapshot_mismatch",
914 "message": "proof/latest.json frontier_hash does not match replayed frontier state.",
915 }));
916 }
917 if latest_payload
918 .get("event_log_hash")
919 .and_then(|value| value.as_str())
920 != Some(event_log_hash.as_str())
921 {
922 issues.push(json!({
923 "rule_id": "proof_event_log_mismatch",
924 "message": "proof/latest.json event_log_hash does not match .vela/events/.",
925 }));
926 }
927 }
928 let proof_digest = directory_hash(&path.join("proof"));
929 if let Some(lock) = &lock {
930 if !lock.proof.digest.is_empty() && lock.proof.digest != proof_digest {
931 issues.push(json!({
932 "rule_id": "proof_digest_mismatch",
933 "message": format!("proof/ digest does not match vela.lock: lock={}, current={proof_digest}", lock.proof.digest),
934 }));
935 }
936 } else {
937 issues.push(json!({
938 "rule_id": "missing_frontier_lock",
939 "message": "vela.lock is missing.",
940 }));
941 }
942
943 Ok(json!({
944 "schema": FRONTIER_PROOF_VERIFY_SCHEMA,
945 "ok": issues.is_empty(),
946 "path": path.display().to_string(),
947 "frontier_id": locked.frontier_id(),
948 "snapshot_hash": snapshot_hash,
949 "event_log_hash": event_log_hash,
950 "proof_digest": proof_digest,
951 "proof": latest_payload,
952 "issues": issues,
953 }))
954}
955
956pub fn proof_explain(path: &Path) -> Result<String, String> {
957 let project = crate::repo::load_from_path(path)?;
958 let report = proof_verify(path)?;
959 let ok = report.get("ok").and_then(|value| value.as_bool()) == Some(true);
960 let locked = project_with_frontier_id(&project)?;
961 let snapshot_hash = prefixed(events::snapshot_hash(&locked));
962 let event_log_hash = prefixed(events::event_log_hash(&locked.events));
963 let open_proposals = project
964 .proposals
965 .iter()
966 .filter(|proposal| {
967 !matches!(
968 proposal.status.as_str(),
969 "accepted" | "applied" | "rejected"
970 )
971 })
972 .count();
973 let status = if ok { "fresh" } else { "stale or invalid" };
974 Ok(format!(
975 "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",
976 project.project.name,
977 locked.frontier_id(),
978 project.events.len(),
979 ))
980}
981
982fn empty_project(name: &str, description: &str, compiled_at: &str) -> Project {
983 Project {
984 vela_version: project::VELA_SCHEMA_VERSION.to_string(),
985 schema: project::VELA_SCHEMA_URL.to_string(),
986 frontier_id: None,
987 project: project::ProjectMeta {
988 name: name.to_string(),
989 description: description.to_string(),
990 compiled_at: compiled_at.to_string(),
991 compiler: project::VELA_COMPILER_VERSION.to_string(),
992 papers_processed: 0,
993 errors: 0,
994 dependencies: Vec::new(),
995 },
996 stats: project::ProjectStats::default(),
997 findings: Vec::new(),
998 sources: Vec::new(),
999 evidence_atoms: Vec::new(),
1000 condition_records: Vec::new(),
1001 review_events: Vec::new(),
1002 confidence_updates: Vec::new(),
1003 events: Vec::new(),
1004 proposals: Vec::new(),
1005 proof_state: proposals::ProofState::default(),
1006 signatures: Vec::new(),
1007 actors: Vec::new(),
1008 artifacts: Vec::new(),
1009 released_diff_packs: Vec::new(),
1010 verdict_conflicts: Vec::new(),
1011 contradictions: Vec::new(),
1012 verifier_attachments: Vec::new(),
1013 attempts: Vec::new(),
1014 attempt_resolutions: Vec::new(),
1015 transfers: Vec::new(),
1016 endorsements: Vec::new(),
1017 statement_attestations: Vec::new(),
1018 anchor_links: Vec::new(),
1019 attempt_claims: Vec::new(),
1020 statement_registrations: Vec::new(),
1021 }
1022}
1023
1024fn write_visible_state(path: &Path, project: &Project, generated_at: &str) -> Result<(), String> {
1025 let bytes = render_visible_state(project, generated_at)?;
1026 fs::write(path.join("frontier.json"), bytes)
1027 .map_err(|e| format!("Failed to write frontier.json: {e}"))
1028}
1029
1030fn render_visible_state(project: &Project, generated_at: &str) -> Result<Vec<u8>, String> {
1031 let visible = project_with_frontier_id(project)?;
1032 let snapshot_hash = prefixed(events::snapshot_hash(&visible));
1033 let event_log_hash = prefixed(events::event_log_hash(&visible.events));
1034 let mut value = serde_json::to_value(&visible)
1035 .map_err(|e| format!("Failed to prepare frontier.json: {e}"))?;
1036 if let Some(object) = value.as_object_mut() {
1037 object.insert(
1038 "_warning".to_string(),
1039 serde_json::Value::String(
1040 "Generated by Vela. Do not edit frontier.json directly; use Vela's task-first receipt, signing, materialization, and proof commands."
1041 .to_string(),
1042 ),
1043 );
1044 object.insert(
1045 "_meta".to_string(),
1046 json!({
1047 "schema": "vela.frontier_state_meta.v0.1",
1048 "generated_at": generated_at,
1049 "materialized_from": ".vela/events/",
1050 "proof": "proof/latest.json",
1051 "lockfile": "vela.lock",
1052 "events_manifest": "proof/events.manifest.jsonl",
1053 "replay_trace": "proof/replay.trace.jsonl",
1054 "snapshot_hash": snapshot_hash,
1055 "event_log_hash": event_log_hash,
1056 "vela_reducer": format!("vela@{}", env!("CARGO_PKG_VERSION")),
1057 }),
1058 );
1059 }
1060 serde_json::to_vec_pretty(&value).map_err(|e| format!("Failed to serialize frontier.json: {e}"))
1061}
1062
1063fn render_synced_manifest(path: &Path, deps: &[ProjectDependency]) -> Result<Vec<u8>, String> {
1064 let mut manifest = match read_manifest(path)? {
1065 Some(m) => m,
1066 None => return Err("frontier.yaml disappeared while rendering visible files".to_string()),
1067 };
1068 manifest.dependencies.frontiers_v2 = deps.to_vec();
1069 serde_yaml::to_string(&manifest)
1070 .map(String::into_bytes)
1071 .map_err(|e| format!("Failed to serialize frontier.yaml: {e}"))
1072}
1073
1074fn write_manifest(path: &Path, project: &Project) -> Result<(), String> {
1075 let yaml = render_manifest(path, project)?;
1076 fs::write(path.join("frontier.yaml"), yaml)
1077 .map_err(|e| format!("Failed to write frontier.yaml: {e}"))
1078}
1079
1080fn render_manifest(path: &Path, project: &Project) -> Result<Vec<u8>, String> {
1081 let existing = read_manifest(path).ok().flatten();
1082 let existing_dependencies = existing
1083 .as_ref()
1084 .map(|manifest| manifest.dependencies.clone())
1085 .unwrap_or_default();
1086 let manifest = FrontierManifest {
1087 schema: FRONTIER_MANIFEST_SCHEMA.to_string(),
1088 layout: FRONTIER_REPO_LAYOUT.to_string(),
1089 mode: "split".to_string(),
1090 frontier_id: Some(project.frontier_id()),
1091 name: project.project.name.clone(),
1092 description: existing
1093 .as_ref()
1094 .map(|manifest| manifest.description.clone())
1095 .unwrap_or_else(|| project.project.description.clone()),
1096 visibility: "public".to_string(),
1097 scope: existing
1098 .as_ref()
1099 .map(|manifest| manifest.scope.clone())
1100 .unwrap_or_else(|| FrontierScope {
1101 question: project.project.description.clone(),
1102 includes: Vec::new(),
1103 excludes: Vec::new(),
1104 }),
1105 vela: VelaManifest {
1106 reducer: format!("vela@{}", env!("CARGO_PKG_VERSION")),
1107 },
1108 paths: FrontierPaths {
1109 state: "frontier.json".to_string(),
1110 sources: "sources/".to_string(),
1111 artifacts: "artifacts/".to_string(),
1112 review: "review/".to_string(),
1113 proof: "proof/".to_string(),
1114 exports: "exports/".to_string(),
1115 },
1116 maintainers: existing
1117 .as_ref()
1118 .map(|manifest| manifest.maintainers.clone())
1119 .unwrap_or_default(),
1120 policies: existing
1121 .as_ref()
1122 .map(|manifest| manifest.policies.clone())
1123 .unwrap_or_default(),
1124 license: existing
1125 .as_ref()
1126 .map(|manifest| manifest.license.clone())
1127 .unwrap_or_default(),
1128 dependencies: ManifestDependencies {
1129 frontiers: existing_dependencies.frontiers,
1130 packages: existing_dependencies.packages,
1131 adapters: existing_dependencies.adapters,
1132 frontiers_v2: project.project.dependencies.clone(),
1133 },
1134 };
1135 serde_yaml::to_string(&manifest)
1136 .map(String::into_bytes)
1137 .map_err(|e| format!("Failed to serialize frontier.yaml: {e}"))
1138}
1139
1140fn write_lock(
1141 path: &Path,
1142 project: &Project,
1143 proof: &ProofWrite,
1144 generated_at: &str,
1145) -> Result<FrontierLock, String> {
1146 let (lock, bytes) = render_lock(path, project, proof, generated_at)?;
1147 fs::write(path.join("vela.lock"), bytes)
1148 .map_err(|e| format!("Failed to write vela.lock: {e}"))?;
1149 Ok(lock)
1150}
1151
1152fn render_lock(
1153 path: &Path,
1154 project: &Project,
1155 proof: &ProofWrite,
1156 generated_at: &str,
1157) -> Result<(FrontierLock, Vec<u8>), String> {
1158 let locked = project_with_frontier_id(project)?;
1159 let reducer_package = format!("vela@{}", env!("CARGO_PKG_VERSION"));
1160 let verifier_package = format!("vela-verify@{}", env!("CARGO_PKG_VERSION"));
1161 let lock = FrontierLock {
1162 schema: FRONTIER_LOCK_SCHEMA.to_string(),
1163 generated_at: generated_at.to_string(),
1164 vela_version: env!("CARGO_PKG_VERSION").to_string(),
1165 frontier_id: locked.frontier_id(),
1166 canonicalization: LockCanonicalization::default(),
1167 reducer: LockPackage {
1168 package: reducer_package.clone(),
1169 digest: identity_digest(&reducer_package),
1170 },
1171 verifiers: LockVerifiers {
1172 package: verifier_package.clone(),
1173 digest: identity_digest(&verifier_package),
1174 kinds: collect_verifier_kinds(path),
1175 },
1176 snapshot_hash: prefixed(events::snapshot_hash(&locked)),
1177 event_log_hash: prefixed(events::event_log_hash(&locked.events)),
1178 proposal_state_hash: proposal_state_hash(&locked.proposals),
1179 sources_hash: directory_hash(&path.join("sources")),
1180 artifacts_hash: directory_hash(&path.join("artifacts")),
1181 review_hash: directory_hash(&path.join("review")),
1182 proof_freshness: proof.freshness.clone(),
1183 proof: LockProof {
1184 latest: proof.latest.clone(),
1185 digest: proof.digest.clone(),
1186 freshness: proof.freshness.clone(),
1187 events_manifest: proof.events_manifest.clone(),
1188 replay_trace: proof.replay_trace.clone(),
1189 },
1190 paths: LockPaths {
1191 frontier: "frontier.json".to_string(),
1192 events: ".vela/events/".to_string(),
1193 },
1194 dependencies: locked
1200 .project
1201 .dependencies
1202 .iter()
1203 .map(|d| LockedDependency {
1204 name: d.name.clone(),
1205 source: d.source.clone(),
1206 vfr_id: d.vfr_id.clone(),
1207 locator: d.locator.clone(),
1208 pinned_snapshot_hash: d.pinned_snapshot_hash.clone(),
1209 })
1210 .collect(),
1211 };
1212 let yaml = serde_yaml::to_string(&lock)
1213 .map(String::into_bytes)
1214 .map_err(|e| format!("Failed to serialize vela.lock: {e}"))?;
1215 Ok((lock, yaml))
1216}
1217
1218fn collect_verifier_kinds(path: &Path) -> Vec<String> {
1224 let witnesses_dir = path.join("witnesses");
1225 let root = if witnesses_dir.is_dir() {
1226 witnesses_dir
1227 } else {
1228 path.to_path_buf()
1229 };
1230 let mut files = Vec::new();
1231 collect_witness_json(&root, &mut files);
1232 let mut kinds: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
1233 for f in files {
1234 if let Ok(text) = fs::read_to_string(&f)
1235 && let Ok(v) = serde_json::from_str::<serde_json::Value>(&text)
1236 && let Some(k) = v.get("kind").and_then(|k| k.as_str())
1237 {
1238 kinds.insert(k.to_string());
1239 }
1240 }
1241 kinds.into_iter().collect()
1242}
1243
1244fn collect_witness_json(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
1245 let Ok(entries) = fs::read_dir(dir) else {
1246 return;
1247 };
1248 for entry in entries.flatten() {
1249 let p = entry.path();
1250 if p.is_dir() {
1251 if matches!(
1252 p.file_name().and_then(|n| n.to_str()),
1253 Some(".vela") | Some(".git")
1254 ) {
1255 continue;
1256 }
1257 collect_witness_json(&p, out);
1258 } else if p
1259 .file_name()
1260 .and_then(|n| n.to_str())
1261 .is_some_and(|n| n.ends_with(".witness.json"))
1262 {
1263 out.push(p);
1264 }
1265 }
1266}
1267
1268fn materialization_generated_at(_path: &Path, project: &Project) -> String {
1277 project
1278 .events
1279 .iter()
1280 .map(|e| e.timestamp.as_str())
1281 .max()
1282 .map(|s| s.to_string())
1283 .unwrap_or_else(|| "1970-01-01T00:00:00Z".to_string())
1284}
1285
1286fn project_with_frontier_id(project: &Project) -> Result<Project, String> {
1287 let frontier_id = project.frontier_id();
1288 let mut value = serde_json::to_value(project)
1289 .map_err(|e| format!("Failed to prepare frontier state: {e}"))?;
1290 if let Some(object) = value.as_object_mut() {
1291 object.insert(
1292 "frontier_id".to_string(),
1293 serde_json::Value::String(frontier_id),
1294 );
1295 }
1296 serde_json::from_value(value).map_err(|e| format!("Failed to normalize frontier state: {e}"))
1297}
1298
1299fn write_frontier_card(path: &Path, name: &str) -> Result<(), String> {
1300 let text = format!(
1301 "# {name}\n\nThis is a Vela frontier repository. Agents follow `next -> work -> land`; a human uses `sign` for deferred decisions, and Git publishes the resulting bytes.\n\n- State entrypoint: `frontier.json`\n- Manifest: `frontier.yaml`\n- Lockfile: `vela.lock`\n\nRun:\n\n```bash\nvela agents sync . --json\nvela status . --json\nvela next . --json\nvela check . --strict --json\n```\n"
1302 );
1303 fs::write(path.join("README.md"), text).map_err(|e| format!("Failed to write README.md: {e}"))
1304}
1305
1306fn write_scope(path: &Path, name: &str) -> Result<(), String> {
1307 let text = format!(
1308 "# 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"
1309 );
1310 fs::write(path.join("SCOPE.md"), text).map_err(|e| format!("Failed to write SCOPE.md: {e}"))
1311}
1312
1313fn write_proof(path: &Path, project: &Project, generated_at: &str) -> Result<ProofWrite, String> {
1314 let rendered = render_proof(path, project, generated_at)?;
1315 let proof_dir = path.join("proof");
1316 fs::create_dir_all(&proof_dir).map_err(|e| format!("Failed to create proof/: {e}"))?;
1317 for (relative_path, bytes) in &rendered.files {
1318 fs::write(proof_dir.join(relative_path), bytes)
1319 .map_err(|e| format!("Failed to write proof/{relative_path}: {e}"))?;
1320 }
1321 Ok(rendered.proof)
1322}
1323
1324fn render_proof(
1325 path: &Path,
1326 project: &Project,
1327 generated_at: &str,
1328) -> Result<RenderedProof, String> {
1329 let locked = project_with_frontier_id(project)?;
1330 let proof_dir = path.join("proof");
1331
1332 let event_log_hash = prefixed(events::event_log_hash(&locked.events));
1341 let snapshot_hash = prefixed(events::snapshot_hash(&locked));
1342 if proof_is_current(&proof_dir, &event_log_hash, &snapshot_hash) {
1343 return Ok(RenderedProof {
1344 files: VisibleRepoFiles::new(),
1345 proof: ProofWrite {
1346 digest: directory_hash(&proof_dir),
1347 freshness: "fresh".to_string(),
1348 latest: "proof/latest.json".to_string(),
1349 events_manifest: "proof/events.manifest.jsonl".to_string(),
1350 replay_trace: "proof/replay.trace.jsonl".to_string(),
1351 },
1352 });
1353 }
1354 let proposal_state_hash = proposal_state_hash(&locked.proposals);
1355 let reducer_package = format!("vela@{}", env!("CARGO_PKG_VERSION"));
1356
1357 let latest = json!({
1358 "schema": "vela.frontier_repo_proof.v0.1",
1359 "frontier_id": locked.frontier_id(),
1360 "frontier_hash": snapshot_hash,
1361 "event_log_hash": event_log_hash,
1362 "proposal_state_hash": proposal_state_hash,
1363 "reducer": {
1364 "name": "vela",
1365 "version": env!("CARGO_PKG_VERSION"),
1366 "package": reducer_package,
1367 "digest": identity_digest(&format!("vela@{}", env!("CARGO_PKG_VERSION"))),
1368 },
1369 "materialized_at": generated_at,
1370 "freshness": "fresh",
1371 "event_count": locked.events.len(),
1372 "paths": {
1373 "frontier": "frontier.json",
1374 "lockfile": "vela.lock",
1375 "events_authority": ".vela/events/",
1376 "events_manifest": "proof/events.manifest.jsonl",
1377 "replay_trace": "proof/replay.trace.jsonl"
1378 },
1379 "warning": "Do not edit frontier.json directly. Use Vela's task-first receipt, signing, materialization, and proof commands."
1380 });
1381 let mut files = VisibleRepoFiles::new();
1382 files.insert(
1383 "latest.json".to_string(),
1384 serde_json::to_vec_pretty(&latest)
1385 .map_err(|e| format!("Failed to serialize proof/latest.json: {e}"))?,
1386 );
1387
1388 let mut manifest_lines = String::new();
1389 let mut trace_lines = String::new();
1390 let mut chained_log_hash = String::new();
1398 let mut ordered: Vec<_> = locked.events.iter().collect();
1402 ordered.sort_by(|a, b| a.id.cmp(&b.id));
1403 for (idx, event) in ordered.into_iter().enumerate() {
1404 let event_hash = prefixed(event_hash(event));
1405 let entry = json!({
1406 "schema": "vela.proof_event_manifest_entry.v0.1",
1407 "index": idx + 1,
1408 "id": event.id,
1409 "kind": event.kind,
1410 "target": event.target,
1411 "actor": event.actor,
1412 "timestamp": event.timestamp,
1413 "event_hash": event_hash,
1414 "before_hash": event.before_hash,
1415 "after_hash": event.after_hash,
1416 "caveat_count": event.caveats.len(),
1417 });
1418 manifest_lines.push_str(
1419 &serde_json::to_string(&entry)
1420 .map_err(|e| format!("Failed to serialize event manifest entry: {e}"))?,
1421 );
1422 manifest_lines.push('\n');
1423
1424 chained_log_hash = hex::encode(Sha256::digest(
1425 format!("{chained_log_hash}{event_hash}").as_bytes(),
1426 ));
1427 let trace = json!({
1428 "schema": "vela.replay_trace_entry.v0.2",
1429 "step": idx + 1,
1430 "event": event.id,
1431 "kind": event.kind,
1432 "event_hash": event_hash,
1433 "event_log_hash_after": prefixed(chained_log_hash.clone()),
1434 "target_after_hash": event.after_hash,
1435 });
1436 trace_lines.push_str(
1437 &serde_json::to_string(&trace)
1438 .map_err(|e| format!("Failed to serialize replay trace entry: {e}"))?,
1439 );
1440 trace_lines.push('\n');
1441 }
1442 files.insert(
1443 "events.manifest.jsonl".to_string(),
1444 manifest_lines.into_bytes(),
1445 );
1446 files.insert("replay.trace.jsonl".to_string(), trace_lines.into_bytes());
1447 files.insert(
1448 "freshness.md".to_string(),
1449 format!(
1450 "# Freshness\n\nCurrent proof status: fresh\n\n`frontier.json` was materialized from `.vela/events/` at {generated_at}.\n\nAccepted events: {}\nEvent log hash: `{event_log_hash}`\nSnapshot hash: `{snapshot_hash}`\n\nRun:\n\n```bash\nvela check . --strict --json\nvela proof verify . --json\n```\n",
1451 locked.events.len()
1452 )
1453 .into_bytes(),
1454 );
1455
1456 let hashes = json!({
1457 "schema": "vela.frontier_repo_hashes.v0.1",
1458 "frontier_id": locked.frontier_id(),
1459 "snapshot_hash": snapshot_hash,
1460 "event_log_hash": event_log_hash,
1461 "proposal_state_hash": proposal_state_hash,
1462 "sources_hash": directory_hash(&path.join("sources")),
1463 "artifacts_hash": directory_hash(&path.join("artifacts")),
1464 "review_hash": directory_hash(&path.join("review")),
1465 });
1466 files.insert(
1467 "hashes.json".to_string(),
1468 serde_json::to_vec_pretty(&hashes)
1469 .map_err(|e| format!("Failed to serialize proof/hashes.json: {e}"))?,
1470 );
1471 let digest = directory_hash_with_replacements(&proof_dir, &files);
1472
1473 Ok(RenderedProof {
1474 files,
1475 proof: ProofWrite {
1476 digest,
1477 freshness: "fresh".to_string(),
1478 latest: "proof/latest.json".to_string(),
1479 events_manifest: "proof/events.manifest.jsonl".to_string(),
1480 replay_trace: "proof/replay.trace.jsonl".to_string(),
1481 },
1482 })
1483}
1484
1485fn proof_is_current(proof_dir: &Path, event_log_hash: &str, snapshot_hash: &str) -> bool {
1490 let Ok(text) = fs::read_to_string(proof_dir.join("latest.json")) else {
1491 return false;
1492 };
1493 let Ok(latest) = serde_json::from_str::<serde_json::Value>(&text) else {
1494 return false;
1495 };
1496 let same_log = latest.get("event_log_hash").and_then(|v| v.as_str()) == Some(event_log_hash);
1497 let same_snapshot = latest.get("frontier_hash").and_then(|v| v.as_str()) == Some(snapshot_hash);
1498 let same_reducer = latest.pointer("/reducer/version").and_then(|v| v.as_str())
1499 == Some(env!("CARGO_PKG_VERSION"));
1500 same_log
1501 && same_snapshot
1502 && same_reducer
1503 && proof_dir.join("events.manifest.jsonl").is_file()
1504 && proof_dir.join("replay.trace.jsonl").is_file()
1505 && proof_dir.join("hashes.json").is_file()
1506}
1507
1508fn proposal_state_hash(proposals: &[crate::proposals::StateProposal]) -> String {
1509 let bytes = crate::canonical::to_canonical_bytes(proposals).unwrap_or_default();
1510 prefixed(hex::encode(Sha256::digest(bytes)))
1511}
1512
1513fn directory_hash(path: &Path) -> String {
1514 let mut entries = Vec::new();
1515 if path.is_dir() {
1516 collect_file_entries(path, path, &mut entries);
1517 }
1518 entries.sort_by(|a, b| a.0.cmp(&b.0));
1519 let bytes = crate::canonical::to_canonical_bytes(&entries).unwrap_or_default();
1520 prefixed(hex::encode(Sha256::digest(bytes)))
1521}
1522
1523fn directory_hash_with_replacements(path: &Path, replacements: &VisibleRepoFiles) -> String {
1524 let mut entries = Vec::new();
1525 if path.is_dir() {
1526 collect_file_entries(path, path, &mut entries);
1527 }
1528 let mut entries = entries.into_iter().collect::<BTreeMap<_, _>>();
1529 for (relative_path, bytes) in replacements {
1530 entries.insert(
1531 relative_path.clone(),
1532 prefixed(hex::encode(Sha256::digest(bytes))),
1533 );
1534 }
1535 let entries = entries.into_iter().collect::<Vec<_>>();
1536 let bytes = crate::canonical::to_canonical_bytes(&entries).unwrap_or_default();
1537 prefixed(hex::encode(Sha256::digest(bytes)))
1538}
1539
1540fn collect_file_entries(root: &Path, path: &Path, entries: &mut Vec<(String, String)>) {
1541 let Ok(read_dir) = fs::read_dir(path) else {
1542 return;
1543 };
1544 for entry in read_dir.flatten() {
1545 let entry_path = entry.path();
1546 let Some(name) = entry_path.file_name().and_then(|s| s.to_str()) else {
1547 continue;
1548 };
1549 if name == ".DS_Store" {
1550 continue;
1551 }
1552 if entry_path.is_dir() {
1553 collect_file_entries(root, &entry_path, entries);
1554 } else if entry_path.is_file() {
1555 let rel = entry_path
1556 .strip_prefix(root)
1557 .unwrap_or(&entry_path)
1558 .to_string_lossy()
1559 .replace('\\', "/");
1560 let digest = fs::read(&entry_path)
1561 .map(|bytes| prefixed(hex::encode(Sha256::digest(bytes))))
1562 .unwrap_or_else(|_| "sha256:unreadable".to_string());
1563 entries.push((rel, digest));
1564 }
1565 }
1566}
1567
1568fn event_hash(event: &crate::events::StateEvent) -> String {
1569 let bytes = crate::canonical::to_canonical_bytes(event).unwrap_or_default();
1570 hex::encode(Sha256::digest(bytes))
1571}
1572
1573fn identity_digest(value: &str) -> String {
1574 prefixed(hex::encode(Sha256::digest(value.as_bytes())))
1575}
1576
1577fn prefixed(hash: String) -> String {
1578 if hash.starts_with("sha256:") {
1579 hash
1580 } else {
1581 format!("sha256:{hash}")
1582 }
1583}
1584
1585fn issue(rule_id: &str, message: impl Into<String>) -> RepoLayoutIssue {
1586 RepoLayoutIssue {
1587 rule_id: rule_id.to_string(),
1588 message: message.into(),
1589 }
1590}
1591
1592fn default_split_mode() -> String {
1593 "split".to_string()
1594}
1595
1596fn default_visibility() -> String {
1597 "public".to_string()
1598}
1599
1600#[cfg(test)]
1601mod tests {
1602 use super::*;
1603
1604 #[test]
1605 fn visible_repo_render_is_read_only_and_byte_equivalent_to_write() {
1606 let tmp = tempfile::tempdir().expect("tempdir");
1607 initialize(
1608 tmp.path(),
1609 InitOptions {
1610 name: "Rendered frontier",
1611 initialize_git: false,
1612 },
1613 )
1614 .expect("initialize frontier");
1615 let source = crate::repo::VelaSource::VelaRepo(tmp.path().to_path_buf());
1616 let mut project = crate::repo::load(&source).expect("load frontier");
1617 project.project.description = "rendered without a frontier write".to_string();
1618 let original_frontier = fs::read(tmp.path().join("frontier.json")).unwrap();
1619
1620 let rendered = render_visible_repo_files(tmp.path(), &project).expect("render files");
1621
1622 assert_eq!(
1623 fs::read(tmp.path().join("frontier.json")).unwrap(),
1624 original_frontier,
1625 "rendering must not modify the frontier"
1626 );
1627 assert!(rendered.contains_key("frontier.json"));
1628 assert!(rendered.contains_key("frontier.yaml"));
1629 assert!(rendered.contains_key("proof/latest.json"));
1630 assert!(rendered.contains_key("vela.lock"));
1631
1632 write_visible_repo_files(tmp.path(), &project).expect("write rendered files");
1633 for (relative_path, expected) in rendered {
1634 assert_eq!(
1635 fs::read(tmp.path().join(&relative_path)).unwrap(),
1636 expected,
1637 "rendered bytes differ for {relative_path}"
1638 );
1639 }
1640 }
1641
1642 #[test]
1643 fn initialize_writes_unfiltered_frontier_gate_for_every_public_root() {
1644 let tmp = tempfile::tempdir().expect("tempdir");
1645 initialize(
1646 tmp.path(),
1647 InitOptions {
1648 name: "Unskippable frontier gate",
1649 initialize_git: false,
1650 },
1651 )
1652 .expect("initialize frontier");
1653
1654 let workflow = fs::read_to_string(tmp.path().join(".github/workflows/vela-frontier.yml"))
1655 .expect("read generated frontier workflow");
1656 let triggers = workflow
1657 .split_once("\npermissions:")
1658 .map(|(triggers, _)| triggers)
1659 .expect("workflow has permissions boundary after triggers");
1660
1661 assert!(triggers.contains(" push:\n branches: [main]"));
1662 assert!(triggers.contains(" pull_request: {}"));
1663 assert!(triggers.contains(" workflow_dispatch: {}"));
1664 let expected_release = current_vela_release();
1665 assert!(workflow.contains(&format!(
1666 " - uses: {VELA_ACTION_REPOSITORY}@{expected_release}"
1667 )));
1668 assert!(workflow.contains(&format!(" vela-version: {expected_release}")));
1669 assert!(!workflow.contains(" strict:"));
1670 assert!(!workflow.contains("@main"));
1671 assert!(!workflow.contains("constellate-science/vela"));
1672 assert!(!workflow.contains("vela sign"));
1673
1674 let has_path_filter = triggers.lines().any(|line| {
1675 let line = line.trim_start();
1676 !line.starts_with('#') && (line.contains("paths:") || line.contains("paths-ignore:"))
1677 });
1678 let public_canonical_changes = [
1679 ".vela/events/ve_example.json",
1680 "witnesses/vw_example/witness.json",
1681 "records/receipt.json",
1682 "sources/source.pdf",
1683 "artifacts/va_example",
1684 "review/decision-brief.json",
1685 "proof/latest.json",
1686 "frontier.json",
1687 "frontier.yaml",
1688 "vela.lock",
1689 ];
1690 for changed_path in public_canonical_changes {
1691 assert!(
1692 !has_path_filter,
1693 "a direct change to public canonical path {changed_path} must trigger the generated frontier gate"
1694 );
1695 }
1696 }
1697
1698 #[test]
1699 fn init_commands_quote_frontier_paths_as_one_shell_argument() {
1700 let commands = init_next_commands(Path::new("frontier with 'quotes' and spaces"));
1701 assert_eq!(
1702 commands[0],
1703 "vela agents sync 'frontier with '\"'\"'quotes'\"'\"' and spaces' --json"
1704 );
1705 assert!(
1706 commands
1707 .iter()
1708 .all(|command| command.contains("'frontier with '\"'\"'quotes'\"'\"' and spaces'"))
1709 );
1710 }
1711
1712 #[test]
1713 fn initialize_writes_canonical_git_attributes() {
1714 let tmp = tempfile::tempdir().expect("tempdir");
1715 let payload = initialize(
1716 tmp.path(),
1717 InitOptions {
1718 name: "Attribute-safe frontier",
1719 initialize_git: false,
1720 },
1721 )
1722 .expect("initialize frontier");
1723
1724 let attributes = fs::read_to_string(tmp.path().join(".gitattributes"))
1725 .expect("read generated attributes");
1726 assert!(attributes.contains("* text=auto eol=lf"));
1727 assert!(attributes.contains(".vela/** -filter -ident -working-tree-encoding -merge -text"));
1728 assert!(attributes.contains(
1729 ".vela/events/** -filter -ident -working-tree-encoding -merge diff text eol=lf"
1730 ));
1731 assert!(attributes.contains(
1732 "frontier.json -filter -ident -working-tree-encoding -merge diff text eol=lf"
1733 ));
1734 assert!(
1735 attributes.contains("review/** -filter -ident -working-tree-encoding -merge -text")
1736 );
1737 assert!(attributes.contains("witnesses/** filter=lfs diff=lfs merge=lfs -text"));
1738 let ignore =
1739 fs::read_to_string(tmp.path().join(".gitignore")).expect("read generated ignore rules");
1740 assert!(ignore.contains("/.vela/agents/"));
1741 assert!(ignore.contains("/.vela/keys/"));
1742 assert!(ignore.contains("/.vela/operation-journals/"));
1743 assert!(ignore.contains("/.vela/work/"));
1744 assert!(ignore.contains("/.vela/artifact-blobs/"));
1745 assert!(ignore.contains("/exports/"));
1746 assert!(
1747 !ignore.lines().any(|line| line.trim() == "/proof/"),
1748 "materialized proof review bytes must remain clone-visible"
1749 );
1750 assert!(
1751 !ignore.lines().any(|line| line.trim() == "/records/"),
1752 "public compatibility records must survive a clean clone"
1753 );
1754 assert!(
1755 payload["wrote"]
1756 .as_array()
1757 .expect("wrote array")
1758 .iter()
1759 .any(|entry| entry == ".gitattributes")
1760 );
1761 }
1762
1763 #[test]
1764 fn proof_current_requires_matching_snapshot_hash() {
1765 let tmp = tempfile::tempdir().expect("tempdir");
1766 let proof_dir = tmp.path();
1767 fs::write(
1768 proof_dir.join("latest.json"),
1769 serde_json::to_string_pretty(&json!({
1770 "event_log_hash": "sha256:event-log",
1771 "frontier_hash": "sha256:old-snapshot",
1772 "reducer": {
1773 "version": env!("CARGO_PKG_VERSION")
1774 }
1775 }))
1776 .expect("serialize proof latest"),
1777 )
1778 .expect("write proof latest");
1779 fs::write(proof_dir.join("events.manifest.jsonl"), "").expect("write events manifest");
1780 fs::write(proof_dir.join("replay.trace.jsonl"), "").expect("write replay trace");
1781 fs::write(proof_dir.join("hashes.json"), "{}").expect("write hashes");
1782
1783 assert!(!proof_is_current(
1784 proof_dir,
1785 "sha256:event-log",
1786 "sha256:new-snapshot"
1787 ));
1788 }
1789
1790 #[test]
1791 fn collect_verifier_kinds_scans_witnesses_dir_sorted_unique() {
1792 let tmp = tempfile::tempdir().expect("tempdir");
1793 let root = tmp.path();
1794 let wdir = root.join("witnesses");
1795 fs::create_dir_all(&wdir).expect("mkdir witnesses");
1796 fs::write(wdir.join("a.witness.json"), r#"{"kind":"sidon","n":8}"#).unwrap();
1797 fs::write(wdir.join("b.witness.json"), r#"{"kind":"golomb","n":5}"#).unwrap();
1798 fs::write(wdir.join("c.witness.json"), r#"{"kind":"sidon","n":9}"#).unwrap();
1799 fs::write(wdir.join("notes.json"), r#"{"kind":"ignored"}"#).unwrap();
1801 fs::write(root.join("stray.witness.json"), r#"{"kind":"cap"}"#).unwrap();
1804 assert_eq!(
1805 collect_verifier_kinds(root),
1806 vec!["golomb".to_string(), "sidon".to_string()]
1807 );
1808 }
1809
1810 #[test]
1811 fn collect_verifier_kinds_falls_back_to_whole_tree_when_no_witnesses_dir() {
1812 let tmp = tempfile::tempdir().expect("tempdir");
1813 let root = tmp.path();
1814 let nested = root.join("discoveries").join("sweep");
1815 fs::create_dir_all(&nested).expect("mkdir nested");
1816 fs::write(nested.join("x.witness.json"), r#"{"kind":"costas"}"#).unwrap();
1817 let vela = root.join(".vela").join("events");
1819 fs::create_dir_all(&vela).unwrap();
1820 fs::write(vela.join("e.witness.json"), r#"{"kind":"should_skip"}"#).unwrap();
1821 assert_eq!(collect_verifier_kinds(root), vec!["costas".to_string()]);
1822 }
1823}