zeph 0.21.2

Lightweight AI agent with hybrid inference, skills-first architecture, and multi-channel I/O
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::path::PathBuf;

use clap::{Parser, Subcommand, ValueEnum};
use zeph_memory::store::agent_sessions::SessionStatus;

#[derive(Parser)]
#[command(
    name = "zeph",
    version,
    about = "Lightweight AI agent with hybrid inference"
)]
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct Cli {
    /// Run with TUI dashboard
    #[arg(long)]
    pub(crate) tui: bool,

    /// Run in headless daemon mode (requires a2a feature)
    #[cfg(feature = "a2a")]
    #[arg(long)]
    pub(crate) daemon: bool,

    /// Run as ACP server over stdio for IDE embedding (requires acp feature)
    #[cfg(feature = "acp")]
    #[arg(long)]
    pub(crate) acp: bool,

    /// Print ACP agent manifest JSON to stdout and exit (requires acp feature)
    #[cfg(feature = "acp")]
    #[arg(long)]
    pub(crate) acp_manifest: bool,

    /// Run as ACP server over HTTP+SSE and WebSocket (requires acp-http feature)
    #[cfg(feature = "acp-http")]
    #[arg(long)]
    pub(crate) acp_http: bool,

    /// Bind address for the ACP HTTP server (requires acp-http feature)
    #[cfg(feature = "acp-http")]
    #[arg(long, value_name = "ADDR")]
    pub(crate) acp_http_bind: Option<String>,

    /// Bearer token for ACP HTTP/WebSocket authentication (overrides `acp.auth_token` config)
    #[cfg(feature = "acp-http")]
    #[arg(long, value_name = "TOKEN")]
    pub(crate) acp_auth_token: Option<String>,

    /// Additional directory ACP clients may reference in session requests (repeatable, overrides config)
    #[cfg(feature = "acp")]
    #[arg(long = "acp-additional-dir", value_name = "PATH")]
    pub(crate) acp_additional_dir: Vec<PathBuf>,

    /// Auth method to advertise in ACP initialize response (only "agent" accepted in MVP)
    #[cfg(feature = "acp")]
    #[arg(long = "acp-auth-method", value_name = "METHOD", value_parser = ["agent"])]
    pub(crate) acp_auth_method: Vec<String>,

    /// Enable echoing of `PromptRequest.message_id` in responses and chunks
    #[cfg(feature = "acp")]
    #[arg(long = "acp-message-ids", overrides_with = "no_acp_message_ids")]
    pub(crate) acp_message_ids: bool,

    /// Disable echoing of `PromptRequest.message_id` in responses and chunks
    #[cfg(feature = "acp")]
    #[arg(long = "no-acp-message-ids", overrides_with = "acp_message_ids")]
    pub(crate) no_acp_message_ids: bool,

    /// Connect TUI to a remote daemon via A2A SSE (requires tui + a2a features)
    #[cfg(all(feature = "tui", feature = "a2a"))]
    #[arg(long, value_name = "URL")]
    pub(crate) connect: Option<String>,

    /// Path to config file
    #[arg(long, value_name = "PATH")]
    pub(crate) config: Option<PathBuf>,

    /// Secrets backend: "env" or "age"
    #[arg(long, value_name = "BACKEND")]
    pub(crate) vault: Option<String>,

    /// Path to age identity (private key) file
    #[arg(long, value_name = "PATH")]
    pub(crate) vault_key: Option<PathBuf>,

    /// Path to age-encrypted secrets file
    #[arg(long, value_name = "PATH")]
    pub(crate) vault_path: Option<PathBuf>,

    /// Enable Claude thinking mode: `extended:<budget_tokens>` or `adaptive` or `adaptive:<effort>`
    /// where effort is `low`, `medium`, or `high`. Overrides config.toml thinking setting.
    /// Examples: `--thinking extended:10000`  `--thinking adaptive`  `--thinking adaptive:high`
    #[arg(long, value_name = "MODE")]
    pub(crate) thinking: Option<String>,

    /// Additional sub-agent definition paths (file or directory containing .md files).
    /// Can be specified multiple times. Takes highest priority over all other sources.
    #[arg(long = "agents", value_name = "PATH")]
    pub(crate) agents: Vec<PathBuf>,

    /// Enable LLM-based guardrail (prompt injection pre-screening).
    /// Overrides `security.guardrail.enabled` from config.
    #[arg(long)]
    pub(crate) guardrail: bool,

    /// Enable graph-based knowledge memory (experimental)
    #[arg(long)]
    pub(crate) graph_memory: bool,

    /// Scan skill content for injection patterns on load (overrides config `scan_on_load`).
    /// Advisory only — results are logged as warnings; does not block tool calls.
    #[arg(long)]
    pub(crate) scan_skills_on_load: bool,

    /// Enable ACON failure-driven compression guidelines for this session.
    /// Overrides `memory.compression_guidelines.enabled` from config.
    /// Requires `compression-guidelines` feature at compile time; silently
    /// ignored if the feature is not enabled.
    #[arg(long)]
    pub(crate) compression_guidelines: bool,

    /// Enable Focus Agent for this session. Overrides `agent.focus.enabled` from config.
    #[arg(long)]
    pub(crate) focus: bool,

    /// Disable Focus Agent for this session.
    #[arg(long, conflicts_with = "focus")]
    pub(crate) no_focus: bool,

    /// Enable `SideQuest` eviction for this session. Overrides `memory.sidequest.enabled` from config.
    #[arg(long)]
    pub(crate) sidequest: bool,

    /// Disable `SideQuest` eviction for this session.
    #[arg(long, conflicts_with = "sidequest")]
    pub(crate) no_sidequest: bool,

    /// Override pruning strategy: reactive, `task_aware`, mig.
    /// Overrides `memory.compression.pruning_strategy` from config.
    #[arg(long, value_name = "STRATEGY")]
    pub(crate) pruning_strategy: Option<zeph_core::config::PruningStrategy>,

    /// Enable Claude server-side context compaction (compact-2026-01-12 beta).
    /// Requires a Claude provider. Overrides `llm.cloud.server_compaction` from config.
    #[arg(long)]
    pub(crate) server_compaction: bool,

    /// Enable Claude 1M extended context window for this session.
    /// Tokens above 200K use long-context pricing. Overrides `llm.cloud.enable_extended_context`
    /// from config. Requires a Claude provider.
    #[arg(long)]
    pub(crate) extended_context: bool,

    /// Enable automatic LSP context injection (diagnostics after writes, hover on reads).
    /// Requires mcpls MCP server configured under [mcp.servers].
    #[arg(long)]
    pub(crate) lsp_context: bool,

    /// Override log file path. Use bare `--log-file` (without a value) to disable file
    /// logging, overriding any config value. When omitted, uses the value from the `logging`
    /// config section (default: .zeph/logs/zeph.log).
    #[arg(long, value_name = "PATH", num_args = 0..=1, default_missing_value = "")]
    pub(crate) log_file: Option<String>,

    /// Enable debug dump: write LLM requests/responses and raw tool output to files.
    /// Omit PATH to use the default directory from config (default: .zeph/debug).
    #[arg(long, value_name = "PATH", num_args = 0..=1, default_missing_value = "")]
    pub(crate) debug_dump: Option<PathBuf>,

    /// Path to external policy rules file (TOML). Overrides `tools.policy.policy_file` from config.
    #[arg(long, value_name = "PATH")]
    pub(crate) policy_file: Option<PathBuf>,

    /// Set the initial capability scope task-type for this session.
    ///
    /// Must match a scope name defined in `[security.capability_scopes]`.
    /// The agent starts with this scope active; the operator can change it at runtime
    /// via `/scope <task_type>` (Phase 2). No-op when `ScopedToolExecutor` is not wired.
    #[arg(long = "scope", value_name = "TASK_TYPE")]
    pub(crate) initial_scope: Option<String>,

    /// Override debug dump format: `json`, `raw`, or `trace` (`OTel` OTLP spans).
    #[arg(long = "dump-format", value_name = "FORMAT")]
    pub(crate) dump_format: Option<zeph_core::debug_dump::DumpFormat>,

    /// Deny network egress to this domain from sandboxed shell commands (repeatable).
    ///
    /// Merges with `[tools.sandbox].denied_domains` from config. Patterns support exact
    /// hostnames (`"pastebin.com"`) and single-level wildcards (`"*.pastebin.com"`).
    /// Has no effect when the sandbox is disabled or unavailable.
    #[arg(long = "deny-domain", value_name = "DOMAIN")]
    pub(crate) deny_domain: Vec<String>,

    /// Abort startup if an effective OS sandbox cannot be activated.
    ///
    /// Equivalent to setting `[tools.sandbox].fail_if_unavailable = true` in config.
    /// Useful when `--deny-domain` is set and the egress filter must be enforced.
    #[arg(long = "no-sandbox-fallback")]
    pub(crate) no_sandbox_fallback: bool,

    /// Override scheduler tick interval in seconds (requires scheduler feature)
    #[cfg(feature = "scheduler")]
    #[arg(long, value_name = "SECS")]
    pub(crate) scheduler_tick: Option<u64>,

    /// Disable the scheduler even if enabled in config (requires scheduler feature)
    #[cfg(feature = "scheduler")]
    #[arg(long)]
    pub(crate) scheduler_disable: bool,

    /// Run a single experiment session and exit (requires experiments feature)
    #[arg(long)]
    pub(crate) experiment_run: bool,

    /// Print experiment results summary and exit (requires experiments feature)
    #[arg(long)]
    pub(crate) experiment_report: bool,

    /// Print default configuration as TOML to stdout and exit.
    ///
    /// Useful for bootstrapping a new config file or exploring available options.
    #[arg(long)]
    pub(crate) dump_config_defaults: bool,

    /// Disable pre-execution verifiers for tool calls.
    /// Use in trusted environments or when verifiers produce false positives.
    #[arg(long)]
    pub(crate) no_pre_execution_verify: bool,

    /// Enable Think-Augmented Function Calling (TAFC) for this session.
    /// Injects a reasoning step into complex tool schemas.
    /// Overrides `tools.tafc.enabled` from config.
    #[arg(long)]
    pub(crate) tafc: bool,

    /// Bare mode: skip skill loading, memory init, MCP connections, scheduler
    /// startup, and filesystem watchers. Useful for scripting and CI pipelines.
    #[arg(long)]
    pub(crate) bare: bool,

    /// Emit structured JSON events to stdout (JSONL, one event per line).
    /// Safe for piping into `jq`. Forces all log output to stderr.
    /// Mutually exclusive with `--tui` and `--acp`.
    #[arg(long)]
    pub(crate) json: bool,

    /// Auto-approve trust-gate prompts. Equivalent to
    /// `[security] autonomy_level = "full"`. The adversarial policy gate (if
    /// enabled) still runs. Destructive-command blocklist still applies.
    #[arg(long = "auto", short = 'y')]
    pub(crate) auto: bool,

    #[command(subcommand)]
    pub(crate) command: Option<Command>,
}

#[cfg(test)]
impl Default for Cli {
    fn default() -> Self {
        use clap::Parser;
        Cli::parse_from(["zeph"])
    }
}

#[derive(Subcommand)]
pub(crate) enum Command {
    /// Interactive configuration wizard
    Init {
        /// Output path for generated config
        #[arg(long, short, value_name = "PATH")]
        output: Option<PathBuf>,
    },
    /// Manage the age-encrypted secrets vault
    Vault {
        #[command(subcommand)]
        command: VaultCommand,
    },
    /// Manage external skills
    Skill {
        #[command(subcommand)]
        command: SkillCommand,
    },
    /// Manage plugins (bundled skills + MCP servers)
    Plugin {
        #[command(subcommand)]
        command: PluginCommand,
    },
    /// Manage memory snapshots
    Memory {
        #[command(subcommand)]
        command: MemoryCommand,
    },
    /// Ingest a document into semantic memory
    Ingest {
        /// Path to document or directory to ingest
        path: PathBuf,
        /// Chunk size in characters
        #[arg(long, default_value = "1000")]
        chunk_size: usize,
        /// Chunk overlap in characters
        #[arg(long, default_value = "100")]
        chunk_overlap: usize,
        /// Target Qdrant collection name
        #[arg(long, default_value = "zeph_documents")]
        collection: String,
    },
    /// Manage scheduled jobs
    #[cfg(feature = "scheduler")]
    Schedule {
        #[command(subcommand)]
        command: ScheduleCommand,
    },
    /// Manage ACP session history
    #[cfg(feature = "acp")]
    Sessions {
        #[command(subcommand)]
        command: SessionsCommand,
    },
    /// Inspect or reset Thompson Sampling router state
    Router {
        #[command(subcommand)]
        command: RouterCommand,
    },
    /// Manage sub-agent definitions
    Agents {
        #[command(subcommand)]
        command: AgentsCommand,
    },
    /// Start the scheduler daemon in the background (Unix only).
    ///
    /// Acquires an exclusive pid file lock so only one instance runs per config.
    /// Use `--foreground` for systemd / launchd managed processes.
    #[cfg(all(unix, feature = "scheduler"))]
    Serve {
        /// Run in the foreground instead of detaching (useful for systemd / launchd).
        #[arg(long)]
        foreground: bool,
        /// Disable catch-up: do not replay overdue tasks on startup.
        #[arg(long)]
        no_catch_up: bool,
    },
    /// Stop the running scheduler daemon (Unix only).
    #[cfg(all(unix, feature = "scheduler"))]
    Stop {
        /// Seconds to wait for graceful shutdown before escalating to SIGKILL. Default: 10.
        #[arg(long, default_value = "10")]
        timeout_secs: u64,
    },
    /// Show scheduler daemon status and recent task runs (Unix only).
    #[cfg(all(unix, feature = "scheduler"))]
    Status {
        /// Emit output as JSON (stable schema for scripting).
        #[arg(long)]
        json: bool,
        /// Number of recent task runs to display. Default: 10.
        #[arg(long, short, default_value = "10")]
        n: usize,
    },
    /// Add missing config parameters as commented-out entries, preserving existing values
    MigrateConfig {
        /// Path to config file (default: `config/default.toml` or `ZEPH_CONFIG`)
        #[arg(long, value_name = "PATH")]
        config: Option<std::path::PathBuf>,
        /// Write the migrated config back to the source file (atomic rename, preserves permissions)
        #[arg(long)]
        in_place: bool,
        /// Show a unified diff instead of the full output
        #[arg(long)]
        diff: bool,
    },
    /// Manage ML classifier models
    Classifiers {
        #[command(subcommand)]
        command: crate::commands::classifiers::ClassifiersCommand,
    },
    /// Manage the database
    Db {
        #[command(subcommand)]
        command: DbCommand,
    },
    /// ACP sub-agent client commands
    #[cfg(feature = "acp")]
    Acp {
        #[command(subcommand)]
        command: AcpCommand,
    },
    /// Run preflight connectivity and configuration checks
    Doctor {
        /// Emit results as JSON (`schema_version` = 1)
        #[arg(long)]
        json: bool,
        /// Timeout in seconds for LLM provider probes and SQLite/Qdrant checks
        #[arg(long, default_value = "10")]
        llm_timeout_secs: u64,
        /// Timeout in seconds for MCP server connection probes
        #[arg(long, default_value = "5")]
        mcp_timeout_secs: u64,
    },
    /// Gonka network diagnostics and credential checks
    #[cfg(feature = "gonka")]
    Gonka {
        #[command(subcommand)]
        command: GonkaCommand,
    },
    /// Cocoon sidecar diagnostics
    #[cfg(feature = "cocoon")]
    Cocoon {
        #[command(subcommand)]
        command: CocoonCommand,
    },
    /// Test notification channels (sends a test notification via enabled channels)
    Notify {
        #[command(subcommand)]
        command: NotifyCommand,
    },
    /// Run agent benchmarks against standardized datasets
    #[cfg(feature = "bench")]
    Bench {
        #[command(subcommand)]
        command: zeph_bench::BenchCommand,
    },
    /// Project-level management commands
    Project {
        #[command(subcommand)]
        command: ProjectCommand,
    },
}

/// Project management subcommands.
#[derive(Subcommand)]
pub(crate) enum ProjectCommand {
    /// Remove all project data: memory, database, skill outcomes, and debug artifacts
    Purge {
        /// Path to config file (overrides default resolution)
        #[arg(long, value_name = "PATH")]
        config: Option<PathBuf>,
        /// Show what would be removed without deleting anything
        #[arg(long)]
        dry_run: bool,
        /// Skip confirmation prompt
        #[arg(long, short)]
        yes: bool,
    },
}

/// ACP sub-agent client subcommands.
#[cfg(feature = "acp")]
#[derive(Subcommand)]
pub(crate) enum AcpCommand {
    /// Run a one-shot prompt against an ACP sub-agent and print the response
    RunAgent {
        /// Shell command to spawn the sub-agent (e.g. "cargo run -- --acp")
        #[arg(long, short)]
        command: String,

        /// Prompt text to send
        #[arg(long, short)]
        prompt: Option<String>,

        /// Working directory for the subprocess (sets both `process_cwd` and `session_cwd`)
        #[arg(long)]
        cwd: Option<std::path::PathBuf>,

        /// Handshake + session timeout in seconds
        #[arg(long, default_value = "600")]
        timeout: u64,
    },
    /// Sub-agent preset management
    Subagent {
        #[command(subcommand)]
        command: AcpSubagentCommand,
    },
}

/// Sub-agent preset subcommands.
#[cfg(feature = "acp")]
#[derive(Subcommand)]
pub(crate) enum AcpSubagentCommand {
    /// List configured sub-agent presets
    List,
}

/// Database subcommands.
#[derive(Subcommand)]
pub(crate) enum DbCommand {
    /// Run pending database migrations
    Migrate,
}

/// Typed session status filter for the `agents fleet` sub-command.
#[derive(Clone, Copy, Debug, ValueEnum)]
pub(crate) enum FleetStatus {
    Active,
    Completed,
    Failed,
    Cancelled,
    Unknown,
}

impl From<FleetStatus> for SessionStatus {
    fn from(s: FleetStatus) -> Self {
        match s {
            FleetStatus::Active => SessionStatus::Active,
            FleetStatus::Completed => SessionStatus::Completed,
            FleetStatus::Failed => SessionStatus::Failed,
            FleetStatus::Cancelled => SessionStatus::Cancelled,
            FleetStatus::Unknown => SessionStatus::Unknown,
        }
    }
}

#[derive(Subcommand)]
pub(crate) enum AgentsCommand {
    /// List all available sub-agent definitions
    List,
    /// Show full definition of a sub-agent
    Show {
        /// Agent name
        name: String,
    },
    /// Create a new sub-agent definition
    Create {
        /// Agent name (must match `[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}`)
        name: String,
        /// Short description
        #[arg(long, short)]
        description: String,
        /// Target directory (default: .zeph/agents)
        #[arg(long, default_value = ".zeph/agents")]
        dir: std::path::PathBuf,
        /// Model to use (optional, inherits from parent config)
        #[arg(long)]
        model: Option<String>,
    },
    /// Edit a sub-agent definition in $VISUAL or $EDITOR
    Edit {
        /// Agent name
        name: String,
    },
    /// Delete a sub-agent definition
    Delete {
        /// Agent name
        name: String,
        /// Skip confirmation prompt
        #[arg(long, short)]
        yes: bool,
    },
    /// List agent sessions recorded in the fleet database
    Fleet {
        /// Filter by session status
        #[arg(long, short)]
        status: Option<FleetStatus>,
        /// Maximum number of sessions to show
        #[arg(long, default_value = "20")]
        limit: u32,
    },
}

#[derive(Subcommand)]
pub(crate) enum MemoryCommand {
    /// Export memory to a JSON snapshot file
    Export {
        /// Output file path
        path: PathBuf,
    },
    /// Import memory from a JSON snapshot file
    Import {
        /// Input file path
        path: PathBuf,
    },
    /// Run the `SleepGate` forgetting sweep once and print the result
    ForgettingSweep,
    /// Show trajectory memory statistics (entry count by kind)
    Trajectory,
    /// Show memory tree statistics (node count by level)
    Tree,
}

#[derive(Subcommand)]
pub(crate) enum SkillCommand {
    /// Install a skill from a git URL or local path
    Install {
        /// Git URL or local directory path
        source: String,
    },
    /// Remove an installed skill
    Remove {
        /// Skill name
        name: String,
    },
    /// List installed skills
    List,
    /// Verify skill integrity (blake3 hash check)
    Verify {
        /// Skill name (omit to verify all)
        name: Option<String>,
    },
    /// Set trust level for a skill
    Trust {
        /// Skill name
        name: String,
        /// Trust level: trusted, verified, quarantined, blocked
        level: String,
    },
    /// Block a skill
    Block {
        /// Skill name
        name: String,
    },
    /// Unblock a skill (sets to quarantined)
    Unblock {
        /// Skill name
        name: String,
    },
    /// Preview a skill body with trust-aware sanitization (same pipeline as the agent)
    Invoke {
        /// Skill name
        name: String,
        /// Optional arguments appended as <args>…</args> block
        #[arg(long)]
        args: Option<String>,
    },
}

#[derive(Subcommand)]
pub(crate) enum PluginCommand {
    /// List installed plugins, optionally showing the active config overlay
    List {
        /// Show plugin overlay: which plugins contributed to the active config and which
        /// were skipped (with reasons). Values shown against `Config::default()` — use
        /// --config for live intersection.
        #[arg(long)]
        overlay: bool,
    },
    /// Install a plugin from a local directory path
    Add {
        /// Local directory path to the plugin root (must contain plugin.toml)
        source: String,
    },
    /// Remove an installed plugin
    Remove {
        /// Plugin name
        name: String,
    },
}

#[cfg(feature = "scheduler")]
#[derive(Subcommand)]
pub(crate) enum ScheduleCommand {
    /// List all active scheduled jobs
    List,
    /// Add a new periodic cron job
    Add {
        /// Cron expression (5 or 6 fields, e.g. "0 * * * *")
        cron: String,
        /// Task prompt to execute on each trigger
        prompt: String,
        /// Job name (auto-generated from prompt if omitted)
        #[arg(long)]
        name: Option<String>,
        /// Task kind (default: "custom")
        #[arg(long, default_value = "custom")]
        kind: String,
    },
    /// Remove a scheduled job by name
    Remove {
        /// Job name to remove
        name: String,
    },
    /// Show details of a scheduled job
    Show {
        /// Job name to inspect
        name: String,
    },
}

#[cfg(feature = "acp")]
#[derive(Subcommand)]
pub(crate) enum SessionsCommand {
    /// List recent ACP sessions
    List,
    /// Resume a past session by ID (print events to stdout)
    Resume {
        /// Session ID
        id: String,
    },
    /// Delete an ACP session and its events
    Delete {
        /// Session ID
        id: String,
    },
}

#[derive(Subcommand)]
pub(crate) enum RouterCommand {
    /// Show current Thompson Sampling alpha/beta per provider
    Stats {
        /// Path to Thompson state file (default: `~/.zeph/router_thompson_state.json`)
        #[arg(long, value_name = "PATH")]
        state_path: Option<std::path::PathBuf>,
    },
    /// Delete the Thompson state file (resets to uniform priors)
    Reset {
        /// Path to Thompson state file (default: `~/.zeph/router_thompson_state.json`)
        #[arg(long, value_name = "PATH")]
        state_path: Option<std::path::PathBuf>,
    },
}

/// Gonka network subcommands.
#[cfg(feature = "gonka")]
#[derive(Subcommand)]
pub(crate) enum GonkaCommand {
    /// Run Gonka connectivity and credential diagnostics
    Doctor {
        /// Emit results as JSON (`schema_version` = 1)
        #[arg(long)]
        json: bool,
        /// Timeout in seconds for node probe requests
        #[arg(long, default_value = "10")]
        timeout_secs: u64,
    },
}

/// Cocoon sidecar subcommands.
#[cfg(feature = "cocoon")]
#[derive(Subcommand)]
pub(crate) enum CocoonCommand {
    /// Run Cocoon sidecar connectivity and configuration diagnostics
    Doctor {
        /// Emit results as JSON (`schema_version` = 1)
        #[arg(long)]
        json: bool,
        /// Timeout in seconds for HTTP checks (default 5)
        #[arg(long, default_value = "5")]
        timeout_secs: u64,
    },
}

/// Notification management subcommands.
#[derive(Subcommand)]
pub(crate) enum NotifyCommand {
    /// Send a test notification via all configured channels
    Test,
}

#[derive(Subcommand)]
pub(crate) enum VaultCommand {
    /// Generate age keypair and empty encrypted vault
    Init,

    /// Encrypt and store a secret.
    /// Note: VALUE is visible in process listing (ps/history). For sensitive values
    /// prefer setting the variable in the shell and passing via env instead.
    Set {
        #[arg()]
        key: String,
        #[arg()]
        value: String,
    },
    /// Decrypt and print a secret value
    Get {
        #[arg()]
        key: String,
    },
    /// List stored secret keys (no values)
    List,
    /// Remove a secret
    Rm {
        #[arg()]
        key: String,
    },
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::Cli;

    #[cfg(feature = "scheduler")]
    #[test]
    fn cli_parses_schedule_list() {
        use super::{Command, ScheduleCommand};
        let cli = Cli::try_parse_from(["zeph", "schedule", "list"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Schedule {
                command: ScheduleCommand::List
            })
        ));
    }

    #[cfg(feature = "scheduler")]
    #[test]
    fn cli_parses_schedule_add() {
        use super::{Command, ScheduleCommand};
        let cli =
            Cli::try_parse_from(["zeph", "schedule", "add", "0 * * * *", "run report"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Schedule {
                command: ScheduleCommand::Add { .. }
            })
        ));
    }

    #[cfg(feature = "scheduler")]
    #[test]
    fn cli_parses_schedule_remove() {
        use super::{Command, ScheduleCommand};
        let cli = Cli::try_parse_from(["zeph", "schedule", "remove", "my-job"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Schedule {
                command: ScheduleCommand::Remove { .. }
            })
        ));
    }

    #[cfg(feature = "scheduler")]
    #[test]
    fn cli_parses_schedule_show() {
        use super::{Command, ScheduleCommand};
        let cli = Cli::try_parse_from(["zeph", "schedule", "show", "my-job"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Schedule {
                command: ScheduleCommand::Show { .. }
            })
        ));
    }

    #[test]
    fn cli_parses_extended_context_flag() {
        let cli = Cli::try_parse_from(["zeph", "--extended-context"]).unwrap();
        assert!(cli.extended_context);
    }

    #[test]
    fn cli_extended_context_defaults_to_false() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(!cli.extended_context);
    }

    #[test]
    fn cli_parses_graph_memory_flag() {
        let cli = Cli::try_parse_from(["zeph", "--graph-memory"]).unwrap();
        assert!(cli.graph_memory);
    }

    #[test]
    fn cli_graph_memory_flag_defaults_to_false() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(!cli.graph_memory);
    }

    #[test]
    fn cli_parses_compression_guidelines_flag() {
        let cli = Cli::try_parse_from(["zeph", "--compression-guidelines"]).unwrap();
        assert!(cli.compression_guidelines);
    }

    #[test]
    fn cli_compression_guidelines_defaults_to_false() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(!cli.compression_guidelines);
    }

    #[test]
    fn cli_parses_scan_skills_on_load_flag() {
        let cli = Cli::try_parse_from(["zeph", "--scan-skills-on-load"]).unwrap();
        assert!(cli.scan_skills_on_load);
    }

    #[test]
    fn cli_scan_skills_on_load_defaults_to_false() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(!cli.scan_skills_on_load);
    }
    #[test]
    fn cli_parses_experiment_run_flag() {
        let cli = Cli::try_parse_from(["zeph", "--experiment-run"]).unwrap();
        assert!(cli.experiment_run);
    }
    #[test]
    fn cli_parses_experiment_report_flag() {
        let cli = Cli::try_parse_from(["zeph", "--experiment-report"]).unwrap();
        assert!(cli.experiment_report);
    }
    #[test]
    fn cli_experiment_flags_default_to_false() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(!cli.experiment_run);
        assert!(!cli.experiment_report);
    }

    #[test]
    fn cli_parses_log_file_flag() {
        let cli = Cli::try_parse_from(["zeph", "--log-file", "/tmp/test.log"]).unwrap();
        assert_eq!(cli.log_file.as_deref(), Some("/tmp/test.log"));
    }

    #[test]
    fn cli_log_file_defaults_to_none() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(cli.log_file.is_none());
    }

    #[test]
    fn cli_log_file_bare_flag_disables_logging() {
        let cli = Cli::try_parse_from(["zeph", "--log-file"]).unwrap();
        assert_eq!(cli.log_file.as_deref(), Some(""));
    }

    #[test]
    fn cli_dump_format_defaults_to_none() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(cli.dump_format.is_none());
    }

    #[test]
    fn cli_dump_format_parses_trace() {
        let cli = Cli::try_parse_from(["zeph", "--dump-format", "trace"]).unwrap();
        assert_eq!(
            cli.dump_format,
            Some(zeph_core::debug_dump::DumpFormat::Trace)
        );
    }

    #[test]
    fn cli_dump_format_parses_raw() {
        let cli = Cli::try_parse_from(["zeph", "--dump-format", "raw"]).unwrap();
        assert_eq!(
            cli.dump_format,
            Some(zeph_core::debug_dump::DumpFormat::Raw)
        );
    }

    #[test]
    fn cli_parses_focus_flag() {
        let cli = Cli::try_parse_from(["zeph", "--focus"]).unwrap();
        assert!(cli.focus);
    }

    #[test]
    fn cli_parses_no_focus_flag() {
        let cli = Cli::try_parse_from(["zeph", "--no-focus"]).unwrap();
        assert!(cli.no_focus);
    }

    #[test]
    fn cli_parses_sidequest_flag() {
        let cli = Cli::try_parse_from(["zeph", "--sidequest"]).unwrap();
        assert!(cli.sidequest);
    }

    #[test]
    fn cli_parses_no_sidequest_flag() {
        let cli = Cli::try_parse_from(["zeph", "--no-sidequest"]).unwrap();
        assert!(cli.no_sidequest);
    }

    #[test]
    fn cli_parses_pruning_strategy_task_aware() {
        let cli = Cli::try_parse_from(["zeph", "--pruning-strategy", "task_aware"]).unwrap();
        assert_eq!(
            cli.pruning_strategy,
            Some(zeph_core::config::PruningStrategy::TaskAware)
        );
    }

    #[test]
    fn cli_parses_pruning_strategy_mig() {
        let cli = Cli::try_parse_from(["zeph", "--pruning-strategy", "mig"]).unwrap();
        assert_eq!(
            cli.pruning_strategy,
            Some(zeph_core::config::PruningStrategy::Mig)
        );
    }

    #[test]
    fn cli_pruning_strategy_task_aware_mig_falls_back_to_reactive() {
        // task_aware_mig was removed; FromStr now returns Reactive with a warning.
        let parsed: zeph_core::config::PruningStrategy = "task_aware_mig".parse().unwrap();
        assert_eq!(parsed, zeph_core::config::PruningStrategy::Reactive);
    }

    #[test]
    fn cli_focus_and_no_focus_conflict() {
        assert!(Cli::try_parse_from(["zeph", "--focus", "--no-focus"]).is_err());
    }

    #[test]
    fn cli_sidequest_and_no_sidequest_conflict() {
        assert!(Cli::try_parse_from(["zeph", "--sidequest", "--no-sidequest"]).is_err());
    }

    #[test]
    fn cli_defaults_compression_flags_to_false() {
        let cli = Cli::try_parse_from(["zeph"]).unwrap();
        assert!(!cli.focus);
        assert!(!cli.no_focus);
        assert!(!cli.sidequest);
        assert!(!cli.no_sidequest);
        assert!(cli.pruning_strategy.is_none());
    }

    #[test]
    fn cli_parses_pruning_strategy_task_aware_kebab() {
        let cli = Cli::try_parse_from(["zeph", "--pruning-strategy", "task-aware"]).unwrap();
        assert_eq!(
            cli.pruning_strategy,
            Some(zeph_core::config::PruningStrategy::TaskAware)
        );
    }

    #[test]
    fn cli_parses_project_purge() {
        use super::{Command, ProjectCommand};
        let cli = Cli::try_parse_from(["zeph", "project", "purge"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Project {
                command: ProjectCommand::Purge {
                    dry_run: false,
                    yes: false,
                    ..
                }
            })
        ));
    }

    #[test]
    fn cli_parses_project_purge_dry_run() {
        use super::{Command, ProjectCommand};
        let cli = Cli::try_parse_from(["zeph", "project", "purge", "--dry-run"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Project {
                command: ProjectCommand::Purge {
                    dry_run: true,
                    yes: false,
                    ..
                }
            })
        ));
    }

    #[test]
    fn cli_parses_project_purge_yes() {
        use super::{Command, ProjectCommand};
        let cli = Cli::try_parse_from(["zeph", "project", "purge", "--yes"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Project {
                command: ProjectCommand::Purge {
                    dry_run: false,
                    yes: true,
                    ..
                }
            })
        ));
    }

    #[test]
    fn cli_parses_project_purge_with_config() {
        use super::{Command, ProjectCommand};
        let cli = Cli::try_parse_from(["zeph", "project", "purge", "--config", "/tmp/test.toml"])
            .unwrap();
        if let Some(Command::Project {
            command: ProjectCommand::Purge { config, .. },
        }) = cli.command
        {
            assert_eq!(config, Some(std::path::PathBuf::from("/tmp/test.toml")));
        } else {
            panic!("unexpected command variant");
        }
    }
}