devist 0.19.0

Project bootstrap CLI for AI-assisted development. Spin up new projects from templates, manage backends, and keep your codebase comprehensible.
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
use anyhow::{anyhow, Context, Result};
use clap::Subcommand;
use console::style;
use std::io::{self, Write};
use std::path::PathBuf;
use std::thread;
use std::time::Duration;

use crate::paths;
use crate::worker::config::WorkerConfig;
use crate::worker::daemon;
use crate::worker::db::Db;

#[derive(Subcommand)]
pub enum WorkerCmd {
    /// Start the background worker daemon (configures monitor folder if absent)
    Start,
    /// Stop the running worker daemon
    Stop,
    /// Show daemon status (PID, monitor folder, sync state)
    Status,
    /// Tail recent worker events in the terminal
    Watch {
        /// Number of recent events to show on startup
        #[arg(long, default_value_t = 20)]
        tail: usize,
        /// Polling interval in milliseconds
        #[arg(long, default_value_t = 500)]
        interval_ms: u64,
    },
    /// Inspect or modify worker config
    #[command(subcommand)]
    Config(ConfigCmd),
    /// List recent advice generated by the worker
    Advice {
        /// Filter by project name (optional)
        #[arg(long)]
        project: Option<String>,
        /// Number of items to show
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// Search long-term memory (mem0 semantic index)
    Memory {
        #[command(subcommand)]
        cmd: MemoryCmd,
    },
    /// macOS only: register the worker as a LaunchAgent so it auto-starts
    /// on login and auto-restarts after `cargo install` / `brew upgrade`.
    #[cfg(target_os = "macos")]
    Enable,
    /// macOS only: remove the LaunchAgent registration (`worker start`
    /// still works manually).
    #[cfg(target_os = "macos")]
    Disable,
    /// Internal: actually run the daemon loop (invoked by `worker start`).
    /// Hidden from help.
    #[command(name = "__run", hide = true)]
    RunInternal,
}

#[derive(Subcommand)]
pub enum MemoryCmd {
    /// Semantic search across stored memories
    Search {
        query: String,
        #[arg(long, default_value_t = 5)]
        limit: usize,
    },
}

#[derive(Subcommand)]
pub enum ConfigCmd {
    /// Print the current config
    Show,
    /// Print a single config value
    Get { key: String },
    /// Update a config value (monitor_dir, supabase_url, supabase_key, sync_interval_secs, debounce_ms)
    Set { key: String, value: String },
    /// Open the config file path
    Path,
}

pub fn run(cmd: WorkerCmd) -> Result<()> {
    match cmd {
        WorkerCmd::Start => start(),
        WorkerCmd::Stop => stop(),
        WorkerCmd::Status => status(),
        WorkerCmd::Watch { tail, interval_ms } => watch(tail, interval_ms),
        WorkerCmd::Config(c) => config_cmd(c),
        WorkerCmd::Advice { project, limit } => advice_list(project, limit),
        WorkerCmd::Memory { cmd } => memory_cmd(cmd),
        #[cfg(target_os = "macos")]
        WorkerCmd::Enable => enable(),
        #[cfg(target_os = "macos")]
        WorkerCmd::Disable => disable(),
        WorkerCmd::RunInternal => daemon::run_loop(),
    }
}

fn advice_list(project: Option<String>, limit: usize) -> Result<()> {
    let cfg = WorkerConfig::load()?;
    let db = Db::open(&cfg.db_path)?;
    let recent = db.recent(limit * 5)?; // overshoot, then filter
    let mut shown = 0;
    println!("{}", style("devist worker advice").bold());
    println!();
    for ev in recent.iter().rev() {
        if ev.event_type != "advice" && ev.event_type != "advice_error" {
            continue;
        }
        if let Some(p) = &project {
            if &ev.project != p {
                continue;
            }
        }
        if shown >= limit {
            break;
        }
        let ts = ev.created_at.split('T').nth(1).unwrap_or(&ev.created_at);
        let ts = ts.split('.').next().unwrap_or(ts);
        let sev = match ev.severity.as_str() {
            "warn" => style(format!("[{}]", ev.severity)).yellow().to_string(),
            "block" => style(format!("[{}]", ev.severity)).red().to_string(),
            "suggest" => style(format!("[{}]", ev.severity)).cyan().to_string(),
            _ => style(format!("[{}]", ev.severity)).dim().to_string(),
        };
        let text = serde_json::from_str::<serde_json::Value>(&ev.payload)
            .ok()
            .and_then(|v| {
                v.get("text")
                    .or_else(|| v.get("error"))
                    .and_then(|x| x.as_str().map(|s| s.to_string()))
            })
            .unwrap_or_else(|| ev.payload.clone());
        println!(
            "{} {} {}{}",
            style(ts).dim(),
            sev,
            style(&ev.project).cyan(),
            text
        );
        shown += 1;
    }
    if shown == 0 {
        println!("  {} no advice yet", style("(empty)").dim());
    }
    Ok(())
}

fn memory_cmd(cmd: MemoryCmd) -> Result<()> {
    let cfg = WorkerConfig::load()?;
    let api_key = cfg.mem0_api_key.clone().ok_or_else(|| {
        anyhow!("mem0_api_key not set. `devist worker config set mem0_api_key <key>`")
    })?;
    let user_id = cfg
        .mem0_user_id
        .clone()
        .ok_or_else(|| anyhow!("mem0_user_id not set"))?;
    let client = crate::worker::mem0::Mem0Client::new(api_key, user_id)?;
    match cmd {
        MemoryCmd::Search { query, limit } => {
            let results = client.search(&query, limit)?;
            if results.is_empty() {
                println!("{}", style("(no memories matched)").dim());
                return Ok(());
            }
            for (i, m) in results.iter().enumerate() {
                let score = m
                    .score
                    .map(|s| format!("{:.2}", s))
                    .unwrap_or_else(|| "?".into());
                println!(
                    "{} {} {}",
                    style(format!("{}.", i + 1)).dim(),
                    style(format!("[score {}]", score)).cyan(),
                    m.memory
                );
            }
            Ok(())
        }
    }
}

fn start() -> Result<()> {
    println!("{}", style("devist worker start").bold());

    let st = daemon::status()?;
    if st.running {
        println!(
            "  {} already running (pid {})",
            style("[OK]").green(),
            st.pid.unwrap()
        );
        return Ok(());
    }
    if st.stale_pid_file {
        println!(
            "  {} stale PID file from previous run (pid {}) — cleaned up",
            style("[CLEAN]").dim(),
            st.pid.unwrap()
        );
    }

    if !WorkerConfig::exists() {
        let cfg = first_run_setup()?;
        cfg.save()?;
        println!("  {} config saved", style("[CFG]").cyan());
    }

    let cfg = WorkerConfig::load()?;
    if !cfg.monitor_dir.exists() {
        return Err(anyhow!(
            "Monitor folder does not exist: {}\n  Update with: devist worker config set monitor_dir <path>",
            cfg.monitor_dir.display()
        ));
    }

    // If a LaunchAgent is registered, ask launchd to (re)spawn instead
    // of forking ourselves — that way the daemon stays under launchd's
    // KeepAlive and survives logout.
    #[cfg(target_os = "macos")]
    if crate::worker::launchd::is_enabled().unwrap_or(false) {
        kickstart_via_launchd()?;
        println!(
            "  {} launchd ({}) — auto-restart on login + binary update",
            style("[UP]").green(),
            crate::worker::launchd::LABEL
        );
        print_runtime_paths(&cfg)?;
        return Ok(());
    }

    let pid = daemon::spawn_detached()?;
    println!("  {} pid {}", style("[UP]").green(), pid);
    print_runtime_paths(&cfg)?;
    Ok(())
}

fn print_runtime_paths(cfg: &WorkerConfig) -> Result<()> {
    println!(
        "  {} {}",
        style("[WATCH]").cyan(),
        style(cfg.monitor_dir.display()).bold()
    );
    println!(
        "  {} {}",
        style("[LOG]").dim(),
        paths::worker_log_file()?.display()
    );
    println!("  {} {}", style("[DB]").dim(), cfg.db_path.display());
    Ok(())
}

#[cfg(target_os = "macos")]
fn kickstart_via_launchd() -> Result<()> {
    use std::process::Command;
    let uid = unsafe { libc::getuid() };
    let target = format!("gui/{}/{}", uid, crate::worker::launchd::LABEL);
    let out = Command::new("launchctl")
        .args(["kickstart", "-k", &target])
        .output()
        .context("run launchctl kickstart")?;
    if !out.status.success() {
        return Err(anyhow!(
            "launchctl kickstart failed: {}\n{}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(())
}

fn stop() -> Result<()> {
    println!("{}", style("devist worker stop").bold());

    // Under launchd, sending SIGTERM is fine — KeepAlive will respawn
    // unless we also disable, but `stop` is a one-shot signal so we
    // just kill the running PID. To make it persistent, user must call
    // `worker disable` to remove the LaunchAgent.
    daemon::stop()?;
    #[cfg(target_os = "macos")]
    if crate::worker::launchd::is_enabled().unwrap_or(false) {
        println!(
            "  {} launchd will respawn — run `devist worker disable` to make this permanent",
            style("[NOTE]").yellow()
        );
    }
    println!("  {} stopped", style("[DOWN]").yellow());
    Ok(())
}

#[cfg(target_os = "macos")]
fn enable() -> Result<()> {
    println!("{}", style("devist worker enable").bold());
    if !WorkerConfig::exists() {
        return Err(anyhow!(
            "Worker is not configured yet — run `devist worker start` first to set up monitor folder."
        ));
    }
    crate::worker::launchd::enable()?;
    println!(
        "  {} LaunchAgent installed at ~/Library/LaunchAgents/{}.plist",
        style("[OK]").green(),
        crate::worker::launchd::LABEL
    );
    println!(
        "  {} auto-starts on login + auto-restarts on binary update",
        style("[INFO]").cyan()
    );
    Ok(())
}

#[cfg(target_os = "macos")]
fn disable() -> Result<()> {
    println!("{}", style("devist worker disable").bold());
    crate::worker::launchd::disable()?;
    println!("  {} LaunchAgent removed", style("[OK]").green());
    println!(
        "  {} daemon may still be running — `devist worker stop` to stop it now",
        style("[INFO]").dim()
    );
    Ok(())
}

fn status() -> Result<()> {
    println!("{}", style("devist worker status").bold());
    let st = daemon::status()?;
    if st.running {
        println!("  {} running (pid {})", style("").green(), st.pid.unwrap());
    } else if st.stale_pid_file {
        println!(
            "  {} stopped (stale PID file: {})",
            style("").yellow(),
            st.pid.unwrap()
        );
    } else {
        println!("  {} stopped", style("").dim());
    }

    #[cfg(target_os = "macos")]
    {
        let enabled = crate::worker::launchd::is_enabled().unwrap_or(false);
        if enabled {
            println!(
                "  {} {}",
                style("launchd:").dim(),
                style("enabled (auto-start on login)").green()
            );
        } else {
            println!(
                "  {} {}",
                style("launchd:").dim(),
                style("disabled — `devist worker enable` to persist").dim()
            );
        }
    }

    if let Ok(cfg) = WorkerConfig::load() {
        println!(
            "  {} {}",
            style("monitor:").dim(),
            cfg.monitor_dir.display()
        );
        println!("  {} {}", style("db:     ").dim(), cfg.db_path.display());
        match cfg.supabase_url.as_deref() {
            Some(u) => println!("  {} {}", style("supabase:").dim(), u),
            None => println!(
                "  {} {}",
                style("supabase:").dim(),
                style("not configured").dim()
            ),
        }

        if let Ok(db) = Db::open(&cfg.db_path) {
            if let Ok(c) = db.counts() {
                println!(
                    "  {} {} events ({} pending sync)",
                    style("data:    ").dim(),
                    c.total,
                    c.unsynced
                );
            }
        }
    } else {
        println!(
            "  {} {}",
            style("config:").dim(),
            style("not configured — run `devist worker start`").dim()
        );
    }
    Ok(())
}

fn watch(tail: usize, interval_ms: u64) -> Result<()> {
    let cfg = WorkerConfig::load()?;
    let db = Db::open(&cfg.db_path)?;
    println!(
        "{} (db: {})  press Ctrl+C to stop",
        style("devist worker watch").bold(),
        style(cfg.db_path.display()).dim()
    );
    println!();

    let initial = db.recent(tail)?;
    let mut last_id = 0i64;
    for ev in &initial {
        print_event(ev);
        if let Some(id) = ev.id {
            last_id = id;
        }
    }

    loop {
        thread::sleep(Duration::from_millis(interval_ms));
        let new_events = db.since(last_id, 200)?;
        for ev in &new_events {
            print_event(ev);
            if let Some(id) = ev.id {
                last_id = id;
            }
        }
    }
}

fn print_event(ev: &crate::worker::db::Event) {
    let ts = ev.created_at.split('T').nth(1).unwrap_or(&ev.created_at);
    let ts = ts.split('.').next().unwrap_or(ts);
    let sev_styled = match ev.severity.as_str() {
        "warn" => style(format!("[{}]", ev.severity)).yellow().to_string(),
        "block" => style(format!("[{}]", ev.severity)).red().to_string(),
        "suggest" => style(format!("[{}]", ev.severity)).cyan().to_string(),
        _ => style(format!("[{}]", ev.severity)).dim().to_string(),
    };
    println!(
        "{} {} {} {} {}",
        style(ts).dim(),
        sev_styled,
        style(&ev.event_type).bold(),
        style(&ev.project).cyan(),
        ev.path.as_deref().unwrap_or("")
    );
}

fn config_cmd(cmd: ConfigCmd) -> Result<()> {
    match cmd {
        ConfigCmd::Show => {
            let cfg = WorkerConfig::load()?;
            println!("{}", toml::to_string_pretty(&cfg)?);
            Ok(())
        }
        ConfigCmd::Get { key } => {
            let cfg = WorkerConfig::load()?;
            let v = match key.as_str() {
                "monitor_dir" => cfg.monitor_dir.display().to_string(),
                "db_path" => cfg.db_path.display().to_string(),
                "supabase_url" => cfg.supabase_url.unwrap_or_default(),
                "supabase_key" => cfg.supabase_key.unwrap_or_default(),
                "sync_interval_secs" => cfg.sync_interval_secs.to_string(),
                "debounce_ms" => cfg.debounce_ms.to_string(),
                _ => return Err(anyhow!("Unknown key: {}", key)),
            };
            println!("{}", v);
            Ok(())
        }
        ConfigCmd::Set { key, value } => {
            let mut cfg = WorkerConfig::load()?;
            cfg.set_key(&key, &value)?;
            cfg.save()?;
            println!("  {} {} = {}", style("[CFG]").green(), key, value);
            let st = daemon::status()?;
            if st.running {
                println!(
                    "  {} restart with `devist worker stop && devist worker start` to apply",
                    style("[NOTE]").yellow()
                );
            }
            Ok(())
        }
        ConfigCmd::Path => {
            println!("{}", paths::worker_config_file()?.display());
            Ok(())
        }
    }
}

fn first_run_setup() -> Result<WorkerConfig> {
    println!();
    println!("  {} first-time setup", style("[SETUP]").cyan());
    println!("  Enter the folder to monitor (a parent folder containing your projects).");
    let default = paths::home()?.join("Workspace");
    let prompt_default = if default.exists() {
        default.display().to_string()
    } else {
        String::new()
    };
    print!(
        "  monitor_dir [{}]: ",
        if prompt_default.is_empty() {
            "required"
        } else {
            &prompt_default
        }
    );
    io::stdout().flush().ok();
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    let entered = line.trim().to_string();
    let monitor_dir = if entered.is_empty() {
        if prompt_default.is_empty() {
            return Err(anyhow!("monitor_dir is required"));
        }
        PathBuf::from(prompt_default)
    } else {
        PathBuf::from(entered)
    };

    if !monitor_dir.exists() {
        return Err(anyhow!(
            "Monitor folder does not exist: {}",
            monitor_dir.display()
        ));
    }

    WorkerConfig::new_default(monitor_dir)
}