quorum-rs 0.7.0

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! `quorum init` — non-interactive workspace bootstrap.
//!
//! Writes a minimal `nsed.yaml` pointing at a remote orchestrator,
//! room, and bearer-token env var. Designed for one-shot setups
//! (demos, CI fixtures, new-machine onboarding) where the interactive
//! wizard in `nsed init` would be too heavy.
//!
//! The output is identical in shape to what `WorkspaceConfig`
//! deserializes — `quorum status` / `quorum run` work against the
//! resulting file immediately.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

/// Default orchestrator URL when `--orchestrator-url` is omitted.
pub const DEFAULT_ORCHESTRATOR_URL: &str = "https://api.peeramid.xyz";

/// Default room name when `--room` is omitted.
pub const DEFAULT_ROOM: &str = "demo";

/// Default env-var name the generated yaml interpolates for the
/// bearer token when `--token-env` is omitted.
pub const DEFAULT_TOKEN_ENV: &str = "QUORUM_DEMO_TOKEN";

/// Inputs for the generated `nsed.yaml` workspace template. Named fields so the
/// several same-typed string args can't be transposed by callers.
pub struct WorkspaceSpec<'a> {
    pub orchestrator_url: &'a str,
    pub room: &'a str,
    /// Token reference embedded verbatim: `${ENV}` (generic one-shot),
    /// `file:<path>` (invite onboarding — points at the redeemed
    /// `operator.token`), or a literal. Resolved at runtime by
    /// [`crate::config::resolve_env_token`].
    pub token_ref: &'a str,
    pub agents: &'a [String],
}

/// Build the workspace yaml body. Pure string-templating — no filesystem side
/// effects — so tests can pin the exact output.
///
/// An empty `agents` list emits an editable `agents: []` placeholder; the
/// orchestrator rejects a policy with neither `agents` nor `roles`, so `quorum
/// run` surfaces a clear error until the user fills it in.
pub fn render_workspace(spec: &WorkspaceSpec<'_>) -> String {
    let orchestrator_url = spec.orchestrator_url;
    let room = spec.room;
    let token_ref = spec.token_ref;
    let agents = spec.agents;
    let agents_yaml = if agents.is_empty() {
        // Emit a commented-out placeholder so the user sees where to
        // put their agent names. Leave `agents:` empty so the file
        // still parses; `quorum run` will refuse cleanly with
        // "must specify either agents or roles" until the user edits.
        String::from(
            "    # Edit: list the agent names this room dispatches to, e.g.\n    #   agents: [\"CortexA\", \"CortexB\"]\n    agents: []\n",
        )
    } else {
        let quoted: Vec<String> = agents.iter().map(|a| format!("\"{a}\"")).collect();
        format!("    agents: [{}]\n", quoted.join(", "))
    };

    format!(
        r#"# =============================================================================
# quorum workspace — generated by `quorum init`
# =============================================================================
#
# This is a minimal workspace pointing at one remote orchestrator and
# one room. Edit freely — the file format matches the schema documented
# at https://docs.rs/quorum-cli (WorkspaceConfig).
#
# To run a deliberation (export the bearer first if `token` above is an
# ${{ENV}} reference; a file: reference needs no export):
#     quorum run --room {room} "<your topic>"

orchestrators:
  primary:
    mode: remote
    address: "{orchestrator_url}"
    # Bearer token resolved at runtime — an env var (${{VAR}}) or a
    # file (file:/path). Never commit the raw secret here.
    token: "{token_ref}"

policies:
  default:
{agents_yaml}    max_rounds: 3
    effort: 0.7

rooms:
  {room}:
    policy: default
    orchestrator: primary

default_room: {room}
"#,
    )
}

/// Drop a `nsed.yaml` (or whatever path was passed via `--config`) at
/// `target` from `spec`. Fails (non-zero `ExitCode`) if the file already
/// exists and `force` is false. The "next steps" hint includes an `export`
/// line only when the token is an `${ENV}` reference (a `file:` ref needs no
/// export).
pub fn run(target: &Path, spec: &WorkspaceSpec<'_>, force: bool) -> ExitCode {
    if target.exists() && !force {
        eprintln!(
            "error: {} already exists. Re-run with --force to overwrite.",
            target.display()
        );
        return ExitCode::FAILURE;
    }

    let body = render_workspace(spec);

    if let Some(parent) = target.parent()
        && !parent.as_os_str().is_empty()
        && let Err(e) = fs::create_dir_all(parent)
    {
        eprintln!("error: failed to create parent directory {parent:?}: {e}");
        return ExitCode::FAILURE;
    }

    if let Err(e) = fs::write(target, &body) {
        eprintln!("error: failed to write {}: {e}", target.display());
        return ExitCode::FAILURE;
    }

    let export_hint = spec
        .token_ref
        .strip_prefix("${")
        .and_then(|s| s.strip_suffix('}'))
        .map(|env| format!("  export {env}=<your bearer token>\n"))
        .unwrap_or_default();
    println!(
        "Wrote workspace config to {}\n\nNext steps:\n{export_hint}  quorum run --room {} \"<your topic>\"",
        target.display(),
        spec.room,
    );

    ExitCode::SUCCESS
}

/// Verify `target`'s directory is writable by creating and removing a probe
/// file. Used to pre-flight onboarding BEFORE redeem consumes the single-use
/// invite, so a non-writable cwd (e.g. running from `/`) fails fast instead of
/// burning the invite with nothing scaffolded.
fn preflight_writable(target: &Path) -> Result<(), String> {
    let parent = target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    if !parent.exists() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let probe = parent.join(".nsed-write-probe");
    std::fs::write(&probe, b"").map_err(|e| e.to_string())?;
    let _ = std::fs::remove_file(&probe);
    Ok(())
}

/// Build the `file:<path>` token reference for an onboarded workspace, pointing
/// at the `operator.token` that `quorum redeem` just wrote into `out_dir`
/// (default `~/.nsed`). Absolute, so the workspace authenticates from any cwd.
fn token_ref_for_onboard(out_dir: Option<&Path>) -> String {
    let dir = out_dir
        .map(Path::to_path_buf)
        .or_else(crate::cli::endpoint::nsed_dir)
        .unwrap_or_else(|| PathBuf::from("."));
    let path = dir.join("operator.token");
    let abs = std::fs::canonicalize(&path).unwrap_or(path);
    format!("file:{}", abs.display())
}

/// Reject agent names that would break YAML when interpolated raw
/// into the fleet template (`:`, `#`, quotes, newlines, …) — and
/// match the documented constraint operators see in the tutorial
/// ("alphanumeric + `-` / `_` / `.`"). Empty names also rejected.
fn is_valid_agent_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
}

/// Render an `agent.yml` (fleet config) template. All four
/// provider types ship commented except the first; an operator
/// picks one by uncommenting (or by editing the active block).
/// Mirrors `quorum serve`'s dispatch order so a copy/paste from
/// the running operator matches what the runner expects.
///
/// Caller must pre-validate agent names with
/// [`is_valid_agent_name`]; this function interpolates them raw.
fn render_fleet_yaml(agents: &[String]) -> String {
    let agent_names: Vec<String> = if agents.is_empty() {
        vec!["cortex-a".to_string()]
    } else {
        agents.iter().map(|s| s.to_string()).collect()
    };
    let mut agent_entries = String::new();
    for name in &agent_names {
        agent_entries.push_str(&format!(
            "  - name: {name}\n    provider_id: openai\n    model_name: gpt-4o-mini\n",
        ));
    }
    format!(
        r#"# =============================================================================
# quorum agent fleet — generated by `quorum init --agent-fleet`
# =============================================================================
#
# This file configures the AGENT PROCESS that `quorum serve` runs.
# Each entry under `agents:` becomes one worker connected to the
# orchestrator's NATS bus.
#
# Distinct from `nsed.yaml` (which configures task SUBMISSION via
# `quorum run`/`status`/`trace`/`tui`).
#
# Run:
#   quorum serve --nats-url <url-from-quorum-redeem>
#
# By default `quorum serve` reads `./agent.yml` + `~/.nsed/agent.creds`
# from `quorum redeem`. Override with --config / --nats-creds.

providers:
  # ── OpenAI-compatible LLMs ───────────────────────────────────────────
  # Default option. Works for OpenAI itself, plus any provider that
  # speaks the OpenAI wire format (Groq, DeepSeek, Together,
  # local llama.cpp, etc.) — just change `base_url`.
  # For self-hosted vLLM, point `base_url` at it and uncomment `engine`.
  openai:
    type: openai
    base_url: "https://api.openai.com/v1"
    api_key: "${{OPENAI_API_KEY}}"   # resolved from your shell env at runtime
    # engine: vllm   # tool-call parsing strategy. vllm | vllm_xml_responses |
    #                # gpt-oss (alias harmony). Omit for the default OpenAI style.

  # ── Claude CLI ───────────────────────────────────────────────────────
  # Uncomment if you have `claude` on $PATH and want the CLI to be the
  # agent runtime. No api_key here — Claude CLI handles its own auth.
  # claude_cli:
  #   type: claude

  # ── Subprocess agent (any language) via the exec protocol ────────────
  # Uncomment to drive an agent from Python/TypeScript/etc. via
  # stdin/stdout framing. See docs/reference/exec-agent-protocol.md.
  # exec_local:
  #   type: exec

  # ── Subprocess agent via Model Context Protocol ──────────────────────
  # Uncomment for an MCP-server-backed agent (Claude Code, generic MCP).
  # See docs/reference/mcp-agent-protocol.md.
  # mcp_local:
  #   type: mcp

agents:
{agent_entries}"#,
    )
}

/// Drop an `agent.yml` (fleet config for `quorum serve`) at
/// `target`. Fails when the file exists unless `force` is set.
pub fn run_agent_fleet(target: &Path, agents: &[String], force: bool) -> ExitCode {
    for name in agents {
        if !is_valid_agent_name(name) {
            eprintln!(
                "error: invalid agent name {name:?}. Allowed characters: ASCII letters, digits, `-`, `_`, `.` (and non-empty)."
            );
            return ExitCode::FAILURE;
        }
    }

    if target.exists() && !force {
        eprintln!(
            "error: {} already exists. Re-run with --force to overwrite.",
            target.display()
        );
        return ExitCode::FAILURE;
    }

    let body = render_fleet_yaml(agents);

    if let Some(parent) = target.parent()
        && !parent.as_os_str().is_empty()
        && let Err(e) = fs::create_dir_all(parent)
    {
        eprintln!("error: failed to create parent directory {parent:?}: {e}");
        return ExitCode::FAILURE;
    }

    if let Err(e) = fs::write(target, &body) {
        eprintln!("error: failed to write {}: {e}", target.display());
        return ExitCode::FAILURE;
    }

    println!(
        "Wrote agent fleet config to {}\n\n\
         Next steps:\n\
         \x20 1. Edit {} — pick a provider section (only the first is active),\n\
         \x20    set the api_key env var (or remove it if your provider doesn't need one).\n\
         \x20 2. Make sure ~/.nsed/agent.creds exists (run `quorum redeem <invite>` first).\n\
         \x20 3. Run: quorum serve --nats-url <url-from-quorum-redeem>",
        target.display(),
        target.display(),
    );

    ExitCode::SUCCESS
}

/// Retry budget for the redeem leg of `init --invite`, mirroring
/// `quorum redeem`'s own default so onboarding is equally resilient.
const ONBOARD_REDEEM_MAX_ATTEMPTS: u32 = 5;

/// Write a pre-rendered fleet (`agent.yml`) body to `target`, honoring
/// `force` and creating parent dirs. Shares the overwrite/IO contract
/// with [`run_agent_fleet`] but takes an already-rendered body (from the
/// interactive agent setup) instead of the static template.
fn write_fleet_body(target: &Path, body: &str, force: bool) -> ExitCode {
    if target.exists() && !force {
        eprintln!(
            "error: {} already exists. Re-run with --force to overwrite.",
            target.display()
        );
        return ExitCode::FAILURE;
    }

    if let Some(parent) = target.parent()
        && !parent.as_os_str().is_empty()
        && let Err(e) = fs::create_dir_all(parent)
    {
        eprintln!("error: failed to create parent directory {parent:?}: {e}");
        return ExitCode::FAILURE;
    }

    if let Err(e) = fs::write(target, body) {
        eprintln!("error: failed to write {}: {e}", target.display());
        return ExitCode::FAILURE;
    }

    println!("Wrote agent fleet config to {}", target.display());
    ExitCode::SUCCESS
}

/// Extract the fleet half (LLM providers + agents) of a rendered `agent.yml`,
/// dropping its `orchestrators:` list. The unified `quorum.yml` carries a single
/// workspace `orchestrators:` map, so keeping the fleet's list too would be a
/// duplicate top-level YAML key and break parsing. The providers section header
/// is a stable split point.
pub(crate) fn fleet_sections_of(agent_yaml: &str) -> &str {
    match agent_yaml.find("# LLM Providers") {
        Some(idx) => {
            let start = agent_yaml[..idx].rfind("# ====").unwrap_or(idx);
            &agent_yaml[start..]
        }
        None => agent_yaml,
    }
}

/// Scaffold a SINGLE unified `quorum.yml` after an invite redeem: workspace
/// (orchestrators/rooms/policies, with the operator token serve registers
/// agents under) AND the fleet (providers/agents) in one file. No more
/// `nsed.yaml` + `agent.yml` split — every command reads this one file.
///
/// `interactive` gates only the fleet half: when true the agent personas /
/// providers / file-access are gathered interactively
/// ([`crate::init::run_agent_setup`]); when false a static fleet template is
/// used so CI/Docker onboarding stays non-interactive.
async fn scaffold_after_redeem(
    target: &Path,
    spec: &WorkspaceSpec<'_>,
    force: bool,
    interactive: bool,
) -> ExitCode {
    let fleet_yaml = if interactive {
        match crate::init::run_agent_setup(spec.orchestrator_url, spec.token_ref).await {
            Ok(Some(result)) if !result.agent_config_yaml.is_empty() => result.agent_config_yaml,
            // User skipped, or it produced nothing — fall back to the static template.
            Ok(_) => render_fleet_yaml(spec.agents),
            Err(e) => {
                eprintln!("error: agent setup failed: {e:#}");
                return ExitCode::FAILURE;
            }
        }
    } else {
        render_fleet_yaml(spec.agents)
    };

    let quorum_yaml = format!(
        "{}\n{}",
        render_workspace(spec),
        fleet_sections_of(&fleet_yaml)
    );
    write_fleet_body(target, &quorum_yaml, force)
}

/// Arguments for [`run_onboard`]. A named struct so the wide CLI-dispatch call
/// site (in `main`) reads clearly and can't transpose the path/string args.
pub struct OnboardSpec<'a> {
    /// Invite code (JWT) to redeem.
    pub code: &'a str,
    pub orchestrator_url: &'a str,
    /// Where redeem writes creds/token/endpoint (default `~/.nsed`).
    pub out_dir: Option<&'a Path>,
    /// Path for the generated unified `quorum.yml`.
    pub target: &'a Path,
    pub room: &'a str,
    pub agents: &'a [String],
    pub non_interactive: bool,
    pub force: bool,
}

/// `quorum init --invite <code>` — onboarding is simply **redeem then init**:
/// it redeems the invite (writing creds/token/endpoint via the same path as
/// `quorum redeem`) and then runs the ordinary init flow, producing ONE unified
/// `quorum.yml`. On a TTY that's the interactive wizard (the redeemed
/// `operator.token` shows up as its "Use existing token" option, so no
/// re-auth); with `--non-interactive` (or no TTY) a static template is written.
/// There is no separate onboarding scaffolder — `--invite` is the redeem step
/// chained in front of `init`.
pub async fn run_onboard(spec: OnboardSpec<'_>) -> ExitCode {
    // Redeem consumes a single-use invite, so confirm we can write the
    // scaffolded config BEFORE burning it — otherwise a non-writable cwd
    // (e.g. running from `/`) spends the invite with nothing to show.
    if let Err(e) = preflight_writable(spec.target) {
        eprintln!(
            "error: cannot write {} ({e}).\n       \
             cd to a writable directory (e.g. your home), or pass --config <path>, then re-run.\n       \
             Your invite has NOT been redeemed yet.",
            spec.target.display()
        );
        return ExitCode::FAILURE;
    }

    if let Err(e) = crate::cli::commands::redeem::run(
        spec.code,
        spec.orchestrator_url,
        spec.out_dir,
        spec.force,
        None,
        ONBOARD_REDEEM_MAX_ATTEMPTS,
    )
    .await
    {
        eprintln!("error: redeem failed: {e:#}");
        return ExitCode::FAILURE;
    }

    let interactive = !spec.non_interactive && std::io::IsTerminal::is_terminal(&std::io::stdin());
    if interactive {
        // Chain into the ONE init flow. Redeem just wrote operator.token, which
        // the wizard offers as "Use existing token" — no second scaffolder.
        return crate::cli::commands::init_wizard::run(spec.target).await;
    }

    println!("\nScaffolding quorum.yml (workspace + agents)…\n");
    // Point the workspace at the bearer redeem just persisted, so `quorum
    // run`/`tui` authenticate with no manual `export`.
    let token_ref = token_ref_for_onboard(spec.out_dir);
    let workspace = WorkspaceSpec {
        orchestrator_url: spec.orchestrator_url,
        room: spec.room,
        token_ref: &token_ref,
        agents: spec.agents,
    };
    // Non-interactive only (the interactive path chained into the wizard above).
    scaffold_after_redeem(spec.target, &workspace, spec.force, false).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    /// Build a [`WorkspaceSpec`] for tests.
    fn ws<'a>(
        orchestrator_url: &'a str,
        room: &'a str,
        token_ref: &'a str,
        agents: &'a [String],
    ) -> WorkspaceSpec<'a> {
        WorkspaceSpec {
            orchestrator_url,
            room,
            token_ref,
            agents,
        }
    }

    // ── --invite onboarding: scaffold BOTH nsed.yaml + agent.yml ──────

    #[tokio::test]
    async fn scaffold_writes_single_unified_quorum_yml() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("quorum.yml");
        let exit = scaffold_after_redeem(
            &target,
            &ws(
                DEFAULT_ORCHESTRATOR_URL,
                DEFAULT_ROOM,
                "file:/tmp/operator.token",
                &[],
            ),
            false,
            false, // non-interactive → static fleet template
        )
        .await;
        assert_eq!(exit, ExitCode::SUCCESS);
        assert!(target.exists(), "quorum.yml must be written");
        let body = fs::read_to_string(&target).unwrap();
        assert!(body.contains("orchestrators:"));
        assert!(
            body.contains("token: \"file:/tmp/operator.token\""),
            "workspace must reference the redeemed token file, got:\n{body}"
        );
        assert!(
            body.contains("providers:"),
            "fleet providers must be present"
        );
        // The fleet's `orchestrators:` LIST must be stripped — only the
        // workspace map remains, so the file parses as one QuorumConfig.
        let parsed: crate::cli::workspace::QuorumConfig =
            serde_yaml::from_str(&body).expect("unified file must parse as QuorumConfig");
        assert!(parsed.orchestrators.contains_key("primary"));
    }

    #[tokio::test]
    async fn scaffold_refuses_to_overwrite_existing_without_force() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("quorum.yml");
        fs::write(&target, "existing").unwrap();
        let exit = scaffold_after_redeem(
            &target,
            &ws(
                DEFAULT_ORCHESTRATOR_URL,
                DEFAULT_ROOM,
                "file:/tmp/operator.token",
                &[],
            ),
            false, // no force → write refused
            false,
        )
        .await;
        assert_eq!(exit, ExitCode::FAILURE);
        assert_eq!(fs::read_to_string(&target).unwrap(), "existing");
    }

    #[test]
    fn render_workspace_embeds_file_token_ref_verbatim() {
        let yaml = render_workspace(&ws(
            "https://example.test",
            "demo",
            "file:/home/u/.nsed/operator.token",
            &[],
        ));
        assert!(
            yaml.contains("token: \"file:/home/u/.nsed/operator.token\""),
            "file token ref must be embedded verbatim, got:\n{yaml}"
        );
        assert!(!yaml.contains("${file:"));
    }

    #[test]
    fn render_workspace_embeds_env_token_ref() {
        let yaml = render_workspace(&ws("https://example.test", "demo", "${MY_TOKEN}", &[]));
        assert!(yaml.contains("token: \"${MY_TOKEN}\""));
    }

    #[test]
    fn token_ref_for_onboard_points_at_operator_token_in_out_dir() {
        let dir = tempdir().unwrap();
        // canonicalize requires the file to exist (redeem writes it first).
        fs::write(dir.path().join("operator.token"), "bearer\n").unwrap();
        let token_ref = token_ref_for_onboard(Some(dir.path()));
        assert!(token_ref.starts_with("file:"));
        assert!(
            token_ref.ends_with("operator.token"),
            "must point at operator.token, got: {token_ref}"
        );
        // The referenced path resolves to the real bearer.
        let path = token_ref.strip_prefix("file:").unwrap();
        assert_eq!(
            crate::config::resolve_env_token("token", &format!("file:{path}")),
            "bearer"
        );
    }

    #[test]
    fn preflight_writable_ok_for_writable_dir_and_creates_missing_parent() {
        let dir = tempdir().unwrap();
        // existing writable dir
        assert!(preflight_writable(&dir.path().join("nsed.yaml")).is_ok());
        // missing nested parent is created
        assert!(preflight_writable(&dir.path().join("nested/deep/nsed.yaml")).is_ok());
        assert!(dir.path().join("nested/deep").exists());
        // probe must not leave a file behind
        assert!(!dir.path().join(".nsed-write-probe").exists());
    }

    #[test]
    fn preflight_writable_errs_when_parent_is_a_file() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("not-a-dir");
        fs::write(&file, "x").unwrap();
        // parent of the target is a regular file → cannot write there
        assert!(preflight_writable(&file.join("nsed.yaml")).is_err());
    }

    #[test]
    fn write_fleet_body_writes_creates_parents_and_respects_force() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("nested/agent.yml");
        assert_eq!(
            write_fleet_body(&target, "providers: {}\n", false),
            ExitCode::SUCCESS
        );
        assert!(target.exists());
        // refuse overwrite without force
        assert_eq!(write_fleet_body(&target, "new", false), ExitCode::FAILURE);
        assert_eq!(fs::read_to_string(&target).unwrap(), "providers: {}\n");
        // force overwrites
        assert_eq!(write_fleet_body(&target, "new", true), ExitCode::SUCCESS);
        assert_eq!(fs::read_to_string(&target).unwrap(), "new");
    }

    fn agents(names: &[&str]) -> Vec<String> {
        names.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn renders_with_provided_inputs() {
        let yaml = render_workspace(&ws("https://example.test", "myroom", "${MY_TOKEN}", &[]));
        assert!(yaml.contains(r#"address: "https://example.test""#));
        assert!(yaml.contains("token: \"${MY_TOKEN}\""));
        assert!(yaml.contains("\n  myroom:\n    policy: default"));
        assert!(yaml.contains("default_room: myroom"));
    }

    #[test]
    fn renders_with_defaults() {
        let yaml = render_workspace(&ws(
            DEFAULT_ORCHESTRATOR_URL,
            DEFAULT_ROOM,
            "${QUORUM_DEMO_TOKEN}",
            &[],
        ));
        assert!(yaml.contains("https://api.peeramid.xyz"));
        assert!(yaml.contains("${QUORUM_DEMO_TOKEN}"));
        assert!(yaml.contains("\n  demo:\n    policy: default"));
        assert!(yaml.contains("default_room: demo"));
    }

    #[test]
    fn rendered_output_parses_as_yaml() {
        let yaml = render_workspace(&ws(
            DEFAULT_ORCHESTRATOR_URL,
            DEFAULT_ROOM,
            "${QUORUM_DEMO_TOKEN}",
            &agents(&["CortexA", "CortexB"]),
        ));
        let parsed: serde_yaml::Value =
            serde_yaml::from_str(&yaml).expect("rendered yaml must round-trip through serde");
        assert!(parsed["orchestrators"]["primary"]["address"].is_string());
        assert_eq!(parsed["default_room"].as_str(), Some("demo"));
        let agents_node = &parsed["policies"]["default"]["agents"];
        assert!(agents_node.is_sequence(), "agents must serialise as a list");
        let names: Vec<&str> = agents_node
            .as_sequence()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(names, vec!["CortexA", "CortexB"]);
    }

    #[test]
    fn renders_with_named_agents() {
        let yaml = render_workspace(&ws(
            "https://example.test",
            "demo",
            "${TOK}",
            &agents(&["A", "B"]),
        ));
        assert!(
            yaml.contains(r#"agents: ["A", "B"]"#),
            "agents list must appear in the rendered policy"
        );
    }

    #[test]
    fn empty_agents_emits_editable_placeholder() {
        let yaml = render_workspace(&ws("https://example.test", "demo", "${TOK}", &[]));
        assert!(
            yaml.contains("agents: []"),
            "empty agents must still emit a parseable agents: [] line so the file round-trips through serde"
        );
        assert!(
            yaml.contains("Edit: list the agent names"),
            "empty agents must include an inline edit hint"
        );
    }

    #[test]
    fn run_writes_file_and_succeeds_when_target_absent() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("nsed.yaml");
        let exit = run(
            &target,
            &ws(
                DEFAULT_ORCHESTRATOR_URL,
                DEFAULT_ROOM,
                "${QUORUM_DEMO_TOKEN}",
                &[],
            ),
            false,
        );
        assert_eq!(exit, ExitCode::SUCCESS);
        let body = fs::read_to_string(&target).unwrap();
        assert!(body.contains("https://api.peeramid.xyz"));
    }

    #[test]
    fn run_refuses_to_overwrite_without_force() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("nsed.yaml");
        fs::write(&target, "existing content").unwrap();
        let exit = run(
            &target,
            &ws(
                DEFAULT_ORCHESTRATOR_URL,
                DEFAULT_ROOM,
                "${QUORUM_DEMO_TOKEN}",
                &[],
            ),
            false,
        );
        assert_eq!(exit, ExitCode::FAILURE);
        let body = fs::read_to_string(&target).unwrap();
        assert_eq!(body, "existing content", "file must NOT be overwritten");
    }

    #[test]
    fn run_overwrites_with_force() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("nsed.yaml");
        fs::write(&target, "existing content").unwrap();
        let exit = run(
            &target,
            &ws(
                DEFAULT_ORCHESTRATOR_URL,
                DEFAULT_ROOM,
                "${QUORUM_DEMO_TOKEN}",
                &[],
            ),
            true,
        );
        assert_eq!(exit, ExitCode::SUCCESS);
        let body = fs::read_to_string(&target).unwrap();
        assert!(body.contains("https://api.peeramid.xyz"));
        assert!(!body.contains("existing content"));
    }

    #[test]
    fn run_creates_parent_directory_if_missing() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("nested/path/nsed.yaml");
        let exit = run(
            &target,
            &ws(
                DEFAULT_ORCHESTRATOR_URL,
                DEFAULT_ROOM,
                "${QUORUM_DEMO_TOKEN}",
                &[],
            ),
            false,
        );
        assert_eq!(exit, ExitCode::SUCCESS);
        assert!(target.exists());
    }

    #[test]
    fn rendered_output_uses_provided_token_env() {
        let yaml = render_workspace(&ws("https://example.test", "demo", "${CUSTOM_TOK}", &[]));
        assert!(yaml.contains("${CUSTOM_TOK}"));
        assert!(!yaml.contains("${QUORUM_DEMO_TOKEN}"));
    }

    // ── --agent-fleet path ───────────────────────────────────────────

    #[test]
    fn fleet_yaml_includes_active_openai_provider() {
        let yaml = render_fleet_yaml(&[]);
        assert!(yaml.contains("providers:"));
        assert!(yaml.contains("openai:"));
        assert!(
            yaml.contains("api_key: \"${OPENAI_API_KEY}\""),
            "default template references env-var; operator overrides"
        );
        // Claude / exec / mcp provider stanzas exist but are
        // commented (operator uncomments to pick).
        assert!(
            yaml.contains("# claude_cli:"),
            "claude provider must ship commented"
        );
        assert!(
            yaml.contains("# exec_local:"),
            "exec provider must ship commented"
        );
        assert!(
            yaml.contains("# mcp_local:"),
            "mcp provider must ship commented"
        );
        // The `engine` field ships commented inline on the active provider.
        assert!(
            yaml.contains("# engine: vllm"),
            "engine field must ship commented on the openai provider"
        );
    }

    #[test]
    fn fleet_yaml_defaults_to_one_agent_when_none_provided() {
        let yaml = render_fleet_yaml(&[]);
        assert!(yaml.contains("- name: cortex-a"));
        assert!(yaml.contains("model_name: gpt-4o-mini"));
    }

    #[test]
    fn fleet_yaml_emits_one_entry_per_named_agent() {
        let names = agents(&["one", "two", "three"]);
        let yaml = render_fleet_yaml(&names);
        for name in &names {
            assert!(
                yaml.contains(&format!("- name: {name}")),
                "expected entry for {name}, got:\n{yaml}"
            );
        }
    }

    #[test]
    fn fleet_yaml_parses_as_valid_yaml() {
        let yaml = render_fleet_yaml(&agents(&["cortex-a", "cortex-b"]));
        let parsed: serde_yaml::Value =
            serde_yaml::from_str(&yaml).expect("fleet yaml must round-trip via serde_yaml");
        assert!(parsed["providers"]["openai"]["type"].is_string());
        assert_eq!(
            parsed["providers"]["openai"]["type"].as_str(),
            Some("openai")
        );
        let agents_seq = parsed["agents"].as_sequence().expect("agents is a list");
        assert_eq!(agents_seq.len(), 2);
        assert_eq!(agents_seq[0]["name"].as_str(), Some("cortex-a"));
    }

    #[test]
    fn run_agent_fleet_writes_file() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("agent.yml");
        let exit = run_agent_fleet(&target, &agents(&["cortex-a"]), false);
        assert_eq!(exit, ExitCode::SUCCESS);
        assert!(target.exists());
        let body = std::fs::read_to_string(&target).unwrap();
        assert!(body.contains("providers:"));
        assert!(body.contains("- name: cortex-a"));
    }

    #[test]
    fn run_agent_fleet_refuses_to_overwrite_without_force() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("agent.yml");
        std::fs::write(&target, "stale").unwrap();
        let exit = run_agent_fleet(&target, &[], false);
        assert_eq!(exit, ExitCode::FAILURE);
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "stale");
    }

    #[test]
    fn run_agent_fleet_overwrites_with_force() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("agent.yml");
        std::fs::write(&target, "stale").unwrap();
        let exit = run_agent_fleet(&target, &[], true);
        assert_eq!(exit, ExitCode::SUCCESS);
        let body = std::fs::read_to_string(&target).unwrap();
        assert!(!body.contains("stale"));
        assert!(body.contains("providers:"));
    }

    #[test]
    fn run_agent_fleet_creates_parent_directory() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("nested/agent.yml");
        let exit = run_agent_fleet(&target, &[], false);
        assert_eq!(exit, ExitCode::SUCCESS);
        assert!(target.exists());
    }

    #[test]
    fn is_valid_agent_name_accepts_documented_alphabet() {
        for ok in ["cortex-a", "Cortex_B", "agent.v1", "a", "0", "A1_b.2-x"] {
            assert!(is_valid_agent_name(ok), "expected {ok:?} valid");
        }
    }

    #[test]
    fn is_valid_agent_name_rejects_yaml_breakers() {
        // Empty + every character that could break YAML when
        // interpolated raw into `  - name: {name}\n`.
        for bad in [
            "",
            "foo: bar",
            "name#with hash",
            "has\"quote",
            "has'quote",
            "line\nbreak",
            "tab\there",
            "back\\slash",
            "space here",
            "uni¢ode",
        ] {
            assert!(!is_valid_agent_name(bad), "expected {bad:?} invalid");
        }
    }

    #[test]
    fn run_agent_fleet_rejects_invalid_name_and_does_not_write_file() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("agent.yml");
        let exit = run_agent_fleet(&target, &agents(&["bad: name"]), false);
        assert_eq!(exit, ExitCode::FAILURE);
        assert!(
            !target.exists(),
            "must not leave a broken agent.yml on disk when validation rejects"
        );
    }
}