codetether-agent 4.5.7

A2A-native AI coding agent for the CodeTether ecosystem
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
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
1083
1084
//! CLI command definitions and handlers

pub mod auth;
pub mod config;
pub mod go_ralph;
pub mod oracle;
pub mod run;

use clap::{Parser, Subcommand};
use std::path::PathBuf;

/// CodeTether Agent - A2A-native AI coding agent
///
/// By default, runs as an A2A worker connecting to the CodeTether server.
/// Use the 'tui' subcommand for interactive terminal mode.
#[derive(Parser, Debug)]
#[command(name = "codetether")]
#[command(version, about, long_about = None)]
pub struct Cli {
    /// Project directory to operate on
    #[arg(global = true, last = true)]
    pub project: Option<PathBuf>,

    /// Print logs to stderr
    #[arg(long, global = true)]
    pub print_logs: bool,

    /// Log level
    #[arg(long, global = true, value_parser = ["DEBUG", "INFO", "WARN", "ERROR"])]
    pub log_level: Option<String>,

    // Default A2A args (when no subcommand)
    /// A2A server URL (default mode)
    #[arg(short, long, env = "CODETETHER_SERVER")]
    pub server: Option<String>,

    /// Authentication token
    #[arg(short, long, env = "CODETETHER_TOKEN")]
    pub token: Option<String>,

    /// Worker name
    #[arg(short, long, env = "CODETETHER_WORKER_NAME")]
    pub name: Option<String>,

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

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Start interactive terminal UI
    Tui(TuiArgs),

    /// Start a headless API server
    Serve(ServeArgs),

    /// Run with a message (non-interactive)
    Run(RunArgs),

    /// Create or update GitHub pull requests with CodeTether provenance
    Pr(PrArgs),

    /// Authenticate provider credentials and store in Vault
    Auth(AuthArgs),

    /// Manage configuration
    Config(ConfigArgs),

    /// A2A worker mode (explicit - also the default)
    Worker(A2aArgs),

    /// Internal command: Git credential helper for worker-managed repositories.
    #[command(hide = true)]
    GitCredentialHelper(GitCredentialHelperArgs),

    /// Spawn an A2A agent runtime with auto card registration and peer discovery
    Spawn(SpawnArgs),

    /// Execute task with parallel sub-agents (swarm mode)
    Swarm(SwarmArgs),

    /// Internal command: execute one swarm subtask payload.
    #[command(hide = true)]
    SwarmSubagent(SwarmSubagentArgs),

    /// Analyze large content with RLM (Recursive Language Model)
    Rlm(RlmArgs),

    /// Deterministic oracle utilities (validate/sync)
    Oracle(OracleArgs),

    /// Autonomous PRD-driven agent loop (Ralph)
    Ralph(RalphArgs),

    /// Model Context Protocol (MCP) server/client
    Mcp(McpArgs),

    /// Show telemetry and execution statistics
    Stats(StatsArgs),

    /// Clean up orphaned worktrees and branches from failed Ralph runs
    Cleanup(CleanupArgs),

    /// List available models from all configured providers
    Models(ModelsArgs),

    /// Build a persistent codebase index for faster workspace introspection
    Index(IndexArgs),

    /// Run benchmark suite against models using Ralph PRDs
    Benchmark(BenchmarkArgs),

    /// Moltbook — social network for AI agents
    Moltbook(MoltbookArgs),

    /// Manage OKRs (Objectives and Key Results)
    Okr(OkrArgs),

    /// OKR-governed autonomous opportunity scanner/executor
    Forage(ForageArgs),
}

#[derive(Parser, Debug)]
pub struct AuthArgs {
    #[command(subcommand)]
    pub command: AuthCommand,
}

#[derive(Subcommand, Debug)]
pub enum AuthCommand {
    /// Authenticate with GitHub Copilot using device flow
    Copilot(CopilotAuthArgs),

    /// Authenticate OpenAI Codex with a ChatGPT subscription via OAuth (Plus/Pro/Team/Enterprise)
    Codex(CodexAuthArgs),

    /// Import browser cookies (Netscape format) into Vault for a provider
    Cookies(CookieAuthArgs),

    /// Register a new CodeTether account with email/password
    Register(RegisterAuthArgs),

    /// Login to a CodeTether server with email/password
    Login(LoginAuthArgs),
}

#[derive(Parser, Debug)]
pub struct RegisterAuthArgs {
    /// CodeTether server URL (e.g., https://api.codetether.run)
    #[arg(short, long, env = "CODETETHER_SERVER")]
    pub server: String,

    /// Email address
    #[arg(short, long)]
    pub email: Option<String>,

    /// First name (optional)
    #[arg(long)]
    pub first_name: Option<String>,

    /// Last name (optional)
    #[arg(long)]
    pub last_name: Option<String>,

    /// Referral source (optional)
    #[arg(long)]
    pub referral_source: Option<String>,
}

#[derive(Parser, Debug)]
pub struct LoginAuthArgs {
    /// CodeTether server URL (e.g., https://api.codetether.io)
    #[arg(short, long, env = "CODETETHER_SERVER")]
    pub server: String,

    /// Email address
    #[arg(short, long)]
    pub email: Option<String>,
}

#[derive(Parser, Debug)]
pub struct CopilotAuthArgs {
    /// GitHub Enterprise URL or domain (e.g. company.ghe.com)
    #[arg(long)]
    pub enterprise_url: Option<String>,

    /// GitHub OAuth app client ID for Copilot device flow
    #[arg(long, env = "CODETETHER_COPILOT_OAUTH_CLIENT_ID")]
    pub client_id: Option<String>,
}

#[derive(Parser, Debug)]
pub struct CodexAuthArgs {
    /// Use ChatGPT device-code authentication flow (recommended for remote SSH sessions)
    #[arg(long, default_value_t = false)]
    pub device_code: bool,
}

#[derive(Parser, Debug)]
pub struct CookieAuthArgs {
    /// Provider ID to store under (e.g. nextdoor-web, gemini-web)
    #[arg(long, default_value = "nextdoor-web")]
    pub provider: String,

    /// Path to Netscape cookies export file
    #[arg(long)]
    pub file: PathBuf,

    /// Keep all valid cookies instead of filtering to auth-focused names
    #[arg(long, default_value_t = false)]
    pub keep_all: bool,
}

#[derive(Parser, Debug)]
pub struct TuiArgs {
    /// Project directory
    pub project: Option<PathBuf>,

    /// Allow network access in sandboxed commands
    #[arg(long)]
    pub allow_network: bool,
}

#[derive(Parser, Debug)]
pub struct ServeArgs {
    /// Port to listen on
    #[arg(short, long, default_value = "4096")]
    pub port: u16,

    /// Hostname to bind to
    #[arg(long, default_value = "127.0.0.1")]
    pub hostname: String,

    /// Enable mDNS discovery
    #[arg(long)]
    pub mdns: bool,
}

#[derive(Parser, Debug)]
pub struct RunArgs {
    /// Message to send (can be multiple words, quoted or unquoted)
    pub message: String,

    /// Continue the last session
    #[arg(short, long)]
    pub continue_session: bool,

    /// Session ID to continue
    #[arg(short, long)]
    pub session: Option<String>,

    /// Model to use (provider/model format)
    #[arg(short, long)]
    pub model: Option<String>,

    /// Agent to use
    #[arg(long)]
    pub agent: Option<String>,

    /// Output format
    #[arg(long, default_value = "default", value_parser = ["default", "json"])]
    pub format: String,

    /// Files to attach
    #[arg(short, long)]
    pub file: Vec<PathBuf>,

    /// Import and continue a Codex CLI session by ID
    #[arg(long)]
    pub codex_session: Option<String>,

    /// Maximum agentic loop steps (default: 250, minimum: 1)
    #[arg(long)]
    pub max_steps: Option<usize>,
}

#[derive(Parser, Debug)]
pub struct PrArgs {
    #[command(subcommand)]
    pub command: PrCommand,
}

#[derive(Subcommand, Debug)]
pub enum PrCommand {
    /// Create or update a pull request for the current branch
    Create(CreatePrArgs),
}

#[derive(Parser, Debug, Clone)]
pub struct CreatePrArgs {
    /// Pull request title
    #[arg(long)]
    pub title: String,

    /// Optional pull request body
    #[arg(long)]
    pub body: Option<String>,

    /// Optional path to a pull request body file
    #[arg(long)]
    pub body_file: Option<PathBuf>,

    /// Base branch
    #[arg(long, default_value = "main")]
    pub base: String,

    /// Head branch override (defaults to current branch)
    #[arg(long)]
    pub head: Option<String>,

    /// Create the PR as draft
    #[arg(long, default_value_t = false)]
    pub draft: bool,

    /// Emit JSON instead of KEY=VALUE lines
    #[arg(long, default_value_t = false)]
    pub json: bool,

    /// Project directory override
    #[arg(long)]
    pub project: Option<PathBuf>,
}

/// Arguments for standalone worker HTTP server (testing/debugging)
#[derive(Parser, Debug, Clone)]
pub struct WorkerServerArgs {
    /// Hostname to bind
    #[arg(long, default_value = "0.0.0.0")]
    pub hostname: String,

    /// Port to bind
    #[arg(short, long, default_value = "8080")]
    pub port: u16,
}

#[derive(Parser, Debug, Clone)]
pub struct A2aArgs {
    /// A2A server URL
    #[arg(short, long, env = "CODETETHER_SERVER", default_value = crate::a2a::worker::DEFAULT_A2A_SERVER_URL)]
    pub server: String,

    /// Authentication token
    #[arg(short, long, env = "CODETETHER_TOKEN")]
    pub token: Option<String>,

    /// Worker name
    #[arg(short, long, env = "CODETETHER_WORKER_NAME")]
    pub name: Option<String>,

    /// Comma-separated list of workspace paths (alias: --codebases)
    #[arg(short, long, visible_alias = "codebases")]
    pub workspaces: Option<String>,

    /// Maximum number of tasks this worker will process concurrently
    #[arg(
        long,
        env = "CODETETHER_WORKER_MAX_CONCURRENT_TASKS",
        default_value_t = 4
    )]
    pub max_concurrent_tasks: usize,

    /// Auto-approve policy: all, safe (read-only), none
    #[arg(long, default_value = "safe", value_parser = ["all", "safe", "none"])]
    pub auto_approve: String,

    /// Email for task completion reports
    #[arg(short, long)]
    pub email: Option<String>,

    /// Push notification endpoint URL
    #[arg(long)]
    pub push_url: Option<String>,

    /// Hostname to bind the worker HTTP server
    #[arg(long, default_value = "0.0.0.0", env = "CODETETHER_WORKER_HOST")]
    pub hostname: String,

    /// Port for the worker HTTP server (for health/readiness probes)
    #[arg(long, default_value = "8080", env = "CODETETHER_WORKER_PORT")]
    pub port: u16,

    /// Public base URL advertised for this worker's HTTP interfaces.
    #[arg(long, env = "CODETETHER_WORKER_PUBLIC_URL")]
    pub public_url: Option<String>,

    /// Disable the worker HTTP server (for environments without K8s)
    #[arg(long, env = "CODETETHER_WORKER_HTTP_DISABLED")]
    pub no_http_server: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct GitCredentialHelperArgs {
    /// Workspace/codebase ID for which Git credentials should be minted.
    #[arg(long = "workspace-id", alias = "codebase-id")]
    pub workspace_id: String,

    /// CodeTether server URL.
    #[arg(long, env = "CODETETHER_SERVER")]
    pub server: Option<String>,

    /// CodeTether bearer token.
    #[arg(long, env = "CODETETHER_TOKEN")]
    pub token: Option<String>,

    /// Worker ID requesting the credential.
    #[arg(long, env = "CODETETHER_WORKER_ID")]
    pub worker_id: Option<String>,

    /// Git helper operation (get/store/erase). Git passes this positionally.
    pub operation: Option<String>,
}

#[derive(Parser, Debug, Clone)]
pub struct SpawnArgs {
    /// Agent name
    #[arg(short, long)]
    pub name: Option<String>,

    /// Hostname to bind the spawned A2A agent
    #[arg(long, default_value = "127.0.0.1")]
    pub hostname: String,

    /// Port to bind the spawned A2A agent
    #[arg(short, long, default_value = "4097")]
    pub port: u16,

    /// Public URL published in the agent card (defaults to http://<hostname>:<port>)
    #[arg(long)]
    pub public_url: Option<String>,

    /// Optional custom agent description for the card
    #[arg(short, long)]
    pub description: Option<String>,

    /// Peer seed URLs to discover and talk to (repeat flag or comma-separated)
    #[arg(long, value_delimiter = ',', env = "CODETETHER_A2A_PEERS")]
    pub peer: Vec<String>,

    /// Discovery interval in seconds
    #[arg(long, default_value = "15")]
    pub discovery_interval_secs: u64,

    /// Disable sending an automatic intro message to newly discovered peers
    #[arg(long = "no-auto-introduce", action = clap::ArgAction::SetFalse, default_value_t = true)]
    pub auto_introduce: bool,
}

#[derive(Parser, Debug)]
pub struct ConfigArgs {
    /// Show current configuration
    #[arg(long)]
    pub show: bool,

    /// Initialize default configuration
    #[arg(long)]
    pub init: bool,

    /// Set a configuration value
    #[arg(long)]
    pub set: Option<String>,
}

#[derive(Parser, Debug)]
pub struct SwarmArgs {
    /// Task to execute with swarm
    pub task: String,

    /// Model to use (provider/model format, e.g. zai/glm-5 or openrouter/z-ai/glm-5)
    #[arg(short, long)]
    pub model: Option<String>,

    /// Decomposition strategy: auto, domain, data, stage, none
    #[arg(short = 's', long, default_value = "auto")]
    pub strategy: String,

    /// Maximum number of concurrent sub-agents
    #[arg(long, default_value = "100")]
    pub max_subagents: usize,

    /// Maximum steps per sub-agent
    #[arg(long, default_value = "100")]
    pub max_steps: usize,

    /// Timeout per sub-agent (seconds)
    #[arg(long, default_value = "300")]
    pub timeout: u64,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Sub-agent execution mode: local | k8s
    #[arg(long, default_value = "local", value_parser = ["local", "k8s", "kubernetes", "kubernetes-pod", "pod"])]
    pub execution_mode: String,

    /// Maximum concurrent Kubernetes sub-agent pods when execution mode is k8s.
    #[arg(long, default_value = "8")]
    pub k8s_pod_budget: usize,

    /// Optional image override for Kubernetes sub-agent pods.
    #[arg(long)]
    pub k8s_image: Option<String>,
}

#[derive(Parser, Debug)]
pub struct SwarmSubagentArgs {
    /// Base64 payload for the remote subtask (JSON encoded)
    #[arg(long)]
    pub payload_base64: Option<String>,

    /// Read payload from an environment variable
    #[arg(long, default_value = "CODETETHER_SWARM_SUBTASK_PAYLOAD")]
    pub payload_env: String,
}

#[derive(Parser, Debug)]
pub struct RlmArgs {
    /// Query to answer about the content
    pub query: String,

    /// Model to use (provider/model format)
    #[arg(short, long)]
    pub model: Option<String>,

    /// File paths to analyze
    #[arg(short, long)]
    pub file: Vec<PathBuf>,

    /// Direct content to analyze (use - for stdin)
    #[arg(long)]
    pub content: Option<String>,

    /// Content type hint: code, logs, conversation, documents, auto
    #[arg(long, default_value = "auto")]
    pub content_type: String,

    /// Maximum tokens for output
    #[arg(long, default_value = "4000")]
    pub max_tokens: usize,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Enable verbose output (shows context summary)
    #[arg(short, long)]
    pub verbose: bool,

    /// Deprecated no-op: oracle verification is now always enabled by default
    #[arg(long)]
    pub oracle_verify: bool,

    /// Disable deterministic oracle verification (emergency opt-out)
    #[arg(long)]
    pub no_oracle_verify: bool,

    /// Number of independent runs for semantic consensus verification
    #[arg(long, default_value = "1")]
    pub consensus_runs: usize,

    /// Consensus threshold for semantic verification (1.0 = unanimous)
    #[arg(long, default_value = "1.0")]
    pub consensus_threshold: f32,

    /// Temperature for RLM generation (defaults: 0.3 single run, 0.75 consensus)
    #[arg(long)]
    pub analysis_temperature: Option<f32>,

    /// Directory to write split oracle JSONL datasets
    #[arg(long)]
    pub oracle_out_dir: Option<PathBuf>,

    /// Output prefix for oracle split JSONL files
    #[arg(long, default_value = "rlm_oracle")]
    pub oracle_prefix: String,
}

#[derive(Parser, Debug)]
pub struct OracleArgs {
    #[command(subcommand)]
    pub command: OracleCommand,
}

#[derive(Subcommand, Debug)]
pub enum OracleCommand {
    /// Validate a FINAL(JSON) payload deterministically against source content
    Validate(OracleValidateArgs),
    /// Sync pending oracle spool files to MinIO/S3
    Sync(OracleSyncArgs),
}

#[derive(Parser, Debug)]
pub struct OracleValidateArgs {
    /// Query associated with the payload (used as trace prompt)
    #[arg(long)]
    pub query: String,

    /// Source file to validate against
    #[arg(short, long)]
    pub file: Option<PathBuf>,

    /// Source content to validate against (use - for stdin)
    #[arg(long)]
    pub content: Option<String>,

    /// FINAL(JSON) payload string
    #[arg(long)]
    pub payload: Option<String>,

    /// Path to a file containing FINAL(JSON) payload
    #[arg(long)]
    pub payload_file: Option<PathBuf>,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Persist validated record to oracle storage pipeline
    #[arg(long)]
    pub persist: bool,
}

#[derive(Parser, Debug)]
pub struct OracleSyncArgs {
    /// Output as JSON
    #[arg(long)]
    pub json: bool,
}

#[derive(Parser, Debug)]
pub struct RalphArgs {
    /// Action to perform
    #[arg(value_parser = ["run", "status", "create-prd"])]
    pub action: String,

    /// Path to prd.json file
    #[arg(short, long, default_value = "prd.json")]
    pub prd: PathBuf,

    /// Feature name (for create-prd)
    #[arg(short, long)]
    pub feature: Option<String>,

    /// Project name (for create-prd)
    #[arg(long = "project-name")]
    pub project_name: Option<String>,

    /// Maximum iterations
    #[arg(long, default_value = "10")]
    pub max_iterations: usize,

    /// Model to use
    #[arg(short, long)]
    pub model: Option<String>,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,
}

#[derive(Parser, Debug)]
pub struct McpArgs {
    /// Action to perform
    #[arg(value_parser = ["serve", "connect", "list-tools", "call"])]
    pub action: String,

    /// Command to spawn for connecting to MCP server (flag form)
    #[arg(short, long)]
    pub command: Option<String>,

    /// Server name for registry
    #[arg(long)]
    pub server_name: Option<String>,

    /// Tool name for call action
    #[arg(long)]
    pub tool: Option<String>,

    /// JSON arguments for tool call
    #[arg(long)]
    pub arguments: Option<String>,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Resolve a worker's first-class bus connection via the control plane.
    #[arg(long)]
    pub worker_id: Option<String>,

    /// Resolve the owning worker via a registered workspace ID.
    #[arg(long)]
    pub workspace_id: Option<String>,

    /// URL of the CodeTether HTTP server's bus SSE endpoint.
    /// When set, the MCP server connects to the agent bus and exposes
    /// bus_events, bus_status, and ralph_status tools plus codetether:// resources.
    /// Example: http://localhost:8001/v1/bus/stream
    #[arg(long)]
    pub bus_url: Option<String>,

    /// Command (and args) to spawn for connecting to MCP server (positional form).
    /// Example: `codetether mcp connect npx -y @modelcontextprotocol/server-filesystem /path`
    #[arg(allow_hyphen_values = true)]
    pub command_args: Vec<String>,
}

#[derive(Parser, Debug)]
pub struct StatsArgs {
    /// Show tool execution history
    #[arg(short, long)]
    pub tools: bool,

    /// Show file change history
    #[arg(short, long)]
    pub files: bool,

    /// Show token usage
    #[arg(long)]
    pub tokens: bool,

    /// Filter by tool name
    #[arg(long)]
    pub tool: Option<String>,

    /// Filter by file path
    #[arg(long)]
    pub file: Option<String>,

    /// Number of recent entries to show
    #[arg(short, long, default_value = "20")]
    pub limit: usize,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Show all/summary (default shows summary)
    #[arg(long)]
    pub all: bool,
}

#[derive(Parser, Debug)]
pub struct CleanupArgs {
    /// Dry run - show what would be cleaned up without deleting
    #[arg(short, long)]
    pub dry_run: bool,

    /// Clean up worktrees only (not branches)
    #[arg(long)]
    pub worktrees_only: bool,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,
}

#[derive(Parser, Debug)]
pub struct ModelsArgs {
    /// Filter by provider name
    #[arg(short, long)]
    pub provider: Option<String>,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,
}

#[derive(Parser, Debug)]
pub struct IndexArgs {
    /// Root directory to index (defaults to current directory)
    #[arg(short, long)]
    pub path: Option<PathBuf>,

    /// Output file for index JSON (defaults to CODETETHER_DATA_DIR/indexes/...)
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Maximum file size to index in KiB
    #[arg(long, default_value = "1024")]
    pub max_file_size_kib: u64,

    /// Local open-source embedding model identifier
    #[arg(long, default_value = "hash-v1")]
    pub embedding_model: String,

    /// Embedding provider ID (`local`, `huggingface`, etc.)
    #[arg(long, default_value = "local")]
    pub embedding_provider: String,

    /// Embedding vector dimensions
    #[arg(long, default_value = "384")]
    pub embedding_dimensions: usize,

    /// Number of documents per embedding batch
    #[arg(long, default_value = "32")]
    pub embedding_batch_size: usize,

    /// Maximum retry attempts for a failed remote embedding batch
    #[arg(long, default_value = "3")]
    pub embedding_max_retries: u32,

    /// Initial retry backoff in milliseconds for remote embedding failures
    #[arg(long, default_value = "250")]
    pub embedding_retry_initial_ms: u64,

    /// Maximum retry backoff in milliseconds for remote embedding failures
    #[arg(long, default_value = "2000")]
    pub embedding_retry_max_ms: u64,

    /// Max characters per file used for embedding input
    #[arg(long, default_value = "8000")]
    pub embedding_input_chars: usize,

    /// Include hidden files/directories (dotfiles)
    #[arg(long, default_value_t = false)]
    pub include_hidden: bool,

    /// Output result as JSON
    #[arg(long)]
    pub json: bool,
}

#[derive(Parser, Debug)]
pub struct MoltbookArgs {
    #[command(subcommand)]
    pub command: MoltbookCommand,
}

#[derive(Subcommand, Debug)]
pub enum MoltbookCommand {
    /// Register a new agent on Moltbook
    Register(MoltbookRegisterArgs),

    /// Check claim status
    Status,

    /// View your Moltbook profile
    Profile,

    /// Update your profile description
    UpdateProfile(MoltbookUpdateProfileArgs),

    /// Create a post (defaults to m/general)
    Post(MoltbookPostArgs),

    /// Post a CodeTether introduction to Moltbook
    Intro,

    /// Run a heartbeat — check feed, show recent posts
    Heartbeat,

    /// Comment on a Moltbook post
    Comment(MoltbookCommentArgs),

    /// Search Moltbook posts and comments
    Search(MoltbookSearchArgs),
}

#[derive(Parser, Debug)]
pub struct MoltbookRegisterArgs {
    /// Agent name to register on Moltbook
    pub name: String,

    /// Optional extra description (CodeTether branding is always included)
    #[arg(short, long)]
    pub description: Option<String>,
}

#[derive(Parser, Debug)]
pub struct MoltbookUpdateProfileArgs {
    /// Extra description to append
    #[arg(short, long)]
    pub description: Option<String>,
}

#[derive(Parser, Debug)]
pub struct MoltbookPostArgs {
    /// Post title
    pub title: String,

    /// Post content
    #[arg(short, long)]
    pub content: String,

    /// Submolt to post in
    #[arg(short, long, default_value = "general")]
    pub submolt: String,
}

#[derive(Parser, Debug)]
pub struct MoltbookCommentArgs {
    /// Post ID to comment on
    pub post_id: String,

    /// Comment content
    pub content: String,
}

#[derive(Parser, Debug)]
pub struct MoltbookSearchArgs {
    /// Search query
    pub query: String,

    /// Max results
    #[arg(short, long, default_value = "10")]
    pub limit: usize,
}

#[derive(Parser, Debug)]
pub struct BenchmarkArgs {
    /// Directory containing benchmark PRD files
    #[arg(long, default_value = "benchmarks")]
    pub prd_dir: String,

    /// Models to benchmark (comma-separated, format: provider:model)
    #[arg(short, long, value_delimiter = ',')]
    pub models: Vec<String>,

    /// Only run PRDs matching this tier (1, 2, or 3)
    #[arg(long)]
    pub tier: Option<u8>,

    /// Run model×PRD combos in parallel
    #[arg(long)]
    pub parallel: bool,

    /// Maximum iterations per story
    #[arg(long, default_value = "10")]
    pub max_iterations: usize,

    /// Timeout per story in seconds
    #[arg(long, default_value = "300")]
    pub story_timeout: u64,

    /// Output file path
    #[arg(short, long, default_value = "benchmark_results.json")]
    pub output: String,

    /// Cost ceiling per run in USD (prevents runaway spending)
    #[arg(long, default_value = "50.0")]
    pub cost_ceiling: f64,

    /// Submit results to this API URL
    #[arg(long)]
    pub submit_url: Option<String>,

    /// API key for submitting results (Bearer token)
    #[arg(long, env = "BENCHMARK_API_KEY")]
    pub submit_key: Option<String>,

    /// Output as JSON to stdout
    #[arg(long)]
    pub json: bool,
}

#[derive(Parser, Debug)]
pub struct OkrArgs {
    /// Action to perform
    #[arg(value_parser = ["list", "status", "create", "runs", "export", "stats", "report"])]
    pub action: String,

    /// OKR ID (UUID)
    #[arg(short, long)]
    pub id: Option<String>,

    /// OKR title (for create)
    #[arg(short, long)]
    pub title: Option<String>,

    /// OKR description (for create)
    #[arg(short, long)]
    pub description: Option<String>,

    /// Target value for key result (for create)
    #[arg(long)]
    pub target: Option<f64>,

    /// Unit for key result (for create)
    #[arg(long, default_value = "%")]
    pub unit: String,

    /// Filter by status: draft, active, completed, cancelled, on_hold
    #[arg(long)]
    pub status: Option<String>,

    /// Filter by owner
    #[arg(long)]
    pub owner: Option<String>,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Include evidence links in output
    #[arg(long)]
    pub evidence: bool,
}

#[derive(Parser, Debug)]
#[command(
    about = "OKR-governed autonomous opportunity scanner/executor",
    long_about = "Scan OKRs/KRs for high-priority opportunities and optionally execute the top selections with the build agent.",
    after_long_help = "Examples:\n  codetether forage --top 5\n  codetether forage --loop --interval-secs 600\n  codetether forage --loop --execute --top 1 --interval-secs 600 --max-cycles 48 --run-timeout-secs 900 --model minimax/MiniMax-M2.5\n  codetether forage --loop --execute --execution-engine swarm --swarm-max-subagents 8 --swarm-strategy auto --model zai/glm-5"
)]
pub struct ForageArgs {
    /// Show top-N opportunities each cycle
    #[arg(long, default_value = "3")]
    pub top: usize,

    /// Keep running continuously
    #[arg(long = "loop")]
    pub loop_mode: bool,

    /// Seconds between loop cycles
    #[arg(long, default_value = "120")]
    pub interval_secs: u64,

    /// Maximum cycles when looping (0 = unlimited)
    #[arg(long, default_value = "0")]
    pub max_cycles: usize,

    /// Execute selected opportunities via `codetether run`
    #[arg(long)]
    pub execute: bool,

    /// Disable S3/MinIO archival requirement (for local-only execution)
    #[arg(long)]
    pub no_s3: bool,

    /// Moonshot mission statement(s) used as a strategic rubric for prioritization.
    ///
    /// Repeat the flag to provide multiple missions.
    #[arg(long = "moonshot")]
    pub moonshots: Vec<String>,

    /// Optional file containing moonshot mission statements (JSON array or newline-delimited text).
    #[arg(long)]
    pub moonshot_file: Option<PathBuf>,

    /// Require minimum moonshot alignment for an opportunity to be selected.
    #[arg(long)]
    pub moonshot_required: bool,

    /// Minimum moonshot alignment ratio when `--moonshot-required` is enabled.
    #[arg(long, default_value = "0.10")]
    pub moonshot_min_alignment: f64,

    /// Execution engine for `--execute`: run | swarm | go
    #[arg(long, default_value = "run", value_parser = ["run", "swarm", "go"])]
    pub execution_engine: String,

    /// Timeout per execution task in seconds (only used with --execute)
    #[arg(long, default_value = "900")]
    pub run_timeout_secs: u64,

    /// Stop immediately on execution error/timeout (default: continue loop)
    #[arg(long)]
    pub fail_fast: bool,

    /// Swarm decomposition strategy when --execution-engine=swarm
    #[arg(long, default_value = "auto", value_parser = ["auto", "domain", "data", "stage", "none"])]
    pub swarm_strategy: String,

    /// Maximum concurrent sub-agents when --execution-engine=swarm
    #[arg(long, default_value = "8")]
    pub swarm_max_subagents: usize,

    /// Maximum steps per sub-agent when --execution-engine=swarm
    #[arg(long, default_value = "100")]
    pub swarm_max_steps: usize,

    /// Timeout per sub-agent in seconds when --execution-engine=swarm
    #[arg(long, default_value = "300")]
    pub swarm_subagent_timeout_secs: u64,

    /// Optional model override for execution mode
    #[arg(short, long)]
    pub model: Option<String>,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,
}