reasonkit 0.1.6

The Reasoning Engine — Complete ReasonKit Suite | Auditable Reasoning for Production AI
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
// ReasonKit — Unified CLI
//
// Complete command-line interface for the ReasonKit suite.
//
// This binary provides a unified entry point to all ReasonKit components:
// - `reasonkit think` — Reasoning engine (via reasonkit-core)
// - `reasonkit mem` — Memory operations (via reasonkit-mem)
// - `reasonkit web` — Web/browser automation (via reasonkit-web)
// - `reasonkit serve` — Start MCP server

use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};
#[cfg(feature = "org")]
use std::process;
use tracing::{info, Level};
use tracing_subscriber::FmtSubscriber;

// =============================================================================
// CLI STRUCTURE
// =============================================================================

#[derive(Parser)]
#[command(name = "reasonkit")]
#[command(author = "ReasonKit Team <team@reasonkit.sh>")]
#[command(version)]
#[command(about = "The Reasoning Engine — Auditable Reasoning for Production AI")]
#[command(long_about = r#"
ReasonKit — Complete Suite for Structured AI Reasoning

This unified CLI provides access to all ReasonKit components:

  REASONING (reasonkit-core):
    reasonkit think      Execute ThinkTools protocols
    reasonkit verify     Triangulate claims with 3+ sources

  MEMORY (reasonkit-mem):
    reasonkit mem        Memory and knowledge base operations
    reasonkit rag        Retrieval-augmented generation

  WEB (reasonkit-web):
    reasonkit web        Browser automation and capture
    reasonkit serve      Start MCP server

  ORG (reasonkit-org):
    reasonkit task       Taskwarrior passthrough
    reasonkit time       Timewarrior passthrough
    reasonkit org        Operational tooling (doctor/status)
    reasonkit job        Jobs-to-be-Done management

EXAMPLES:
    # Quick reasoning analysis
    reasonkit think --profile quick "Is this a good investment?"

    # Deep analysis with full protocol chain
    reasonkit think --profile paranoid "Validate this architecture"

    # Search knowledge base
    reasonkit mem search "machine learning fundamentals"

    # Start unified MCP server
    reasonkit serve

WEBSITE: https://reasonkit.sh
DOCS:    https://docs.rs/reasonkit
"#)]
struct Cli {
    /// Verbosity level (-v, -vv, -vvv)
    #[arg(short, long, action = clap::ArgAction::Count, global = true)]
    verbose: u8,

    /// Output format (text, json)
    #[arg(short, long, default_value = "text", global = true)]
    format: OutputFormat,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum OutputFormat {
    Text,
    Json,
}

#[derive(Subcommand)]
enum Commands {
    // =========================================================================
    // CORE: Reasoning Engine
    // =========================================================================
    /// Execute structured reasoning protocols (ThinkTools)
    #[cfg(feature = "core")]
    #[command(alias = "t")]
    Think {
        /// The query or question to analyze
        query: String,

        /// Protocol to execute (gigathink, laserlogic, bedrock, proofguard, brutalhonesty)
        #[arg(short, long)]
        protocol: Option<String>,

        /// Profile to execute (quick, balanced, deep, paranoid)
        #[arg(long, default_value = "balanced")]
        profile: String,

        /// LLM provider
        #[arg(long, default_value = "anthropic")]
        provider: String,

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

        /// Use mock LLM (for testing)
        #[arg(long)]
        mock: bool,

        /// List available protocols and profiles
        #[arg(long)]
        list: bool,
    },

    /// Triangulate and verify claims with 3+ sources
    #[cfg(feature = "core")]
    #[command(alias = "v")]
    Verify {
        /// Claim or statement to verify
        claim: String,

        /// Minimum number of sources required
        #[arg(short, long, default_value = "3")]
        sources: usize,
    },

    // =========================================================================
    // MEMORY: Knowledge Base Operations
    // =========================================================================
    /// Memory and knowledge base operations
    #[cfg(feature = "mem")]
    #[command(alias = "m")]
    Mem {
        #[command(subcommand)]
        action: MemAction,
    },

    /// Retrieval-augmented generation queries
    #[cfg(feature = "mem")]
    Rag {
        /// Query for RAG retrieval
        query: String,

        /// Number of results to retrieve
        #[arg(short = 'k', long, default_value = "5")]
        top_k: usize,

        /// Use hybrid search (BM25 + vector)
        #[arg(long)]
        hybrid: bool,
    },

    // =========================================================================
    // WEB: Browser Automation
    // =========================================================================
    /// Browser automation and web capture
    #[cfg(feature = "web")]
    #[command(alias = "w")]
    Web {
        #[command(subcommand)]
        action: WebAction,
    },

    // =========================================================================
    // ORG: Operational Tooling
    // =========================================================================
    /// Taskwarrior passthrough (fully Taskwarrior-compatible)
    ///
    /// Examples:
    /// - rk task project:rk-project list
    /// - rk task 42 start
    #[cfg(feature = "org")]
    Task {
        /// Arguments passed directly to `task`
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Timewarrior passthrough (fully Timewarrior-compatible)
    ///
    /// Examples:
    /// - rk time summary :today
    /// - rk time stop
    #[cfg(feature = "org")]
    Time {
        /// Arguments passed directly to `timew`
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Task orchestration utilities (reasonkit-org)
    #[cfg(feature = "org")]
    #[command(alias = "o")]
    Org {
        #[command(subcommand)]
        action: OrgAction,
    },

    /// Jobs-to-be-Done management (reasonkit-org)
    #[cfg(feature = "org")]
    #[command(alias = "j")]
    Job {
        #[command(subcommand)]
        action: JobAction,
    },

    // =========================================================================
    // SERVERS
    // =========================================================================
    /// Start the ReasonKit MCP server
    Serve {
        /// Host to bind to
        #[arg(long, default_value = "127.0.0.1")]
        host: String,

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

        /// Server mode (core, web, full)
        #[arg(long, default_value = "full")]
        mode: ServerMode,
    },

    // =========================================================================
    // UTILITIES
    // =========================================================================
    /// Show version information for all components
    Version,

    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },

    // =========================================================================
    // SETUP & DIAGNOSTICS
    // =========================================================================
    /// Interactive setup wizard for new users
    #[command(alias = "setup")]
    Init {
        /// Skip interactive prompts, use defaults
        #[arg(long)]
        non_interactive: bool,

        /// Force re-initialization even if already configured
        #[arg(long)]
        force: bool,
    },

    /// Show system status and health check
    #[command(alias = "health")]
    Status {
        /// Show detailed component information
        #[arg(short, long)]
        detailed: bool,

        /// Output format (text, json)
        #[arg(long, default_value = "text")]
        output: String,
    },

    /// Run a quick demo showcasing ReasonKit capabilities
    Demo {
        /// Demo type (reasoning, memory, web, all)
        #[arg(long, default_value = "reasoning")]
        demo_type: DemoType,

        /// Use mock LLM (no API key required)
        #[arg(long)]
        mock: bool,
    },
}

#[cfg(feature = "mem")]
#[derive(Subcommand)]
enum MemAction {
    /// Docset ingestion and refresh (Cursor-like @Docs)
    Docs {
        #[command(subcommand)]
        action: DocsAction,
    },
}

#[cfg(feature = "mem")]
#[derive(Subcommand)]
enum DocsAction {
    /// Add a new docset
    Add {
        /// Name of the docset
        name: String,
        /// Starting URL for the docset
        start_url: String,
        /// Allowed URL prefixes (defaults to start_url if not specified)
        allowed_prefixes: Option<Vec<String>>,
    },

    /// List all docsets
    List,

    /// Query documents in docsets
    Query {
        /// Search query
        query: String,

        /// Filter by docset name or ID
        #[arg(long)]
        docset: Option<String>,

        /// Number of results to return
        #[arg(short = 'k', long, default_value = "8")]
        top_k: usize,

        /// Output in JSON format
        #[arg(long)]
        json: bool,
    },

    /// Remove a docset
    Remove {
        /// Docset ID to remove
        docset_id: String,

        /// Keep the index (don't delete indexed documents)
        #[arg(long)]
        keep_index: bool,
    },

    /// Refresh docsets
    Refresh {
        /// Only refresh docsets whose refresh policy is due
        #[arg(long)]
        due: bool,

        /// Maximum pages to fetch per docset
        #[arg(long)]
        max_pages: Option<usize>,

        /// Concurrency level for fetching
        #[arg(long)]
        concurrency: Option<usize>,

        /// Request timeout in seconds
        #[arg(long)]
        timeout_secs: Option<u64>,
    },
}

#[cfg(feature = "web")]
#[derive(Subcommand)]
enum WebAction {
    /// Navigate to a URL and capture content
    Capture {
        /// URL to capture
        url: String,
        /// Save screenshot
        #[arg(long)]
        screenshot: bool,
    },
    /// Extract content from a URL
    Extract {
        /// URL to extract from
        url: String,
        /// Extraction mode (text, links, metadata)
        #[arg(long, default_value = "text")]
        mode: String,
    },
}

#[cfg(feature = "org")]
#[derive(Subcommand)]
enum OrgAction {
    /// Validate local Taskwarrior/Timewarrior setup
    Doctor,
    /// Show current operational status (active task + timer)
    Status,
}

#[cfg(feature = "org")]
#[derive(Subcommand)]
enum JobAction {
    /// Define a new job
    Add {
        /// Job statement
        statement: String,
    },

    /// Add outcome to job
    Outcome {
        /// Job ID
        job_id: String,

        /// Outcome description
        description: String,

        /// Outcome type (functional/emotional/social)
        #[arg(short, long, default_value = "functional")]
        outcome_type: String,
    },

    /// Link tasks to job (UUID or numeric Taskwarrior ID)
    Link {
        /// Job ID
        job_id: String,

        /// Task selectors (uuid or numeric id)
        tasks: Vec<String>,
    },

    /// List jobs
    List,

    /// Show job progress
    Progress {
        /// Job ID
        job_id: String,
    },
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum ServerMode {
    Core,
    Web,
    Full,
}

#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
enum DemoType {
    /// Showcase reasoning/ThinkTools
    #[default]
    Reasoning,
    /// Showcase memory/RAG operations
    Memory,
    /// Showcase web/browser automation
    Web,
    /// Run all demos
    All,
}

// =============================================================================
// LOGGING SETUP
// =============================================================================

fn setup_logging(verbosity: u8) {
    let level = match verbosity {
        0 => Level::WARN,
        1 => Level::INFO,
        2 => Level::DEBUG,
        _ => Level::TRACE,
    };

    let subscriber = FmtSubscriber::builder()
        .with_max_level(level)
        .with_target(false)
        .with_thread_ids(false)
        .with_file(verbosity >= 3)
        .with_line_number(verbosity >= 3)
        .finish();

    let _ = tracing::subscriber::set_global_default(subscriber);
}

// =============================================================================
// COMMAND HANDLERS
// =============================================================================

#[cfg(feature = "core")]
#[allow(clippy::too_many_arguments)]
async fn handle_think(
    query: String,
    protocol: Option<String>,
    profile: String,
    _provider: String,
    _model: Option<String>,
    mock: bool,
    list: bool,
    format: OutputFormat,
) -> anyhow::Result<()> {
    use reasonkit_core::thinktool::{ProtocolExecutor, ProtocolInput};

    let executor = if mock {
        ProtocolExecutor::mock()?
    } else {
        ProtocolExecutor::new()?
    };

    if list {
        println!("Available Protocols:");
        for p in executor.list_protocols() {
            println!("  - {}", p);
        }
        println!("\nAvailable Profiles:");
        for p in executor.list_profiles() {
            println!("  - {}", p);
        }
        return Ok(());
    }

    let input = ProtocolInput::query(&query);

    let output = if let Some(proto) = protocol {
        executor.execute(&proto, input).await?
    } else {
        executor.execute_profile(&profile, input).await?
    };

    match format {
        OutputFormat::Text => {
            println!("Thinking Process:");
            for step in &output.steps {
                println!("\n[{}] {}", step.step_id, step.as_text().unwrap_or(""));
            }
            println!("\nConfidence: {:.2}", output.confidence);
        }
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
    }

    Ok(())
}

#[cfg(feature = "core")]
async fn handle_verify(claim: String, sources: usize) -> anyhow::Result<()> {
    println!("Verifying claim: {}", claim);
    println!("Minimum sources required: {}", sources);
    println!("\n[Not yet implemented - use rk-core verify]");
    Ok(())
}

#[cfg(feature = "mem")]
async fn handle_mem(action: MemAction, format: OutputFormat) -> anyhow::Result<()> {
    match action {
        MemAction::Docs {
            action: _docs_action,
        } => {
            // Note: This currently proxies to the new rk-mem-clap binary
            // In the future, we could call reasonkit-mem APIs directly
            println!("Memory operations via rk-mem (docset management)");
            println!("Commands: add, list, query, remove, refresh");
            println!("\nFor detailed usage: rk-mem docs --help");
            println!("   Example: rk mem docs list");
            println!("            rk mem docs add react https://react.dev/reference/");
        }
    }
    let _ = format; // Suppress warning
    Ok(())
}

#[cfg(feature = "mem")]
async fn handle_rag(query: String, top_k: usize, hybrid: bool) -> anyhow::Result<()> {
    println!(
        "RAG Query: {} (top_k: {}, hybrid: {})",
        query, top_k, hybrid
    );
    println!("\n[Not yet implemented - use rk-core rag]");
    Ok(())
}

#[cfg(feature = "web")]
async fn handle_web(action: WebAction) -> anyhow::Result<()> {
    match action {
        WebAction::Capture { url, screenshot } => {
            println!("Capturing URL: {} (screenshot: {})", url, screenshot);
            println!("\n[Not yet implemented - use rk-web capture]");
        }
        WebAction::Extract { url, mode } => {
            println!("Extracting from URL: {} (mode: {})", url, mode);
            println!("\n[Not yet implemented - use rk-web extract]");
        }
    }
    Ok(())
}

#[allow(unreachable_code)]
async fn handle_serve(host: String, port: u16, mode: ServerMode) -> anyhow::Result<()> {
    info!("Starting ReasonKit server on {}:{}", host, port);
    info!("Mode: {:?}", mode);

    match mode {
        #[cfg(all(feature = "core", feature = "mcp-server-pro"))]
        ServerMode::Core | ServerMode::Full => {
            info!("Starting Core MCP server...");
            reasonkit_core::mcp::server::run_server().await?;
        }
        #[cfg(all(feature = "core", not(feature = "mcp-server-pro")))]
        ServerMode::Core | ServerMode::Full => {
            anyhow::bail!("MCP server requires mcp-server-pro feature (Pro license). Contact sales@reasonkit.sh");
        }
        #[cfg(not(feature = "core"))]
        ServerMode::Core => {
            anyhow::bail!("Core feature not enabled. Rebuild with --features core");
        }
        #[cfg(feature = "web")]
        ServerMode::Web => {
            info!("Starting Web MCP server...");
            // reasonkit_web::McpServer::run().await?;
            println!("[Web server not yet integrated]");
        }
        #[cfg(not(feature = "web"))]
        ServerMode::Web => {
            anyhow::bail!("Web feature not enabled. Rebuild with --features web");
        }
        #[cfg(not(feature = "core"))]
        ServerMode::Full => {
            anyhow::bail!("Full mode requires core feature. Rebuild with --features full");
        }
    }

    Ok(())
}

fn handle_version(format: OutputFormat) -> anyhow::Result<()> {
    let info = reasonkit::version_info();

    match format {
        OutputFormat::Text => {
            println!("ReasonKit Suite v{}", info.reasonkit);
            println!();
            println!("Components:");
            if let Some(v) = &info.core {
                println!("  reasonkit-core: v{}", v);
            } else {
                println!("  reasonkit-core: not enabled");
            }
            if let Some(v) = &info.mem {
                println!("  reasonkit-mem:  v{}", v);
            } else {
                println!("  reasonkit-mem:  not enabled");
            }
            if let Some(v) = &info.web {
                println!("  reasonkit-web:  v{}", v);
            } else {
                println!("  reasonkit-web:  not enabled");
            }
            println!();
            println!("Website: https://reasonkit.sh");
        }
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&info)?);
        }
    }

    Ok(())
}

fn handle_init(non_interactive: bool, force: bool) -> anyhow::Result<()> {
    use std::io::{self, BufRead, Write};

    println!();
    println!("  ReasonKit Setup Wizard");
    println!("  ----------------------");
    println!();

    // Check if already configured
    let config_dir = dirs::config_dir()
        .map(|d| d.join("reasonkit"))
        .unwrap_or_else(|| std::path::PathBuf::from(".reasonkit"));

    let config_file = config_dir.join("config.toml");

    if config_file.exists() && !force {
        println!("  ReasonKit is already configured at:");
        println!("    {}", config_file.display());
        println!();
        println!("  Run with --force to reconfigure.");
        return Ok(());
    }

    // Create config directory
    std::fs::create_dir_all(&config_dir)?;

    // Detect environment
    println!("  Detecting environment...");
    println!();

    // Check for API keys in environment
    let anthropic_key = std::env::var("ANTHROPIC_API_KEY").ok();
    let openai_key = std::env::var("OPENAI_API_KEY").ok();
    let gemini_key = std::env::var("GOOGLE_API_KEY")
        .or_else(|_| std::env::var("GEMINI_API_KEY"))
        .ok();

    let mut default_provider = "mock";
    if anthropic_key.is_some() {
        println!("    [x] ANTHROPIC_API_KEY detected");
        default_provider = "anthropic";
    } else {
        println!("    [ ] ANTHROPIC_API_KEY not set");
    }
    if openai_key.is_some() {
        println!("    [x] OPENAI_API_KEY detected");
        if default_provider == "mock" {
            default_provider = "openai";
        }
    } else {
        println!("    [ ] OPENAI_API_KEY not set");
    }
    if gemini_key.is_some() {
        println!("    [x] GOOGLE_API_KEY detected");
        if default_provider == "mock" {
            default_provider = "gemini";
        }
    } else {
        println!("    [ ] GOOGLE_API_KEY not set");
    }

    println!();

    // Component availability
    println!("  Components available:");
    #[cfg(feature = "core")]
    println!("    [x] reasonkit-core (reasoning engine)");
    #[cfg(not(feature = "core"))]
    println!("    [ ] reasonkit-core (not compiled)");

    #[cfg(feature = "mem")]
    println!("    [x] reasonkit-mem (memory/RAG)");
    #[cfg(not(feature = "mem"))]
    println!("    [ ] reasonkit-mem (not compiled)");

    #[cfg(feature = "web")]
    println!("    [x] reasonkit-web (browser automation)");
    #[cfg(not(feature = "web"))]
    println!("    [ ] reasonkit-web (not compiled)");

    println!();

    let provider: String;
    let profile: String;

    if non_interactive {
        provider = default_provider.to_string();
        profile = "balanced".to_string();
        println!("  Using defaults (non-interactive mode):");
    } else {
        // Interactive configuration
        let stdin = io::stdin();
        let mut stdout = io::stdout();

        print!("  Default LLM provider [{}]: ", default_provider);
        stdout.flush()?;
        let mut input = String::new();
        stdin.lock().read_line(&mut input)?;
        let input_provider = input.trim().to_string();
        provider = if input_provider.is_empty() {
            default_provider.to_string()
        } else {
            input_provider
        };

        print!("  Default reasoning profile [balanced]: ");
        stdout.flush()?;
        input.clear();
        stdin.lock().read_line(&mut input)?;
        let input_profile = input.trim().to_string();
        profile = if input_profile.is_empty() {
            "balanced".to_string()
        } else {
            input_profile
        };

        println!();
        println!("  Configuration:");
    }

    println!("    Provider: {}", provider);
    println!("    Profile:  {}", profile);
    println!();

    // Write config file
    let config_content = format!(
        r#"# ReasonKit Configuration
# Generated by `rk init`

[defaults]
provider = "{}"
profile = "{}"

[providers.anthropic]
# model = "claude-opus-4-5"

[providers.openai]
# model = "gpt-5.2"

[providers.gemini]
# model = "gemini-3.0-pro"
"#,
        provider, profile
    );

    std::fs::write(&config_file, config_content)?;

    println!("  Configuration saved to:");
    println!("    {}", config_file.display());
    println!();

    // Shell completion hint
    println!("  TIP: Enable shell completions with:");
    println!("    rk completions bash >> ~/.bashrc");
    println!("    rk completions zsh >> ~/.zshrc");
    println!("    rk completions fish > ~/.config/fish/completions/rk.fish");
    println!();

    // Quick start hint
    println!("  Get started:");
    println!("    rk demo --mock          # Try a demo (no API key needed)");
    println!("    rk think \"Your query\"   # Run reasoning analysis");
    println!("    rk status               # Check system health");
    println!();

    Ok(())
}

fn handle_status(detailed: bool, output: &str) -> anyhow::Result<()> {
    use serde::Serialize;

    #[derive(Serialize)]
    struct StatusReport {
        version: String,
        components: ComponentStatus,
        environment: EnvStatus,
        health: HealthStatus,
    }

    #[derive(Serialize)]
    struct ComponentStatus {
        core: bool,
        mem: bool,
        web: bool,
    }

    #[derive(Serialize)]
    struct EnvStatus {
        anthropic_api_key: bool,
        openai_api_key: bool,
        google_api_key: bool,
        config_exists: bool,
    }

    #[derive(Serialize)]
    struct HealthStatus {
        overall: String,
        issues: Vec<String>,
    }

    // Gather status
    let config_dir = dirs::config_dir()
        .map(|d| d.join("reasonkit"))
        .unwrap_or_else(|| std::path::PathBuf::from(".reasonkit"));
    let config_exists = config_dir.join("config.toml").exists();

    let anthropic_key = std::env::var("ANTHROPIC_API_KEY").is_ok();
    let openai_key = std::env::var("OPENAI_API_KEY").is_ok();
    let google_key =
        std::env::var("GOOGLE_API_KEY").is_ok() || std::env::var("GEMINI_API_KEY").is_ok();

    let mut issues = Vec::new();

    #[cfg(feature = "core")]
    let core_enabled = true;
    #[cfg(not(feature = "core"))]
    let core_enabled = false;

    #[cfg(feature = "mem")]
    let mem_enabled = true;
    #[cfg(not(feature = "mem"))]
    let mem_enabled = false;

    #[cfg(feature = "web")]
    let web_enabled = true;
    #[cfg(not(feature = "web"))]
    let web_enabled = false;

    if !core_enabled {
        issues.push("Core component not enabled".to_string());
    }
    if !anthropic_key && !openai_key && !google_key {
        issues.push("No LLM API keys configured".to_string());
    }
    if !config_exists {
        issues.push("Not configured (run: rk init)".to_string());
    }

    let overall = if issues.is_empty() {
        "healthy".to_string()
    } else if issues.len() <= 2 {
        "degraded".to_string()
    } else {
        "unhealthy".to_string()
    };

    let report = StatusReport {
        version: reasonkit::VERSION.to_string(),
        components: ComponentStatus {
            core: core_enabled,
            mem: mem_enabled,
            web: web_enabled,
        },
        environment: EnvStatus {
            anthropic_api_key: anthropic_key,
            openai_api_key: openai_key,
            google_api_key: google_key,
            config_exists,
        },
        health: HealthStatus {
            overall: overall.clone(),
            issues: issues.clone(),
        },
    };

    if output == "json" {
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }

    // Text output
    println!();
    println!("  ReasonKit Status");
    println!("  ----------------");
    println!();

    // Health indicator
    let health_icon = match overall.as_str() {
        "healthy" => "[OK]",
        "degraded" => "[!!]",
        _ => "[XX]",
    };
    println!("  Health: {} {}", health_icon, overall);
    println!();

    // Version
    println!("  Version: {}", report.version);
    println!();

    // Components
    println!("  Components:");
    let icon = |b: bool| if b { "[x]" } else { "[ ]" };
    println!("    {} reasonkit-core", icon(report.components.core));
    println!("    {} reasonkit-mem", icon(report.components.mem));
    println!("    {} reasonkit-web", icon(report.components.web));
    println!();

    // Environment
    println!("  Environment:");
    println!(
        "    {} ANTHROPIC_API_KEY",
        icon(report.environment.anthropic_api_key)
    );
    println!(
        "    {} OPENAI_API_KEY",
        icon(report.environment.openai_api_key)
    );
    println!(
        "    {} GOOGLE_API_KEY",
        icon(report.environment.google_api_key)
    );
    println!(
        "    {} Configuration file",
        icon(report.environment.config_exists)
    );
    println!();

    if detailed {
        // Show config location
        println!("  Paths:");
        println!("    Config: {}", config_dir.display());
        if let Some(data_dir) = dirs::data_dir() {
            println!("    Data:   {}", data_dir.join("reasonkit").display());
        }
        println!();
    }

    // Issues
    if !issues.is_empty() {
        println!("  Issues:");
        for issue in &issues {
            println!("    - {}", issue);
        }
        println!();
    }

    Ok(())
}

#[cfg(feature = "core")]
async fn handle_demo(demo_type: DemoType, mock: bool) -> anyhow::Result<()> {
    use reasonkit_core::thinktool::{ProtocolExecutor, ProtocolInput};

    println!();
    println!("  ReasonKit Demo");
    println!("  --------------");
    println!();

    match demo_type {
        DemoType::Reasoning | DemoType::All => {
            println!("  [Reasoning Demo]");
            println!();

            let executor = if mock {
                println!("  Using mock LLM (no API key required)");
                ProtocolExecutor::mock()?
            } else {
                ProtocolExecutor::new()?
            };

            let query = "Should a startup prioritize growth or profitability in year one?";
            println!("  Query: {}", query);
            println!();

            let input = ProtocolInput::query(query);
            let output = executor.execute_profile("quick", input).await?;

            println!("  Reasoning Chain:");
            for (i, step) in output.steps.iter().enumerate() {
                let text = step.as_text().unwrap_or("(no output)");
                // Truncate for demo
                let display: String = text.chars().take(200).collect();
                println!("    Step {}: {}...", i + 1, display);
            }
            println!();
            println!("  Confidence: {:.0}%", output.confidence * 100.0);
            println!();
        }
        DemoType::Memory => {
            #[cfg(feature = "mem")]
            {
                println!("  [Memory Demo]");
                println!("  (Memory operations require Qdrant - skipping live demo)");
                println!();
                println!("  Example commands:");
                println!("    rk mem search \"machine learning\"");
                println!("    rk mem ingest ./documents/");
                println!("    rk rag \"What is gradient descent?\"");
            }
            #[cfg(not(feature = "mem"))]
            {
                println!("  [Memory Demo]");
                println!("  Memory component not enabled.");
                println!("  Rebuild with: cargo install reasonkit --features mem");
            }
            println!();
        }
        DemoType::Web => {
            #[cfg(feature = "web")]
            {
                println!("  [Web Demo]");
                println!("  (Web operations require Chrome - skipping live demo)");
                println!();
                println!("  Example commands:");
                println!("    rk web capture https://example.com");
                println!("    rk web extract https://example.com --mode text");
            }
            #[cfg(not(feature = "web"))]
            {
                println!("  [Web Demo]");
                println!("  Web component not enabled.");
                println!("  Rebuild with: cargo install reasonkit --features web");
            }
            println!();
        }
        #[allow(unreachable_patterns)]
        _ => {}
    }

    if matches!(demo_type, DemoType::All) {
        // Recursively show other demos
        if !matches!(demo_type, DemoType::Memory) {
            Box::pin(handle_demo(DemoType::Memory, mock)).await?;
        }
        if !matches!(demo_type, DemoType::Web) {
            Box::pin(handle_demo(DemoType::Web, mock)).await?;
        }
    }

    println!("  Learn more: https://reasonkit.sh/docs");
    println!();

    Ok(())
}

#[cfg(not(feature = "core"))]
async fn handle_demo(_demo_type: DemoType, _mock: bool) -> anyhow::Result<()> {
    println!();
    println!("  ReasonKit Demo");
    println!("  --------------");
    println!();
    println!("  Demo requires the 'core' feature.");
    println!("  Rebuild with: cargo install reasonkit --features core");
    println!();
    Ok(())
}

// =============================================================================
// MAIN
// =============================================================================

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    setup_logging(cli.verbose);

    info!("ReasonKit v{}", reasonkit::VERSION);

    match cli.command {
        #[cfg(feature = "core")]
        Commands::Think {
            query,
            protocol,
            profile,
            provider,
            model,
            mock,
            list,
        } => {
            handle_think(
                query, protocol, profile, provider, model, mock, list, cli.format,
            )
            .await?;
        }

        #[cfg(feature = "core")]
        Commands::Verify { claim, sources } => {
            handle_verify(claim, sources).await?;
        }

        #[cfg(feature = "mem")]
        Commands::Mem { action } => {
            handle_mem(action, cli.format).await?;
        }

        #[cfg(feature = "mem")]
        Commands::Rag {
            query,
            top_k,
            hybrid,
        } => {
            handle_rag(query, top_k, hybrid).await?;
        }

        #[cfg(feature = "web")]
        Commands::Web { action } => {
            handle_web(action).await?;
        }

        #[cfg(feature = "org")]
        Commands::Task { args } => {
            let status = reasonkit_org::integration::taskwarrior::run(&args)?;
            if !status.success() {
                process::exit(exit_code(status));
            }
        }

        #[cfg(feature = "org")]
        Commands::Time { args } => {
            let status = reasonkit_org::integration::timewarrior::run(&args)?;
            if !status.success() {
                process::exit(exit_code(status));
            }
        }

        #[cfg(feature = "org")]
        Commands::Org { action } => match action {
            OrgAction::Doctor => {
                let report = reasonkit_org::integration::doctor::run()?;
                print!("{report}");
                if !report.ok() {
                    process::exit(1);
                }
            }
            OrgAction::Status => {
                let report = reasonkit_org::integration::status::run()?;
                print!("{report}");
                if !report.ok() {
                    process::exit(1);
                }
            }
        },

        #[cfg(feature = "org")]
        Commands::Job { action } => {
            handle_job(action)?;
        }

        Commands::Serve { host, port, mode } => {
            handle_serve(host, port, mode).await?;
        }

        Commands::Version => {
            handle_version(cli.format)?;
        }

        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            generate(shell, &mut cmd, "reasonkit", &mut std::io::stdout());
        }

        Commands::Init {
            non_interactive,
            force,
        } => {
            handle_init(non_interactive, force)?;
        }

        Commands::Status { detailed, output } => {
            handle_status(detailed, &output)?;
        }

        Commands::Demo { demo_type, mock } => {
            handle_demo(demo_type, mock).await?;
        }
    }

    Ok(())
}

#[cfg(feature = "org")]
fn exit_code(status: std::process::ExitStatus) -> i32 {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        status
            .code()
            .or_else(|| status.signal().map(|s| 128 + s))
            .unwrap_or(1)
    }

    #[cfg(not(unix))]
    {
        status.code().unwrap_or(1)
    }
}

#[cfg(feature = "org")]
fn handle_job(action: JobAction) -> anyhow::Result<()> {
    use anyhow::Context;
    use reasonkit_org::jtbd::{Job, JobStore, Outcome};
    use reasonkit_org::storage::Storage;
    use reasonkit_org::Uuid;

    let storage = Storage::new(Storage::default_location()?)?;
    let store = JobStore::open(storage.jobs_db().parent().context("invalid jobs db path")?)?;

    match action {
        JobAction::Add { statement } => {
            let job = Job::new(statement);
            store.add_job(&job)?;
            println!("Created job: {} - {}", job.uuid, job.statement);
        }
        JobAction::Outcome {
            job_id,
            description,
            outcome_type,
        } => {
            let job_uuid =
                Uuid::parse_str(&job_id).with_context(|| format!("invalid job id: {job_id}"))?;
            let outcome = match outcome_type.as_str() {
                "functional" => Outcome::functional(&description),
                "emotional" => Outcome::emotional(&description),
                "social" => Outcome::social(&description),
                other => {
                    anyhow::bail!("invalid outcome type: {other} (use functional|emotional|social)")
                }
            };
            store.add_outcome(job_uuid, &outcome)?;
            println!(
                "Added outcome to job {}: {:?} - {}",
                job_uuid, outcome.outcome_type, outcome.description
            );
        }
        JobAction::Link { job_id, tasks } => {
            let job_uuid =
                Uuid::parse_str(&job_id).with_context(|| format!("invalid job id: {job_id}"))?;

            let mut resolved = Vec::with_capacity(tasks.len());
            for selector in tasks {
                resolved.push(resolve_task_uuid(&selector)?);
            }

            for task_uuid in &resolved {
                store.link_task(job_uuid, *task_uuid)?;
            }

            println!("Linked {} tasks to job {}", resolved.len(), job_uuid);
        }
        JobAction::List => {
            let jobs = store.list_jobs()?;
            if jobs.is_empty() {
                println!("No jobs.");
                return Ok(());
            }

            println!("Jobs:");
            for job in jobs {
                println!(
                    "  - {} [{:?}] {:>3.0}% {}",
                    job.uuid,
                    job.status,
                    job.progress * 100.0,
                    job.statement
                );
            }
        }
        JobAction::Progress { job_id } => {
            let job_uuid =
                Uuid::parse_str(&job_id).with_context(|| format!("invalid job id: {job_id}"))?;
            let Some(job) = store.get_job(job_uuid)? else {
                anyhow::bail!("job not found: {job_uuid}");
            };

            println!(
                "Job {} [{:?}] {:>3.0}% {}",
                job.uuid,
                job.status,
                job.progress * 100.0,
                job.statement
            );

            if !job.outcomes.is_empty() {
                println!("Outcomes:");
                for outcome in &job.outcomes {
                    println!(
                        "  - [{}] {:?}: {}",
                        if outcome.achieved { "x" } else { " " },
                        outcome.outcome_type,
                        outcome.description
                    );
                }
            }

            if !job.tasks.is_empty() {
                println!("Linked tasks:");
                for task_uuid in &job.tasks {
                    println!("  - {}", task_uuid);
                }
            }
        }
    }

    Ok(())
}

#[cfg(feature = "org")]
fn resolve_task_uuid(selector: &str) -> anyhow::Result<reasonkit_org::Uuid> {
    use anyhow::Context;

    // 1) UUID form
    if let Ok(uuid) = reasonkit_org::Uuid::parse_str(selector) {
        return Ok(uuid);
    }

    // 2) Numeric Taskwarrior ID (resolved via `task <id> export`)
    let id: u32 = selector.parse().with_context(|| {
        format!("invalid task selector '{selector}' (expected uuid or numeric id)")
    })?;

    let task = reasonkit_org::integration::taskwarrior_export::export_by_id(id)?
        .ok_or_else(|| anyhow::anyhow!("task not found for id {}", id))?;

    Ok(task.uuid)
}