OXYGENHUB

Coverage / src/cli/mod.rs 84.7%

205 of 242 lines run, 36 of 88 functions · run #29 on main · run missed

1
//! The `spectra` command line (spec §19). Output is modern: colour and
2
//! glyphs on a UTF-8 terminal, plain when piped, with `--plain` or with
3
//! `NO_COLOR`; `--json` prints one document on stdout and nothing else.
4
5
pub mod admin;
6
pub mod agent;
7
pub mod brief;
8
pub mod connect;
9
pub mod format;
10
pub mod human;
11
pub mod identity;
12
pub mod marks;
13
pub mod mcp;
14
pub mod open;
15
pub mod project;
16
pub mod serve;
17
pub mod setup;
18
pub mod ui;
19
20
use anyhow::{bail, Context, Result};
21
use clap::{Parser, Subcommand};
22
use std::path::PathBuf;
23
24
#[derive(Parser)]
25
#[command(name = "spectra", version = env!("SPECTRA_VERSION_LONG"), about = "A control plane for AI coding agents")]
26
pub struct Cli {
27
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
28
    #[arg(long, global = true)]
29
    pub plain: bool,
30
    /// The data directory (default: $XDG_DATA_HOME/spectra, else ~/.local/share/spectra)
31
    #[arg(long, global = true, env = "SPECTRA_DATA")]
32
    pub data: Option<PathBuf>,
33
    #[command(subcommand)]
34
    pub command: Command,
35
}
36
37
#[derive(Subcommand)]
38
pub enum Command {
39
    /// The version and build of this binary
40
    Version {
41
        /// Machine-readable output
42
        #[arg(long)]
43
        json: bool,
44
    },
45
    /// Make this machine's Spectra: record the owner's identity (read from
46
    /// their OXY_HOME and proven by signing) and make the instance key
47
    Init {
48
        /// The owner's identity home (default: $SPECTRA_HOME, else ~/.config/spectra)
49
        #[arg(long)]
50
        owner_home: Option<PathBuf>,
51
        /// This instance's name (default: the host name)
52
        #[arg(long)]
53
        name: Option<String>,
54
        /// Set up a server without the owner's secret key: name the owner's
55
        /// KeyId, and they claim it from their machine with `spectra
56
        /// connect` (spec §8.6)
57
        #[arg(long, value_name = "KEYID", conflicts_with = "owner_home")]
58
        owner: Option<String>,
59
    },
60
    /// Use a Spectra on another machine: trust it through your delegation to
61
    /// its instance key, pin its certificate, and claim it if it is new
62
    Connect {
63
        /// The server, https://HOST[:PORT]
64
        url: String,
65
        /// Trust the server if its instance key starts with this, without asking
66
        #[arg(long, value_name = "KEYID-PREFIX")]
67
        expect: Option<String>,
68
        /// Trust it without asking (for scripts)
69
        #[arg(long, short = 'y')]
70
        yes: bool,
71
        /// The owner's identity home (default: $SPECTRA_HOME, else ~/.config/spectra)
72
        #[arg(long)]
73
        owner_home: Option<PathBuf>,
74
    },
75
    /// What is set up here: your identity, and the Spectra you use
76
    Status {
77
        #[arg(long)]
78
        json: bool,
79
    },
80
    /// What a server is (its name and instance key), without trusting it
81
    Probe {
82
        /// The server, https://HOST[:PORT]
83
        url: String,
84
        #[arg(long)]
85
        json: bool,
86
    },
87
    /// Sign as you for a program that cannot (the VS Code extension): a
88
    /// loopback proxy that ends when its input closes
89
    Bridge {
90
        #[arg(long, default_value_t = 0)]
91
        port: u16,
92
        #[arg(long)]
93
        owner_home: Option<PathBuf>,
94
    },
95
    /// What the agents are told: the overall brief and each project's
96
    Brief {
97
        #[command(subcommand)]
98
        command: BriefCmd,
99
    },
100
    /// The owner's and the instance's identities: show, refresh
101
    Identity {
102
        #[command(subcommand)]
103
        command: IdentityCmd,
104
    },
105
    /// Run the daemon: the ledger, Tuner on the Unix socket and a loopback port
106
    Serve {
107
        /// The address and port for browsers and HTTP clients (default:
108
        /// `[server] bind`, else 127.0.0.1:7350); beyond loopback, other
109
        /// machines connect over TLS (spec §8.6)
110
        #[arg(long)]
111
        bind: Option<String>,
112
        /// TLS on the TCP port: auto (beyond loopback only), on, or off
113
        /// (default: `[server] tls`, else auto)
114
        #[arg(long)]
115
        tls: Option<String>,
116
        /// Allow a non-loopback address in plain HTTP
117
        #[arg(long)]
118
        insecure: bool,
119
        /// Open Radar in the browser once serving (signs a link as the owner)
120
        #[arg(long)]
121
        open: bool,
122
    },
123
    /// Sign in to Radar: a one-time link signed with the owner's key
124
    Open {
125
        #[arg(long)]
126
        owner_home: Option<PathBuf>,
127
        /// Print the link without opening a browser
128
        #[arg(long)]
129
        no_browser: bool,
130
        /// With Spectra on another machine: the loopback port of the proxy
131
        /// Radar is served through (spec §8.6)
132
        #[arg(long, default_value_t = 7350)]
133
        port: u16,
134
        /// The page to land on: live, constellation, briefs, channels or log
135
        #[arg(long)]
136
        page: Option<String>,
137
    },
138
    /// The stdio MCP server for one agent: signs with its key and forwards to the daemon
139
    Mcp {
140
        /// The agent it speaks for
141
        #[arg(long)]
142
        agent: String,
143
        /// The agent's home (default: the one recorded when it was added)
144
        #[arg(long)]
145
        home: Option<PathBuf>,
146
    },
147
    /// Post a message as yourself
148
    Say {
149
        /// What to say (Markdown; @name mentions)
150
        body: String,
151
        /// The channel (default: #general)
152
        #[arg(short, long)]
153
        channel: Option<String>,
154
        /// Reply in the thread of this message
155
        #[arg(long)]
156
        reply_to: Option<String>,
157
        #[arg(long)]
158
        json: bool,
159
        #[arg(long)]
160
        owner_home: Option<PathBuf>,
161
    },
162
    /// Your unread mentions and direct messages; --follow waits for more
163
    Inbox {
164
        #[arg(long)]
165
        follow: bool,
166
        #[arg(long)]
167
        json: bool,
168
        #[arg(long)]
169
        owner_home: Option<PathBuf>,
170
    },
171
    /// Search what was said: words, "phrases", prefix*, AND/OR/NOT
172
    Search {
173
        query: String,
174
        #[arg(long)]
175
        channel: Option<String>,
176
        #[arg(long)]
177
        author: Option<String>,
178
        /// 7d, 3h, 30m
179
        #[arg(long)]
180
        since: Option<String>,
181
        #[arg(long, default_value_t = 20)]
182
        limit: u32,
183
        #[arg(long)]
184
        json: bool,
185
    },
186
    /// Any API call, signed as the owner: JSON out
187
    Api {
188
        method: String,
189
        path: String,
190
        /// The request body (JSON)
191
        #[arg(short = 'd', long = "body")]
192
        body: Option<String>,
193
        #[arg(long)]
194
        owner_home: Option<PathBuf>,
195
    },
196
    /// The checkouts agents work in: add, list
197
    Project {
198
        #[command(subcommand)]
199
        command: ProjectCmd,
200
    },
201
    /// Agents, each its owner's delegate: add, list, disable
202
    Agent {
203
        #[command(subcommand)]
204
        command: AgentCmd,
205
    },
206
    /// The ledger's own checks: verify, check, rebuild
207
    Admin {
208
        #[command(subcommand)]
209
        command: Admin,
210
    },
211
}
212
213
#[derive(Subcommand)]
214
pub enum IdentityCmd {
215
    /// Make your own identity: a key pair that signs as you (spec §8.0)
216
    Create {
217
        /// Your name, as agents and Radar show it
218
        #[arg(long)]
219
        name: String,
220
        /// An email or URL, if you want one shown
221
        #[arg(long, default_value = "")]
222
        contact: String,
223
        /// Where to keep it (default: $SPECTRA_HOME, else ~/.config/spectra)
224
        #[arg(long)]
225
        home: Option<PathBuf>,
226
        #[arg(long)]
227
        json: bool,
228
    },
229
    /// The owner and the instance as the ledger knows them
230
    Show {
231
        #[arg(long)]
232
        json: bool,
233
    },
234
    /// Record the owner's current identity if the ledger has missed a successor
235
    Refresh {
236
        #[arg(long)]
237
        owner_home: Option<PathBuf>,
238
    },
239
}
240
241
#[derive(Subcommand)]
242
pub enum BriefCmd {
243
    /// Show the overall brief, or a project's
244
    Show {
245
        #[arg(long)]
246
        project: Option<String>,
247
        #[arg(long)]
248
        json: bool,
249
    },
250
    /// Set the overall brief, or a project's (an empty text clears it)
251
    Set {
252
        #[arg(long)]
253
        project: Option<String>,
254
        /// The text
255
        text: Option<String>,
256
        /// Read the text from a file (- for standard input)
257
        #[arg(long, short = 'f')]
258
        file: Option<PathBuf>,
259
        #[arg(long)]
260
        owner_home: Option<PathBuf>,
261
    },
262
    /// Edit it in $VISUAL or $EDITOR
263
    Edit {
264
        #[arg(long)]
265
        project: Option<String>,
266
        #[arg(long)]
267
        owner_home: Option<PathBuf>,
268
    },
269
}
270
271
#[derive(Subcommand)]
272
pub enum ProjectCmd {
273
    /// Add a project: any kind of work, with a folder if it has one
274
    Add {
275
        /// A folder (its name becomes the project's), or just a name
276
        target: String,
277
        /// Its name, when TARGET is a folder
278
        #[arg(long)]
279
        name: Option<String>,
280
        /// The work's folder, when TARGET is a name; Spectra never reads it
281
        #[arg(long)]
282
        path: Option<PathBuf>,
283
        /// What the work is, for agents and Radar
284
        #[arg(long, short = 'd', default_value = "")]
285
        description: String,
286
        /// A link to it, if any
287
        #[arg(long)]
288
        url: Option<String>,
289
        #[arg(long)]
290
        owner_home: Option<PathBuf>,
291
    },
292
    /// Say that one project depends on another (`delegate to: downstream` follows links)
293
    Link {
294
        project: String,
295
        #[arg(long)]
296
        depends_on: String,
297
        /// Remove the link instead
298
        #[arg(long)]
299
        remove: bool,
300
        #[arg(long)]
301
        owner_home: Option<PathBuf>,
302
    },
303
    /// Every project with its links and agents
304
    List {
305
        #[arg(long)]
306
        json: bool,
307
    },
308
}
309
310
#[derive(Subcommand)]
311
pub enum AgentCmd {
312
    /// Make an agent's key in its own home, delegate to it, and record it
313
    Add {
314
        /// Lower-case letters, digits and dashes
315
        name: String,
316
        /// claude-code, antigravity, kimi-code, codex or other
317
        #[arg(long)]
318
        kind: String,
319
        /// The project it works in
320
        #[arg(long)]
321
        project: String,
322
        /// The agent's own identity home, where its key is made and kept
323
        #[arg(long)]
324
        home: PathBuf,
325
        /// Bind the key to this Unix user: a request from another is refused
326
        #[arg(long)]
327
        uid: Option<u32>,
328
        /// Bind the key to the Unix user of its first signed connection
329
        #[arg(long, conflicts_with = "uid")]
330
        learn_uid: bool,
331
        /// How long the agent may act for you: 30m, 8h, 7d (default: until disabled)
332
        #[arg(long)]
333
        expires: Option<String>,
334
        /// Delegate without asking (for scripts)
335
        #[arg(long, short = 'y')]
336
        yes: bool,
337
        /// The owner's identity home
338
        #[arg(long)]
339
        owner_home: Option<PathBuf>,
340
    },
341
    /// Give an agent more time: delegate to its key again with a new expiry
342
    Renew {
343
        name: String,
344
        /// 30m, 8h, 7d, or `never`
345
        #[arg(long)]
346
        expires: String,
347
        #[arg(long)]
348
        owner_home: Option<PathBuf>,
349
    },
350
    /// Every agent with its owner, key, delegation and state
351
    List {
352
        #[arg(long)]
353
        json: bool,
354
    },
355
    /// Refuse an agent's key from now on
356
    Disable {
357
        name: String,
358
        #[arg(long)]
359
        owner_home: Option<PathBuf>,
360
    },
361
}
362
363
#[derive(Subcommand)]
364
pub enum Admin {
365
    /// Recompute the hash chain and check every checkpoint and proof (exit 1 on any finding)
366
    Verify {
367
        /// Machine-readable output
368
        #[arg(long)]
369
        json: bool,
370
    },
371
    /// Whether the projections equal a rebuild from the ledger
372
    Check,
373
    /// Replay the ledger into every projection
374
    Rebuild,
375
}
376
377
/// What every command needs: where the data lives.
378
pub struct Ctx {
379
    pub data: PathBuf,
380
}
381
382
impl Ctx {
383
    /// The ledger's database, which must exist.
384180×
    pub fn db(&self) -> Result<PathBuf> {
385180×
        let db = self.data.join("spectra.db");
386180×
        if !db.exists() {
3871×
            bail!("no Spectra in {} (run `spectra init`, or pass --data)", self.data.display());
388179×
        }
389179×
        Ok(db)
390180×
    }
391
392
    /// The ledger, for writing: the instance key signs its checkpoints, and
393
    /// the lock keeps any other writer out.
39460×
    pub async fn writer(&self) -> Result<spectra_core::ledger::Ledger> {
39560×
        let db = self.db()?;
39660×
        let instance = spectra_core::keys::KeyPair::instance(&self.data, "spectra")?;
39760×
        spectra_core::ledger::Ledger::open(&db, Some(instance)).await
39860×
    }
399
400
    /// The daemon's Unix socket.
401133×
    pub fn socket(&self) -> PathBuf {
402133×
        self.data.join("spectra.sock")
403133×
    }
404
405
    /// The Spectra on another machine this one uses, if any (spec §8.6).
406172×
    pub fn remote(&self) -> Result<Option<connect::ClientCfg>> {
407172×
        connect::load()
408172×
    }
409
410
    /// Where the daemon is: the configured server, else the local socket.
4110×
    pub fn endpoint(&self) -> Result<spectra_mcp::client::Endpoint> {
4120×
        Ok(match self.remote()? {
4130×
            Some(c) => c.endpoint()?,
4140×
            None => spectra_mcp::client::Endpoint::Unix(self.socket()),
415
        })
4160×
    }
417
418
    /// A client signing as the owner: to the configured server (spec §8.6),
419
    /// or to the local daemon when it is serving; none when neither. It
420
    /// signs with the owner identity the ledger records, since the daemon
421
    /// may not know a newer one yet.
42250×
    pub async fn owner_client(&self, owner_home: &std::path::Path) -> Result<Option<spectra_mcp::client::Client>> {
423
        use spectra_mcp::client::Client;
42450×
        if let Some(cfg) = self.remote()? {
42510×
            let ep = cfg.endpoint()?;
42610×
            let pair = remote_owner(&ep, owner_home).await?;
42710×
            return Ok(Some(Client::at(ep, Some(pair))));
42840×
        }
42940×
        if !self.data.join("spectra.db").exists() || !Client::alive(&self.socket()).await {
43033×
            return Ok(None);
4317×
        }
4327×
        let ledger = spectra_core::ledger::Ledger::open_read_only(&self.db()?).await?;
4337×
        Ok(Some(Client::new(&self.socket(), Some(identity::recorded_owner(&ledger, owner_home).await?))))
43450×
    }
435
436
    /// Somewhere to append the owner's signed events: the configured server,
437
    /// the local daemon when it is serving, else straight to the ledger
438
    /// (spec §8.5, §8.6).
43961×
    pub async fn owner_writer(&self, owner_home: &std::path::Path) -> Result<Writer> {
44061×
        if let Some(cfg) = self.remote()? {
4414×
            let ep = cfg.endpoint()?;
4424×
            let pair = remote_owner(&ep, owner_home).await?;
4434×
            let recorded = pair.identity.clone();
4444×
            return Ok(Writer::Remote { client: Box::new(spectra_mcp::client::Client::at(ep, Some(pair))), recorded });
44557×
        }
44657×
        let db = self.db()?;
44757×
        if spectra_mcp::client::Client::alive(&self.socket()).await {
4486×
            let ledger = spectra_core::ledger::Ledger::open_read_only(&db).await?;
4496×
            let transport = identity::recorded_owner(&ledger, owner_home).await?;
4506×
            return Ok(Writer::Daemon { ledger, client: Box::new(spectra_mcp::client::Client::new(&self.socket(), Some(transport))) });
45151×
        }
45251×
        Ok(Writer::Direct(self.writer().await?))
45361×
    }
454
455
    /// Refuse a command that needs the ledger file on this machine.
4569×
    pub fn local_only(&self, what: &str) -> Result<()> {
4579×
        if self.remote()?.is_some() {
4581×
            bail!("{what} runs on the server, which holds the ledger (this machine uses {})", connect::path().display());
4598×
        }
4608×
        Ok(())
4619×
    }
462
463
    /// `[owner] home` from spectra.toml.
464113×
    pub fn config_owner_home(&self) -> Option<PathBuf> {
465113×
        let text = std::fs::read_to_string(self.data.join("spectra.toml")).ok()?;
46677×
        let t: toml::Table = text.parse().ok()?;
46777×
        t.get("owner")?.get("home")?.as_str().map(PathBuf::from)
468113×
    }
469
}
470
471
/// Where the owner's events go.
472
pub enum Writer {
473
    Direct(spectra_core::ledger::Ledger),
474
    Daemon {
475
        ledger: spectra_core::ledger::Ledger,
476
        client: Box<spectra_mcp::client::Client>,
477
    },
478
    /// A Spectra on another machine; `recorded` is the owner identity it knows.
479
    Remote {
480
        client: Box<spectra_mcp::client::Client>,
481
        recorded: spectra_core::identity::Identity,
482
    },
483
}
484
485
impl Writer {
486
    /// The ledger on this machine, for reading, if there is one.
48736×
    pub fn ledger(&self) -> Option<&spectra_core::ledger::Ledger> {
48836×
        match self {
48933×
            Writer::Direct(l) | Writer::Daemon { ledger: l, .. } => Some(l),
4903×
            Writer::Remote { .. } => None,
491
        }
49236×
    }
493
494
    /// A client of the daemon, when one is serving.
49536×
    pub fn client(&self) -> Option<&spectra_mcp::client::Client> {
49636×
        match self {
4977×
            Writer::Daemon { client, .. } | Writer::Remote { client, .. } => Some(client),
49829×
            Writer::Direct(_) => None,
499
        }
50036×
    }
501
502
    /// The rotation that brings the recorded owner to the current identity
503
    /// in `home`, if it has moved.
50458×
    pub async fn refresh_event(&self, home: &std::path::Path) -> Result<Option<spectra_core::event::NewEvent>> {
50558×
        match self {
50654×
            Writer::Direct(l) | Writer::Daemon { ledger: l, .. } => identity::refresh_event(l, home).await,
5074×
            Writer::Remote { recorded, .. } => identity::rotation(recorded, home),
508
        }
50958×
    }
510
511
    /// Append events signed over their payload, then checkpoint.
51258×
    pub async fn append(&self, events: Vec<spectra_core::event::NewEvent>) -> Result<()> {
51358×
        match self {
51448×
            Writer::Direct(l) => {
51548×
                l.append(events).await?;
51648×
                l.checkpoint().await?;
517
            }
5186×
            Writer::Daemon { client, .. } | Writer::Remote { client, .. } => {
51910×
                let wire: Vec<_> = events.iter().map(spectra_core::daemon::WireEvent::from_new).collect();
52010×
                let r = client.send("POST", "/api/v1/ledger/events", &[], serde_json::to_vec(&wire)?).await?;
52110×
                if r.status != 200 {
5220×
                    let why = r
5230×
                        .json()
5240×
                        .ok()
5250×
                        .and_then(|v| v.get("title").and_then(|t| t.as_str()).map(String::from))
5260×
                        .unwrap_or_else(|| String::from_utf8_lossy(&r.body).into());
5270×
                    bail!("the daemon refused: {why}");
52810×
                }
529
            }
530
        }
53158×
        Ok(())
53258×
    }
533
}
534
535
/// The owner identity a server records, as a key pair from the owner's
536
/// home: what requests to it are signed with.
53714×
async fn remote_owner(ep: &spectra_mcp::client::Endpoint, home: &std::path::Path) -> Result<spectra_core::keys::KeyPair> {
53814×
    let r = spectra_mcp::client::Client::at(ep.clone(), None).send("GET", "/api/v1/instance", &[], vec![]).await?;
53914×
    let info = r.json()?;
54014×
    let key = info.get("owner").and_then(|o| o.as_str()).context("the server has no owner yet: spectra connect claims it")?;
54114×
    let keys = home.join("keys");
54214×
    spectra_core::keys::KeyPair::load(&keys.join(format!("{key}.secret")), &keys.join(format!("{key}.identity")))
54314×
        .with_context(|| format!("the server's owner {} is not an identity in {}", &key[..12.min(key.len())], home.display()))
54414×
}
545
546
/// An API call; a refusal becomes an error that says why.
54725×
pub async fn call(c: &spectra_mcp::client::Client, method: &str, path: &str, body: Option<serde_json::Value>) -> Result<serde_json::Value> {
54825×
    let r = c.send(method, path, &[], body.map(|b| serde_json::to_vec(&b)).transpose()?.unwrap_or_default()).await?;
54925×
    let v: serde_json::Value = r.json().unwrap_or(serde_json::Value::Null);
55025×
    if r.status >= 400 {
5510×
        let why = v
5520×
            .get("detail")
5530×
            .or(v.get("title"))
5540×
            .and_then(serde_json::Value::as_str)
5550×
            .map(String::from)
5560×
            .unwrap_or_else(|| String::from_utf8_lossy(&r.body).into());
5570×
        bail!("{why}");
55825×
    }
55925×
    Ok(v)
56025×
}
561
562
/// A query string value, percent-encoded.
5634×
pub fn encode(s: &str) -> String {
5644×
    s.bytes()
56526×
        .map(|b| match b {
56626×
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
5670×
            _ => format!("%{b:02X}"),
56826×
        })
5694×
        .collect()
5704×
}
571
57222×
fn init_logging() {
57322×
    let filter = tracing_subscriber::EnvFilter::try_from_env("SPECTRA_LOG").unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
57422×
    tracing_subscriber::fmt().with_env_filter(filter).with_writer(std::io::stderr).init();
57522×
}
576
5770×
fn default_data() -> PathBuf {
5780×
    if let Ok(x) = std::env::var("XDG_DATA_HOME") {
5790×
        return PathBuf::from(x).join("spectra");
5800×
    }
5810×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
5820×
    PathBuf::from(home).join(".local").join("share").join("spectra")
5830×
}
584
585190×
fn runtime() -> Result<tokio::runtime::Runtime> {
586190×
    Ok(tokio::runtime::Builder::new_multi_thread().enable_all().build()?)
587190×
}
588
589191×
pub fn run() -> Result<i32> {
590191×
    let cli = Cli::parse();
591191×
    ui::init(cli.plain);
592191×
    let ctx = Ctx { data: cli.data.unwrap_or_else(default_data) };
59330×
    match cli.command {
5941×
        Command::Version { json } => version(json),
5952×
        Command::Status { json } => runtime()?.block_on(setup::status(&ctx, json)),
5961×
        Command::Probe { url, json } => runtime()?.block_on(setup::probe(&url, json)),
5971×
        Command::Bridge { port, owner_home } => runtime()?.block_on(setup::bridge(&ctx, port, owner_home)),
5988×
        Command::Brief { command } => runtime()?.block_on(async {
5998×
            match command {
6002×
                BriefCmd::Show { project, json } => brief::show(&ctx, project, json).await,
6016×
                BriefCmd::Set { project, text, file, owner_home } => {
6026×
                    brief::set(&ctx, project, brief::text_of(text, file)?, owner_home).await
603
                }
6040×
                BriefCmd::Edit { project, owner_home } => brief::edit(&ctx, project, owner_home).await,
605
            }
6068×
        }),
6078×
        Command::Connect { url, owner_home, expect, yes } => runtime()?.block_on(connect::connect(&ctx, &url, owner_home, expect, yes)),
6086×
        Command::Init { owner_home, name, owner: Some(key) } => {
6096×
            let _ = owner_home;
6106×
            runtime()?.block_on(identity::init_for(&ctx, &key, name))
611
        }
61224×
        Command::Init { owner_home, name, owner: None } => runtime()?.block_on(identity::init(&ctx, owner_home, name)),
6135×
        Command::Identity { command } => runtime()?.block_on(async {
6145×
            match command {
6153×
                IdentityCmd::Create { name, contact, home, json } => identity::create(&name, &contact, home, json),
6162×
                IdentityCmd::Show { json } => identity::show(&ctx, json).await,
6170×
                IdentityCmd::Refresh { owner_home } => identity::refresh(&ctx, owner_home).await,
618
            }
6195×
        }),
62022×
        Command::Serve { bind, tls, insecure, open } => {
62122×
            init_logging();
62222×
            runtime()?.block_on(serve::serve(&ctx, bind, tls, insecure, open))
623
        }
6241×
        Command::Open { owner_home, no_browser, port, page } => runtime()?.block_on(async {
6251×
            if ctx.remote()?.is_some() {
6260×
                open::open_remote(&ctx, owner_home, !no_browser, port, page.as_deref()).await
627
            } else {
6281×
                open::open(&ctx, owner_home, !no_browser, page.as_deref()).await
629
            }
6301×
        }),
6312×
        Command::Mcp { agent, home } => runtime()?.block_on(mcp::run(&ctx, &agent, home)),
6323×
        Command::Say { body, channel, reply_to, json, owner_home } => {
6333×
            runtime()?.block_on(human::say(&ctx, channel, reply_to, body, owner_home, json))
634
        }
6352×
        Command::Inbox { follow, json, owner_home } => runtime()?.block_on(human::inbox(&ctx, follow, owner_home, json)),
6363×
        Command::Search { query, channel, author, since, limit, json } => {
6373×
            runtime()?.block_on(human::search(&ctx, &query, channel, author, since, limit, json))
638
        }
6392×
        Command::Api { method, path, body, owner_home } => runtime()?.block_on(human::raw(&ctx, &method, &path, body, owner_home)),
64033×
        Command::Project { command } => runtime()?.block_on(async {
64133×
            match command {
64226×
                ProjectCmd::Add { target, name, path, description, url, owner_home } => {
64326×
                    project::add(&ctx, project::Add { target, name, path, description, url }, owner_home).await
644
                }
6453×
                ProjectCmd::Link { project, depends_on, remove, owner_home } => {
6463×
                    project::link(&ctx, &project, &depends_on, remove, owner_home).await
647
                }
6484×
                ProjectCmd::List { json } => project::list(&ctx, json).await,
649
            }
65033×
        }),
65136×
        Command::Agent { command } => runtime()?.block_on(async {
65236×
            match command {
65326×
                AgentCmd::Add { name, kind, project, home, uid, learn_uid, expires, yes, owner_home } => {
65426×
                    agent::add(&ctx, agent::Add { name, kind, project, home, uid, learn_uid, expires, yes, owner_home }).await
655
                }
6561×
                AgentCmd::Renew { name, expires, owner_home } => agent::renew(&ctx, &name, &expires, owner_home).await,
6576×
                AgentCmd::List { json } => agent::list(&ctx, json).await,
6583×
                AgentCmd::Disable { name, owner_home } => agent::disable(&ctx, &name, owner_home).await,
659
            }
66036×
        }),
66131×
        Command::Admin { command } => runtime()?.block_on(async {
66231×
            match command {
66322×
                Admin::Verify { json } => admin::verify(&ctx, json).await,
6646×
                Admin::Check => admin::check(&ctx).await,
6653×
                Admin::Rebuild => admin::rebuild(&ctx).await,
666
            }
66731×
        }),
668
    }
669191×
}
670
6711×
fn version(as_json: bool) -> Result<i32> {
6721×
    if as_json {
6731×
        println!(
6741×
            "{}",
6751×
            serde_json::json!({
6761×
                "version": env!("CARGO_PKG_VERSION"),
6771×
                "build": env!("SPECTRA_BUILD_ID"),
6781×
                "mcp_protocol_versions": spectra_mcp::PROTOCOL_VERSIONS,
6791×
                "ledger_format": spectra_core::LEDGER_FORMAT,
6801×
            })
6811×
        );
6821×
    } else {
6830×
        println!("spectra {}", env!("SPECTRA_VERSION_LONG"));
6840×
    }
6851×
    Ok(0)
6861×
}