vela-cli 0.950.0

The Vela command-line tool: inspect, submit, verify, decide, and replay scientific state.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! `vela agents sync|doctor|diff` — generate vendor agent-config adapters from
//! the canonical `VELA.md` (memo §5, §10). One source of truth; the adapter
//! files (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules/vela.mdc`,
//! `.github/copilot-instructions.md`,
//! `.claude/skills/vela-frontier/SKILL.md`,
//! `.agents/skills/vela-frontier/SKILL.md`) are disposable, regenerable
//! leaves. The deletion test holds: delete every adapter, run `agents sync`,
//! the same rules regenerate from VELA.md.
//!
//! The skill adapter is the one exception to "derived from VELA.md": its
//! protocol-level loop and custody rules are embedded below as the single
//! authored template. VELA.md stays the charter for this worktree.

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`. -->";

/// The adapters generated from VELA.md, in deterministic order.
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,
}

/// Pull the body of a `## <heading>` section, up to the next `## ` heading.
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 {
    // Cursor `.mdc` rules. Kept short per memo §10.4; the canonical charter is
    // VELA.md. The frontmatter `alwaysApply` keeps the rule in context.
    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"
    )
}

/// Frontmatter of the Vela frontier skill (Claude Code / Codex shared format:
/// Claude Code discovers it at `.claude/skills/`, Codex at `.agents/skills/`
/// per the open agent-skills standard).
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.
---
"##;

/// Body of the single Vela frontier skill template.
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.
"##;

/// The note stamped into the emitted skill adapter after its frontmatter.
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}")
}

/// Build the full set of adapters from `<root>/VELA.md` without exiting the
/// process. Read-only callers such as `vela doctor` use this fallible core so
/// a missing charter becomes a diagnostic row rather than aborting the report.
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),
                // The same skill text serves both discovery roots: Claude Code
                // reads `.claude/skills/`, Codex reads `.agents/skills/` (the
                // open agent-skills standard; same SKILL.md format). One
                // string, two paths — a test pins the parity.
                ".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()
}

/// Command-facing wrapper: mutating adapter verbs retain their established
/// fail-fast CLI behavior while doctor can use [`try_build_adapters`].
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}");
        }
    }
}

/// Doctor / diff share the comparison core: which adapters are missing, drifted,
/// or in-sync against what `sync` would produce.
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::*;

    /// One source of truth produces byte-identical Claude Code and Codex
    /// adapters.
    #[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"
        );
    }

    /// The emitted adapter must keep the YAML frontmatter first (the skill
    /// loader requires it) with the generated note inside the body.
    #[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"));
        // The note lands after the closing `---`, never inside the frontmatter.
        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"));
    }
}