digital-roster 0.3.2

Rent the intelligence, own the governance — a control plane for workers: software colleagues whose every action passes through a gateway you control (default-deny egress, injected credentials, budgets, approval gates, audit).
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
//! Roster — the trusted host-side control plane, one binary (D20: the language
//! boundary is the trust boundary; TS lives only in the box). The command
//! grammar is the product thesis — rented intelligence, owned governance:
//!
//!   roster server …       the owned machinery: daemon, config, desk, run log
//!   roster connection …   the org's relationships with external services
//!   roster worker …       the governed identities: lifecycle, trust, work, sessions
//!   roster channel …      the conversations the workers serve: trust, settings

mod action;
mod channel;
mod cli;
mod config;
mod credential;
mod gateway;
mod paths;
mod run;
mod statefile;
mod util;
mod work;
mod worker;

use clap::{Parser, Subcommand};

const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", env!("ROSTER_BUILD"), ")");

#[derive(Parser)]
#[command(
    name = "roster",
    version = VERSION,
    about = "roster — digital workers with owned governance",
    after_help = "quickstart: roster talk   (first run: creates a worker and opens a chat)"
)]
struct Cli {
    #[command(subcommand)]
    command: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Initialize the deployment: config, data, and state roots (XDG)
    Init,
    /// The owned machinery: daemon, config, approval desk, run log (bare: status)
    #[command(
        after_help = "glossary: a box is the sandboxed container one session runs in; a gate is a \
                      proposed action awaiting your approval; a grant is an egress rule in org.toml; \
                      an exposure is a credential env var a grant injects; a listener connects a \
                      worker to a chat platform; the heartbeat is the built-in recurring task that \
                      keeps each worker checking its queue"
    )]
    Server {
        #[command(subcommand)]
        cmd: Option<ServerCmd>,
    },
    /// Connections to external services: catalog, add, inspect, remove (bare: ls)
    Connection {
        #[command(subcommand)]
        cmd: Option<ConnectionCmd>,
    },
    #[command(subcommand, hide = true)]
    Credential(CredentialCmd),
    /// The governed identities: lifecycle, trust, work (bare: ls)
    #[command(
        after_help = "glossary: standing marks whose work a task is (owner: always runs; proactive: \
                      paced by budgets); a box is the sandboxed container one session runs in; a \
                      gate is a proposed action awaiting your approval; the store is the worker's \
                      durable directory; a gated repo lands changes through a validated push"
    )]
    Worker {
        #[command(subcommand)]
        cmd: Option<WorkerCmd>,
    },
    /// Conversations the workers serve: trust designation, response mode (bare: ls)
    #[command(
        after_help = "glossary: a surface is a platform-native place the worker exists — a Discord \
                      channel, a Slack DM, your terminal; a channel is the conversation roster \
                      keeps for it: history, purpose, trust, settings. Trusting a channel lets its \
                      participants administer (approve gates, edit purpose) and sends replies \
                      without gating"
    )]
    Channel {
        #[command(subcommand)]
        cmd: Option<ChannelCmd>,
    },
    /// Talk with a worker right here in the terminal — a trusted chat channel
    Talk {
        /// The worker to talk to (omit: list workers, or create "elf" on first run)
        name: Option<String>,
        /// Wind a quiet session down after this many seconds (the
        /// conversation stays open; your next message wakes a fresh one)
        #[arg(long, default_value_t = 300)]
        idle: u64,
    },
    /// Generate shell completions (bash, zsh, fish, …) to stdout
    Completions {
        /// The shell to generate for
        shell: clap_complete::Shell,
    },
}

#[derive(Subcommand)]
enum ServerCmd {
    /// Run the daemon in the foreground: gateway, task dispatch, channel listeners
    #[command(alias = "run")]
    Start {
        /// Max concurrent boxes
        #[arg(long, default_value_t = 3)]
        cap: usize,
        /// Skip channel listeners (dev: never double-connect a bot)
        #[arg(long)]
        no_listen: bool,
        /// Fire due triggers, drain due tasks, then exit
        #[arg(long)]
        once: bool,
        /// Gateway listen address (default: loopback + the docker bridge;
        /// pass 0.0.0.0:7300 to listen on every interface)
        #[arg(long)]
        addr: Option<String>,
    },
    /// Daemon health: components, queue, gates, compiled config
    Status {
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// Parse and check all config; print every error (config loads live)
    #[command(alias = "deploy")]
    Validate,
    /// The approval desk: what is pending your approval; inspect, approve, deny (bare: ls)
    #[command(alias = "gates")]
    Approvals {
        #[command(subcommand)]
        cmd: Option<ApprovalsCmd>,
    },
    /// The pre-promotion spelling of `roster channel` — same commands
    #[command(hide = true)]
    Channel {
        #[command(subcommand)]
        cmd: Option<ChannelCmd>,
    },
    /// The run log: every session, whoever it was attributed to (bare: ls)
    Runs {
        #[command(subcommand)]
        cmd: Option<RunsCmd>,
    },
}

#[derive(Subcommand)]
enum ApprovalsCmd {
    /// What is pending your approval
    Ls {
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// The exact action that would execute (charter/code gates show a diff)
    Show {
        /// Gate id (any unique prefix)
        id: String,
    },
    /// Approve and execute the gated action idempotently
    Approve {
        /// Gate id (any unique prefix)
        id: String,
        /// Note recorded with the decision
        note: Option<String>,
    },
    /// Record the refusal
    Deny {
        /// Gate id (any unique prefix)
        id: String,
        /// Note recorded with the decision
        note: Option<String>,
    },
}

#[derive(Subcommand)]
enum ChannelCmd {
    /// All configured channels
    Ls {
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// One channel's settings, readable
    Show {
        /// Channel id (see: roster channel ls)
        channel_id: String,
    },
    /// Trust a channel: its participants may administer; replies need no gate
    Trust {
        /// Channel id (see: roster channel ls)
        channel_id: String,
    },
    /// Untrust a channel: participants are content-only
    Untrust {
        /// Channel id (see: roster channel ls)
        channel_id: String,
    },
    /// Tune a setting (just the id: list keys, allowed values, current values)
    Set {
        /// Channel id (see: roster channel ls)
        channel_id: String,
        /// A settings key (omit to list them all)
        key: Option<String>,
        /// The new value (omit to list keys and values)
        value: Option<String>,
    },
    /// Link surfaces into one conversation: shared history, purpose, trust,
    /// store. v1 links 1:1 surfaces only (DMs, your terminal)
    Link {
        /// A name for the linked channel (or an existing linked channel to extend)
        name: String,
        /// Surface ids to link (see: roster channel ls)
        #[arg(required = true)]
        surfaces: Vec<String>,
    },
    /// Remove a surface from its linked channel — the channel and its
    /// material stay with the remaining members; nothing is un-shared
    Unlink {
        /// The surface id to unlink
        surface_id: String,
    },
    /// Delete a channel: drop its settings, archive its history and stores
    Rm {
        /// Channel id (see: roster channel ls)
        channel_id: String,
        /// Skip the confirmation prompt
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum ConnectionCmd {
    /// List services available to connect, grouped by what connecting gives you
    Catalog,
    /// Connect a service (bare: guided session — pick from the catalog or declare)
    Add {
        /// Service from the connection catalog (omit for the guided session)
        #[arg(value_name = "SERVICE")]
        service: Option<String>,
        /// Also grant to this worker (repeatable); omit to connect without granting
        #[arg(long)]
        worker: Vec<String>,
        /// Org-wide: every current and future worker (the explicit escalation)
        #[arg(long)]
        org: bool,
        /// Connection and secret name when it differs from the service
        #[arg(long)]
        name: Option<String>,
        /// Allowed hostname (repeatable; required for services outside the catalog)
        #[arg(long)]
        host: Vec<String>,
        /// Header template, for example: "Authorization: Bearer {token}"
        #[arg(long)]
        header: Option<String>,
        /// Environment variable exposed to the worker (default: <NAME>_TOKEN)
        #[arg(long)]
        env: Option<String>,
        /// Allowed HTTP method (repeatable; default: GET)
        #[arg(long)]
        method: Vec<String>,
        /// Which use(s) to set up on a multi-use provider (channel, capability)
        #[arg(long = "use", value_name = "USE")]
        uses: Vec<String>,
        /// Auth method when the provider offers several (api_key, oauth)
        #[arg(long)]
        auth: Option<String>,
        /// Interview for an unknown service; OAuth knowledge lands in providers.toml
        #[arg(long)]
        declare: bool,
        /// Test the stored credential against the live service before finishing
        #[arg(long)]
        verify: bool,
    },
    /// Make a connection available to a worker (the restriction rides on the edge)
    Grant {
        /// Connection name (see: roster connection ls)
        name: String,
        /// Worker to grant to (or --org for the fleet-wide edge)
        #[arg(value_name = "WORKER")]
        worker: Option<String>,
        /// Fleet-wide edge: every current and future worker
        #[arg(long)]
        org: bool,
        /// Scope this edge to provider dimensions, e.g. servers=111,222 or
        /// surfaces=public,dm — ids and classes mix; naming classes is
        /// exhaustive, so surfaces=public means no DMs (repeatable)
        #[arg(long, value_name = "DIM=IDS")]
        restrict: Vec<String>,
    },
    /// Withdraw a worker's edge on a connection (the connection stays)
    Revoke {
        /// Connection name (see: roster connection ls)
        name: String,
        /// Worker whose edge to withdraw (or --org for the fleet-wide edge)
        #[arg(value_name = "WORKER")]
        worker: Option<String>,
        /// The fleet-wide edge
        #[arg(long)]
        org: bool,
    },
    /// Every connection, its use(s) — capability, channel, model — and state
    Ls {
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// Delete the secret and, on confirm, the connection file with its edges
    Rm {
        /// Connection name (see: roster connection ls)
        name: String,
    },
}

/// Retired: the one noun is `connection` (docs/connections.md). Each
/// arm points at its replacement and exits nonzero.
#[derive(Subcommand)]
enum CredentialCmd {
    #[command(hide = true)]
    Add { provider: String },
    #[command(hide = true)]
    Ls {
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum WorkerCmd {
    /// Scaffold a worker: spec, identity, knowledge repo
    #[command(alias = "init")]
    Add {
        /// The new worker's name (lowercase letters/numbers/hyphens)
        name: String,
    },
    /// List workers and their state
    Ls {
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// One worker: spec, budgets and spend, queue, gates, store
    Show {
        /// The worker's name
        name: String,
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// Per-action trust: grants, earned history, promotion rules
    Trust {
        /// The worker's name
        name: String,
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// One governed session, now, bypassing the queue
    Run {
        /// The worker to run
        name: String,
        /// Wall-clock ceiling in minutes
        #[arg(long, default_value_t = 30.0)]
        ceiling: f64,
        /// The prompt (bare words are joined)
        #[arg(required = true, value_name = "PROMPT")]
        prompt: Vec<String>,
    },
    /// Retire a worker: archive its spec, store, and history (never deletes)
    Rm {
        /// The worker to retire
        name: String,
        /// Skip the typed-name confirmation
        #[arg(long)]
        yes: bool,
    },
    /// Scripted stdin session, one message per turn (conversations: roster talk)
    Chat {
        /// The worker to chat with
        name: String,
        /// End after this much quiet, in seconds
        #[arg(long, default_value_t = 20)]
        idle: u64,
    },
    /// Its durable work: add, relay, ls, show, requeue (bare: ls)
    Task {
        #[command(subcommand)]
        cmd: Option<TaskCmd>,
    },
    /// Print the knowledge repo path (then use git)
    Knowledge {
        /// The worker's name
        name: String,
    },
    /// Restore the worker's store from a snapshot (default: the newest)
    Restore {
        /// The worker's name
        name: String,
        /// Snapshot name (see --list); omit for the newest
        #[arg(long)]
        from: Option<String>,
        /// Restore only this conversation's channel store
        #[arg(long)]
        channel: Option<String>,
        /// List available snapshots and exit
        #[arg(long)]
        list: bool,
    },
}

#[derive(Subcommand)]
enum TaskCmd {
    /// File a task for a worker
    Add {
        /// The worker to file it for
        worker: String,
        /// Wall-clock ceiling in minutes
        #[arg(long, default_value_t = 30.0)]
        ceiling: f64,
        /// File as proactive: waits out spent budget windows (owner-filed work always runs)
        #[arg(long)]
        proactive: bool,
        /// The prompt (bare words are joined)
        #[arg(required = true, value_name = "PROMPT")]
        prompt: Vec<String>,
    },
    /// File an inbound message as a task (framed as untrusted content)
    Relay {
        /// The worker to relay it to
        worker: String,
        /// Sender label recorded with the task
        #[arg(long)]
        from: Option<String>,
        /// The message (bare words are joined)
        #[arg(required = true, value_name = "MESSAGE")]
        message: Vec<String>,
    },
    /// List tasks — queued, recurring, and recent outcomes
    Ls {
        /// Only this worker's tasks (omit for all workers)
        worker: Option<String>,
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// Inspect a task: state, gates, journal, prompt
    Show {
        /// Task id (any unique prefix; journaled tasks need the exact id)
        id: String,
    },
    /// Put a stuck, failed, or finished task back to waiting
    Requeue {
        /// Task id (any unique prefix; journaled tasks need the exact id)
        id: String,
    },
}

#[derive(Subcommand)]
enum RunsCmd {
    /// List past sessions, whoever they were attributed to
    Ls {
        /// Only sessions attributed to this worker
        #[arg(long)]
        worker: Option<String>,
        /// Show at most this many
        #[arg(long, default_value_t = 20)]
        limit: usize,
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// One session: transcript, journal, knowledge commits, files
    Show {
        /// Run id (any unique prefix)
        run: String,
    },
    /// The exact compiled prompts a session saw
    Context {
        /// Run id (any unique prefix)
        run: String,
        /// Every turn, not just the last
        #[arg(long)]
        all: bool,
    },
}

#[tokio::main]
async fn main() {
    // Die quietly on a closed pipe (`roster … | head`) instead of panicking:
    // Rust ignores SIGPIPE by default, turning EPIPE into a println panic.
    //
    // NEVER for the daemon. `server start` writes into box stdin pipes and
    // reads box stdout; a box dying mid-turn makes EPIPE routine, and with
    // SIG_DFL the whole daemon dies of SIGPIPE — which systemd counts as a
    // CLEAN exit, so even Restart=on-failure won't bring it back. The
    // daemon keeps Rust's default (EPIPE as an io::Error the session loop
    // already handles); the CLI keeps the quiet-pipe behavior.
    #[cfg(unix)]
    {
        let is_daemon = matches!(
            (
                std::env::args().nth(1).as_deref(),
                std::env::args().nth(2).as_deref()
            ),
            (Some("server"), Some("start" | "run"))
        );
        if !is_daemon {
            unsafe {
                libc::signal(libc::SIGPIPE, libc::SIG_DFL);
            }
        }
    }

    // Old top-level commands point at their new home instead of half-working:
    // the argument shapes changed (positional workers, merged daemons), so a
    // silent translation could misparse. One clear error, one clear fix.
    if let Some(first) = std::env::args().nth(1) {
        if let Some(new_home) = legacy_pointer(&first) {
            eprintln!("roster: `roster {first}` has moved — use: {new_home}");
            std::process::exit(2);
        }
    }

    let cli = Cli::parse();
    // No first-run ceremony: the deployment roots and a starter org.toml
    // exist by the time any command needs them (idempotent, quiet). The
    // explicit `roster init` narrates its own work instead — pre-creating
    // here would make it report "kept" for files it just wrote.
    if !matches!(cli.command, Cmd::Init) {
        if let Err(e) = cli::init::ensure() {
            eprintln!("roster: could not initialize the deployment roots: {e}");
            std::process::exit(1);
        }
    }
    let result: Result<(), Box<dyn std::error::Error>> = match cli.command {
        Cmd::Init => cli::init::run(),
        Cmd::Server { cmd } => match cmd {
            None => cli::server::status(false).await,
            Some(ServerCmd::Start {
                cap,
                no_listen,
                once,
                addr,
            }) => cli::server::run(cap, once, no_listen, addr.as_deref()).await,
            Some(ServerCmd::Status { json }) => cli::server::status(json).await,
            Some(ServerCmd::Validate) => cli::server::validate(),
            Some(ServerCmd::Approvals { cmd }) => match cmd {
                None => cli::approvals::ls(false),
                Some(ApprovalsCmd::Ls { json }) => cli::approvals::ls(json),
                Some(ApprovalsCmd::Show { id }) => cli::approvals::show(&id),
                Some(ApprovalsCmd::Approve { id, note }) => {
                    cli::approvals::approve(&id, note.as_deref()).await
                }
                Some(ApprovalsCmd::Deny { id, note }) => cli::approvals::deny(&id, note.as_deref()),
            },
            Some(ServerCmd::Channel { cmd }) => run_channel_cmd(cmd),
            Some(ServerCmd::Runs { cmd }) => match cmd {
                None => cli::runs::ls(None, 20, false),
                Some(RunsCmd::Ls {
                    worker,
                    limit,
                    json,
                }) => cli::runs::ls(worker.as_deref(), limit, json),
                Some(RunsCmd::Show { run }) => cli::runs::show(&run),
                Some(RunsCmd::Context { run, all }) => cli::runs::context(&run, all),
            },
        },
        Cmd::Connection { cmd } => match cmd {
            None => cli::connections::ls(false),
            Some(ConnectionCmd::Catalog) => cli::connections::catalog(),
            Some(ConnectionCmd::Add {
                service,
                worker,
                org,
                name,
                host,
                header,
                env,
                method,
                uses,
                auth,
                declare,
                verify,
            }) => match service {
                Some(service) => {
                    cli::connections::connect(
                        service,
                        cli::connections::ConnectOptions {
                            workers: worker,
                            org,
                            alias: name,
                            hosts: host,
                            header,
                            env,
                            methods: method,
                            uses,
                            auth,
                            declare,
                            verify,
                        },
                    )
                    .await
                }
                None if org
                    || !worker.is_empty()
                    || name.is_some()
                    || !host.is_empty()
                    || header.is_some()
                    || env.is_some()
                    || !method.is_empty()
                    || !uses.is_empty()
                    || auth.is_some() =>
                {
                    Err("connection options require a service name".into())
                }
                None => cli::connections::guided().await,
            },
            Some(ConnectionCmd::Grant {
                name,
                worker,
                org,
                restrict,
            }) => cli::connections::grant(&name, worker, org, &restrict),
            Some(ConnectionCmd::Revoke { name, worker, org }) => {
                cli::connections::revoke(&name, worker, org)
            }
            Some(ConnectionCmd::Ls { json }) => cli::connections::ls(json),
            Some(ConnectionCmd::Rm { name }) => cli::connections::rm(&name),
        },
        Cmd::Credential(cmd) => match cmd {
            CredentialCmd::Add { provider } => Err(format!(
                "`roster credential add` has retired — run: roster connection add {provider}"
            )
            .into()),
            CredentialCmd::Ls { .. } => {
                Err("`roster credential ls` has retired — run: roster connection ls".into())
            }
        },
        Cmd::Channel { cmd } => run_channel_cmd(cmd),
        Cmd::Talk { name, idle } => match name {
            Some(name) => run::session::talk(&name, idle).await,
            None => talk_bare(idle).await,
        },
        Cmd::Completions { shell } => {
            use clap::CommandFactory;
            clap_complete::generate(shell, &mut Cli::command(), "roster", &mut std::io::stdout());
            Ok(())
        }
        Cmd::Worker { cmd } => match cmd {
            None => cli::worker::ls(false),
            Some(WorkerCmd::Add { name }) => cli::create::run(&name),
            Some(WorkerCmd::Ls { json }) => cli::worker::ls(json),
            Some(WorkerCmd::Show { name, json }) => cli::worker::show(&name, json),
            Some(WorkerCmd::Trust { name, json }) => cli::worker::trust(&name, json),
            Some(WorkerCmd::Run {
                name,
                ceiling,
                prompt,
            }) => run::boxed::run_once(&name, ceiling, prompt.join(" ")).await,
            Some(WorkerCmd::Rm { name, yes }) => cli::worker::rm(&name, yes),
            Some(WorkerCmd::Chat { name, idle }) => run::session::chat(&name, idle).await,
            Some(WorkerCmd::Task { cmd }) => match cmd {
                None => cli::task::ls(None, false),
                Some(TaskCmd::Add {
                    worker,
                    ceiling,
                    proactive,
                    prompt,
                }) => cli::task::add(&worker, ceiling, proactive, prompt.join(" ")),
                Some(TaskCmd::Relay {
                    worker,
                    from,
                    message,
                }) => channel::relay::run(&worker, from.as_deref(), message.join(" ")),
                Some(TaskCmd::Ls { worker, json }) => cli::task::ls(worker.as_deref(), json),
                Some(TaskCmd::Show { id }) => cli::task::show(&id),
                Some(TaskCmd::Requeue { id }) => cli::task::requeue(&id),
            },
            Some(WorkerCmd::Knowledge { name }) => cli::knowledge::run(&name),
            Some(WorkerCmd::Restore {
                name,
                from,
                channel,
                list,
            }) => cli::worker::restore(&name, from.as_deref(), channel.as_deref(), list),
        },
    };

    if let Err(e) = result {
        eprintln!("roster: {e}");
        std::process::exit(1);
    }
}

/// `roster talk` with no worker named: on a fresh deployment scaffold "elf"
/// and start talking — the zero-config first conversation. Otherwise show the
/// talk help and who is available.
/// One handler for both spellings: `roster channel …` (the noun's home) and
/// `roster server channel …` (the pre-promotion path, kept as an alias).
fn run_channel_cmd(cmd: Option<ChannelCmd>) -> Result<(), Box<dyn std::error::Error>> {
    match cmd {
        None => cli::channel::ls(false),
        Some(ChannelCmd::Ls { json }) => cli::channel::ls(json),
        Some(ChannelCmd::Show { channel_id }) => cli::channel::show(&channel_id),
        Some(ChannelCmd::Trust { channel_id }) => cli::channel::set_trust(&channel_id, true),
        Some(ChannelCmd::Untrust { channel_id }) => cli::channel::set_trust(&channel_id, false),
        Some(ChannelCmd::Set {
            channel_id,
            key,
            value,
        }) => match (key, value) {
            (Some(key), Some(value)) => cli::channel::set(&channel_id, &key, &value),
            _ => cli::channel::set_help(&channel_id),
        },
        Some(ChannelCmd::Link { name, surfaces }) => cli::channel::link(&name, &surfaces),
        Some(ChannelCmd::Unlink { surface_id }) => cli::channel::unlink(&surface_id),
        Some(ChannelCmd::Rm { channel_id, yes }) => cli::channel::rm(&channel_id, yes),
    }
}

async fn talk_bare(idle: u64) -> Result<(), Box<dyn std::error::Error>> {
    let workers = worker::names();
    if workers.is_empty() {
        eprintln!("no workers yet — creating one named \"elf\"");
        cli::create::run("elf")?;
        return run::session::talk("elf", idle).await;
    }
    use clap::CommandFactory;
    Cli::command()
        .find_subcommand("talk")
        .expect("talk subcommand exists")
        .clone()
        .bin_name("roster talk")
        .print_help()?;
    println!("\nworkers:");
    for name in workers {
        println!("  {name}");
    }
    Ok(())
}

/// Where each pre-clap command lives now. Kept until the muscle memory fades.
fn legacy_pointer(first: &str) -> Option<&'static str> {
    Some(match first {
        "imp" => "roster worker <add|ls|show|trust|run|chat|task|knowledge>  (imps are now workers)",
        "serve" => "roster server start",
        "supervise" => "roster server start  (the daemons merged; --cap and --once moved there)",
        "listen" => "roster server start  (listeners start for every worker with a [channels] entry)",
        "deploy" => "roster server validate  (config now loads live — there is no deploy step)",
        "gates" => "roster server approvals <ls|show|approve|deny>",
        "connect" => "roster connection add <provider>",
        "create" => "roster worker add <name>",
        "queue" => "roster worker task <add|relay|ls|show|requeue>",
        "relay" => "roster worker task relay <worker> \"<message>\"",
        "knowledge" => "roster worker knowledge <name>",
        "box" => "roster worker run <name> \"<prompt>\"",
        "session" => "roster worker chat <name>",
        "runs" => "roster server runs <ls|show|context|recall>",
        "agent" => {
            "roster worker <run|chat>, roster server runs  (sessions belong to workers; the log to the server)"
        }
        _ => return None,
    })
}