niuse 0.1.8

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
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
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
//! Interactive REPL and one-shot execution.

use std::collections::HashSet;
use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use anyhow::{bail, Context, Result};
use niucode_agent::ApprovalMode;
use niucode_core::{load, Event};
use niucode_provider::Provider;
use niucode_tools::SandboxPolicy;
use niuse_core::policy::{conflicts, secret_reason};
use niuse_core::prompt::compose;
use niuse_core::{Block, Date, LoopItem, MemoryEntry, MemoryKind, Store};
use rustyline::completion::{Completer, Pair};
use rustyline::config::Config;
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::history::FileHistory;
use rustyline::validate::{ValidationContext, ValidationResult, Validator};
use rustyline::{Context as RlContext, Editor, Helper};

const SLASH_COMMANDS: &[&str] = &[
    "/help",
    "/quit",
    "/exit",
    "/mem",
    "/mem recall",
    "/mem show",
    "/mem review",
    "/remember",
    "/forget",
    "/loops",
    "/loop",
    "/done",
    "/journal",
    "/journal search",
    "/journal add",
    "/stats",
    "/doctor",
    "/identity",
    "/identity edit",
    "/user",
    "/user edit",
    "/export",
    "/threads",
    "/sessions",
    "/resume",
    "/new",
    "/cd",
    "/status",
    "/prompt",
    "/model",
    "/cost",
];

fn slash_candidates(prefix: &str) -> Vec<&'static str> {
    if !prefix.starts_with('/') || prefix.ends_with(' ') {
        return Vec::new();
    }
    let mut matches: Vec<&'static str> = SLASH_COMMANDS
        .iter()
        .copied()
        .filter(|command| command.starts_with(prefix))
        .collect();
    matches.sort_by_key(|command| command.len());
    matches
}

#[derive(Clone, Copy)]
enum IdScope {
    Memory,
    Loop,
}

/// Where an id completion starts, the fragment typed so far, and which store.
fn id_query(line: &str) -> Option<(usize, &str, IdScope)> {
    if let Some(rest) = line.strip_prefix("/mem ") {
        let (sub, fragment) = rest.split_once(' ')?;
        let scope = match sub {
            "show" | "edit" | "confirm" | "forget" => IdScope::Memory,
            _ => return None,
        };
        return Some((line.len() - fragment.len(), fragment, scope));
    }
    for (command, scope) in [("/forget ", IdScope::Memory), ("/done ", IdScope::Loop)] {
        if let Some(fragment) = line.strip_prefix(command) {
            if !fragment.contains(' ') {
                return Some((command.len(), fragment, scope));
            }
        }
    }
    None
}

fn id_candidates(store: &Store, scope: IdScope, fragment: &str) -> Vec<Pair> {
    let (prefix, fragment) = match scope {
        IdScope::Memory => match fragment.strip_prefix("m-") {
            Some(rest) => ("m-", rest),
            None => ("", fragment),
        },
        IdScope::Loop => ("", fragment),
    };
    let items: Vec<(String, String)> = match scope {
        IdScope::Memory => store
            .memories()
            .unwrap_or_default()
            .into_iter()
            .map(|entry| (entry.id, entry.text))
            .collect(),
        IdScope::Loop => store
            .loops()
            .unwrap_or_default()
            .into_iter()
            .filter(|item| !item.done)
            .map(|item| (format!("l-{}", item.id), item.text))
            .collect(),
    };
    let mut matches: Vec<Pair> = items
        .into_iter()
        .filter(|(id, _)| id.starts_with(fragment))
        .map(|(id, text)| Pair {
            display: format!(
                "{prefix}{id}  {}",
                text.chars().take(50).collect::<String>()
            ),
            replacement: format!("{prefix}{id}"),
        })
        .collect();
    matches.sort_by(|left, right| left.replacement.cmp(&right.replacement));
    matches
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PathScope {
    Directory,
    Any,
}

fn path_query(line: &str) -> Option<(usize, &str, PathScope)> {
    if let Some(fragment) = line.strip_prefix("/cd ") {
        return Some(("/cd ".len(), fragment, PathScope::Directory));
    }
    if let Some(fragment) = line.strip_prefix("/export ") {
        return Some(("/export ".len(), fragment, PathScope::Any));
    }
    None
}

fn path_candidates(fragment: &str, cwd: &Path, scope: PathScope) -> Vec<Pair> {
    if fragment == "~" || fragment == "." || fragment == ".." {
        let completed = format!("{fragment}/");
        return vec![Pair {
            display: completed.clone(),
            replacement: completed,
        }];
    }
    let (dir_prefix, name_prefix) = match fragment.rfind('/') {
        Some(index) => (&fragment[..=index], &fragment[index + 1..]),
        None => ("", fragment),
    };
    let base = if let Some(rest) = dir_prefix.strip_prefix("~/") {
        match std::env::var_os("HOME") {
            Some(home) => PathBuf::from(home).join(rest),
            None => return Vec::new(),
        }
    } else if dir_prefix.starts_with('/') {
        PathBuf::from(dir_prefix)
    } else if dir_prefix.is_empty() {
        cwd.to_path_buf()
    } else {
        cwd.join(dir_prefix)
    };

    let entries = match fs::read_dir(&base) {
        Ok(entries) => entries,
        Err(_) => return Vec::new(),
    };
    let mut matches = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if !name.starts_with(name_prefix) {
            continue;
        }
        if name.starts_with('.') && !name_prefix.starts_with('.') {
            continue;
        }
        let is_dir = entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false);
        if scope == PathScope::Directory && !is_dir {
            continue;
        }
        let mut replacement = format!("{dir_prefix}{name}");
        if is_dir {
            replacement.push('/');
        }
        matches.push(Pair {
            display: replacement.clone(),
            replacement,
        });
    }
    matches.sort_by(|left, right| left.replacement.cmp(&right.replacement));
    matches
}

struct SlashCompleter {
    root: PathBuf,
    cwd: Arc<Mutex<PathBuf>>,
}

impl Completer for SlashCompleter {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &RlContext<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        let typed = &line[..pos];
        if let Some((start, fragment, scope)) = path_query(typed) {
            let cwd = self
                .cwd
                .lock()
                .map(|guard| guard.clone())
                .unwrap_or_else(|poisoned| poisoned.into_inner().clone());
            return Ok((start, path_candidates(fragment, &cwd, scope)));
        }
        if let Some((start, fragment, scope)) = id_query(typed) {
            let store = Store::at(self.root.clone());
            return Ok((start, id_candidates(&store, scope, fragment)));
        }
        let candidates = slash_candidates(typed)
            .into_iter()
            .map(|command| Pair {
                display: command.to_string(),
                replacement: format!("{command} "),
            })
            .collect();
        Ok((0, candidates))
    }
}

impl Hinter for SlashCompleter {
    type Hint = String;
}

impl Highlighter for SlashCompleter {}

impl Validator for SlashCompleter {
    fn validate(&self, ctx: &mut ValidationContext) -> rustyline::Result<ValidationResult> {
        if ctx
            .input()
            .lines()
            .last()
            .is_some_and(|line| line.ends_with('\\'))
        {
            Ok(ValidationResult::Incomplete)
        } else {
            Ok(ValidationResult::Valid(None))
        }
    }
}

impl Helper for SlashCompleter {}

use crate::commands;
use crate::config::{build_provider, resolve_cwd, resolve_policy, resolve_thread};
use crate::driver::{self, SessionMeta, Thread};
use crate::render::{self, Renderer};
use crate::settings::Settings;
use crate::Cli;

pub struct App {
    pub store: Store,
    pub provider: Arc<dyn Provider>,
    pub provider_id: String,
    pub model: String,
    no_thinking: bool,
    pub policy: SandboxPolicy,
    pub approval: ApprovalMode,
    pub allow_unsandboxed: bool,
    pub cwd: PathBuf,
    completion_cwd: Arc<Mutex<PathBuf>>,
    pub max_steps: usize,
    pub prompt: String,
    pub prompt_tokens: usize,
    pub thread_path: PathBuf,
    memory_enabled: bool,
    suppress_candidates: bool,
    rejected_tags: HashSet<String>,
}

impl App {
    pub fn new(cli: &Cli, settings: &Settings, store: Store) -> Result<Self> {
        let bundle = build_provider(
            &settings.provider,
            settings.model.as_deref(),
            cli.no_thinking,
        )?;
        let (policy, approval, allow_unsandboxed) =
            resolve_policy(&settings.sandbox, &settings.approval, &settings.network)?;
        let cwd = resolve_cwd(cli.cwd.clone())?;
        let completion_cwd = Arc::new(Mutex::new(cwd.clone()));
        let memory_enabled = std::env::var("NIUSE_MEMORY")
            .map(|value| value.trim().to_lowercase() != "off")
            .unwrap_or(true);

        let thread_path = resolve_thread(cli.thread.clone(), &store)?;

        let mut app = Self {
            store,
            provider: bundle.provider,
            provider_id: bundle.provider_id,
            model: bundle.model,
            no_thinking: cli.no_thinking,
            policy,
            approval,
            allow_unsandboxed,
            cwd,
            completion_cwd,
            max_steps: settings.max_steps,
            prompt: String::new(),
            prompt_tokens: 0,
            thread_path,
            memory_enabled,
            suppress_candidates: false,
            rejected_tags: HashSet::new(),
        };
        app.rebuild_prompt()?;
        Ok(app)
    }

    pub fn rebuild_prompt(&mut self) -> Result<()> {
        let today = Date::today();
        let identity = self.store.identity()?;
        let user = self.store.user()?;
        let memories = if self.memory_enabled {
            self.store.memories()?
        } else {
            Vec::new()
        };
        let loops = self.store.loops()?;
        let journal = self.store.recent_journal(3)?;
        let composition = compose(
            identity.as_deref(),
            user.as_deref(),
            &memories,
            &loops,
            &journal,
            today,
        );
        self.prompt = composition.system;
        self.prompt_tokens = composition.tokens;
        Ok(())
    }

    pub async fn run(mut self) -> Result<()> {
        let path = self.thread_path.clone();
        let meta = SessionMeta {
            cwd: &self.cwd,
            model: &self.model,
            provider: &self.provider_id,
            policy: self.policy,
            approval: self.approval,
        };
        let mut thread = driver::open_thread(&path, &meta)?;
        let mut history = driver::history(&thread.path)?;
        self.banner();

        let history_path = self.store.history_path();
        let mut editor = if io::stdin().is_terminal() {
            match Editor::<SlashCompleter, FileHistory>::with_config(Config::default()) {
                Ok(mut editor) => {
                    editor.set_helper(Some(SlashCompleter {
                        root: self.store.root().to_path_buf(),
                        cwd: self.completion_cwd.clone(),
                    }));
                    if history_path.exists() {
                        if let Err(error) = editor.load_history(&history_path) {
                            eprintln!("warning: cannot load history: {error}");
                        }
                    }
                    Some(editor)
                }
                Err(error) => {
                    eprintln!("warning: line editing unavailable: {error}");
                    None
                }
            }
        } else {
            None
        };

        loop {
            let prompt = format!("\n{}", self.prompt_label());
            let line = match editor.as_mut() {
                Some(editor) => match editor.readline(&prompt) {
                    Ok(line) => {
                        let line = join_continuations(&line);
                        let _ = editor.add_history_entry(line.as_str());
                        line
                    }
                    Err(ReadlineError::Interrupted) => {
                        println!("^C");
                        continue;
                    }
                    Err(ReadlineError::Eof) => {
                        println!();
                        break;
                    }
                    Err(error) => {
                        eprintln!("input error: {error}");
                        break;
                    }
                },
                None => {
                    print!("{prompt}");
                    let _ = io::stdout().flush();
                    let Some(line) = render::read_line() else {
                        println!();
                        break;
                    };
                    line
                }
            };
            let input = line.trim();
            if input.is_empty() {
                continue;
            }
            if let Some(argument) = input.strip_prefix("/resume ") {
                let Some(index) = parse_resume_index(argument) else {
                    println!("用法:/resume <n>,编号见 /threads");
                    continue;
                };
                let Some(path) = commands::thread_at(&self.store, &thread.path, index)? else {
                    println!("没有第 {index} 条主线;先看 /threads。");
                    continue;
                };
                if path == thread.path {
                    println!("当前就是第 {index} 条。");
                    continue;
                }
                let meta = SessionMeta {
                    cwd: &self.cwd,
                    model: &self.model,
                    provider: &self.provider_id,
                    policy: self.policy,
                    approval: self.approval,
                };
                match driver::open_thread(&path, &meta) {
                    Ok(resumed) => {
                        driver::append_end(&thread.log)?;
                        thread = resumed;
                        history = driver::history(&thread.path)?;
                        println!("resumed {}", thread.path.display());
                    }
                    Err(error) => eprintln!("cannot resume {}: {error:#}", path.display()),
                }
                continue;
            }
            if input == "/new" {
                driver::append_end(&thread.log)?;
                if let Some(archived) =
                    driver::archive_thread(&thread.path, &self.store.threads_dir())?
                {
                    println!("archived {}", archived.display());
                }
                let active_path = self.store.session_path();
                if thread.path != active_path {
                    if let Some(archived) =
                        driver::archive_thread(&active_path, &self.store.threads_dir())?
                    {
                        println!("archived stale active {}", archived.display());
                    }
                }
                thread = {
                    let meta = SessionMeta {
                        cwd: &self.cwd,
                        model: &self.model,
                        provider: &self.provider_id,
                        policy: self.policy,
                        approval: self.approval,
                    };
                    driver::open_thread(&active_path, &meta)?
                };
                history.clear();
                self.rebuild_prompt()?;
                println!("new thread {}", thread.path.display());
                continue;
            }
            if input.starts_with('/') {
                match self.command(input, &thread) {
                    Ok(Flow::Quit) => break,
                    Ok(Flow::Continue) => {}
                    Err(error) => eprintln!("error: {error:#}"),
                }
                continue;
            }

            let config = driver::agent_config(
                &self.provider_id,
                &self.model,
                &self.cwd,
                self.prompt.clone(),
                self.policy,
                self.approval,
                self.allow_unsandboxed,
                self.max_steps,
            );
            let mut renderer = Renderer::new();
            let result = driver::run_turn(
                self.provider.as_ref(),
                &mut thread.log,
                &config,
                input,
                history,
                &mut renderer,
            )
            .await;
            let parsed = renderer.finish();
            let usage = renderer.usage();
            if usage.input + usage.output + usage.cached > 0 {
                self.metric(
                    "tokens",
                    &format!("{},{},{}", usage.input, usage.output, usage.cached),
                );
            }
            match result {
                Ok(Some(_)) => {
                    self.metric("turn", "ok");
                    let source = thread.log.id().to_string();
                    self.handle_blocks(parsed.blocks, &source)?;
                }
                Ok(None) => {
                    self.metric("turn", "cancelled");
                    println!("[cancelled]");
                }
                Err(error) => {
                    self.metric("turn", "error");
                    eprintln!("error: {error:#}");
                }
            }
            history = match driver::history(&thread.path) {
                Ok(history) => history,
                Err(error) => {
                    eprintln!("warning: cannot reload session history: {error:#}");
                    Vec::new()
                }
            };
        }

        driver::append_end(&thread.log)?;
        if let Some(mut editor) = editor {
            if let Err(error) = editor.save_history(&history_path) {
                eprintln!("warning: cannot save history: {error}");
            }
            secure_history(&history_path);
        }
        Ok(())
    }

    fn banner(&self) {
        let today = Date::today();
        let memories = self.store.memories().unwrap_or_default();
        let stale = memories
            .iter()
            .filter(|entry| entry.is_stale(today) && !entry.is_expired(today))
            .count();
        let open = self
            .store
            .loops()
            .unwrap_or_default()
            .iter()
            .filter(|item| !item.done)
            .count();

        println!(
            "niuse · {} · {} / {}",
            self.model,
            self.policy.mode.as_str(),
            self.approval.as_str()
        );
        println!(
            "{} 条记忆({} 条待验证)· {} 条未完成承诺 · prompt ~{} tokens",
            memories.len(),
            stale,
            open,
            self.prompt_tokens
        );
        println!("/help 查看命令 · Ctrl-C 取消当前 turn · Ctrl-D 退出");
        if !self.memory_enabled {
            println!("NIUSE_MEMORY=off:本次 session 不注入记忆,也不提议新记忆。");
        }
        if self.store.identity().unwrap_or(None).is_none() {
            println!("提示:还没有 identity.md,运行 `niuse identity init` 定义它是谁。");
        }
    }

    fn prompt_label(&self) -> String {
        let name = self
            .cwd
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_else(|| self.cwd.display().to_string());
        format!("{name} › ")
    }

    fn command(&mut self, input: &str, thread: &Thread) -> Result<Flow> {
        let (command, argument) = input.split_once(' ').unwrap_or((input, ""));
        let argument = argument.trim();

        match command {
            "/help" => print_help(),
            "/quit" | "/exit" => return Ok(Flow::Quit),
            "/mem" => {
                if argument == "review" {
                    commands::mem_review(&self.store)?;
                } else if let Some(query) = argument.strip_prefix("recall ") {
                    commands::mem_search(&self.store, query.trim(), false, false, None, None)?;
                } else if let Some(id) = argument.strip_prefix("show ") {
                    commands::mem_show(&self.store, id.trim(), false)?;
                } else {
                    commands::mem_list(&self.store, false, false, None, None)?;
                }
            }
            "/remember" => {
                if argument.is_empty() {
                    println!("用法:/remember <一句话>");
                } else if let Some(reason) = secret_reason(argument) {
                    println!("拒绝:疑似包含 {reason}。");
                } else {
                    let entry = self.store.add_memory(MemoryEntry::new(
                        MemoryKind::Preference,
                        argument,
                        Vec::new(),
                        Date::today(),
                        Some(thread.log.id().to_string()),
                    ))?;
                    self.metric("remember", &entry.id);
                    println!("已记住 m-{}(下一个 session 生效)", entry.id);
                }
            }
            "/forget" => {
                if argument.is_empty() {
                    println!("用法:/forget <id>");
                } else {
                    commands::mem_forget(&self.store, argument)?;
                    self.metric("forget", argument);
                }
            }
            "/threads" => commands::threads(&self.store, &thread.path, false)?,
            "/sessions" => commands::sessions(&self.store, false)?,
            "/export" => {
                let path = export_path(&self.store, &thread.path, argument, &self.cwd);
                commands::export(&self.store, Some(&path), Some(&thread.path))?;
            }
            "/journal" => {
                if let Some(query) = argument.strip_prefix("search ") {
                    commands::journal_search(&self.store, query.trim(), false)?;
                } else if let Some(text) = argument.strip_prefix("add ") {
                    commands::journal_add(&self.store, text.trim())?;
                } else {
                    commands::journal_show(&self.store, 7, false)?;
                }
            }
            "/stats" => commands::stats(&self.store, 7, false, false)?,
            "/doctor" => {
                if let Err(error) = commands::doctor(&self.store, &self.provider_id, false) {
                    println!("{error}");
                }
            }
            "/loops" => commands::loops_list(&self.store, false, false, false)?,
            "/loop" => {
                if argument.is_empty() {
                    println!("用法:/loop <一件你答应要做的事>");
                } else if let Some(reason) = secret_reason(argument) {
                    println!("拒绝:疑似包含 {reason}。");
                } else {
                    let item = self.store.add_loop(LoopItem::new(argument, None))?;
                    self.metric("loop", &item.id);
                    println!("承诺已记录 l-{}", item.id);
                }
            }
            "/done" => {
                if argument.is_empty() {
                    println!("用法:/done <l-id>");
                } else {
                    commands::loops_done(&self.store, argument)?;
                }
            }
            "/cd" => {
                if argument.is_empty() {
                    println!("cwd: {}", self.cwd.display());
                } else {
                    let path = expand_tilde(argument);
                    let path = if path.is_absolute() {
                        path
                    } else {
                        self.cwd.join(path)
                    };
                    let path = path
                        .canonicalize()
                        .with_context(|| format!("resolve {}", path.display()))?;
                    if !path.is_dir() {
                        bail!("{} is not a directory", path.display());
                    }
                    self.cwd = path;
                    if let Ok(mut guard) = self.completion_cwd.lock() {
                        *guard = self.cwd.clone();
                    }
                    println!("cwd: {}", self.cwd.display());
                }
            }
            "/cost" => {
                let totals = usage_totals(&load(&thread.path)?.events);
                let mut line = format!(
                    "session: {} turn{} · {} in · {} out",
                    totals.turns,
                    if totals.turns == 1 { "" } else { "s" },
                    render::compact_tokens(totals.input),
                    render::compact_tokens(totals.output)
                );
                if totals.cached > 0 {
                    line.push_str(&format!(
                        " · {} cached",
                        render::compact_tokens(totals.cached)
                    ));
                }
                println!("{line}");
            }
            "/model" => {
                if argument.is_empty() {
                    println!("model: {} · provider {}", self.model, self.provider_id);
                } else {
                    match build_provider(
                        &self.provider_id,
                        model_override(argument),
                        self.no_thinking,
                    ) {
                        Ok(bundle) => {
                            self.provider = bundle.provider;
                            self.model = bundle.model;
                            println!("model: {}", self.model);
                        }
                        Err(error) => eprintln!("cannot switch model: {error:#}"),
                    }
                }
            }
            "/status" => {
                commands::status(&self.store, &thread.path, false)?;
                let events = load(&thread.path)
                    .map(|loaded| loaded.events.len())
                    .unwrap_or(0);
                println!("provider  {} / {}", self.provider_id, self.model);
                println!(
                    "sandbox   {} / approval {} / network {}",
                    self.policy.mode.as_str(),
                    self.approval.as_str(),
                    self.policy.network.as_str()
                );
                println!("cwd       {}", self.cwd.display());
                println!("session   {} events", events);
            }
            "/user" => {
                if argument == "edit" {
                    commands::user_edit(&self.store)?;
                } else {
                    commands::user_show(&self.store, false)?;
                }
            }
            "/identity" => {
                if argument == "edit" {
                    commands::identity_edit(&self.store)?;
                } else {
                    commands::identity_show(&self.store, false)?;
                }
            }
            "/prompt" => println!("{}", self.prompt),
            other => println!("未知命令 {other};/help 查看可用命令。"),
        }
        Ok(Flow::Continue)
    }

    fn handle_blocks(&mut self, blocks: Vec<Block>, source: &str) -> Result<()> {
        let today = Date::today();
        if !self.memory_enabled {
            // Journal and loops still record the session; memory candidates are
            // suppressed so an A/B run cannot change the store.
            for block in blocks {
                match block {
                    Block::Journal { bullets } => {
                        if self.store.append_journal(today, &bullets)? {
                            self.metric("journal", &bullets.len().to_string());
                        }
                    }
                    Block::Loop { due, text } => {
                        let item = self.store.add_loop(LoopItem::new(text, due))?;
                        self.metric("loop", &item.id);
                    }
                    Block::Memory { .. } => {}
                }
            }
            return Ok(());
        }
        let mut offered_memory = false;

        for block in blocks {
            match block {
                Block::Journal { bullets } => {
                    if self.store.append_journal(today, &bullets)? {
                        self.metric("journal", &bullets.len().to_string());
                        println!("journal +{}", bullets.len());
                    }
                }
                Block::Loop { due, text } => {
                    let item = self.store.add_loop(LoopItem::new(text, due))?;
                    self.metric("loop", &item.id);
                    println!("承诺已记录 l-{}", item.id);
                }
                Block::Memory { kind, tags, text } => {
                    if offered_memory || self.suppress_candidates {
                        continue;
                    }
                    offered_memory = true;
                    self.offer_memory(kind, tags, text, source)?;
                }
            }
        }
        Ok(())
    }

    fn suppress_rejected(&mut self, tags: &[String]) -> bool {
        if suppressed_by_tag(tags, &self.rejected_tags) {
            println!("候选含本 session 已拒绝的 tag,跳过。");
            self.metric("suppress", &tags.join(","));
            return true;
        }
        false
    }

    fn remember_rejected(&mut self, tags: &[String]) {
        for tag in tags {
            self.rejected_tags.insert(tag.to_lowercase());
        }
    }

    fn offer_memory(
        &mut self,
        kind: MemoryKind,
        tags: Vec<String>,
        text: String,
        source: &str,
    ) -> Result<()> {
        if self.suppress_rejected(&tags) {
            return Ok(());
        }
        if let Some(reason) = secret_reason(&text) {
            self.metric("blocked", reason);
            println!("\n[记忆候选被拒绝] 疑似包含 {reason},没有写入。");
            return Ok(());
        }

        let existing = self.store.memories()?;
        let conflicts: Vec<&MemoryEntry> = existing
            .iter()
            .filter(|entry| conflicts(&entry.text, &entry.tags, &text, &tags))
            .collect();

        let tag_label = if tags.is_empty() {
            String::new()
        } else {
            format!(" · {}", tags.join(", "))
        };
        println!("\n记忆候选 [{}{tag_label}]", kind.as_str());
        println!("  {text}");
        self.metric("propose", &tags.join(","));

        if conflicts.is_empty() {
            print!("[y] 接受  [n] 丢弃  [e] 编辑  [s] 本次 session 不再提议 > ");
            let _ = io::stdout().flush();
            match render::read_line()
                .unwrap_or_default()
                .trim()
                .to_lowercase()
                .as_str()
            {
                "y" | "yes" => {
                    let entry = self.save_memory(kind, text, tags, source)?;
                    self.metric("accept", &entry.id);
                    println!("已记住 m-{}", entry.id);
                }
                "e" | "edit" => {
                    if let Some(edited) = commands::edit_text(&text) {
                        if let Some(reason) = secret_reason(&edited) {
                            println!("拒绝:疑似包含 {reason}。");
                        } else {
                            let entry = self.save_memory(kind, edited, tags, source)?;
                            self.metric("accept", &entry.id);
                            self.metric("edit", &entry.id);
                            println!("已记住 m-{}", entry.id);
                        }
                    } else {
                        println!("未修改,已丢弃。");
                    }
                }
                "s" | "stop" => {
                    self.suppress_candidates = true;
                    self.metric("suppress", "");
                    println!("本次 session 不再提议。");
                }
                _ => {
                    self.remember_rejected(&tags);
                    self.metric("discard", &tags.join(","));
                    println!("已丢弃。");
                }
            }
            return Ok(());
        }

        for old in &conflicts {
            println!("  旧 m-{}:{}", old.id, old.text);
        }
        print!("[r] 替换  [k] 并存  [d] 丢弃 > ");
        let _ = io::stdout().flush();
        match render::read_line()
            .unwrap_or_default()
            .trim()
            .to_lowercase()
            .as_str()
        {
            "r" | "replace" => {
                if let Some(old) = conflicts.first() {
                    self.store.remove_memory(&old.id)?;
                }
                let entry = self.save_memory(kind, text, tags, source)?;
                self.metric("accept", &format!("replace:{}", entry.id));
                println!("已替换,新 id m-{}", entry.id);
            }
            "k" | "keep" => {
                let entry = self.save_memory(kind, text, tags, source)?;
                self.metric("accept", &format!("keep:{}", entry.id));
                println!("已并存,新 id m-{}", entry.id);
            }
            _ => {
                self.remember_rejected(&tags);
                self.metric("discard", "conflict");
                println!("已丢弃。");
            }
        }
        Ok(())
    }

    fn metric(&self, kind: &str, detail: &str) {
        if let Err(error) = self.store.append_metric(kind, detail) {
            eprintln!("warning: cannot record metric: {error:#}");
        }
    }

    fn save_memory(
        &self,
        kind: MemoryKind,
        text: String,
        tags: Vec<String>,
        source: &str,
    ) -> Result<MemoryEntry> {
        let entry = MemoryEntry::new(kind, text, tags, Date::today(), Some(source.to_string()));
        self.store.add_memory(entry)
    }
}

enum Flow {
    Continue,
    Quit,
}

pub async fn run_exec(app: App, prompt: String) -> Result<()> {
    let log = driver::new_session(&app.store.root().join("sessions"))?;
    let meta = SessionMeta {
        cwd: &app.cwd,
        model: &app.model,
        provider: &app.provider_id,
        policy: app.policy,
        approval: app.approval,
    };
    driver::append_start(&log, &meta)?;

    let config = driver::agent_config(
        &app.provider_id,
        &app.model,
        &app.cwd,
        app.prompt.clone(),
        app.policy,
        app.approval,
        app.allow_unsandboxed,
        app.max_steps,
    );
    let mut renderer = Renderer::new();
    let mut log = log;
    let result = driver::run_turn(
        app.provider.as_ref(),
        &mut log,
        &config,
        &prompt,
        Vec::new(),
        &mut renderer,
    )
    .await;
    let parsed = renderer.finish();
    let usage = renderer.usage();
    if usage.input + usage.output + usage.cached > 0 {
        app.metric(
            "tokens",
            &format!("{},{},{}", usage.input, usage.output, usage.cached),
        );
    }

    for block in parsed.blocks {
        match block {
            Block::Memory { kind, tags, text } => {
                eprintln!("[candidate:{}:{}] {text}", kind.as_str(), tags.join(","));
            }
            Block::Loop { due, text } => {
                eprintln!(
                    "[loop] {text}{}",
                    due.map(|d| format!(" ({d})")).unwrap_or_default()
                );
            }
            Block::Journal { bullets } => {
                for bullet in bullets {
                    eprintln!("[journal] {bullet}");
                }
            }
        }
    }

    let status = match &result {
        Ok(Some(_)) => "ok",
        Ok(None) => "cancelled",
        Err(_) => "error",
    };
    app.metric("turn", status);

    driver::append_end(&log)?;
    println!("\nsession: {}", log.path().display());
    result.map(|_| ())
}

#[derive(Debug, Default, PartialEq, Eq)]
struct UsageTotals {
    turns: usize,
    input: u64,
    output: u64,
    cached: u64,
}

fn usage_totals(events: &[Event]) -> UsageTotals {
    let mut totals = UsageTotals::default();
    for event in events {
        match event {
            Event::UserMessage { .. } => totals.turns += 1,
            Event::TurnEnd { usage, .. } => {
                totals.input += usage.input_tokens;
                totals.output += usage.output_tokens;
                totals.cached += usage.cached_tokens;
            }
            _ => {}
        }
    }
    totals
}

fn expand_tilde(input: &str) -> PathBuf {
    if input == "~" {
        return std::env::var_os("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("~"));
    }
    if let Some(rest) = input.strip_prefix("~/") {
        if let Some(home) = std::env::var_os("HOME") {
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(input)
}

fn parse_resume_index(argument: &str) -> Option<usize> {
    match argument.trim().parse::<usize>() {
        Ok(index) if index > 0 => Some(index),
        _ => None,
    }
}

fn suppressed_by_tag(tags: &[String], rejected: &HashSet<String>) -> bool {
    tags.iter()
        .any(|tag| rejected.contains(&tag.to_lowercase()))
}

fn model_override(argument: &str) -> Option<&str> {
    if argument.eq_ignore_ascii_case("default") {
        None
    } else {
        Some(argument)
    }
}

fn join_continuations(input: &str) -> String {
    input
        .split('\n')
        .map(|line| line.strip_suffix('\\').unwrap_or(line).trim_end())
        .collect::<Vec<_>>()
        .join("\n")
        .trim()
        .to_string()
}

fn export_path(store: &Store, thread: &Path, argument: &str, cwd: &Path) -> PathBuf {
    if !argument.is_empty() {
        let path = expand_tilde(argument);
        if path.is_absolute() {
            return path;
        }
        return cwd.join(path);
    }
    let stem = thread
        .file_stem()
        .map(|stem| stem.to_string_lossy().to_string())
        .unwrap_or_else(|| "thread".to_string());
    store.root().join(format!("export-{stem}.md"))
}

#[cfg(unix)]
fn secure_history(path: &Path) {
    use std::os::unix::fs::PermissionsExt;

    if let Ok(metadata) = std::fs::metadata(path) {
        let mut permissions = metadata.permissions();
        permissions.set_mode(0o600);
        let _ = std::fs::set_permissions(path, permissions);
    }
}

#[cfg(not(unix))]
fn secure_history(_path: &Path) {}

const HELP: &str = r#"对话
  直接输入一条消息;空行会被忽略。终端里行尾加 \ 可续行。

记忆
  /mem                    列出现行记忆
  /mem recall <query>     检索记忆,包含已过期条目
  /mem show <id>          查看单条记忆的全部字段
  /mem review             复核过期条目(y 保留 / e 编辑 / d 删除 / s 跳过)
  /remember <一句话>      直接记住一条偏好
  /forget <id>            删除一条记忆

承诺与日记
  /loops                  列出承诺
  /loop <text>            记下一条承诺
  /done <l-id>            关闭一条承诺
  /journal                最近 7 天
  /journal search <query> 检索日记条目
  /journal add <text>     追加一条今天的日记

会话
  /export [path]          导出当前主线为 Markdown
  /new                    归档当前主线并开始一条新的
  /cd <path>              切换工作目录(下一个 turn 生效)
  /status                 当前配置与存储状态

模型与成本
  /model [name]           查看或切换模型(default 回退)
  /cost                   本次会话累计 token
  /stats                  最近 7 天的候选接受率与活动计数

身份与设置
  /identity               查看 identity.md(/identity edit 编辑)
  /user                   查看 user.md(/user edit 编辑)
  /doctor                 检查本地设置,不调用模型

调试
  /prompt                 打印完整 system prompt
  /help                   本帮助
  /quit                   退出
"#;

fn print_help() {
    print!("{HELP}");
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    #[test]
    fn slash_completion_matches_prefixes() {
        assert_eq!(slash_candidates("/mem rec"), vec!["/mem recall"]);
        assert!(slash_candidates("/mem r").contains(&"/mem review"));
        assert!(slash_candidates("/mem").contains(&"/mem review"));
        assert_eq!(slash_candidates("/zzz"), Vec::<&str>::new());
        assert_eq!(slash_candidates("hello"), Vec::<&str>::new());
        assert_eq!(slash_candidates("/mem "), Vec::<&str>::new());
    }

    #[test]
    fn usage_totals_counts_turns() {
        let events: Vec<Event> = vec![
            serde_json::from_str(r#"{"type":"user_message","text":"first","ts":0}"#).unwrap(),
            serde_json::from_str(
                r#"{"type":"turn_end","usage":{"input_tokens":100,"output_tokens":10,"cached_tokens":40},"ts":1}"#,
            )
            .unwrap(),
            serde_json::from_str(
                r#"{"type":"turn_end","usage":{"input_tokens":50,"output_tokens":5,"cached_tokens":0},"ts":2}"#,
            )
            .unwrap(),
            serde_json::from_str(r#"{"type":"user_message","text":"second","ts":3}"#).unwrap(),
        ];
        let totals = usage_totals(&events);
        assert_eq!(totals.turns, 2);
        assert_eq!(totals.input, 150);
        assert_eq!(totals.output, 15);
        assert_eq!(totals.cached, 40);
    }

    #[test]
    fn tilde_expands_against_home() {
        if let Some(home) = std::env::var_os("HOME") {
            assert_eq!(
                expand_tilde("~/out.md"),
                PathBuf::from(home.clone()).join("out.md")
            );
            assert_eq!(expand_tilde("~"), PathBuf::from(home));
        }
        assert_eq!(expand_tilde("plain.md"), PathBuf::from("plain.md"));
    }

    #[test]
    fn resume_index_is_one_based_and_strict() {
        assert_eq!(parse_resume_index("1"), Some(1));
        assert_eq!(parse_resume_index(" 2 "), Some(2));
        assert_eq!(parse_resume_index("0"), None);
        assert_eq!(parse_resume_index("abc"), None);
        assert_eq!(parse_resume_index(""), None);
        assert_eq!(parse_resume_index("-1"), None);
    }

    #[test]
    fn rejected_tags_hide_later_candidates() {
        let mut rejected = HashSet::new();
        rejected.insert("rust".to_string());
        assert!(suppressed_by_tag(&["RUST".to_string()], &rejected));
        assert!(!suppressed_by_tag(&["style".to_string()], &rejected));
        assert!(!suppressed_by_tag(&[], &rejected));
    }

    #[test]
    fn default_model_means_provider_default() {
        assert_eq!(model_override("default"), None);
        assert_eq!(model_override("DEFAULT"), None);
        assert_eq!(model_override("deepseek-chat"), Some("deepseek-chat"));
    }

    #[test]
    fn backslash_continuations_join_lines() {
        assert_eq!(join_continuations("hello \\\nthere"), "hello\nthere");
        assert_eq!(join_continuations("one"), "one");
        assert_eq!(join_continuations("a \\\nb \\\nc"), "a\nb\nc");
    }

    #[test]
    fn path_completion_lists_directories_and_files() {
        let directory = tempfile::tempdir().unwrap();
        fs::create_dir(directory.path().join("alpha")).unwrap();
        fs::write(directory.path().join("beta.txt"), "").unwrap();

        let all = path_candidates("", directory.path(), PathScope::Any);
        let names: Vec<&str> = all.iter().map(|pair| pair.replacement.as_str()).collect();
        assert!(names.contains(&"alpha/"));
        assert!(names.contains(&"beta.txt"));

        let dirs = path_candidates("", directory.path(), PathScope::Directory);
        assert!(!dirs.is_empty());
        assert!(dirs.iter().all(|pair| pair.replacement.ends_with('/')));

        let filtered = path_candidates("al", directory.path(), PathScope::Any);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].replacement, "alpha/");

        let home = path_candidates("~", directory.path(), PathScope::Any);
        assert_eq!(home.len(), 1);
        assert_eq!(home[0].replacement, "~/");
        let up = path_candidates("..", directory.path(), PathScope::Any);
        assert_eq!(up.len(), 1);
        assert_eq!(up[0].replacement, "../");
        assert_eq!(
            path_candidates(".", directory.path(), PathScope::Any)[0].replacement,
            "./"
        );

        assert_eq!(path_query("/cd sr"), Some((4, "sr", PathScope::Directory)));
        assert_eq!(path_query("/export out"), Some((8, "out", PathScope::Any)));
    }

    #[test]
    fn export_path_defaults_next_to_the_home() {
        let home = Path::new("/tmp/niuse");
        let thread = Path::new("/tmp/niuse/threads/thread-42.jsonl");
        assert_eq!(
            export_path(
                &Store::at(home.to_path_buf()),
                thread,
                "",
                Path::new("/tmp/niuse")
            ),
            PathBuf::from("/tmp/niuse/export-thread-42.md")
        );
        assert_eq!(
            export_path(
                &Store::at(home.to_path_buf()),
                thread,
                "out.md",
                Path::new("/work")
            ),
            PathBuf::from("/work/out.md")
        );
    }

    #[test]
    fn id_completion_reads_the_stores() {
        let directory = tempfile::tempdir().unwrap();
        let store = Store::at(directory.path().join(".niuse"));
        let first = store
            .add_memory(MemoryEntry::new(
                MemoryKind::Preference,
                "prefer short paragraphs",
                vec!["style".into()],
                Date::today(),
                None,
            ))
            .unwrap();
        store
            .add_memory(MemoryEntry::new(
                MemoryKind::Lesson,
                "use nextest",
                vec!["rust".into()],
                Date::today(),
                None,
            ))
            .unwrap();
        let matches = id_candidates(&store, IdScope::Memory, &first.id);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].replacement, first.id);

        let line = format!("/mem show {}", &first.id[..2]);
        let (start, fragment, _) = id_query(&line).unwrap();
        assert_eq!(start, "/mem show ".len());
        assert_eq!(fragment, &first.id[..2]);

        let prefixed = id_candidates(&store, IdScope::Memory, &format!("m-{}", first.id));
        assert_eq!(prefixed.len(), 1);
        assert_eq!(prefixed[0].replacement, format!("m-{}", first.id));

        let loop_item = store.add_loop(LoopItem::new("open loop", None)).unwrap();
        let loops = id_candidates(&store, IdScope::Loop, "l-");
        assert_eq!(loops.len(), 1);
        assert_eq!(loops[0].replacement, format!("l-{}", loop_item.id));
    }

    #[test]
    fn history_file_is_private() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("history");
        std::fs::write(&path, "/help\n").unwrap();
        secure_history(&path);
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }
}