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
#![forbid(unsafe_code)]
mod bootstrap;
mod commands;
mod config;
mod driver;
mod export;
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>,
#[command(subcommand)]
command: Option<Command>,
}
#[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,
},
/// Inspect and close open loops
Loops {
#[command(subcommand)]
command: LoopsCommand,
},
/// 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,
/// 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,
},
/// 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 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::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::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::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::Status { json }) => {
let thread = config::resolve_thread(cli.thread.clone(), &store)?;
commands::status(&store, &thread, 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 = store.session_path();
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(store)?;
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,
..niucode::TuiOptions::default()
};
niucode::run_tui_with_hooks(options, Box::new(hooks)).await
}