vela-cli 0.940.1

The vela command-line tool: build, check, sign, replay, and publish scientific frontier 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! `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`, `.mcp.json`,
//! `.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 text
//! is the Vela frontier skill template, embedded below as a const and mirrored
//! byte-for-byte from `integrations/claude-plugin/skills/vela-frontier/SKILL.md`
//! (a test pins the parity). VELA.md stays the charter for THIS worktree; the
//! skill teaches the protocol-level loop, receipt, and custody rules that are
//! the same in every frontier.

use crate::cli::{fail_return, print_json};
use crate::cli_commands::AgentsAction;
use serde::Serialize;
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",
    ".mcp.json",
    ".claude/skills/vela-frontier/SKILL.md",
    ".agents/skills/vela-frontier/SKILL.md",
];

struct Adapter {
    path: String,
    content: String,
}

#[derive(Serialize)]
struct McpAdapter<'a> {
    #[serde(rename = "_generated_by")]
    generated_by: &'static str,
    #[serde(rename = "mcpServers")]
    mcp_servers: McpServers<'a>,
}

#[derive(Serialize)]
struct McpServers<'a> {
    #[serde(rename = "vela-local")]
    vela_local: McpServer<'a>,
}

#[derive(Serialize)]
struct McpServer<'a> {
    args: &'a [String],
    command: &'static str,
}

/// 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"
    )
}

fn mcp_json_adapter(root: &Path) -> String {
    // Pick a serve invocation from durable worktree structure. A tracked
    // `frontier.yaml` identifies a single frontier even when private `.vela/`
    // state is absent from a clean clone; consulting `.vela/` alone made
    // generated adapters differ between local and CI checkouts. Multi-frontier
    // roots serve their conventional catalog (`frontiers/`, else `examples/`).
    // Draft profile: the read surface plus the non-finalizing `work` actions.
    // `decide` is excluded by construction, so
    // this delegates nothing — matching what the skill teaches. Keep the
    // profile and the skill text in step.
    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()
    };
    // Serialize typed structs rather than `serde_json::Value`. A Value map can
    // preserve insertion order or sort keys depending on Cargo feature
    // unification, which previously made release and debug binaries disagree
    // about the generated bytes.
    let value = McpAdapter {
        generated_by: "vela agents sync (from VELA.md) — edit VELA.md, not this file",
        mcp_servers: McpServers {
            vela_local: McpServer {
                args: &args,
                command: "vela",
            },
        },
    };
    let mut s = serde_json::to_string_pretty(&value).expect("serialize .mcp.json");
    s.push('\n');
    s
}

/// 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). Mirrored byte-for-byte from
/// `integrations/claude-plugin/skills/vela-frontier/SKILL.md`; a test pins the
/// parity. Edit the plugin file and this const together.
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 Vela frontier skill. See [`SKILL_FRONTMATTER`] for the mirror
/// rule.
const SKILL_BODY: &str = r##"
# Vela frontier work

Vela is Git-native, authority-scoped state for scientific work. Claims,
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 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 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 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 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. An agent may invoke the protected request, but only the
  registered human may authorize its decision card.

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 one exact `review accept` or `review reject` request. Never authorize
  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 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. The MCP
server (`vela serve . --profile draft`) exposes the read surface plus the
non-finalizing Attempt and Submission tools;
`decide` is excluded by construction, so nothing an agent does through MCP
finalizes state.
"##;

/// The note stamped into the EMITTED skill adapter (after the frontmatter, so
/// the skill still parses). The plugin's copy of the skill carries no note —
/// there it is authored source.
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}")
}

/// 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),
                ".mcp.json" => mcp_json_adapter(root),
                // 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, three copies: the plugin's authored SKILL.md, the
    /// `.claude/skills/` adapter, and the `.agents/skills/` (Codex) adapter
    /// must all carry byte-identical skill text. Edit them together or this
    /// fails.
    #[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"
        );

        // Both skill targets are declared, and both emit the same string via
        // `skill_adapter()`: build the adapters against a minimal VELA.md and
        // compare the two emitted copies byte-for-byte.
        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 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 generated = mcp_json_adapter(tmp.path());
        let value: serde_json::Value = serde_json::from_str(&generated).unwrap();
        assert_eq!(
            value["mcpServers"]["vela-local"]["args"],
            serde_json::json!(["serve", ".", "--profile", "draft"])
        );
        assert!(
            generated.find("\"args\"").unwrap() < generated.find("\"command\"").unwrap(),
            "typed adapter serialization must not depend on serde_json map ordering"
        );
    }
}