niuse 0.1.12

A personal engineering companion built on niucode
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
#![forbid(unsafe_code)]

mod bootstrap;
mod commands;
mod config;
mod digest;
mod driver;
mod evidence;
mod export;
mod memory_tool;
mod projects;
mod render;
mod repl;
mod settings;
#[cfg(feature = "tui")]
mod tui_hook;

use std::path::PathBuf;

use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand};
use niuse_core::Store;

#[derive(Parser, Debug)]
#[command(
    name = "niuse",
    version,
    about = "A personal engineering companion built on niucode"
)]
struct Cli {
    /// Provider preset (deepseek or openai); defaults from config
    #[arg(long, global = true)]
    preset: Option<String>,
    /// Override the preset model
    #[arg(long, global = true)]
    model: Option<String>,
    /// Disable DeepSeek thinking mode
    #[arg(long, global = true)]
    no_thinking: bool,
    /// Working directory (defaults to cwd); `/cd` changes it at runtime
    #[arg(long, global = true)]
    cwd: Option<PathBuf>,
    /// Sandbox: read-only, workspace-write, or full-access; defaults from config
    #[arg(long, global = true)]
    sandbox: Option<String>,
    /// Approval: ask, on-failure, or never; defaults from config
    #[arg(long, global = true)]
    approval: Option<String>,
    /// Network: on or off; defaults from config
    #[arg(long, global = true)]
    network: Option<String>,
    /// Override the niuse home (defaults to $NIUSE_HOME or ~/.niuse)
    #[arg(long, global = true)]
    home: Option<PathBuf>,
    /// Thread JSONL to resume (defaults to ~/.niuse/thread.jsonl)
    #[arg(long, global = true)]
    thread: Option<PathBuf>,
    /// Maximum model turns per user request (0 = no hard cap); defaults from config
    #[arg(long, global = true)]
    max_steps: Option<usize>,
    /// Start in read-only plan mode (read/grep/glob)
    #[arg(long, global = true)]
    plan: bool,
    /// Mount MCP servers whose manifest has read_only = false and write_tools
    #[arg(long, global = true)]
    allow_mcp_write: bool,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand, Debug, Clone)]
enum McpCommand {
    /// Write the bundled read-only packs and a trust manifest
    Init {
        /// Notes directory for the notes pack
        #[arg(long)]
        notes: Option<PathBuf>,
        /// iCalendar file for the calendar pack
        #[arg(long)]
        calendar: Option<PathBuf>,
        /// Manifest path (defaults to ~/.niucode/mcp.toml)
        #[arg(long)]
        config: Option<PathBuf>,
        /// Where to write the bundled server scripts (defaults to ~/.niuse/packs)
        #[arg(long)]
        packs: Option<PathBuf>,
        /// Replace an existing manifest (no merge)
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand, Debug, Clone)]
enum PlanCommand {
    /// List open steps (or all with --all)
    List {
        #[arg(long)]
        all: bool,
        #[arg(long)]
        json: bool,
    },
    /// Add one step
    Add { text: String },
    /// Close a step; requires a passing verification for p-N
    Done {
        id: u32,
        /// Thread containing the verification (defaults to the main thread)
        #[arg(long)]
        thread: Option<PathBuf>,
    },
}

#[derive(Subcommand, Debug, Clone)]
enum Command {
    /// Run one prompt through the agent, then exit
    Exec { prompt: String },
    /// Inspect and edit durable memory
    Mem {
        #[command(subcommand)]
        command: MemCommand,
    },
    /// Read-only weekly review across metrics, stores, and dogfood
    Report {
        /// Window in days
        #[arg(long, default_value_t = 7)]
        days: u64,
        /// Dogfood table (defaults to docs/dogfood.md when present)
        #[arg(long)]
        dogfood: Option<PathBuf>,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Record today's dogfood row from local metrics
    Dogfood {
        /// Markdown file with the dogfood table (defaults to ~/.niuse/dogfood.md)
        #[arg(long)]
        file: Option<PathBuf>,
        /// One concrete note for the day
        #[arg(long)]
        note: Option<String>,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Inspect and close open loops
    Loops {
        #[command(subcommand)]
        command: LoopsCommand,
    },
    /// Manage human-owned goals
    Goals {
        #[command(subcommand)]
        command: GoalsCommand,
    },
    /// Export a session log as Markdown
    Export {
        /// Write to a file instead of stdout
        #[arg(long)]
        out: Option<PathBuf>,
        /// Session JSONL to export (defaults to the main thread)
        #[arg(long)]
        session: Option<PathBuf>,
    },
    /// List the active thread and archived chapters
    Threads {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Experimental: run niucode's TUI with niuse hooks
    #[cfg(feature = "tui")]
    Tui {
        /// Replay normalized provider turns from a fixture JSON (testing)
        #[arg(long)]
        replay: Option<PathBuf>,
    },
    /// Generate shell completions
    Completions {
        /// Target shell
        shell: clap_complete::Shell,
    },
    /// List one-shot `exec` session logs
    Sessions {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Show or search the journal
    Journal {
        #[arg(long, default_value_t = 7)]
        days: usize,
        /// Search entries instead of listing recent days
        #[arg(long)]
        search: Option<String>,
        /// Append an entry to today instead of listing
        #[arg(long)]
        add: Option<String>,
        /// Emit JSON for show or search
        #[arg(long)]
        json: bool,
    },
    /// Create, show, or edit identity.md
    Identity {
        #[command(subcommand)]
        command: IdentityCommand,
    },
    /// Mine sessions for memory candidates or a user profile
    Bootstrap {
        /// Maximum number of sessions to scan
        #[arg(long, default_value_t = 40)]
        limit: usize,
        /// Only sessions modified within this many days
        #[arg(long, default_value_t = 90)]
        since_days: i64,
        /// List the sessions that would be scanned, without calling a model
        #[arg(long)]
        dry_run: bool,
        /// Also draft user.md from the selected sessions
        #[arg(long)]
        profile: bool,
        /// Overwrite an existing user.md when drafting
        #[arg(long)]
        force_profile: bool,
        /// Draft user.md only; skip memory candidates
        #[arg(long)]
        profile_only: bool,
    },
    /// Review bootstrapped candidates
    Review,
    /// Summarize the current thread into the journal
    Digest {
        /// Session JSONL to digest (defaults to the main thread)
        #[arg(long)]
        thread: Option<PathBuf>,
        /// Print the bullets without writing
        #[arg(long)]
        dry_run: bool,
        /// Maximum number of recent user/assistant messages to read
        #[arg(long, default_value_t = 40)]
        limit: usize,
    },
    /// Check local setup without calling a model
    Doctor {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Inspect or edit user.md
    User {
        #[command(subcommand)]
        command: UserCommand,
    },
    /// Inspect or create ~/.niuse/config.toml
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Show local acceptance counters
    Stats {
        /// Window in local calendar days; 0 means all time
        #[arg(long, default_value_t = 7)]
        days: u64,
        /// Add a per-day breakdown
        #[arg(long)]
        trend: bool,
        /// Emit JSON (summary plus per-day rows)
        #[arg(long)]
        json: bool,
    },
    /// Install read-only MCP packs and write a trust manifest
    Mcp {
        #[command(subcommand)]
        command: McpCommand,
    },
    /// Human-owned plan steps, with a verification gate for closing
    Plan {
        #[command(subcommand)]
        command: PlanCommand,
    },
    /// Run a verification command and append its result to the thread
    Verify {
        /// Thread JSONL to append to (defaults to the main thread)
        #[arg(long)]
        thread: Option<PathBuf>,
        /// Emit JSON
        #[arg(long)]
        json: bool,
        /// Plan step this check verifies, for example p-2
        #[arg(long)]
        step: Option<String>,
        /// Command and arguments, after `--`
        #[arg(last = true, required = true)]
        command: Vec<String>,
    },
    /// Show tool calls, files, checks, and failures from a thread
    Evidence {
        /// Thread JSONL to inspect (defaults to the main thread)
        #[arg(long)]
        thread: Option<PathBuf>,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Show what needs attention today
    Brief {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Search memory, journal, and loops
    Recall {
        /// Search terms
        query: String,
        /// Maximum number of hits
        #[arg(long, default_value_t = 20)]
        limit: usize,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// List recent niucode projects
    Projects {
        /// Maximum number to show
        #[arg(long, default_value_t = 10)]
        limit: usize,
        /// Include missing and temporary projects
        #[arg(long)]
        all: bool,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Show store and prompt status
    Status {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug, Clone)]
enum MemCommand {
    /// List memories
    List {
        /// Include expired entries
        #[arg(long)]
        all: bool,
        /// Emit JSON
        #[arg(long)]
        json: bool,
        /// Only preference or lesson
        #[arg(long)]
        kind: Option<String>,
        /// Only entries carrying this tag
        #[arg(long)]
        tag: Option<String>,
    },
    /// Add a memory directly
    Add {
        text: String,
        /// preference or lesson
        #[arg(long, default_value = "preference")]
        kind: String,
        #[arg(long, value_delimiter = ',')]
        tags: Vec<String>,
        /// Store even if the secret scan or duplicate check matches
        #[arg(long)]
        force: bool,
    },
    /// Search memories, including expired ones
    Search {
        query: String,
        /// Exclude expired entries
        #[arg(long)]
        fresh: bool,
        /// Emit JSON
        #[arg(long)]
        json: bool,
        /// Only preference or lesson
        #[arg(long)]
        kind: Option<String>,
        /// Only entries carrying this tag
        #[arg(long)]
        tag: Option<String>,
    },
    /// Show one memory in full
    Show {
        id: String,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Edit a memory in $EDITOR
    Edit { id: String },
    /// Delete a memory
    Forget { id: String },
    /// Refresh the confirmation date
    Confirm { id: String },
    /// Review stale memories interactively
    Review,
    /// Remove memories older than 90 days (dry run by default)
    Prune {
        /// Actually delete the expired entries
        #[arg(long)]
        apply: bool,
    },
}

#[derive(Subcommand, Debug, Clone)]
enum GoalsCommand {
    /// List goals
    List {
        /// Include completed goals
        #[arg(long)]
        all: bool,
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Add a goal manually
    Add { text: String },
    /// Complete a goal
    Done { id: String },
}

#[derive(Subcommand, Debug, Clone)]
enum LoopsCommand {
    /// List loops
    List {
        /// Include closed loops
        #[arg(long)]
        all: bool,
        /// Emit JSON
        #[arg(long)]
        json: bool,
        /// Only overdue loops
        #[arg(long)]
        overdue: bool,
    },
    /// Add a loop manually
    Add {
        text: String,
        /// Optional due date (YYYY-MM-DD)
        #[arg(long)]
        due: Option<String>,
    },
    /// Close a loop
    Done { id: String },
}

#[derive(Subcommand, Debug, Clone)]
enum UserCommand {
    /// Print user.md
    Show {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Edit user.md in $EDITOR
    Edit,
}

#[derive(Subcommand, Debug, Clone)]
enum ConfigCommand {
    /// Write a commented template
    Init {
        /// Overwrite an existing config
        #[arg(long)]
        force: bool,
    },
    /// Print the config file
    Show,
    /// Print the merged effective values
    Effective {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug, Clone)]
enum IdentityCommand {
    /// Answer eight questions and write identity.md
    Init {
        /// Overwrite an existing identity.md
        #[arg(long)]
        force: bool,
    },
    /// Print identity.md
    Show {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Edit identity.md in $EDITOR
    Edit,
}

/// Turn a closed stdout into a clean exit.
///
/// Rust ignores SIGPIPE, so `niuse ... | head` panics when the reader closes
/// early. Restoring SIGPIPE globally would also affect network writes; a panic
/// hook scoped to this one message is safer.
fn install_pipe_guard() {
    let default = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let broken = info
            .payload()
            .downcast_ref::<&str>()
            .is_some_and(|message| message.contains("Broken pipe"))
            || info
                .payload()
                .downcast_ref::<String>()
                .is_some_and(|message| message.contains("Broken pipe"));
        if broken {
            std::process::exit(0);
        }
        default(info);
    }));
}

#[tokio::main]
async fn main() -> Result<()> {
    install_pipe_guard();
    let cli = Cli::parse();
    let command = cli.command.clone();
    if let Some(Command::Completions { shell }) = &command {
        let mut command = Cli::command();
        clap_complete::generate(*shell, &mut command, "niuse", &mut std::io::stdout());
        return Ok(());
    }

    let store = match &cli.home {
        Some(path) => Store::at(path.clone()),
        None => Store::discover()?,
    };
    store.init()?;

    match command {
        #[cfg(feature = "tui")]
        Some(Command::Tui { replay }) => run_tui(&cli, &store, replay).await,
        Some(Command::Completions { .. }) => Ok(()),
        None => {
            let settings = settings::resolve(&cli, &store)?;
            let app = repl::App::new(&cli, &settings, store)?;
            app.run().await
        }
        Some(Command::Exec { prompt }) => {
            let settings = settings::resolve(&cli, &store)?;
            let app = repl::App::new(&cli, &settings, store)?;
            repl::run_exec(app, prompt).await
        }
        Some(Command::Mem { command }) => match command {
            MemCommand::List {
                all,
                json,
                kind,
                tag,
            } => commands::mem_list(&store, all, json, kind.as_deref(), tag.as_deref()),
            MemCommand::Add {
                text,
                kind,
                tags,
                force,
            } => commands::mem_add(&store, &text, &kind, tags, force),
            MemCommand::Search {
                query,
                fresh,
                json,
                kind,
                tag,
            } => commands::mem_search(&store, &query, fresh, json, kind.as_deref(), tag.as_deref()),
            MemCommand::Show { id, json } => commands::mem_show(&store, &id, json),
            MemCommand::Edit { id } => commands::mem_edit(&store, &id),
            MemCommand::Forget { id } => commands::mem_forget(&store, &id),
            MemCommand::Confirm { id } => commands::mem_confirm(&store, &id),
            MemCommand::Review => commands::mem_review(&store),
            MemCommand::Prune { apply } => commands::mem_prune(&store, apply),
        },
        Some(Command::Report {
            days,
            dogfood,
            json,
        }) => {
            let dogfood = dogfood.or_else(|| {
                let path = PathBuf::from("docs/dogfood.md");
                path.is_file().then_some(path)
            });
            commands::report(&store, days, dogfood, json)
        }
        Some(Command::Dogfood { file, note, json }) => commands::dogfood(&store, file, note, json),
        Some(Command::Loops { command }) => match command {
            LoopsCommand::List { all, json, overdue } => {
                commands::loops_list(&store, all, json, overdue)
            }
            LoopsCommand::Add { text, due } => commands::loops_add(&store, &text, due.as_deref()),
            LoopsCommand::Done { id } => commands::loops_done(&store, &id),
        },
        Some(Command::Goals { command }) => match command {
            GoalsCommand::List { all, json } => commands::goals_list(&store, all, json),
            GoalsCommand::Add { text } => commands::goals_add(&store, &text),
            GoalsCommand::Done { id } => commands::goals_done(&store, &id),
        },
        Some(Command::Sessions { json }) => commands::sessions(&store, json),
        Some(Command::Threads { json }) => {
            let active = config::resolve_thread(cli.thread.clone(), &store)?;
            commands::threads(&store, &active, json)
        }
        Some(Command::Export { out, session }) => {
            commands::export(&store, out.as_deref(), session.as_deref())
        }
        Some(Command::Journal {
            days,
            search,
            add,
            json,
        }) => {
            if let Some(text) = add {
                commands::journal_add(&store, &text)
            } else if let Some(query) = search {
                commands::journal_search(&store, &query, json)
            } else {
                commands::journal_show(&store, days, json)
            }
        }
        Some(Command::Identity { command }) => match command {
            IdentityCommand::Init { force } => commands::identity_init(&store, force),
            IdentityCommand::Show { json } => commands::identity_show(&store, json),
            IdentityCommand::Edit => commands::identity_edit(&store),
        },
        Some(Command::Bootstrap {
            limit,
            since_days,
            dry_run,
            profile,
            force_profile,
            profile_only,
        }) => {
            let settings = settings::resolve(&cli, &store)?;
            let app = repl::App::new(&cli, &settings, store)?;
            bootstrap::run(
                &app.store,
                app.provider.as_ref(),
                &app.model,
                bootstrap::BootstrapOptions {
                    limit,
                    since_days,
                    dry_run,
                    profile,
                    force_profile,
                    profile_only,
                },
            )
            .await
        }
        Some(Command::Review) => bootstrap::review(&store),
        Some(Command::Digest {
            thread,
            dry_run,
            limit,
        }) => {
            let settings = settings::resolve(&cli, &store)?;
            let thread = config::resolve_thread(thread.or(cli.thread.clone()), &store)?;
            let cwd = config::resolve_cwd(cli.cwd.clone())?;
            let project = cwd
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_else(|| "unknown".to_string());
            let app = repl::App::new(&cli, &settings, store)?;
            digest::run(
                &app.store,
                app.provider.as_ref(),
                &app.model,
                &thread,
                &project,
                digest::DigestOptions { dry_run, limit },
            )
            .await
        }
        Some(Command::Doctor { json }) => {
            let settings = settings::resolve(&cli, &store)?;
            commands::doctor(&store, &settings.provider, json)
        }
        Some(Command::User { command }) => match command {
            UserCommand::Show { json } => commands::user_show(&store, json),
            UserCommand::Edit => commands::user_edit(&store),
        },
        Some(Command::Config { command }) => match command {
            ConfigCommand::Init { force } => {
                if settings::init(&store, force)? {
                    println!("wrote {}", store.config_path().display());
                } else {
                    println!(
                        "{} already exists; pass --force to overwrite",
                        store.config_path().display()
                    );
                }
                Ok(())
            }
            ConfigCommand::Show => settings::show(&store),
            ConfigCommand::Effective { json } => {
                let settings = settings::resolve(&cli, &store)?;
                if json {
                    let payload = serde_json::json!({
                        "provider": settings.provider,
                        "model": settings.model,
                        "sandbox": settings.sandbox,
                        "approval": settings.approval,
                        "network": settings.network,
                        "max_steps": settings.max_steps,
                    });
                    println!("{}", serde_json::to_string_pretty(&payload)?);
                    return Ok(());
                }
                println!("provider    {}", settings.provider);
                println!(
                    "model       {}",
                    settings.model.as_deref().unwrap_or("(provider default)")
                );
                println!("sandbox     {}", settings.sandbox);
                println!("approval    {}", settings.approval);
                println!("network     {}", settings.network);
                println!(
                    "max_steps   {}",
                    if settings.max_steps == 0 {
                        "unlimited".to_string()
                    } else {
                        settings.max_steps.to_string()
                    }
                );
                Ok(())
            }
        },
        Some(Command::Stats { days, trend, json }) => commands::stats(&store, days, trend, json),
        Some(Command::Mcp { command }) => match command {
            McpCommand::Init {
                notes,
                calendar,
                config,
                packs,
                force,
            } => commands::mcp_init(
                &store,
                commands::McpInitOptions {
                    notes,
                    calendar,
                    config,
                    packs,
                    force,
                },
            ),
        },
        Some(Command::Plan { command }) => match command {
            PlanCommand::List { all, json } => commands::plan_list(&store, all, json),
            PlanCommand::Add { text } => {
                let step = commands::plan_add(&store, &text)?;
                println!("added {}", step.label());
                Ok(())
            }
            PlanCommand::Done { id, thread } => {
                let thread = config::resolve_thread(thread.or(cli.thread.clone()), &store)?;
                let step = commands::plan_done(&store, &thread, id)?;
                println!("done {}", step.label());
                Ok(())
            }
        },
        Some(Command::Verify {
            thread,
            json,
            step,
            command,
        }) => {
            let thread = config::resolve_thread(thread.or(cli.thread.clone()), &store)?;
            let outcome = commands::verify_with_step(&thread, &command, step.as_deref(), json)?;
            std::process::exit(outcome.code);
        }
        Some(Command::Evidence { thread, json }) => {
            let thread = config::resolve_thread(thread.or(cli.thread.clone()), &store)?;
            commands::evidence(&thread, &store, json)
        }
        Some(Command::Brief { json }) => {
            let cwd = config::resolve_cwd(cli.cwd.clone())?;
            commands::brief(&store, &cwd, json)
        }
        Some(Command::Recall { query, limit, json }) => {
            commands::recall(&store, &query, limit, json)
        }
        Some(Command::Projects { limit, all, json }) => commands::projects(limit, all, json),
        Some(Command::Status { json }) => {
            let thread = config::resolve_thread(cli.thread.clone(), &store)?;
            let cwd = config::resolve_cwd(cli.cwd.clone())?;
            commands::status(&store, &thread, &cwd, json)
        }
    }
}

#[cfg(feature = "tui")]
async fn run_tui(cli: &Cli, store: &Store, replay: Option<PathBuf>) -> Result<()> {
    let settings = settings::resolve(cli, store)?;
    let cwd = config::resolve_cwd(cli.cwd.clone())?;
    let (policy, approval, _) =
        config::resolve_policy(&settings.sandbox, &settings.approval, &settings.network)?;
    let model = settings
        .model
        .clone()
        .unwrap_or_else(|| "deepseek-flash".to_string());
    let thread = config::resolve_thread(cli.thread.clone(), store)?;
    let meta = driver::SessionMeta {
        cwd: &cwd,
        model: &model,
        provider: &settings.provider,
        policy,
        approval,
    };
    drop(driver::open_thread(&thread, &meta)?);

    let hooks =
        tui_hook::CompanionHooks::new_with_thread(store, thread.clone())?.with_cwd(cwd.clone());
    let options = niucode::TuiOptions {
        preset: settings.provider,
        model: Some(model),
        max_steps: settings.max_steps,
        no_thinking: cli.no_thinking,
        cwd: Some(cwd),
        session_dir: Some(store.root().to_path_buf()),
        resume: Some(thread),
        sandbox: settings.sandbox,
        approval: settings.approval,
        network: settings.network,
        replay,
        plan: cli.plan,
        approval_keys: niucode::ApprovalKeys::custom('y', 'n', 's')
            .expect("distinct approval keys"),
        extra_tools: memory_tool::tools(store.root().to_path_buf()),
        allow_mcp_write: cli.allow_mcp_write,
        ..niucode::TuiOptions::default()
    };
    niucode::run_tui_with_hooks(options, Box::new(hooks)).await
}

#[cfg(test)]
mod docs_tests {
    use super::*;
    use clap::CommandFactory;
    use std::collections::HashSet;

    const README: &str = include_str!("../../../README.md");

    #[test]
    fn readme_cli_examples_name_real_subcommands() {
        let mut known: HashSet<String> = Cli::command()
            .get_subcommands()
            .map(|command| command.get_name().to_string())
            .collect();
        // `tui` is feature-gated; the docs are still correct for that build.
        known.insert("tui".to_string());
        let mut checked = 0;
        let mut fenced = false;
        for line in README.lines() {
            let line = line.trim();
            if line.starts_with("```") {
                fenced = !fenced;
                continue;
            }
            if !fenced {
                continue;
            }
            let Some(rest) = line.strip_prefix("niuse ") else {
                continue;
            };
            if rest.starts_with(char::is_whitespace) {
                continue;
            }
            let Some(first) = rest.split_whitespace().next() else {
                continue;
            };
            if first.starts_with('-') || first.starts_with('#') {
                continue;
            }
            assert!(
                known.contains(first),
                "README example `niuse {first}` is not a subcommand; known: {known:?}"
            );
            checked += 1;
        }
        assert!(
            checked >= 10,
            "expected the README command table, saw {checked}"
        );
    }

    #[test]
    fn readme_cli_flags_exist_on_the_documented_command() {
        let root = Cli::command();
        let mut checked = 0;
        let mut fenced = false;
        for line in README.lines() {
            let line = line.trim();
            if line.starts_with("```") {
                fenced = !fenced;
                continue;
            }
            if !fenced {
                continue;
            }
            let Some(rest) = line.strip_prefix("niuse ") else {
                continue;
            };
            if rest.starts_with(char::is_whitespace) {
                continue;
            }
            let tokens: Vec<&str> = rest.split_whitespace().collect();
            let Some(first) = tokens.first() else {
                continue;
            };
            if first.starts_with('-') || first.starts_with('#') || *first == "tui" {
                continue;
            }
            let Some(command) = root.find_subcommand(first).cloned() else {
                continue;
            };
            let mut commands = vec![command.clone()];
            commands.extend(command.get_subcommands().cloned());
            let mut valid: HashSet<String> = commands
                .iter()
                .flat_map(|command| command.get_arguments())
                .filter_map(|argument| argument.get_long().map(ToString::to_string))
                .collect();
            valid.extend(
                root.get_arguments()
                    .filter_map(|argument| argument.get_long().map(ToString::to_string)),
            );
            for flag in flags_in(line) {
                if flag == "help" || flag == "version" {
                    continue;
                }
                assert!(
                    valid.contains(&flag),
                    "README flag `--{flag}` is not valid for `niuse {first}`; valid: {valid:?}"
                );
                checked += 1;
            }
        }
        assert!(checked >= 5, "expected documented flags, saw {checked}");
    }

    fn flags_in(line: &str) -> Vec<String> {
        let mut flags = Vec::new();
        let mut chars = line.chars().peekable();
        while let Some(character) = chars.next() {
            if character != '-' || chars.peek() != Some(&'-') {
                continue;
            }
            chars.next();
            let mut flag = String::new();
            while let Some(next) = chars.peek().copied() {
                if next.is_ascii_alphanumeric() || next == '-' {
                    flag.push(next);
                    chars.next();
                } else {
                    break;
                }
            }
            if !flag.is_empty() {
                flags.push(flag);
            }
        }
        flags
    }

    #[test]
    fn readme_repl_commands_are_registered() {
        let line = README
            .lines()
            .find(|line| line.starts_with("Inside the REPL:"))
            .expect("README has an inside-the-REPL line");
        let mut checked = 0;
        for token in line.split('`') {
            let Some(command) = token.split_whitespace().next() else {
                continue;
            };
            if !command.starts_with('/') {
                continue;
            }
            assert!(
                repl::SLASH_COMMANDS.contains(&command),
                "README REPL command {command} is not registered"
            );
            checked += 1;
        }
        assert!(checked >= 10, "expected REPL commands, saw {checked}");
    }
}