use crate::cli::{fail_return, print_json};
use crate::cli_commands::AgentsAction;
use serde_json::json;
use std::path::Path;
pub(crate) fn cmd_agents(action: AgentsAction) {
match action {
AgentsAction::Sync { root, json } => cmd_agents_sync(&root, json),
AgentsAction::Doctor { root, json } => cmd_agents_doctor(&root, json),
AgentsAction::Diff { root, json } => cmd_agents_diff(&root, json),
}
}
const BEGIN: &str = "<!-- BEGIN GENERATED BY VELA. DO NOT EDIT DIRECTLY. -->";
const END: &str = "<!-- END GENERATED BY VELA. EDIT VELA.md AND RUN `vela agents sync`. -->";
const TARGETS: &[&str] = &[
"AGENTS.md",
"CLAUDE.md",
".github/copilot-instructions.md",
".cursor/rules/vela.mdc",
".claude/skills/vela-frontier/SKILL.md",
".agents/skills/vela-frontier/SKILL.md",
];
struct Adapter {
path: String,
content: String,
}
fn extract_section(md: &str, heading: &str) -> Option<String> {
let mut body: Vec<&str> = Vec::new();
let mut in_section = false;
for line in md.lines() {
if in_section {
if line.starts_with("## ") {
break;
}
body.push(line);
} else if line.trim() == heading {
in_section = true;
}
}
let joined = body.join("\n").trim().to_string();
if joined.is_empty() {
None
} else {
Some(joined)
}
}
fn markdown_adapter(title: &str, rules: &str, commands: &str) -> String {
format!(
"{BEGIN}\n\
# {title}\n\n\
Generated from VELA.md. Do not edit here — edit VELA.md and run `vela agents sync`.\n\
VELA.md is the canonical, full agent charter for this worktree.\n\n\
## Agent rules\n\n{rules}\n\n\
## Fast commands\n\n{commands}\n\n\
See VELA.md for the full charter: hard rules, layout, contribution path, design, git.\n\
{END}\n"
)
}
fn cursor_adapter(rules: &str) -> String {
format!(
"---\ndescription: Vela frontier rules (generated from VELA.md)\nalwaysApply: true\n---\n\n\
{BEGIN}\n\
# Vela frontier rules\n\n\
Generated from VELA.md. Edit VELA.md and run `vela agents sync`; do not edit here.\n\n\
{rules}\n\n\
Use `vela status --json` before proposing changes. Every proposed transition is a\n\
draft until a key-holding human accepts it. The full charter is VELA.md.\n\
{END}\n"
)
}
const SKILL_FRONTMATTER: &str = r##"---
name: vela-frontier
description: Working in a repository that has a .vela/ directory (a Vela Frontier). Use when inspecting standing, starting Attempts, submitting evidence, importing Verification Records, or reviewing exact Proposals. The producer loop is next → start → submit; only authorized Decisions change standing.
---
"##;
const SKILL_BODY: &str = r##"
# Vela frontier work
Vela is Git-native, authority-scoped state for scientific work. Claims,
Submissions, Verification Records, Decisions, and repository-authority
transitions bind exact content and replay deterministically. Activity is not
state: a script that ran is activity; a witness plus a declared frozen
verifier is evidence for one scoped result; only an authorized Decision
changes Standing. A repository with a `.vela/` directory is a Frontier, and
this skill is how an agent works inside one.
## The loop
Three producer verbs; everything else is inspection, verification, decision,
or plumbing.
```text
next -> start -> submit
```
- `vela next --json` — the offer: ranked open targets with the compounding
payload pre-loaded (premises to build on, banked routes, prior attempts,
dead channels). Returns `{targets: [{lane, id, title, why, next_command, task?}]}`.
Trust the ranking; it already encodes what the frontier knows.
- `vela start <target> --as agent:<you> --json` — claim the lease, load the
briefing, and write one typed private Attempt under `.vela/work/`.
A same-actor retry returns that exact active Attempt without another lease
event. Read the returned briefing before working; do not edit the Attempt
record.
- `vela submit --attempt <vat_id> --claim <result> --type <type>
--replayability <class> --artifact <path>:<kind> --caveat <limit>
--as agent:<you> --json` — build and register Submission v1 from the exact
Attempt. Registration creates a pending Proposal and no accepted-state
change. A foreign producer may pass one signed `submission.json`.
- `vela submit --claim <replacement> --type <type> --replayability <class>
--artifact <path>:<kind> --caveat <limit> --supersedes <full_vcl_id>
--target-root <full_sha256_root> --as agent:<you> --json` — request one exact
supersession without inventing a ranked work target. New Claims still
require an Attempt. This producer action cannot decide the Proposal.
- `vela start <target> --drop --reason <why> --as agent:<you> --json` — sign a
same-owner zero-TTL lease update, then remove private scratch. Deleting files
by hand does not release a lease.
- `vela review list . --json` — the pending queue, newest first. Each compact
row includes `created_at`; use `vela review show . <vpr_id> --json` for one
exact pending Review Packet or signed terminal Decision record.
- When a task supplies a full `vpr_` ID, start with `vela review show`; it
returns the pending Review Packet or signed terminal Decision. Rejected
Proposals remain inspectable; they do not create accepted Claim standing.
- `vela review accept . <vpr_id> --reason <text> --json` or
`vela review reject . <vpr_id> --reason <text> --json` prepares one exact
Decision Plan and executes it through repository authority. An agent may
prepare or explain the exact command, but may not invoke either action.
For a frozen-verifier witness, run `vela reproduce <witness>` first, then
submit the result through the active Attempt with `vela submit --attempt <vat_id>
--artifact <witness>:witness --as agent:<you> --json`. A producer outside the
frontier can emit the same portable Submission v1 and call `vela submit
submission.json`. Producer checks remain producer-reported; an independent
Verification Record is separate.
Every verb takes `--json` and returns one object with `ok` and `command`; no
prose leaks into a JSON stream. Exit codes: 0 ok, 1 domain failure, 2 usage,
3 not found, 4 custody refused, 5 already exists. The frontier argument is
discovered by walking upward from the current directory, like git.
## The submission
A Vela Submission (`vela.submission.v1`) is authenticated producer input from
a notebook, search run, proof attempt, or research harness. It can request a
change, but it cannot assert Standing, mint Verification, or create a Decision:
```json
{
"schema": "vela.submission.v1",
"claim": {
"assertion": "what is now known / bounded / refuted",
"type": "computational",
"conditions": ["the exact bounded range"]
},
"artifacts": [{
"path": "witness.json",
"kind": "witness",
"digest": "sha256:..."
}],
"caveats": ["what this does NOT establish"],
"producer_checks": [{
"method": "local replay",
"outcome": "pass",
"authority": "producer_reported"
}]
}
```
The claim is one scoped sentence a skeptical reviewer could sign against.
Artifact paths must exist and match their full digest. Caveats state what the
work does not establish. Producer checks report only what the producer ran;
independent Verification is a separate signed record. Bounded negative results
remain useful submissions and save the next Attempt from repeating them.
## Registration and decision
`vela submit` registers the exact Submission and a pending Proposal. It returns
a Vela-issued Registration Record proving intake, not truth. Independent
Verification Records may then attach scoped results. Only `review accept` or
`review reject` creates an authorized Decision; registration and verification
never imply acceptance.
## Custody
- Never run legacy `sign`. You may inspect `review list` and `review show`, and
prepare or explain one exact `review accept` or `review reject` command.
Never invoke either action, access repository-authority credentials, or
claim that preparing a command caused a Decision.
- Every write carries an explicit acting identity: `--as agent:<you>`, or set
`VELA_ACTOR_ID=agent:<you>` for the session. Never write as a human.
- Never sign anything, read or handle key material, or sit in a trust path. A
model may produce a candidate witness; a frozen verifier may report its
scoped result; only an authorized principal may make the Decision.
- Never pre-fill a verdict the human did not explicitly give. Presenting
evidence is yours; the judgment is not.
- Never hand-edit canonical objects, repository-authority history, or derived
views. Use the exact current CLI and never bulk-move `.vela/`.
## The gate
Frontier repos carry a conformance gate. When the harness supports suites, run
the suites selected from the affected paths and require 0 FAIL in each one.
Trust-path changes run every deterministic suite selected from their affected
paths. Release certification runs the deterministic full Vela union. Live
network and platform-pinned adapter checks stay explicit and cannot block an
unrelated Vela release. A selected suite fails if a required verifier toolchain
is absent; a non-selected suite is not a pass.
`vela check . --strict` is the current repository integrity bar. `vela
reproduce <frontier>` re-runs the frozen verifiers over stored witnesses from
scratch. Run it before claiming a reproduction, and never silently break the
reproduction of a retained result.
## Reading state
`vela status --json` is the one-screen summary of Claims, replay integrity,
policy state, review depth, and the next bounded action.
`vela show <dir> <typed_id>` inspects an exact object; `vela why <dir>
<claim_id>` explains its standing; `vela log <dir>` reads canonical history.
Agents invoke these exact CLI contracts directly. Execution harnesses such as
Canopus remain optional producers and do not become part of Vela's authority
or repository state.
"##;
const SKILL_NOTE: &str = "<!-- GENERATED BY `vela agents sync`. The canonical skill template ships inside the vela binary.\n Do not edit here; upgrade vela and re-run `vela agents sync`. -->";
fn skill_adapter() -> String {
format!("{SKILL_FRONTMATTER}\n{SKILL_NOTE}\n{SKILL_BODY}")
}
fn try_build_adapters(root: &Path) -> Result<Vec<Adapter>, String> {
let vela_md_path = root.join("VELA.md");
let md = std::fs::read_to_string(&vela_md_path).map_err(|_| {
format!(
"no VELA.md at {} — author the canonical agent charter first (it is the one source the adapters generate from; see the memo \u{00a7}5)",
vela_md_path.display()
)
})?;
let rules = extract_section(&md, "## Agent rules").ok_or_else(|| {
"VELA.md is missing a `## Agent rules` section (the adapters derive from it)".to_string()
})?;
let commands = extract_section(&md, "## Fast commands").ok_or_else(|| {
"VELA.md is missing a `## Fast commands` section (the adapters derive from it)".to_string()
})?;
TARGETS
.iter()
.map(|&path| {
let content = match path {
"AGENTS.md" => markdown_adapter("Vela \u{2014} agent guide", &rules, &commands),
"CLAUDE.md" => {
markdown_adapter("Vela \u{2014} Claude Code guide", &rules, &commands)
}
".github/copilot-instructions.md" => {
markdown_adapter("Vela \u{2014} Copilot instructions", &rules, &commands)
}
".cursor/rules/vela.mdc" => cursor_adapter(&rules),
".claude/skills/vela-frontier/SKILL.md"
| ".agents/skills/vela-frontier/SKILL.md" => skill_adapter(),
other => return Err(format!("unknown adapter target {other}")),
};
Ok(Adapter {
path: path.to_string(),
content,
})
})
.collect()
}
fn build_adapters(root: &Path) -> Vec<Adapter> {
try_build_adapters(root).unwrap_or_else(|error| fail_return(&error))
}
pub(crate) fn cmd_agents_sync(root: &Path, json_output: bool) {
let adapters = build_adapters(root);
let mut wrote: Vec<String> = Vec::new();
let mut unchanged: Vec<String> = Vec::new();
for a in &adapters {
let target = root.join(&a.path);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)
.unwrap_or_else(|e| fail_return(&format!("create dir for {}: {e}", a.path)));
}
let current = std::fs::read_to_string(&target).ok();
if current.as_deref() == Some(a.content.as_str()) {
unchanged.push(a.path.clone());
continue;
}
std::fs::write(&target, &a.content)
.unwrap_or_else(|e| fail_return(&format!("write {}: {e}", a.path)));
wrote.push(a.path.clone());
}
if json_output {
print_json(&json!({
"command": "agents sync",
"source": "VELA.md",
"wrote": wrote,
"unchanged": unchanged,
}));
} else {
println!(
"\u{00b7} agents sync: {} adapter(s) generated from VELA.md ({} written, {} already current)",
adapters.len(),
wrote.len(),
unchanged.len()
);
for p in &wrote {
println!(" wrote {p}");
}
}
}
type AdapterComparison = (Vec<String>, Vec<String>, Vec<String>);
pub(crate) fn compare(root: &Path) -> AdapterComparison {
try_compare(root).unwrap_or_else(|error| fail_return(&error))
}
pub(crate) fn try_compare(root: &Path) -> Result<AdapterComparison, String> {
let adapters = try_build_adapters(root)?;
let (mut missing, mut drifted, mut in_sync) = (Vec::new(), Vec::new(), Vec::new());
for a in &adapters {
match std::fs::read_to_string(root.join(&a.path)) {
Err(_) => missing.push(a.path.clone()),
Ok(c) if c == a.content => in_sync.push(a.path.clone()),
Ok(_) => drifted.push(a.path.clone()),
}
}
Ok((in_sync, drifted, missing))
}
pub(crate) fn cmd_agents_doctor(root: &Path, json_output: bool) {
let (in_sync, drifted, missing) = compare(root);
let ok = drifted.is_empty() && missing.is_empty();
if json_output {
print_json(&json!({
"command": "agents doctor",
"ok": ok,
"in_sync": in_sync,
"drifted": drifted,
"missing": missing,
}));
} else if ok {
println!(
"\u{00b7} agents doctor: ok \u{2014} all {} adapter(s) in sync with VELA.md",
in_sync.len()
);
} else {
println!("\u{00b7} agents doctor: out of sync with VELA.md");
for p in &drifted {
println!(" drifted {p} (run `vela agents sync`)");
}
for p in &missing {
println!(" missing {p} (run `vela agents sync`)");
}
}
if !ok {
std::process::exit(1);
}
}
pub(crate) fn cmd_agents_diff(root: &Path, json_output: bool) {
let (in_sync, drifted, missing) = compare(root);
let would_change: Vec<String> = drifted.iter().chain(missing.iter()).cloned().collect();
if json_output {
print_json(&json!({
"command": "agents diff",
"would_change": would_change,
"in_sync": in_sync,
}));
} else if would_change.is_empty() {
println!("\u{00b7} agents diff: nothing to change \u{2014} adapters match VELA.md");
} else {
println!(
"\u{00b7} agents diff: {} adapter(s) would change on `vela agents sync`:",
would_change.len()
);
for p in &would_change {
println!(" {p}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn skill_template_emits_identical_agent_adapters() {
for path in [
".claude/skills/vela-frontier/SKILL.md",
".agents/skills/vela-frontier/SKILL.md",
] {
assert!(TARGETS.contains(&path), "{path} missing from TARGETS");
}
let tmp = tempfile::TempDir::new().unwrap();
std::fs::write(
tmp.path().join("VELA.md"),
"# Vela\n\n## Agent rules\n\n- rule\n\n## Fast commands\n\n- cmd\n",
)
.unwrap();
let adapters = build_adapters(tmp.path());
let skill_copies: Vec<&str> = adapters
.iter()
.filter(|a| a.path.ends_with("skills/vela-frontier/SKILL.md"))
.map(|a| a.content.as_str())
.collect();
assert_eq!(skill_copies.len(), 2, "expected exactly two skill adapters");
assert_eq!(
skill_copies[0], skill_copies[1],
".claude/skills and .agents/skills adapters drifted apart"
);
assert_eq!(
skill_copies[0],
skill_adapter(),
"skill adapters must emit skill_adapter() verbatim"
);
}
#[test]
fn skill_adapter_keeps_frontmatter_first() {
let s = skill_adapter();
assert!(s.starts_with("---\nname: vela-frontier\n"));
assert!(s.contains("GENERATED BY `vela agents sync`"));
assert!(s.contains("# Vela frontier work"));
let fm_end = s.find("\n---\n").expect("frontmatter closes");
let note_at = s.find("GENERATED BY").expect("note present");
assert!(note_at > fm_end);
}
#[test]
fn skill_adapter_keeps_decisions_out_of_agent_authority() {
let s = skill_adapter();
assert!(s.contains("may not invoke either action"));
assert!(s.contains("Never invoke either action"));
assert!(!s.contains("may invoke the protected request"));
assert!(!s.contains("Never authorize its decision card"));
}
}