starweaver-cli 0.10.0

Command-line interface for Starweaver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! CLI argument parsing.

use std::{ffi::OsString, path::PathBuf};

use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::Shell;
use serde::{Deserialize, Serialize};

use crate::{CliError, CliResult};

/// Top-level CLI.
#[derive(Clone, Debug, Parser)]
#[command(name = "starweaver-cli", version, about = "Starweaver local CLI")]
pub struct Cli {
    /// Prompt shorthand for headless runs.
    #[arg(short = 'p', long = "prompt", global = false)]
    pub prompt: Option<String>,
    /// Append a run to the selected session.
    #[arg(
        short = 's',
        long,
        global = false,
        conflicts_with_all = ["new_session", "continue_session"]
    )]
    pub session: Option<String>,
    /// Continue the latest local session.
    #[arg(long = "continue", global = false, conflicts_with = "new_session")]
    pub continue_session: bool,
    /// Create a fresh session.
    #[arg(long, global = false)]
    pub new_session: bool,
    /// Restore from a specific run before appending a run.
    #[arg(long, global = false)]
    pub run: Option<String>,
    /// Branch from a specific run before appending a run.
    #[arg(long, global = false, conflicts_with = "run")]
    pub branch_from: Option<String>,
    /// Agent profile name or YAML path.
    #[arg(long, global = false)]
    pub profile: Option<String>,
    /// Agent materialization semantics for a restored run.
    #[arg(long, global = false, default_value = "preserve")]
    pub continuation_mode: ContinuationModeArg,
    /// Enable worker mode or set an optional worker label.
    #[arg(long, global = false, num_args = 0..=1, default_missing_value = "true")]
    pub worker: Option<String>,
    /// Explicit worker label.
    #[arg(long = "worker-label", global = false)]
    pub worker_label: Option<String>,
    /// Enable a git worktree or set an optional worktree name/path.
    #[arg(
        short = 'w',
        long,
        global = false,
        num_args = 0..=1,
        default_missing_value = "true"
    )]
    pub worktree: Option<String>,
    /// Explicit worktree name/path.
    #[arg(long = "worktree-name", global = false)]
    pub worktree_name: Option<String>,
    /// Git branch for worktree metadata.
    #[arg(long, global = false)]
    pub branch: Option<String>,
    /// Output mode.
    #[arg(long, global = false)]
    pub output: Option<OutputMode>,
    /// Headless human-in-the-loop policy for prompt shorthand.
    #[arg(long, global = false)]
    pub hitl: Option<HitlPolicy>,
    /// Override local store database path.
    #[arg(long, global = true)]
    pub store: Option<String>,
    /// Optional subcommand.
    #[command(subcommand)]
    pub command: Option<CliCommand>,
}

/// CLI command families.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, Subcommand)]
pub enum CliCommand {
    /// Print SDK identity.
    Version,
    /// Run a prompt.
    Run(RunCommand),
    /// Manage local sessions.
    Session {
        /// Session subcommand.
        #[command(subcommand)]
        command: SessionCommand,
    },
    /// Manage canonical storage migrations and imports.
    Storage {
        /// Storage subcommand.
        #[command(subcommand)]
        command: StorageCommand,
    },
    /// Manage agent profiles.
    Profile {
        /// Profile subcommand.
        #[command(subcommand)]
        command: ProfileCommand,
    },
    /// Initialize local CLI configuration and catalogs.
    Setup(SetupCommand),
    /// Inspect OAuth-backed provider authentication.
    Auth {
        /// Auth subcommand.
        #[command(subcommand)]
        command: AuthCommand,
    },
    /// Inspect configured skills.
    Skill {
        /// Skill subcommand.
        #[command(subcommand)]
        command: CatalogCommand,
    },
    /// Inspect configured subagents.
    Subagent {
        /// Subagent subcommand.
        #[command(subcommand)]
        command: CatalogCommand,
    },
    /// Inspect configured MCP servers.
    Mcp {
        /// MCP subcommand.
        #[command(subcommand)]
        command: CatalogCommand,
    },
    /// Inspect default CLI tool catalog and policy.
    Tools {
        /// Tools subcommand.
        #[command(subcommand)]
        command: ToolsCommand,
    },
    /// Render a retained terminal UI from local session display messages.
    Tui(TuiCommand),
    /// Manage persisted approval requests.
    Approval {
        /// Approval subcommand.
        #[command(subcommand)]
        command: ApprovalCommand,
    },
    /// Manage deferred tool calls.
    Deferred {
        /// Deferred subcommand.
        #[command(subcommand)]
        command: DeferredCommand,
    },
    /// Resume a waiting session by appending a continuation run.
    Resume(ResumeCommand),
    /// Remove runtime session state while preserving configuration.
    Reset(ResetCommand),
    /// Print diagnostics.
    Diagnostics,
    /// Print replay-check guidance.
    ReplayCheck,
    /// Update installed Starweaver components.
    Update(UpdateCommand),
    /// Get or set configuration values.
    Config {
        /// Config subcommand.
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Generate shell completion scripts.
    Completion {
        /// Target shell.
        shell: Shell,
    },
}

/// Prompt run command.
#[derive(Clone, Debug, Args)]
pub struct RunCommand {
    /// Prompt text.
    #[arg(short = 'p', long = "prompt")]
    pub prompt: Option<String>,
    /// Positional prompt text.
    pub prompt_parts: Vec<String>,
    /// Append a run to the selected session.
    #[arg(short = 's', conflicts_with_all = ["new_session", "continue_session"], long)]
    pub session: Option<String>,
    /// Continue the latest local session.
    #[arg(long = "continue", conflicts_with = "new_session")]
    pub continue_session: bool,
    /// Create a fresh session.
    #[arg(long)]
    pub new_session: bool,
    /// Restore from a specific run before appending a run.
    #[arg(long)]
    pub run: Option<String>,
    /// Branch from a specific run before appending a run.
    #[arg(long, conflicts_with = "run")]
    pub branch_from: Option<String>,
    /// Agent profile name or YAML path.
    #[arg(long)]
    pub profile: Option<String>,
    /// Agent materialization semantics for a restored run.
    #[arg(long, default_value = "preserve")]
    pub continuation_mode: ContinuationModeArg,
    /// Enable worker mode or set an optional worker label.
    #[arg(long, num_args = 0..=1, default_missing_value = "true")]
    pub worker: Option<String>,
    /// Explicit worker label.
    #[arg(long = "worker-label")]
    pub worker_label: Option<String>,
    /// Enable a git worktree or set an optional worktree name/path.
    #[arg(short = 'w', long, num_args = 0..=1, default_missing_value = "true")]
    pub worktree: Option<String>,
    /// Explicit worktree name/path.
    #[arg(long = "worktree-name")]
    pub worktree_name: Option<String>,
    /// Git branch for worktree metadata.
    #[arg(long)]
    pub branch: Option<String>,
    /// Output mode.
    #[arg(long)]
    pub output: Option<OutputMode>,
    /// Headless human-in-the-loop policy.
    #[arg(long)]
    pub hitl: Option<HitlPolicy>,
    /// Internal runtime goal-mode options.
    #[arg(skip)]
    pub goal: Option<GoalCommandOptions>,
    /// Internal stable provider-routing affinity id.
    #[arg(skip)]
    pub session_affinity_id: Option<String>,
    /// Internal CLI environment attachments.
    #[arg(skip)]
    pub(crate) environment_attachments: Vec<crate::environment::EnvironmentAttachmentRef>,
    /// Internal marker requiring an exclusive durable HITL continuation claim.
    #[arg(skip)]
    pub hitl_resume: bool,
}

/// Internal goal-mode options attached by product surfaces such as the TUI.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoalCommandOptions {
    /// Goal objective.
    pub objective: String,
    /// Maximum runtime goal retry iterations.
    pub max_iterations: usize,
}

impl RunCommand {
    /// Return prompt text.
    pub fn prompt_text(&self) -> CliResult<String> {
        let prompt = self
            .prompt
            .clone()
            .unwrap_or_else(|| self.prompt_parts.join(" "));
        if prompt.trim().is_empty() {
            Err(CliError::Usage(
                "usage: starweaver-cli run -p <prompt>".to_string(),
            ))
        } else {
            Ok(prompt)
        }
    }
}

/// Canonical storage administration commands.
#[derive(Clone, Debug, Subcommand)]
pub enum StorageCommand {
    /// Import a legacy project-local database incrementally and idempotently.
    ImportLegacy(StorageImportLegacyCommand),
}

/// Explicit legacy project database import.
#[derive(Clone, Debug, Args)]
pub struct StorageImportLegacyCommand {
    /// Legacy `SQLite` database to import. Defaults to the current project's legacy location.
    #[arg(long)]
    pub source: Option<PathBuf>,
    /// Workspace identity assigned to imported sessions that do not already have one.
    #[arg(long)]
    pub workspace: Option<PathBuf>,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Compact session commands.
#[derive(Clone, Debug, Subcommand)]
pub enum SessionCommand {
    /// List local sessions.
    List(SessionListCommand),
    /// Search local sessions by metadata and approved text projections.
    Search(SessionSearchCommand),
    /// Show one session with recent runs.
    Show(SessionShowCommand),
    /// Replay stored display messages.
    Replay(SessionReplayCommand),
    /// Delete one local session and its retained evidence.
    Delete(SessionDeleteCommand),
    /// Trim retained run evidence.
    Trim(SessionTrimCommand),
}

/// Session list command.
#[derive(Clone, Debug, Args)]
pub struct SessionListCommand {
    /// Output mode.
    #[arg(long, default_value = "display-jsonl")]
    pub output: OutputMode,
    /// Maximum sessions to show.
    #[arg(long, default_value_t = 50)]
    pub limit: usize,
}

/// Session search command.
#[derive(Clone, Debug, Args)]
pub struct SessionSearchCommand {
    /// Optional case-insensitive literal text. Omit it to browse metadata.
    pub text: Option<String>,
    /// Exact session status.
    #[arg(long)]
    pub status: Option<SessionSearchStatusArg>,
    /// Exact profile name.
    #[arg(long)]
    pub profile: Option<String>,
    /// Exact workspace display value.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Search source; repeat to select multiple sources.
    #[arg(long = "source", value_enum)]
    pub sources: Vec<SessionSearchSourceArg>,
    /// Result grouping level.
    #[arg(long, value_enum, default_value = "session")]
    pub granularity: SessionSearchGranularityArg,
    /// Maximum hits to return.
    #[arg(long, default_value_t = 20)]
    pub limit: u32,
    /// Opaque next-page cursor.
    #[arg(long = "after")]
    pub cursor: Option<String>,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Session status accepted by search.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
#[value(rename_all = "snake_case")]
pub enum SessionSearchStatusArg {
    /// Active session.
    Active,
    /// Archived session.
    Archived,
    /// Failed session.
    Failed,
}

/// Search source accepted by the CLI.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
#[value(rename_all = "snake_case")]
pub enum SessionSearchSourceArg {
    /// Session title and approved metadata.
    SessionMetadata,
    /// Canonical text input.
    RunInput,
    /// Bounded run output preview.
    RunOutputPreview,
    /// User-visible display messages.
    #[value(alias = "display")]
    DisplayMessage,
}

/// Search grouping accepted by the CLI.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
#[value(rename_all = "snake_case")]
pub enum SessionSearchGranularityArg {
    /// One hit per session.
    Session,
    /// One hit per session/run pair.
    Run,
    /// Every stable projected occurrence.
    Occurrence,
}

/// Session show command.
#[derive(Clone, Debug, Args)]
pub struct SessionShowCommand {
    /// Session id.
    pub session_id: String,
    /// Output mode.
    #[arg(long, default_value = "display-jsonl")]
    pub output: OutputMode,
    /// Recent run limit.
    #[arg(long, default_value_t = 20)]
    pub runs: usize,
}

/// Session replay command.
#[derive(Clone, Debug, Args)]
pub struct SessionReplayCommand {
    /// Session id.
    pub session_id: String,
    /// Optional run id.
    #[arg(long)]
    pub run: Option<String>,
    /// Cursor sequence to replay after.
    #[arg(long)]
    pub after: Option<usize>,
    /// Output mode.
    #[arg(long, default_value = "display-jsonl")]
    pub output: OutputMode,
}

/// Session delete command.
#[derive(Clone, Debug, Args)]
pub struct SessionDeleteCommand {
    /// Session id or unique prefix.
    pub session_id: String,
    /// Confirm deletion.
    #[arg(long)]
    pub yes: bool,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Session trim command.
#[derive(Clone, Debug, Args)]
pub struct SessionTrimCommand {
    /// Trim current session.
    #[arg(long)]
    pub current: bool,
    /// Trim all sessions.
    #[arg(long)]
    pub all: bool,
    /// Trim a selected session.
    #[arg(long)]
    pub session: Option<String>,
    /// Retain this many recent runs per session.
    #[arg(long, default_value_t = 20)]
    pub keep_runs: usize,
    /// Trim runs older than a duration such as 7d, 24h, or 3600s.
    #[arg(long)]
    pub older_than: Option<String>,
    /// Preview trim results.
    #[arg(long)]
    pub dry_run: bool,
    /// Output mode.
    #[arg(long, default_value = "display-jsonl")]
    pub output: OutputMode,
}

/// Profile commands.
#[derive(Clone, Debug, Subcommand)]
pub enum ProfileCommand {
    /// List built-in and configured profiles.
    List,
    /// Show one built-in or configured profile.
    Show { name: String },
}

/// Setup command.
#[derive(Clone, Debug, Args)]
pub struct SetupCommand {
    /// Initialize global configuration only.
    #[arg(long, conflicts_with = "project")]
    pub global: bool,
    /// Initialize project configuration only.
    #[arg(long)]
    pub project: bool,
    /// Replace existing generated files.
    #[arg(long)]
    pub force: bool,
}

/// Auth commands.
#[derive(Clone, Debug, Subcommand)]
pub enum AuthCommand {
    /// Log in to an OAuth provider.
    Login(AuthProviderCommand),
    /// Print provider auth status.
    Status(AuthStatusCommand),
    /// Refresh provider credentials.
    Refresh(AuthProviderCommand),
    /// Remove provider credentials from the local auth store.
    Logout(AuthLogoutCommand),
    /// Inspect OAuth store health without printing tokens.
    Doctor(AuthDoctorCommand),
}

/// Provider-scoped auth command.
#[derive(Clone, Debug, Args)]
pub struct AuthProviderCommand {
    /// Provider name.
    #[arg(default_value = "codex", value_parser = ["codex"])]
    pub provider: String,
    /// Auth file path. Defaults to ~/.starweaver/auth.json.
    #[arg(long = "auth-file")]
    pub auth_file: Option<String>,
    /// Device authorization timeout in seconds.
    #[arg(long, default_value_t = 15 * 60)]
    pub timeout_seconds: u64,
}

/// Auth status command.
#[derive(Clone, Debug, Args)]
pub struct AuthStatusCommand {
    /// Provider name.
    #[arg(default_value = "codex", value_parser = ["codex"])]
    pub provider: Option<String>,
    /// Auth file path. Defaults to ~/.starweaver/auth.json.
    #[arg(long = "auth-file")]
    pub auth_file: Option<String>,
}

/// Auth logout command.
#[derive(Clone, Debug, Args)]
pub struct AuthLogoutCommand {
    /// Provider name.
    #[arg(default_value = "codex", value_parser = ["codex"])]
    pub provider: String,
    /// Auth file path. Defaults to ~/.starweaver/auth.json.
    #[arg(long = "auth-file")]
    pub auth_file: Option<String>,
    /// Revoke provider tokens before deleting local credentials.
    #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
    pub revoke: bool,
}

/// Auth doctor command.
#[derive(Clone, Debug, Args)]
pub struct AuthDoctorCommand {
    /// Auth file path. Defaults to ~/.starweaver/auth.json.
    #[arg(long = "auth-file")]
    pub auth_file: Option<String>,
}

/// Catalog inspection commands.
#[derive(Clone, Debug, Subcommand)]
pub enum CatalogCommand {
    /// List configured entries.
    List,
    /// Show one configured entry.
    Show { name: String },
    /// Validate configured entries and print findings.
    Doctor,
}

/// Tool catalog commands.
#[derive(Clone, Debug, Subcommand)]
pub enum ToolsCommand {
    /// List default first-party tools.
    List,
    /// Validate tool policy and default catalog.
    Doctor,
}

/// TUI command.
#[derive(Clone, Debug, Args)]
pub struct TuiCommand {
    /// Session id to render. Omit for a clean welcome screen.
    #[arg(long)]
    pub session: Option<String>,
    /// Optional run id to render.
    #[arg(long)]
    pub run: Option<String>,
    /// Render only messages after this display cursor.
    #[arg(long)]
    pub after: Option<usize>,
    /// Force interactive terminal UI when stdout is a TTY.
    #[arg(long)]
    pub interactive: bool,
    /// Force deterministic snapshot output for scripts and tests.
    #[arg(long, conflicts_with = "interactive")]
    pub snapshot: bool,
    /// Output mode for non-interactive TUI snapshots.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
    /// Transcript rendering mode for interactive TUI.
    #[arg(long = "render-mode")]
    pub render_mode: Option<TuiRenderMode>,
}

/// Approval commands.
#[derive(Clone, Debug, Subcommand)]
pub enum ApprovalCommand {
    /// List persisted approval records.
    List(ApprovalListCommand),
    /// Show one approval record.
    Show { approval_id: String },
    /// Approve one pending approval record.
    Approve(ApprovalDecisionCommand),
    /// Reject one pending approval record.
    Reject(ApprovalDecisionCommand),
}

/// Approval list command.
#[derive(Clone, Debug, Args)]
pub struct ApprovalListCommand {
    /// Filter by session id.
    #[arg(long)]
    pub session: Option<String>,
    /// Filter by run id.
    #[arg(long)]
    pub run: Option<String>,
    /// Output mode.
    #[arg(long, default_value = "display-jsonl")]
    pub output: OutputMode,
}

/// Approval decision command.
#[derive(Clone, Debug, Args)]
pub struct ApprovalDecisionCommand {
    /// Approval id.
    pub approval_id: String,
    /// Decision reason.
    #[arg(long)]
    pub reason: Option<String>,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Deferred tool commands.
#[derive(Clone, Debug, Subcommand)]
pub enum DeferredCommand {
    /// List persisted deferred tool records.
    List(DeferredListCommand),
    /// Show one deferred tool record.
    Show { deferred_id: String },
    /// Complete one deferred tool record with a JSON result payload.
    Complete(DeferredCompleteCommand),
    /// Fail one deferred tool record with an error message.
    Fail(DeferredFailCommand),
}

/// Deferred list command.
#[derive(Clone, Debug, Args)]
pub struct DeferredListCommand {
    /// Filter by session id.
    #[arg(long)]
    pub session: Option<String>,
    /// Filter by run id.
    #[arg(long)]
    pub run: Option<String>,
    /// Output mode.
    #[arg(long, default_value = "display-jsonl")]
    pub output: OutputMode,
}

/// Deferred complete command.
#[derive(Clone, Debug, Args)]
pub struct DeferredCompleteCommand {
    /// Deferred id.
    pub deferred_id: String,
    /// JSON result payload.
    #[arg(long)]
    pub result: String,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Deferred failure command.
#[derive(Clone, Debug, Args)]
pub struct DeferredFailCommand {
    /// Deferred id.
    pub deferred_id: String,
    /// Error message.
    #[arg(long)]
    pub error: String,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Resume command.
#[derive(Clone, Debug, Args)]
pub struct ResumeCommand {
    /// Session id to resume. Defaults to current or latest session.
    #[arg(long)]
    pub session: Option<String>,
    /// Run id to resume from. Defaults to the session active or head run.
    #[arg(long)]
    pub run: Option<String>,
    /// Prompt to append for the continuation run.
    #[arg(short = 'p', long = "prompt", default_value = "resume waiting run")]
    pub prompt: String,
    /// Output mode.
    #[arg(long)]
    pub output: Option<OutputMode>,
    /// Headless human-in-the-loop policy.
    #[arg(long)]
    pub hitl: Option<HitlPolicy>,
    /// Agent materialization semantics for the continuation.
    #[arg(long, default_value = "preserve")]
    pub continuation_mode: ContinuationModeArg,
}

/// Explicit continuation materialization mode.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum ContinuationModeArg {
    /// Require the exact source materialization fingerprint.
    #[default]
    Preserve,
    /// Permit only an `AgentSpec` revision with otherwise equivalent bindings.
    Compatible,
    /// Deliberately accept and report all materialization drift.
    Switch,
}

impl From<ContinuationModeArg> for starweaver_agent::ContinuationMaterializationMode {
    fn from(value: ContinuationModeArg) -> Self {
        match value {
            ContinuationModeArg::Preserve => Self::Preserve,
            ContinuationModeArg::Compatible => Self::Compatible,
            ContinuationModeArg::Switch => Self::Switch,
        }
    }
}

/// Reset command.
#[derive(Clone, Debug, Args)]
pub struct ResetCommand {
    /// Confirm runtime state removal.
    #[arg(long)]
    pub yes: bool,
    /// Output mode.
    #[arg(long, default_value = "text")]
    pub output: OutputMode,
}

/// Update command.
#[derive(Clone, Debug, Args)]
pub struct UpdateCommand {
    /// Update target, defaults to cli.
    #[arg(default_value = "cli")]
    pub target: String,
    /// Print the update plan without downloading or installing.
    #[arg(long)]
    pub dry_run: bool,
    /// Reinstall even when the selected release matches the current version.
    #[arg(long, short = 'f')]
    pub force: bool,
}

/// Config commands.
#[derive(Clone, Debug, Subcommand)]
pub enum ConfigCommand {
    /// Initialize a Starweaver config file.
    Init {
        /// Write the global config file.
        #[arg(long, conflicts_with = "project")]
        global: bool,
        /// Write the project config file.
        #[arg(long)]
        project: bool,
        /// Replace an existing config file.
        #[arg(long)]
        force: bool,
    },
    /// Get a resolved config value.
    Get { key: String },
    /// Set a config value.
    Set {
        /// Write the global config file.
        #[arg(long, conflicts_with = "project")]
        global: bool,
        /// Write the project config file.
        #[arg(long)]
        project: bool,
        /// Config key.
        key: String,
        /// Config value.
        value: String,
    },
}

/// TUI transcript render mode.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum TuiRenderMode {
    /// Show assistant text, reasoning, tool calls, and tool returns.
    #[default]
    Normal,
    /// Hide ordinary tool calls from transcript while keeping high-level events.
    Concise,
    /// Show detailed diagnostic rendering.
    Debug,
}

/// Output mode.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum OutputMode {
    /// Human-readable text.
    Text,
    /// Starweaver durable `DisplayMessage` JSON lines.
    #[default]
    DisplayJsonl,
    /// Starweaver/AGUI top-level event JSON lines.
    AguiJsonl,
    /// Compact JSON command result.
    Json,
    /// Persist and print compact status.
    Silent,
}

/// HITL policy.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum HitlPolicy {
    /// Deny approvals.
    Deny,
    /// Defer approvals.
    Defer,
    /// Fail on approvals.
    Fail,
    /// Prompt interactively.
    #[default]
    Prompt,
}

/// Build the clap command schema.
#[must_use]
pub fn command() -> clap::Command {
    Cli::command()
}

/// Parse CLI arguments.
pub fn parse(args: impl IntoIterator<Item = String>) -> CliResult<Cli> {
    Cli::try_parse_from(args).map_err(|error| clap_error(&error))
}

/// Parse CLI arguments from OS strings.
#[allow(dead_code)]
pub fn parse_os(args: impl IntoIterator<Item = OsString>) -> CliResult<Cli> {
    Cli::try_parse_from(args).map_err(|error| clap_error(&error))
}

fn clap_error(error: &clap::Error) -> CliError {
    match error.kind() {
        clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => {
            CliError::Display(error.to_string())
        }
        _ => CliError::Usage(error.to_string()),
    }
}