scema-cli 0.2.0

Scematica Omni — the `scema` command: a terminal-native agent runtime over the omni cognitive loop.
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
//! # `scema` — Scematica Omni from the terminal
//!
//! One binary over the whole loop. The verbs are the stages, so what the runtime does is
//! legible from `--help` rather than from a diagram:
//!
//! ```text
//!   scema observe .                          perceive an environment
//!   scema simulate "add tests to scema-cli"  rank branches, write nothing
//!   scema decide   "add tests to scema-cli"  rank branches, seal a record
//!   scema explain  8f92a1c4                  why that decision came out that way
//!   scema verify   8f92a1c4                  recompute the commitment
//!   scema remember --stats                   what the agent has retained
//!   scema policy                             the weights and the specialists
//! ```
//!
//! ## The verbs that exist and refuse
//!
//! `execute`, `delegate`, `discover` and `pay` are registered and exit non-zero with a
//! statement of what is missing. They are in the help text on purpose: the shape of the
//! runtime includes an action path, an agent-to-agent path and a payment path, and an
//! operator should be able to find out from the tool itself that those are not built rather
//! than from a README they may not read. A verb that silently did not exist would be
//! indistinguishable from one that failed.
//!
//! ## `simulate` versus `decide`
//!
//! `simulate` never persists. It is a counterfactual — "what would this look like" — and a
//! record it left behind would later read as a decision the agent made. `decide` seals a
//! record and appends memory. Both compute exactly the same thing; only the side effects
//! differ, which is why they share one code path with a flag rather than being two.

mod connect;
mod doctor;
mod launch;

use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::{anyhow, Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use scema_agent::{Agent, Cycle};
use scema_memory::{MemoryKind, Recall};
// The render rule lives with the types it protects, not with each front end. See
// `scema_policy::render`.
use scema_policy::render;
use scema_verify::{verify, RecordStore};
use scema_world::{Constraint, Goal};

/// Default state directory, relative to the working directory.
const DEFAULT_ROOT: &str = ".scema";

#[derive(Parser)]
#[command(
    name = "scema",
    version,
    about = "Scematica Omni — an agent runtime with a world model, counterfactual simulation and verifiable decisions",
    long_about = None
)]
struct Cli {
    /// State directory for decision records and memory.
    #[arg(long, global = true, default_value = DEFAULT_ROOT)]
    root: PathBuf,

    /// Deep Q* checkpoint (the sniper's `scematica-nn-agent.json`), for trading worlds.
    #[arg(long, global = true)]
    dqstar: Option<String>,

    /// Emit JSON instead of a rendered report.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Perceive an environment and print the world state.
    Observe {
        /// Path to observe.
        #[arg(default_value = ".")]
        locator: String,
    },
    /// Rank competing branches against a goal. Writes nothing.
    Simulate {
        goal: String,
        #[arg(long, default_value = ".")]
        path: String,
        /// A thing the agent must not touch. Repeatable. Format: `subject[:detail]`.
        #[arg(long = "must-not")]
        must_not: Vec<String>,
        /// Assert that this goal addresses a counted signal, by id. Repeatable.
        ///
        /// Nothing infers this. Without it the goal branch is ungrounded, scores at or
        /// below zero, and the agent abstains — which is the honest answer to an
        /// instruction the observed world says nothing about. Run `scema observe` to see
        /// the signal ids.
        #[arg(long = "ground")]
        ground: Vec<String>,
        /// Show the failure modes of the top branch.
        #[arg(long)]
        failures: bool,
    },
    /// Rank branches, choose or abstain, and seal a decision record.
    Decide {
        goal: String,
        #[arg(long, default_value = ".")]
        path: String,
        #[arg(long = "must-not")]
        must_not: Vec<String>,
        /// Assert that this goal addresses a counted signal, by id. Repeatable.
        #[arg(long = "ground")]
        ground: Vec<String>,
    },
    /// Everything `decide` does, with the full narration.
    Mission {
        goal: String,
        #[arg(long, default_value = ".")]
        path: String,
        #[arg(long = "must-not")]
        must_not: Vec<String>,
        /// Assert that this goal addresses a counted signal, by id. Repeatable.
        #[arg(long = "ground")]
        ground: Vec<String>,
    },
    /// Re-read a sealed decision.
    Explain {
        /// Record id, or any unique prefix.
        id: Option<String>,
        /// List known records instead.
        #[arg(long)]
        list: bool,
    },
    /// Recompute a record's commitment and report what moved.
    Verify {
        /// Record id or unique prefix.
        id: Option<String>,
        /// Verify a record file directly, wherever it is.
        #[arg(long)]
        file: Option<PathBuf>,
        /// Verify every record in the store.
        #[arg(long)]
        all: bool,
    },
    /// What the agent has retained.
    Remember {
        /// Per-kind counts and projection calibration.
        #[arg(long)]
        stats: bool,
        /// Recall records whose subject contains this.
        #[arg(long)]
        about: Option<String>,
        #[arg(long, default_value = "10")]
        limit: usize,
    },
    /// The utility weights and the registered specialists.
    Policy,
    /// Open the console — the loop as a full-screen terminal application.
    ///
    /// A separate binary (`scema-tui`), handed over to rather than linked in, so that
    /// `cargo install scema-cli` does not drag a terminal stack onto a CI machine whose
    /// only use for this is `scema verify`.
    Tui {
        /// Arguments forwarded verbatim to `scema-tui`.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Run the local daemon (`scema-omnid`) — loopback HTTP, token-authenticated.
    Daemon {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Run the MCP server (`scema-mcp`) — the loop as tools, over stdio, for a model.
    Mcp {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Create the state directory, so the first `decide` is not also the first write.
    Init {
        /// Overwrite an existing `.gitignore` entry rather than leaving it alone.
        #[arg(long)]
        force: bool,
    },

    /// Wire the MCP server into an assistant — Claude Code, Cursor, VS Code, Zed, Codex.
    ///
    /// Prints the exact snippet and where it goes. `--write` merges it, and only into
    /// project-local files: a user-level assistant config is shared by every project, and
    /// editing it on your behalf would mean a tool installed for one repository quietly
    /// gaining the ability to observe all of them.
    Connect {
        /// Which assistant. Omit with `--list` to see them all.
        host: Option<String>,
        /// List every host this knows about.
        #[arg(long)]
        list: bool,
        /// Merge the entry into the project-local config file.
        #[arg(long)]
        write: bool,
        /// The directory the MCP server is confined to. Defaults to the working directory.
        #[arg(long)]
        allow: Option<PathBuf>,
        /// Let the model seal decision records. Off by default, and `omni_decide` is not
        /// even advertised without it.
        #[arg(long)]
        allow_decide: bool,
    },

    /// What is installed, what is wired up, and what is quietly broken. Changes nothing.
    Doctor,

    /// Emit a shell completion script.
    Completions {
        /// bash | zsh | fish | powershell | elvish
        shell: Shell,
    },

    /// Not implemented: carry out a chosen action.
    Execute,
    /// Not implemented: hire another agent.
    Delegate,
    /// Not implemented: find purchasable capabilities.
    Discover,
    /// Not implemented: settle for a capability over x402.
    Pay,
}

fn parse_constraints(specs: &[String]) -> Vec<Constraint> {
    specs
        .iter()
        .filter_map(|s| {
            let (subject, detail) = match s.split_once(':') {
                Some((a, b)) => (a.trim(), b.trim()),
                None => (s.trim(), "declared on the command line"),
            };
            // An empty subject would forbid everything by substring match. Dropping it is
            // safer than the alternative, and the warning says so rather than failing
            // silently.
            if subject.is_empty() {
                eprintln!("scema: ignoring an empty --must-not (an empty subject would forbid every branch)");
                return None;
            }
            Some(Constraint::must_not(subject, detail))
        })
        .collect()
}

fn build_goal(statement: &str, must_not: &[String], ground: &[String]) -> Goal {
    let mut g = Goal::new("goal", statement);
    for c in parse_constraints(must_not) {
        g = g.with_constraint(c);
    }
    for id in ground {
        g = g.grounded(id.trim());
    }
    g
}

/// Warn about `--ground` ids that name no signal in the observed world.
///
/// The simulator drops them, so this is not a correctness issue — it is a usability one.
/// A typo in a signal id otherwise produces a silent abstention that looks like the agent
/// disagreeing rather than the operator mistyping.
fn warn_dangling_grounds(world: &scema_world::WorldState, goal: &Goal) {
    for id in &goal.grounded_in {
        if !world.signals.iter().any(|s| &s.id == id) {
            eprintln!(
                "scema: --ground `{id}` names no signal in this world; it will be ignored.                  Run `scema observe` for the ids."
            );
        }
    }
}

fn print_cycle(c: &Cycle, json: bool, failures: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(&c.record)?);
        return Ok(());
    }
    println!("{}\n", render::world_header(&c.world));
    println!("{}\n", render::signals(&c.world));
    print!("{}", render::matrix(&c.decision, &c.projections));
    println!();
    println!("{}\n", render::evaluators(&c.decision));
    println!("{}", render::verdict(&c.decision));

    if failures {
        if let Some(top) = c.decision.ranked.first() {
            if let Some(p) = c.projections.iter().find(|p| p.hypothesis == top.hypothesis) {
                let text = render::failure_modes(p);
                if !text.is_empty() {
                    println!("\n{text}");
                }
            }
        }
    }

    match &c.record_path {
        Some(p) => println!(
            "\nRECORD    {}  ({})\n          {} memory record(s) appended",
            c.record.id,
            p.display(),
            c.remembered
        ),
        None => println!(
            "\nRECORD    not written — `simulate` is a counterfactual and leaves no trace.\n          Run `scema decide` to seal this as {}.",
            c.record.id
        ),
    }
    Ok(())
}

fn run(cli: Cli) -> Result<ExitCode> {
    let agent_for = |persist: bool| {
        let mut a = Agent::new(cli.root.clone(), cli.dqstar.clone());
        a.persist = persist;
        a
    };

    match &cli.command {
        Command::Observe { locator } => {
            let agent = agent_for(false);
            let w = agent.observe(locator)?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&w)?);
            } else {
                println!("{}\n", render::world_header(&w));
                println!("{}\n", render::signals(&w));
                println!("OBJECTS  {}", w.objects.len());
                for o in w.objects.iter().take(20) {
                    let attrs: Vec<String> = o
                        .attrs
                        .iter()
                        .map(|(k, v)| format!("{k}={}", v.render()))
                        .collect();
                    println!(
                        "  {:<10} {:<24} {}",
                        o.provenance.label(),
                        o.label,
                        if attrs.is_empty() {
                            "(no values — unseen, not empty)".to_string()
                        } else {
                            attrs.join(" ")
                        }
                    );
                }
                if w.objects.len() > 20 {
                    println!("{} more", w.objects.len() - 20);
                }
            }
            Ok(ExitCode::SUCCESS)
        }

        Command::Simulate { goal, path, must_not, ground, failures } => {
            let agent = agent_for(false);
            let world = agent.observe(path)?;
            let goal = build_goal(goal, must_not, ground);
            warn_dangling_grounds(&world, &goal);
            let c = agent.cycle_over(world, goal)?;
            print_cycle(&c, cli.json, *failures)?;
            Ok(ExitCode::SUCCESS)
        }

        Command::Decide { goal, path, must_not, ground }
        | Command::Mission { goal, path, must_not, ground } => {
            let agent = agent_for(true);
            let world = agent.observe(path)?;
            let goal = build_goal(goal, must_not, ground);
            warn_dangling_grounds(&world, &goal);
            let c = agent.cycle_over(world, goal)?;
            let narrate = matches!(cli.command, Command::Mission { .. });
            print_cycle(&c, cli.json, narrate)?;
            // A decision that abstained is not a failure of the program, and must not exit
            // non-zero: a script that treats "the agent declined" as a crash will be
            // rewritten to ignore the exit code, and then it will ignore real crashes too.
            Ok(ExitCode::SUCCESS)
        }

        Command::Explain { id, list } => {
            let store = RecordStore::new(cli.root.clone());
            if *list || id.is_none() {
                let ids = store.ids()?;
                if ids.is_empty() {
                    println!("No decision records under {}.", cli.root.display());
                    println!("Run `scema decide \"<goal>\"` to seal one.");
                    return Ok(ExitCode::SUCCESS);
                }
                println!("{} record(s), newest first:", ids.len());
                for id in ids {
                    match store.load(&id) {
                        Ok(r) => println!(
                            "  {}  {:<40}  {}",
                            r.id,
                            {
                                let s = r.goal.statement.clone();
                                if s.chars().count() > 40 {
                                    s.chars().take(39).collect::<String>() + ""
                                } else {
                                    s
                                }
                            },
                            match (&r.decision.chosen, &r.decision.abstention) {
                                (Some(c), _) => format!("chose {c}"),
                                (None, Some(a)) => format!("abstained — {}", a.headline()),
                                _ => "".into(),
                            }
                        ),
                        // An unreadable record still gets a line. Hiding it would make a
                        // corrupt store look like a smaller one.
                        Err(e) => println!("  {id}  <unreadable: {e}>"),
                    }
                }
                return Ok(ExitCode::SUCCESS);
            }

            let record = store.load(id.as_ref().unwrap())?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&record)?);
                return Ok(ExitCode::SUCCESS);
            }
            println!("RECORD    {}  runtime {}", record.id, record.runtime);
            println!("GOAL      {}", record.goal.statement);
            for c in &record.goal.constraints {
                println!("          constraint {:?} `{}` — {}", c.kind, c.subject, c.detail);
            }
            println!();
            println!("{}\n", render::world_header(&record.world));
            print!("{}", render::matrix(&record.decision, &record.projections));
            println!();
            println!("{}\n", render::evaluators(&record.decision));
            println!("{}", render::verdict(&record.decision));
            let v = verify(&record);
            println!(
                "\nCOMMITMENT {}\n           root {}",
                if v.valid { "VALID — the record matches its commitment" } else { "INVALID" },
                record.commitment.root
            );
            Ok(ExitCode::SUCCESS)
        }

        Command::Verify { id, file, all } => {
            let store = RecordStore::new(cli.root.clone());
            let records = if let Some(f) = file {
                vec![RecordStore::load_path(f).with_context(|| format!("reading {}", f.display()))?]
            } else if *all {
                store.ids()?.iter().filter_map(|i| store.load(i).ok()).collect()
            } else {
                let id = id
                    .as_ref()
                    .ok_or_else(|| anyhow!("give a record id, --file, or --all"))?;
                vec![store.load(id)?]
            };
            if records.is_empty() {
                println!("Nothing to verify under {}.", cli.root.display());
                return Ok(ExitCode::SUCCESS);
            }

            let results: Vec<_> = records.iter().map(verify).collect();
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&results)?);
            } else {
                for v in &results {
                    println!("{}  {}", v.id, if v.valid { "VALID" } else { "INVALID" });
                    for m in &v.mismatches {
                        println!(
                            "    {:<12} committed {}…  recomputed {}",
                            m.field,
                            &m.committed[..m.committed.len().min(12)],
                            &m.recomputed[..m.recomputed.len().min(12)]
                        );
                    }
                    if v.root_only {
                        println!("    every part verifies but the root does not — the root was edited on its own");
                    }
                }
                println!(
                    "\nThis proves the record was not edited after sealing. It does NOT prove the\nworld was as described — provenance carries that, not the digest."
                );
            }
            if results.iter().all(|v| v.valid) {
                Ok(ExitCode::SUCCESS)
            } else {
                Ok(ExitCode::FAILURE)
            }
        }

        Command::Remember { stats, about, limit } => {
            let agent = agent_for(false);
            let mem = agent.memory();
            if *stats || about.is_none() {
                let counts = mem.counts()?;
                println!("MEMORY   {}", mem.root().join("memory").display());
                for (kind, n, corrupt) in counts {
                    println!(
                        "  {:<16} {:>6} record(s){}",
                        format!("{kind:?}"),
                        n,
                        if corrupt > 0 { format!("   {corrupt} unreadable line(s)") } else { String::new() }
                    );
                }
                let c = mem.calibration()?;
                println!("\nCALIBRATION");
                println!("  branches not taken, recorded   {}", c.recorded);
                println!("  of those, later resolved       {}", c.resolved);
                println!("  unresolved                     {}", c.unresolved);
                match c.mean_abs_error {
                    Some(e) => println!("  mean |projected − realised|    {e:.3}"),
                    None => println!(
                        "  mean |projected − realised|    — (nothing resolved; a branch nobody ran has no outcome)"
                    ),
                }
                return Ok(ExitCode::SUCCESS);
            }
            let query = Recall {
                subject: about.clone(),
                limit: Some(*limit),
                ..Default::default()
            };
            for kind in MemoryKind::all() {
                let hits = mem.recall(kind, &query)?;
                if hits.is_empty() {
                    continue;
                }
                println!("{kind:?}");
                for h in hits {
                    println!("  {}  {}  {}", h.id, h.subject, serde_json::to_string(&h.body)?);
                }
            }
            Ok(ExitCode::SUCCESS)
        }

        Command::Policy => {
            let agent = agent_for(false);
            let w = agent.config.weights;
            println!("UTILITY   U = R − λ₁K − λ₂C − λ₃U + λ₄V");
            println!("  λ₁ risk           {:.2}", w.risk);
            println!("  λ₂ cost           {:.2}", w.cost);
            println!("  λ₃ uncertainty    {:.2}", w.uncertainty);
            println!("  λ₄ reversibility  {:.2}", w.reversibility);
            println!("\n  These are a stated preference, not a fitted parameter. They are hashed");
            println!("  into every record so a ranking can be re-read against them later.");
            println!("\nGATES");
            println!("  min measured fraction  {:.0}%", agent.config.min_coverage * 100.0);
            println!("  specialist veto at     ≤ {:.2}", agent.config.veto_at_or_below);
            println!("\nOBSERVERS");
            for o in agent.observers() {
                println!("  {:<10} {}", o.name(), o.about());
            }
            println!("\nEVALUATORS");
            for e in agent.evaluators() {
                println!("  {:<10} {}", e.name(), e.about());
            }
            Ok(ExitCode::SUCCESS)
        }

        Command::Tui { args } => launch::run(launch::TUI, args),
        Command::Daemon { args } => launch::run(launch::DAEMON, args),
        Command::Mcp { args } => launch::run(launch::MCP, args),

        Command::Init { force } => {
            let root = &cli.root;
            std::fs::create_dir_all(root.join("decisions"))
                .with_context(|| format!("creating {}", root.join("decisions").display()))?;
            std::fs::create_dir_all(root.join("memory"))
                .with_context(|| format!("creating {}", root.join("memory").display()))?;

            // `.scema/` is machine-local and full of absolute paths, so it is ignored rather
            // than committed. Writing the ignore *inside* the directory rather than editing
            // the project's root `.gitignore` is deliberate: this tool has no business
            // rewriting a file the whole repository shares, and a self-ignoring directory
            // works whatever the project's own ignore rules say.
            let ignore = root.join(".gitignore");
            if !ignore.exists() || *force {
                std::fs::write(
                    &ignore,
                    "# Machine-local. Decision records cite absolute paths and memory is a\n\
                     # per-checkout history; neither is meaningful in somebody else's clone.\n\
                     *\n",
                )
                .with_context(|| format!("writing {}", ignore.display()))?;
            }

            println!("Initialised {}", root.display());
            println!("  decisions/   sealed decision records, one JSON file each");
            println!("  memory/      four append-only JSONL logs");
            println!("  .gitignore   this directory is machine-local");
            println!();
            println!("Nothing has been decided yet. Start with:");
            println!("  scema observe .                        # what is out there");
            println!("  scema simulate \"<goal>\" --ground <id>   # rank branches, write nothing");
            println!("  scema tui                              # the same thing, interactively");
            Ok(ExitCode::SUCCESS)
        }

        Command::Connect { host, list, write, allow, allow_decide } => {
            if *list || host.is_none() {
                println!("Assistants this can wire up:\n");
                for (key, h) in connect::catalogue() {
                    println!(
                        "  {:<15} {:<32} {}",
                        key,
                        h.label,
                        match h.scope {
                            connect::Scope::Project => format!("project: {}", h.project_path),
                            connect::Scope::User =>
                                "user-level (printed, never written)".to_string(),
                        }
                    );
                }
                println!("\n  scema connect <host>            print the snippet and where it goes");
                println!("  scema connect <host> --write    merge it, project-local hosts only");
                return Ok(ExitCode::SUCCESS);
            }

            let key = host.as_deref().unwrap();
            let h = connect::host(key).ok_or_else(|| {
                anyhow!(
                    "unknown host `{key}`. Known: {}",
                    connect::catalogue().keys().cloned().collect::<Vec<_>>().join(", ")
                )
            })?;
            let project = doctor::cwd();
            let allow_path = allow.clone().unwrap_or_else(|| project.clone());
            let text = connect::snippet(h, &allow_path, *allow_decide)?;

            if *write {
                match connect::write(h, &project, &allow_path, *allow_decide) {
                    Ok(connect::Written::Created(p)) => println!("created {}", p.display()),
                    Ok(connect::Written::Merged(p)) => {
                        println!("merged the `scema` entry into {} (nothing else touched)", p.display())
                    }
                    Ok(connect::Written::Unchanged(p)) => {
                        println!("{} already has this exact entry", p.display())
                    }
                    Err(e) => {
                        // Not a hard failure: the snippet is still useful, and the whole
                        // point of refusing a user-level write is that pasting it is the
                        // correct next step rather than a workaround.
                        eprintln!("scema connect: {e:#}\n");
                        println!("{text}");
                        return Ok(ExitCode::from(2));
                    }
                }
            } else {
                match h.scope {
                    connect::Scope::Project => println!("{}{}\n", h.label, h.project_path),
                    connect::Scope::User => println!("{}\n{}\n", h.label, h.user_hint),
                }
                println!("{text}");
            }
            println!("Then: {}", h.after);
            if !*allow_decide {
                println!(
                    "\nNote: `omni_decide` is not advertised to the model. The server can perceive,\n\
                     simulate, explain and verify; it cannot seal a record. Add --allow-decide if\n\
                     you want that, having decided you want it."
                );
            }
            Ok(ExitCode::SUCCESS)
        }

        Command::Doctor => {
            let project = doctor::cwd();
            let findings = doctor::run(&cli.root, &project);
            if cli.json {
                let rows: Vec<_> = findings
                    .iter()
                    .map(|f| {
                        serde_json::json!({
                            "verdict": format!("{:?}", f.verdict).to_lowercase(),
                            "check": f.check,
                            "detail": f.detail,
                            "fix": f.fix,
                        })
                    })
                    .collect();
                println!("{}", serde_json::to_string_pretty(&rows)?);
            } else {
                println!("scema doctor — {}\n", scema_agent::RUNTIME);
                for f in &findings {
                    println!("  [{}] {:<24} {}", f.verdict.glyph(), f.check, f.detail);
                    if !f.fix.is_empty() {
                        println!("         {:<24} → {}", "", f.fix);
                    }
                }
                println!("\nThis command changes nothing. Every finding names the fix and stops there.");
            }
            // Only a real failure is non-zero. A missing optional console must not fail a
            // pipeline, or the pipeline stops running this.
            Ok(match doctor::worst(&findings) {
                doctor::Verdict::Fail => ExitCode::FAILURE,
                _ => ExitCode::SUCCESS,
            })
        }

        Command::Completions { shell } => {
            let mut cmd = Cli::command();
            let name = cmd.get_name().to_string();
            clap_complete::generate(*shell, &mut cmd, name, &mut std::io::stdout());
            Ok(ExitCode::SUCCESS)
        }

        Command::Execute => not_built(
            "execute",
            "Nothing in this workspace writes to an environment it observed. An action path \
             needs the approval model from `alchem-link` — risk declared per tool, no \
             terminal means deny, secrets refused before the prompt — wired in front of it.",
        ),
        Command::Delegate => not_built(
            "delegate",
            "Agent-to-agent hiring runs over the ScemaDEX relay and needs a bonded result \
             format, so a specialist that answers badly can be slashed rather than merely \
             disbelieved.",
        ),
        Command::Discover => not_built(
            "discover",
            "Capability discovery needs the relay's catalogue endpoint and a policy for \
             which capabilities this agent is allowed to want.",
        ),
        Command::Pay => not_built(
            "pay",
            "x402 settlement exists in `scematica-protocol`, but paying on the agent's own \
             initiative needs a spend policy first. A runtime that can spend without one is \
             a runtime nobody should install.",
        ),
    }
}

fn not_built(verb: &str, why: &str) -> Result<ExitCode> {
    eprintln!("scema {verb}: not built yet.\n");
    eprintln!("  {why}");
    eprintln!("\n  It is listed in `--help` on purpose: the shape of this runtime includes");
    eprintln!("  this verb, and finding that out from the tool beats finding it out later.");
    Ok(ExitCode::from(2))
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(cli) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("scema: {e:#}");
            ExitCode::FAILURE
        }
    }
}