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",
".mcp.json",
".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"
)
}
fn mcp_json_adapter(root: &Path) -> String {
let args: Vec<String> = if root.join("frontier.yaml").is_file() || root.join(".vela").is_dir() {
["serve", ".", "--profile", "draft"]
.iter()
.map(|s| s.to_string())
.collect()
} else {
let frontiers_dir = if root.join("frontiers").is_dir() {
"frontiers"
} else {
"examples"
};
["serve", "--frontiers", frontiers_dir, "--profile", "draft"]
.iter()
.map(|s| s.to_string())
.collect()
};
let value = json!({
"_generated_by": "vela agents sync (from VELA.md) — edit VELA.md, not this file",
"mcpServers": {
"vela-local": {
"command": "vela",
"args": args
}
}
});
let mut s = serde_json::to_string_pretty(&value).expect("serialize .mcp.json");
s.push('\n');
s
}
const SKILL_FRONTMATTER: &str = r##"---
name: vela-frontier
description: Working in a repository that has a .vela/ directory (a Vela frontier). Use when picking targets, running verifiers, writing receipts, landing results, or inspecting protected review. The producer loop is next → work → land; humans authorize exact decisions.
---
"##;
const SKILL_BODY: &str = r##"
# Vela frontier work
Vela is Git-native, authority-scoped state for scientific work. Findings,
evidence, provenance, and proofs are bound to content-addressed, signed,
replayable events; everything else (frontier.json, proof packets, rollups) is a
derived view. Activity is not state: a script that ran is activity; a witness
plus a declared frozen verifier is evidence for that verifier's scoped result;
only an authorized accepted event changes frontier state. 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 reading, review, or plumbing.
```text
next -> work -> land
```
- `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 work <target> --as agent:<you> --json` — claim the lease, load the
briefing, and write one typed private `session.json` under `.vela/work/`.
A same-actor retry returns that exact active session without another lease
event. Read the returned briefing before working; do not edit the session
record.
- `vela land --work <target> --claim <result> --artifact <path>:<kind>
--caveat <limit> --as agent:<you> --json` — build Receipt v1 from the exact
session and use the shared write edge. With exactly one active session for
this actor, `--work` is inferred. A committed Permit or Defer closes only
`session.json`; Deny or invalid input keeps it for repair. Foreign producers
may still use `vela land receipt.json`.
- `vela work <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 artifact retract <frontier> <va_id> --as agent:<you> --reason <why>
--json` — draft retirement of a malformed or obsolete artifact. It remains
pending; only the human ceremony may remove its active proof-readiness weight.
- `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 Decision Brief or signed terminal decision record.
- When a task supplies a full `vpr_` ID, start with `vela review show`; it
returns the pending brief or signed terminal decision. Rejected proposal
findings are intentionally absent from accepted `finding show` and `log`
views. That absence is not deletion.
- `vela review decide . <vpr_id> --accept|--reject --reason <text> --json` — a
key-free exact Decision Plan. An agent may prepare and invoke the protected
request, but only the registered human may approve its decision card.
For a frozen-verifier witness, run `vela reproduce <witness>` first, then land
the result through the active work session with `vela land --work <target>
--artifact <witness>:witness --as agent:<you> --json`. A producer outside the
frontier can instead emit the same portable Receipt v1 and call `vela land
receipt.json`. Both paths cross the one Receipt/land write edge; the frontier's
Action may separately run `vela ci verdict` for merge policy.
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 receipt
A Vela Receipt (`vela.receipt.v1`) is the portable JSON any tool exports —
a notebook, a search run, a proof attempt:
```json
{
"schema": "vela.receipt.v1",
"claim": "what is now known / bounded / refuted",
"type": "computational | theoretical | empirical | negative",
"artifacts": [{"path": "witness.json", "kind": "witness"}],
"caveats": ["what this does NOT establish"],
"verifier_runs": [{"method": "…", "outcome": "pass", "log": "…"}]
}
```
The claim is one scoped sentence a skeptical reviewer could sign against.
Artifact paths must exist — they are hashed at land time. Caveats state what
the work does not establish; write at least one unless the claim is genuinely
unconditional. Verifier runs record only what actually ran, with honest
outcomes. Negative results (channel exhausted, bound unimproved) are landable
state and save the next session the respend.
## Landing routes
Landing routes by the frontier's signed policy:
- **Permit** — admitted canonically with no key ceremony. The human's
authority arrived earlier, once, as the policy signature; the event carries
the certificate and replay verifies it.
- **Defer** — parked for an exact protected human `review decide` decision.
- **Deny** — refuses canonical admission. The returned structured result states
what, if anything, was retained; zero-delta Deny is not assumed by clients.
Truth-bearing claims stay human-keyed in every mode. There is no configuration
in which an agent's proposal becomes accepted state without a human key.
## Custody
- Never run legacy `sign`. You may inspect `review list` and `review show`, and
prepare one exact `review decide` request. Never approve its decision card or
claim that requesting it caused acceptance.
- 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, never read or handle key material, never sit in a
trust path. A model may produce a candidate witness; only a frozen verifier
may check it, and only a key-holding human accepts a truth-bearing proposal.
- Never pre-fill a verdict the human did not explicitly give. Presenting
evidence is yours; the judgment is not.
- Artifact retirement preserves the record and its historical audit issues. It
does not retract or judge the truth or quality of linked findings.
- Never hand-edit accepted events or derived views (`frontier.json`, proof
packets); regenerate with `vela frontier materialize`. Never bulk-move
Vela-canonical paths (`examples/`, `projects/`, `lean/`, `.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 same frontier-state bar the hub's ingestor
enforces. `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 banked result.
## Reading state
`vela status --json` is the one-screen summary (findings, replay integrity,
policy state and Permit readiness, sign-queue depth, compounding metrics).
`vela finding show <dir> <vf_id> --view standing` is one finding's claim-state
cell; `vela log <dir> <vf_id>` is its history. The MCP
server (`vela serve . --profile draft`) exposes the read surface plus the
non-finalizing `work` tool (claim|land|drop);
`decide` is excluded by construction, so nothing an agent does through MCP
finalizes state.
"##;
const SKILL_NOTE: &str = "<!-- GENERATED BY `vela agents sync`. The skill template ships inside the vela\n binary (mirror of integrations/claude-plugin/skills/vela-frontier/SKILL.md).\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),
".mcp.json" => mcp_json_adapter(root),
".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_mirrors_plugin_skill() {
let plugin: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../integrations/claude-plugin/skills/vela-frontier/SKILL.md"
));
let embedded = format!("{SKILL_FRONTMATTER}{SKILL_BODY}");
assert_eq!(
plugin, embedded,
"integrations/claude-plugin/skills/vela-frontier/SKILL.md and the \
SKILL_* consts in cli_agents.rs drifted apart"
);
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 mcp_adapter_uses_tracked_frontier_manifest() {
let tmp = tempfile::TempDir::new().unwrap();
std::fs::write(tmp.path().join("frontier.yaml"), "schema: test\n").unwrap();
let value: serde_json::Value = serde_json::from_str(&mcp_json_adapter(tmp.path())).unwrap();
assert_eq!(
value["mcpServers"]["vela-local"]["args"],
serde_json::json!(["serve", ".", "--profile", "draft"])
);
}
}