scope-cli 0.9.2

Code intelligence CLI for LLM coding agents — structural navigation, dependency graphs, and semantic search without reading full source files
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
/// `scope workspace` — manage multi-project workspaces.
///
/// Subcommands:
///   init  — discover projects and create scope-workspace.toml
///   list  — show workspace members and their index status
///   index — index all workspace members sequentially
///
/// Examples:
///   scope workspace init                — discover and create manifest
///   scope workspace init --name my-ws   — set workspace name
///   scope workspace list                — show all members
///   scope workspace list --json         — machine-readable output
///   scope workspace index               — incremental index all members
///   scope workspace index --full        — full re-index all members
use anyhow::{bail, Result};
use clap::{Args, Subcommand};
use serde::Serialize;
use std::path::Path;
use std::time::Instant;

use crate::config::workspace::WorkspaceConfig;
use crate::config::ProjectConfig;
use crate::core::graph::Graph;
use crate::core::indexer::Indexer;
use crate::core::searcher::Searcher;
use crate::output::formatter;
use crate::output::json::JsonOutput;

/// Manage multi-project workspaces.
///
/// A workspace groups multiple Scope projects (each with its own .scope/
/// directory) and enables federated queries across all members.
///
/// Use `scope workspace init` to create a workspace manifest by discovering
/// existing Scope projects in subdirectories. Use `scope workspace list`
/// to check the health of all members.
#[derive(Args, Debug)]
pub struct WorkspaceArgs {
    #[command(subcommand)]
    pub command: WorkspaceCommands,
}

/// Workspace subcommands.
#[derive(Subcommand, Debug)]
pub enum WorkspaceCommands {
    /// Discover projects in the current directory tree and create scope-workspace.toml.
    ///
    /// Walks subdirectories (max depth 3) looking for .scope/config.toml markers.
    /// Each discovered project becomes a [[workspace.members]] entry.
    ///
    /// If projects have not been initialised yet, run `scope init` in each
    /// project first, then run `scope workspace init` from the parent directory.
    ///
    /// Examples:
    ///   scope workspace init                    — discover and create manifest
    ///   scope workspace init --name my-workspace  — set workspace name
    Init(WorkspaceInitArgs),

    /// Show all workspace members and their index status.
    ///
    /// Reads scope-workspace.toml and checks each member for .scope/graph.db
    /// existence, symbol count, and last indexed time. Use this to verify the
    /// workspace is healthy before querying.
    ///
    /// Output columns: name, path, status, files, symbols, last indexed.
    ///
    /// Examples:
    ///   scope workspace list
    ///   scope workspace list --json
    List(WorkspaceListArgs),

    /// Index all workspace members.
    ///
    /// Reads scope-workspace.toml and indexes each member project sequentially.
    /// Members without .scope/config.toml are skipped with a warning.
    ///
    /// With --watch, starts a file watcher for each member that auto re-indexes
    /// on file changes. Each member gets its own watcher process. Press Ctrl+C
    /// to stop all watchers.
    ///
    /// Examples:
    ///   scope workspace index              — incremental index all members
    ///   scope workspace index --full       — full re-index all members
    ///   scope workspace index --watch      — watch all members for changes
    ///   scope workspace index --json       — machine-readable output
    Index(WorkspaceIndexArgs),
}

/// Arguments for `scope workspace init`.
#[derive(Args, Debug)]
pub struct WorkspaceInitArgs {
    /// Workspace name. Defaults to the current directory name.
    #[arg(long)]
    pub name: Option<String>,
}

/// Arguments for `scope workspace list`.
#[derive(Args, Debug)]
pub struct WorkspaceListArgs {
    /// Output as JSON instead of human-readable format.
    #[arg(long, short = 'j')]
    pub json: bool,
}

/// Arguments for `scope workspace index`.
#[derive(Args, Debug)]
pub struct WorkspaceIndexArgs {
    /// Rebuild the entire index from scratch for all members.
    #[arg(long)]
    pub full: bool,

    /// Watch all members for file changes and auto re-index.
    /// Spawns one watcher per member. Runs until Ctrl+C.
    #[arg(long)]
    pub watch: bool,

    /// Output as JSON instead of human-readable format.
    #[arg(long, short = 'j')]
    pub json: bool,
}

/// Status information for a single workspace member.
#[derive(Debug, Serialize)]
pub struct MemberStatus {
    /// Member display name.
    pub name: String,
    /// Path relative to workspace root.
    pub path: String,
    /// Index status: "indexed", "not initialised", or "not indexed".
    pub status: String,
    /// Number of indexed files (0 if not indexed).
    pub file_count: usize,
    /// Number of symbols in the index (0 if not indexed).
    pub symbol_count: usize,
    /// Unix timestamp of last indexing, if available.
    pub last_indexed_at: Option<i64>,
}

/// JSON data payload for `scope workspace list`.
#[derive(Debug, Serialize)]
pub struct WorkspaceListData {
    /// Workspace name from the manifest.
    pub workspace_name: String,
    /// Status of each member.
    pub members: Vec<MemberStatus>,
}

/// Result of indexing a single workspace member.
#[derive(Debug, Serialize)]
pub struct MemberIndexResult {
    /// Member display name.
    pub name: String,
    /// Path relative to workspace root.
    pub path: String,
    /// Whether the member was indexed successfully.
    pub status: String,
    /// Indexing mode: "full", "incremental", or "skipped".
    pub mode: String,
    /// Number of symbols after indexing.
    pub symbol_count: usize,
    /// Number of edges after indexing.
    pub edge_count: usize,
    /// Duration in seconds.
    pub duration_secs: f64,
}

/// JSON data payload for `scope workspace index`.
#[derive(Debug, Serialize)]
pub struct WorkspaceIndexData {
    /// Workspace name from the manifest.
    pub workspace_name: String,
    /// Per-member indexing results.
    pub members: Vec<MemberIndexResult>,
    /// Total symbols across all indexed members.
    pub total_symbols: usize,
    /// Total edges across all indexed members.
    pub total_edges: usize,
    /// Total duration in seconds.
    pub total_duration_secs: f64,
}

/// Run the `scope workspace` command.
pub fn run(args: &WorkspaceArgs, project_root: &Path) -> Result<()> {
    match &args.command {
        WorkspaceCommands::Init(init_args) => run_init(init_args, project_root),
        WorkspaceCommands::List(list_args) => run_list(list_args, project_root),
        WorkspaceCommands::Index(index_args) => run_index(index_args, project_root),
    }
}

/// Run `scope workspace init` — discover projects and write scope-workspace.toml.
fn run_init(args: &WorkspaceInitArgs, project_root: &Path) -> Result<()> {
    let manifest_path = project_root.join("scope-workspace.toml");

    if manifest_path.exists() {
        bail!("Workspace already initialized. Edit scope-workspace.toml directly.");
    }

    // Discover projects by walking subdirectories (max depth 3)
    let mut members: Vec<(String, String)> = Vec::new();

    discover_projects(project_root, project_root, 0, 3, &mut members)?;

    if members.is_empty() {
        bail!(
            "No Scope projects found in subdirectories.\n\
             Run 'scope init' in each project directory first, then retry."
        );
    }

    // Sort members by path for deterministic output
    members.sort_by(|a, b| a.0.cmp(&b.0));

    // Determine workspace name
    let ws_name = args.name.clone().unwrap_or_else(|| {
        project_root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("workspace")
            .to_string()
    });

    let toml_content = WorkspaceConfig::generate_toml(&ws_name, &members);
    std::fs::write(&manifest_path, toml_content)?;

    // Report to stderr (progress/info goes to stderr)
    let member_names: Vec<&str> = members.iter().map(|(_, name)| name.as_str()).collect();
    eprintln!(
        "Found {} projects: {}",
        members.len(),
        member_names.join(", ")
    );
    eprintln!("Created scope-workspace.toml");

    Ok(())
}

/// Recursively discover Scope projects by looking for `.scope/config.toml`.
fn discover_projects(
    base_root: &Path,
    current: &Path,
    depth: usize,
    max_depth: usize,
    members: &mut Vec<(String, String)>,
) -> Result<()> {
    if depth > max_depth {
        return Ok(());
    }

    let entries = match std::fs::read_dir(current) {
        Ok(entries) => entries,
        Err(e) => {
            tracing::warn!(
                "Cannot read directory {}: {e}. Skipping.",
                current.display()
            );
            return Ok(());
        }
    };

    for entry in entries {
        let entry = entry?;
        let path = entry.path();

        if !path.is_dir() {
            continue;
        }

        // Skip hidden directories and common non-project dirs
        let dir_name = match path.file_name().and_then(|n| n.to_str()) {
            Some(name) => name.to_string(),
            None => continue,
        };

        if dir_name.starts_with('.')
            || dir_name == "node_modules"
            || dir_name == "target"
            || dir_name == "dist"
            || dir_name == "build"
        {
            continue;
        }

        // Check if this directory has .scope/config.toml
        let scope_config = path.join(".scope").join("config.toml");
        if scope_config.exists() {
            // Compute relative path from workspace root
            let rel_path = path
                .strip_prefix(base_root)
                .unwrap_or(&path)
                .to_string_lossy()
                .replace('\\', "/");

            let name = dir_name;
            members.push((rel_path, name));

            // Don't recurse into discovered projects (they're self-contained)
            continue;
        }

        // Recurse into subdirectories
        discover_projects(base_root, &path, depth + 1, max_depth, members)?;
    }

    Ok(())
}

/// Run `scope workspace list` — show workspace members and their status.
fn run_list(args: &WorkspaceListArgs, project_root: &Path) -> Result<()> {
    // Find scope-workspace.toml (in CWD or walk upward)
    let manifest_path = find_workspace_manifest(project_root)?;
    let workspace_root = manifest_path.parent().unwrap_or(project_root);

    let config = WorkspaceConfig::load(&manifest_path)?;

    let mut member_statuses: Vec<MemberStatus> = Vec::new();

    for entry in &config.workspace.members {
        let name = WorkspaceConfig::resolve_member_name(entry);
        let member_path = workspace_root.join(&entry.path);

        let scope_dir = member_path.join(".scope");
        let db_path = scope_dir.join("graph.db");

        let status = if !scope_dir.exists() {
            MemberStatus {
                name,
                path: entry.path.clone(),
                status: "not initialised".to_string(),
                file_count: 0,
                symbol_count: 0,
                last_indexed_at: None,
            }
        } else if !db_path.exists() {
            MemberStatus {
                name,
                path: entry.path.clone(),
                status: "not indexed".to_string(),
                file_count: 0,
                symbol_count: 0,
                last_indexed_at: None,
            }
        } else {
            match Graph::open(&db_path) {
                Ok(graph) => {
                    let symbol_count = graph.symbol_count().unwrap_or(0);
                    let file_count = graph.file_count().unwrap_or(0);
                    let last_indexed_at = graph.last_indexed_at().unwrap_or(None);

                    MemberStatus {
                        name,
                        path: entry.path.clone(),
                        status: "indexed".to_string(),
                        file_count,
                        symbol_count,
                        last_indexed_at,
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to open graph for member '{}': {e}", name);
                    MemberStatus {
                        name,
                        path: entry.path.clone(),
                        status: format!("error: {e}"),
                        file_count: 0,
                        symbol_count: 0,
                        last_indexed_at: None,
                    }
                }
            }
        };

        member_statuses.push(status);
    }

    if args.json {
        let data = WorkspaceListData {
            workspace_name: config.workspace.name.clone(),
            members: member_statuses,
        };
        let output = JsonOutput {
            command: "workspace list",
            symbol: None,
            data,
            truncated: false,
            total: config.workspace.members.len(),
        };
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        formatter::print_workspace_list(&config.workspace.name, &member_statuses);
    }

    Ok(())
}

/// Run `scope workspace index` — index all workspace members, or watch all.
fn run_index(args: &WorkspaceIndexArgs, project_root: &Path) -> Result<()> {
    if args.watch {
        return run_workspace_watch(project_root);
    }
    let manifest_path = find_workspace_manifest(project_root)?;
    let workspace_root = manifest_path.parent().unwrap_or(project_root);

    let config = WorkspaceConfig::load(&manifest_path)?;
    let total_members = config.workspace.members.len();
    let overall_start = Instant::now();

    let mut results: Vec<MemberIndexResult> = Vec::new();
    let mut indexed_count: usize = 0;
    let mut total_symbols: usize = 0;
    let mut total_edges: usize = 0;

    for entry in &config.workspace.members {
        let name = WorkspaceConfig::resolve_member_name(entry);
        let member_path = workspace_root.join(&entry.path);
        let scope_dir = member_path.join(".scope");
        let config_path = scope_dir.join("config.toml");

        // Skip members without .scope/config.toml
        if !config_path.exists() {
            eprintln!("[{}] Skipped: no .scope/config.toml found", name);
            results.push(MemberIndexResult {
                name,
                path: entry.path.clone(),
                status: "skipped".to_string(),
                mode: "skipped".to_string(),
                symbol_count: 0,
                edge_count: 0,
                duration_secs: 0.0,
            });
            continue;
        }

        let member_start = Instant::now();

        // Load project config
        let project_config = match ProjectConfig::load(&scope_dir) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("[{}] Error loading config: {}", name, e);
                results.push(MemberIndexResult {
                    name,
                    path: entry.path.clone(),
                    status: "error".to_string(),
                    mode: if args.full { "full" } else { "incremental" }.to_string(),
                    symbol_count: 0,
                    edge_count: 0,
                    duration_secs: member_start.elapsed().as_secs_f64(),
                });
                continue;
            }
        };

        // Open graph database
        let db_path = scope_dir.join("graph.db");
        let mut graph = match Graph::open(&db_path) {
            Ok(g) => g,
            Err(e) => {
                eprintln!("[{}] Error opening graph: {}", name, e);
                results.push(MemberIndexResult {
                    name,
                    path: entry.path.clone(),
                    status: "error".to_string(),
                    mode: if args.full { "full" } else { "incremental" }.to_string(),
                    symbol_count: 0,
                    edge_count: 0,
                    duration_secs: member_start.elapsed().as_secs_f64(),
                });
                continue;
            }
        };

        // Create indexer
        let mut indexer = match Indexer::new() {
            Ok(i) => i,
            Err(e) => {
                eprintln!("[{}] Error creating indexer: {}", name, e);
                results.push(MemberIndexResult {
                    name,
                    path: entry.path.clone(),
                    status: "error".to_string(),
                    mode: if args.full { "full" } else { "incremental" }.to_string(),
                    symbol_count: 0,
                    edge_count: 0,
                    duration_secs: member_start.elapsed().as_secs_f64(),
                });
                continue;
            }
        };

        // Open search index (optional)
        let searcher = match Searcher::open(&db_path) {
            Ok(s) => Some(s),
            Err(e) => {
                tracing::warn!("[{}] Search index unavailable: {e}", name);
                None
            }
        };

        // Run indexing
        let mode = if args.full { "full" } else { "incremental" };
        let (symbol_count, edge_count) = if args.full {
            match indexer.index_full(&member_path, &project_config, &mut graph, searcher.as_ref()) {
                Ok(stats) => (stats.symbol_count, stats.edge_count),
                Err(e) => {
                    eprintln!("[{}] Error during indexing: {}", name, e);
                    results.push(MemberIndexResult {
                        name,
                        path: entry.path.clone(),
                        status: "error".to_string(),
                        mode: mode.to_string(),
                        symbol_count: 0,
                        edge_count: 0,
                        duration_secs: member_start.elapsed().as_secs_f64(),
                    });
                    continue;
                }
            }
        } else {
            match indexer.index_incremental(
                &member_path,
                &project_config,
                &mut graph,
                searcher.as_ref(),
            ) {
                Ok(stats) => (stats.symbol_count, stats.edge_count),
                Err(e) => {
                    eprintln!("[{}] Error during indexing: {}", name, e);
                    results.push(MemberIndexResult {
                        name,
                        path: entry.path.clone(),
                        status: "error".to_string(),
                        mode: mode.to_string(),
                        symbol_count: 0,
                        edge_count: 0,
                        duration_secs: member_start.elapsed().as_secs_f64(),
                    });
                    continue;
                }
            }
        };

        let duration = member_start.elapsed();
        total_symbols += symbol_count;
        total_edges += edge_count;
        indexed_count += 1;

        if !args.json {
            eprintln!(
                "[{}] Indexed: {} symbols, {} edges ({:.1}s)",
                name,
                symbol_count,
                edge_count,
                duration.as_secs_f64()
            );
        }

        results.push(MemberIndexResult {
            name,
            path: entry.path.clone(),
            status: "indexed".to_string(),
            mode: mode.to_string(),
            symbol_count,
            edge_count,
            duration_secs: duration.as_secs_f64(),
        });
    }

    let total_duration = overall_start.elapsed();

    if args.json {
        let data = WorkspaceIndexData {
            workspace_name: config.workspace.name.clone(),
            members: results,
            total_symbols,
            total_edges,
            total_duration_secs: total_duration.as_secs_f64(),
        };
        let output = JsonOutput {
            command: "workspace index",
            symbol: None,
            data,
            truncated: false,
            total: total_members,
        };
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        eprintln!(
            "Workspace indexed: {}/{} members, {} total symbols",
            indexed_count, total_members, total_symbols
        );
    }

    Ok(())
}

/// Walk upward from the given directory looking for `scope-workspace.toml`.
///
/// Returns the path to the manifest file if found.
pub fn find_workspace_manifest(start: &Path) -> Result<std::path::PathBuf> {
    let mut current = start.to_path_buf();

    loop {
        let candidate = current.join("scope-workspace.toml");
        if candidate.exists() {
            return Ok(candidate);
        }

        if !current.pop() {
            break;
        }
    }

    bail!(
        "No scope-workspace.toml found.\n\
         Run 'scope workspace init' to create one."
    );
}

/// Run `scope workspace index --watch` — spawn a watcher per member.
///
/// Each member gets its own `scope index --watch` child process.
/// The parent monitors all children and shuts down on Ctrl+C.
fn run_workspace_watch(project_root: &Path) -> Result<()> {
    let manifest_path = find_workspace_manifest(project_root)?;
    let workspace_root = manifest_path.parent().unwrap_or(project_root);
    let config = WorkspaceConfig::load(&manifest_path)?;

    if config.workspace.members.is_empty() {
        bail!("Workspace has no members. Add projects to scope-workspace.toml.");
    }

    // Find the scope binary path (same binary that's running now)
    let scope_bin = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("scope"));

    let mut children: Vec<(String, std::process::Child)> = Vec::new();

    for entry in &config.workspace.members {
        let name = WorkspaceConfig::resolve_member_name(entry);
        let member_path = workspace_root.join(&entry.path);
        let scope_dir = member_path.join(".scope");

        if !scope_dir.join("config.toml").exists() {
            eprintln!("[{name}] Skipped: no .scope/config.toml");
            continue;
        }

        match std::process::Command::new(&scope_bin)
            .args(["index", "--watch"])
            .current_dir(&member_path)
            .stderr(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
        {
            Ok(child) => {
                eprintln!("[{name}] Watcher started (PID {})", child.id());
                children.push((name, child));
            }
            Err(e) => {
                eprintln!("[{name}] Failed to start watcher: {e}");
            }
        }
    }

    if children.is_empty() {
        bail!("No watchers started. Ensure workspace members are initialised.");
    }

    eprintln!(
        "\nWatching {} member{} (Ctrl+C to stop all)...",
        children.len(),
        if children.len() == 1 { "" } else { "s" }
    );

    // Set up Ctrl+C handler
    let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
    let running_ctrlc = running.clone();
    ctrlc::set_handler(move || {
        running_ctrlc.store(false, std::sync::atomic::Ordering::SeqCst);
    })
    .map_err(|e| anyhow::anyhow!("Failed to set Ctrl+C handler: {e}"))?;

    // Wait for Ctrl+C, periodically checking if children are alive
    while running.load(std::sync::atomic::Ordering::SeqCst) {
        std::thread::sleep(std::time::Duration::from_millis(500));

        // Check if any child exited unexpectedly
        for (name, child) in &mut children {
            match child.try_wait() {
                Ok(Some(status)) => {
                    if !status.success() {
                        eprintln!("[{name}] Watcher exited with {status}");
                    }
                }
                Ok(None) => {} // still running
                Err(e) => {
                    eprintln!("[{name}] Failed to check watcher status: {e}");
                }
            }
        }
    }

    // Ctrl+C received — kill all children
    eprintln!("\nShutting down watchers...");
    for (name, mut child) in children {
        match child.kill() {
            Ok(()) => {
                let _ = child.wait();
                eprintln!("[{name}] Stopped");
            }
            Err(e) => {
                // Already exited
                if e.kind() != std::io::ErrorKind::InvalidInput {
                    eprintln!("[{name}] Failed to stop: {e}");
                }
                let _ = child.wait();
            }
        }
    }

    eprintln!("All watchers stopped.");
    Ok(())
}