sqry-cli 14.0.3

CLI for sqry - semantic code search
Documentation
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
//! Workspace command implementations (`sqry workspace …`)

use crate::args::{Cli, WorkspaceCommand, WorkspaceDiscoveryMode};
use crate::output::{JsonFormatter, NameDisplayMode, OutputStreams, TextFormatter};
use anyhow::{Context, Result, anyhow, bail};
use sqry_core::workspace::{
    DiscoveryMode, WorkspaceIndex, WorkspaceRegistry, WorkspaceRepoId, WorkspaceRepository,
    discover_repositories,
};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

const REGISTRY_FILE: &str = ".sqry-workspace";

/// Entry point for all workspace subcommands.
///
/// # Errors
/// Returns an error if any subcommand fails to execute.
///
/// # STEP_8 invariant
///
/// `sqry workspace …` is incompatible with the global `--workspace` /
/// `SQRY_WORKSPACE_FILE` flag — each `WorkspaceCommand` variant carries its
/// own positional `<workspace>` argument, and silently choosing between the
/// two is a footgun. The collision is rejected by `main.rs` *before* entering
/// this function; reaching here implies `cli.workspace.is_none()`.
pub fn run_workspace(cli: &Cli, action: &WorkspaceCommand) -> Result<()> {
    match action {
        WorkspaceCommand::Init {
            workspace,
            mode,
            name,
        } => init_workspace(cli, workspace, *mode, name.as_ref()),
        WorkspaceCommand::Scan {
            workspace,
            mode,
            prune_stale,
        } => scan_workspace(cli, workspace, *mode, *prune_stale),
        WorkspaceCommand::Add {
            workspace,
            repo,
            name,
        } => add_repository(cli, workspace, repo, name.as_ref()),
        WorkspaceCommand::Remove { workspace, repo_id } => {
            remove_repository(cli, workspace, repo_id)
        }
        WorkspaceCommand::Query {
            workspace,
            query,
            threads,
        } => query_workspace(cli, workspace, query, *threads),
        WorkspaceCommand::Stats { workspace } => stats_workspace(cli, workspace),
        WorkspaceCommand::Status {
            workspace,
            json,
            no_cache,
        } => crate::commands::workspace_status::run(cli, workspace, *json, *no_cache),
        WorkspaceCommand::Clean {
            root,
            apply,
            force,
            include_user_state,
            json,
        } => crate::commands::workspace_clean::run(
            cli,
            root,
            *apply,
            *force,
            *include_user_state,
            *json,
        ),
    }
}

fn init_workspace(
    cli: &Cli,
    workspace: &str,
    mode: WorkspaceDiscoveryMode,
    name: Option<&String>,
) -> Result<()> {
    let workspace_root = PathBuf::from(workspace);
    fs::create_dir_all(&workspace_root).with_context(|| {
        format!(
            "Failed to create workspace directory {}",
            workspace_root.display()
        )
    })?;

    let registry_path = registry_path(&workspace_root);
    if registry_path.exists() {
        bail!(
            "Workspace registry already exists at {}. Use `sqry workspace scan` or other commands instead.",
            registry_path.display()
        );
    }

    let mut registry = WorkspaceRegistry::new(
        name.cloned()
            .or_else(|| derive_workspace_name(&workspace_root)),
    );
    registry.metadata.default_discovery_mode = Some(mode_label(mode).to_string());
    registry
        .save(&registry_path)
        .with_context(|| format!("Failed to write registry at {}", registry_path.display()))?;

    let mut streams = OutputStreams::with_pager(cli.pager_config());
    streams.write_result(&format!(
        "Workspace initialised at {}",
        registry_path.display()
    ))?;
    if let Some(name) = &registry.metadata.workspace_name {
        streams.write_result(&format!("Name: {name}"))?;
    }
    streams.write_result(&format!("Default discovery mode: {}", mode_label(mode)))?;
    streams.finish_checked()
}

fn scan_workspace(
    cli: &Cli,
    workspace: &str,
    mode: WorkspaceDiscoveryMode,
    prune_stale: bool,
) -> Result<()> {
    let workspace_root = canonicalize_existing(workspace)
        .with_context(|| format!("Workspace path {workspace} not found"))?;
    let registry_path = registry_path(&workspace_root);

    let mut registry = WorkspaceRegistry::load(&registry_path)
        .with_context(|| format!("Failed to load registry at {}", registry_path.display()))?;

    let discovery_mode = convert_mode(mode);
    let discovered = discover_repositories(&workspace_root, discovery_mode).with_context(|| {
        format!(
            "Failed to discover repositories under {}",
            workspace_root.display()
        )
    })?;

    let mut known_ids: HashSet<_> = registry
        .repositories
        .iter()
        .map(|repo| repo.id.clone())
        .collect();

    let mut added = 0usize;
    let mut updated = 0usize;

    for mut repo in discovered {
        // Refresh metadata (discovery already sets last_indexed_at but be defensive)
        if let Ok(meta) = fs::metadata(&repo.index_path)
            && let Ok(modified) = meta.modified()
        {
            repo.last_indexed_at = Some(modified);
        }

        if known_ids.contains(&repo.id) {
            updated += 1;
        } else {
            added += 1;
            known_ids.insert(repo.id.clone());
        }
        registry.upsert_repo(repo)?;
    }

    let mut pruned = 0usize;
    if prune_stale {
        let before = registry.repositories.len();
        registry
            .repositories
            .retain(|repo| repo.index_path.exists());
        pruned = before.saturating_sub(registry.repositories.len());
    }

    registry.metadata.default_discovery_mode = Some(mode_label(mode).to_string());
    registry
        .save(&registry_path)
        .with_context(|| format!("Failed to update registry at {}", registry_path.display()))?;

    let mut streams = OutputStreams::with_pager(cli.pager_config());
    streams.write_result(&format!(
        "Scan complete: {} added, {} updated{}",
        added,
        updated,
        if prune_stale {
            format!(", {pruned} pruned")
        } else {
            String::new()
        }
    ))?;
    streams.write_result(&format!("Registry saved to {}", registry_path.display()))?;
    streams.finish_checked()
}

fn add_repository(cli: &Cli, workspace: &str, repo: &str, name: Option<&String>) -> Result<()> {
    let workspace_root = canonicalize_existing(workspace)
        .with_context(|| format!("Workspace path {workspace} not found"))?;
    let registry_path = registry_path(&workspace_root);
    let mut registry = WorkspaceRegistry::load(&registry_path)
        .with_context(|| format!("Failed to load registry at {}", registry_path.display()))?;

    let repo_root =
        canonicalize_existing(repo).with_context(|| format!("Repository path {repo} not found"))?;
    // Check for the unified graph index path (.sqry/graph)
    let index_path = repo_root.join(".sqry").join("graph");
    if !index_path.exists() {
        bail!(
            "Repository {} does not contain an index. Run `sqry index {}` first.",
            repo_root.display(),
            repo_root.display()
        );
    }

    let relative = repo_root.strip_prefix(&workspace_root).map_err(|_| {
        anyhow!(
            "Repository {} is not inside the workspace {}",
            repo_root.display(),
            workspace_root.display()
        )
    })?;
    let repo_id = WorkspaceRepoId::new(relative);
    let repo_name = name
        .cloned()
        .or_else(|| derive_workspace_name(&repo_root))
        .ok_or_else(|| {
            anyhow!(
                "Unable to determine repository name for {}",
                repo_root.display()
            )
        })?;

    let last_indexed_at = fs::metadata(&index_path)
        .ok()
        .and_then(|meta| meta.modified().ok());
    let repo_entry = WorkspaceRepository::new(
        repo_id.clone(),
        repo_name.clone(),
        repo_root.clone(),
        index_path,
        last_indexed_at,
    );

    let existed = registry
        .repositories
        .iter()
        .any(|existing| existing.id == repo_id);
    registry.upsert_repo(repo_entry)?;
    registry
        .save(&registry_path)
        .with_context(|| format!("Failed to update registry at {}", registry_path.display()))?;

    let mut streams = OutputStreams::with_pager(cli.pager_config());
    if existed {
        streams.write_result(&format!(
            "Updated repository {} ({}) in {}",
            repo_name,
            repo_id.as_str(),
            registry_path.display()
        ))?;
    } else {
        streams.write_result(&format!(
            "Added repository {} ({}) to {}",
            repo_name,
            repo_id.as_str(),
            registry_path.display()
        ))?;
    }
    streams.finish_checked()
}

fn remove_repository(cli: &Cli, workspace: &str, repo_id: &str) -> Result<()> {
    let workspace_root = canonicalize_existing(workspace)
        .with_context(|| format!("Workspace path {workspace} not found"))?;
    let registry_path = registry_path(&workspace_root);
    let mut registry = WorkspaceRegistry::load(&registry_path)
        .with_context(|| format!("Failed to load registry at {}", registry_path.display()))?;

    let removed = registry.remove_repo(&WorkspaceRepoId::new(repo_id));
    if !removed {
        bail!("Repository '{repo_id}' not found in workspace");
    }

    registry
        .save(&registry_path)
        .with_context(|| format!("Failed to update registry at {}", registry_path.display()))?;
    let mut streams = OutputStreams::with_pager(cli.pager_config());
    streams.write_result(&format!(
        "Removed repository '{}' from {}",
        repo_id,
        registry_path.display()
    ))?;
    streams.finish_checked()
}

fn query_workspace(
    cli: &Cli,
    workspace: &str,
    query_str: &str,
    threads: Option<usize>,
) -> Result<()> {
    if threads.is_some() {
        log::info!("Thread override not applicable for workspace queries (build-time only)");
    }

    let workspace_root = canonicalize_existing(workspace)
        .with_context(|| format!("Workspace path {workspace} not found"))?;
    let registry_path = registry_path(&workspace_root);

    let mut index = WorkspaceIndex::open(&workspace_root, &registry_path)
        .with_context(|| format!("Failed to open workspace at {}", registry_path.display()))?;

    let mut results = index
        .query(query_str)
        .with_context(|| "Workspace query execution failed".to_string())?;

    let total_results = results.len();
    if let Some(limit) = cli.limit
        && results.len() > limit
    {
        results.truncate(limit);
    }

    if cli.count {
        println!("{}", results.len());
        return Ok(());
    }
    let mut streams = OutputStreams::with_pager(cli.pager_config());

    if cli.json {
        JsonFormatter::format_workspace(&results, &mut streams)?;
    } else {
        let mode = if cli.qualified_names {
            NameDisplayMode::Qualified
        } else {
            NameDisplayMode::Simple
        };
        let theme = crate::output::resolve_theme(cli);
        let use_color = !cli.no_color
            && theme != crate::output::ThemeName::None
            && std::env::var("NO_COLOR").is_err();
        let formatter = TextFormatter::new(use_color, mode, theme);
        formatter.format_workspace(&results, &mut streams)?;
        if let Some(limit) = cli.limit
            && total_results > limit
        {
            streams.write_diagnostic(&format!(
                "Note: showing {} of {} results (--limit={})",
                results.len(),
                total_results,
                limit
            ))?;
        }
    }

    streams.finish_checked()
}

fn stats_workspace(cli: &Cli, workspace: &str) -> Result<()> {
    let workspace_root = canonicalize_existing(workspace)
        .with_context(|| format!("Workspace path {workspace} not found"))?;
    let registry_path = registry_path(&workspace_root);

    let index = WorkspaceIndex::open(&workspace_root, &registry_path)
        .with_context(|| format!("Failed to open workspace at {}", registry_path.display()))?;
    let detailed_stats = index.detailed_stats();
    let metadata = &index.registry().metadata;

    let mut streams = OutputStreams::with_pager(cli.pager_config());

    let registry = index.registry();
    let project_root_mode = registry.project_root_mode.as_str();
    let member_folder_count = registry.member_folders.len();
    let exclusion_count = registry.exclusions.len();

    if cli.json {
        let json = serde_json::json!({
            "workspace": {
                "path": workspace_root,
                "name": metadata.workspace_name,
                "default_discovery_mode": metadata.default_discovery_mode,
                "project_root_mode": project_root_mode,
                "schema_version": metadata.version,
            },
            "repositories": {
                "total": detailed_stats.total_repos,
                "indexed": detailed_stats.indexed_repos,
                "unindexed": detailed_stats.unindexed_repos,
            },
            "member_folders": { "total": member_folder_count },
            "exclusions": { "total": exclusion_count },
            "symbols": {
                "total": detailed_stats.total_symbols,
                "avg_per_repo": detailed_stats.avg_symbols_per_repo,
            },
            "freshness": {
                "fresh": detailed_stats.freshness.fresh,
                "recent": detailed_stats.freshness.recent,
                "stale": detailed_stats.freshness.stale,
                "very_stale": detailed_stats.freshness.very_stale,
                "never_indexed": detailed_stats.freshness.never_indexed,
            },
            "health": {
                "score": detailed_stats.health_score(),
                "status": detailed_stats.health_status(),
            }
        });
        streams.write_result(&serde_json::to_string_pretty(&json)?)?;
    } else {
        streams.write_result(&format!("Workspace: {}", workspace_root.display()))?;
        if let Some(name) = &metadata.workspace_name {
            streams.write_result(&format!("Name: {name}"))?;
        }
        if let Some(mode) = &metadata.default_discovery_mode {
            streams.write_result(&format!("Default discovery mode: {mode}"))?;
        }
        streams.write_result("")?;
        streams.write_result(&format!("Project root mode: {project_root_mode}"))?;
        streams.write_result(&format!(
            "Source roots: {} total ({} indexed, {} unindexed)",
            detailed_stats.total_repos,
            detailed_stats.indexed_repos,
            detailed_stats.unindexed_repos
        ))?;
        streams.write_result(&format!("Member folders: {member_folder_count}"))?;
        streams.write_result(&format!("Exclusions: {exclusion_count}"))?;
        streams.write_result(&format!(
            "Total symbols: {} ({:.1} avg per repo)",
            detailed_stats.total_symbols, detailed_stats.avg_symbols_per_repo
        ))?;
        streams.write_result("")?;
        streams.write_result("Freshness:")?;
        streams.write_result(&format!(
            "  Fresh (< 1 hour):     {}",
            detailed_stats.freshness.fresh
        ))?;
        streams.write_result(&format!(
            "  Recent (< 1 day):     {}",
            detailed_stats.freshness.recent
        ))?;
        streams.write_result(&format!(
            "  Stale (< 1 week):     {}",
            detailed_stats.freshness.stale
        ))?;
        streams.write_result(&format!(
            "  Very stale (> 1 week): {}",
            detailed_stats.freshness.very_stale
        ))?;
        streams.write_result(&format!(
            "  Never indexed:        {}",
            detailed_stats.freshness.never_indexed
        ))?;
        streams.write_result("")?;
        streams.write_result(&format!(
            "Health: {} ({:.1}%)",
            detailed_stats.health_status(),
            detailed_stats.health_score() * 100.0
        ))?;
    }

    streams.finish_checked()
}

fn registry_path(workspace_root: &Path) -> PathBuf {
    workspace_root.join(REGISTRY_FILE)
}

fn convert_mode(mode: WorkspaceDiscoveryMode) -> DiscoveryMode {
    match mode {
        WorkspaceDiscoveryMode::IndexFiles => DiscoveryMode::IndexFiles,
        WorkspaceDiscoveryMode::GitRoots => DiscoveryMode::GitRoots,
    }
}

fn mode_label(mode: WorkspaceDiscoveryMode) -> &'static str {
    match mode {
        WorkspaceDiscoveryMode::IndexFiles => "index-files",
        WorkspaceDiscoveryMode::GitRoots => "git-roots",
    }
}

fn derive_workspace_name(path: &Path) -> Option<String> {
    path.file_name()
        .or_else(|| {
            path.components()
                .next_back()
                .map(std::path::Component::as_os_str)
        })
        .map(|os| os.to_string_lossy().into_owned())
}

fn canonicalize_existing(path: &str) -> Result<PathBuf> {
    let candidate = PathBuf::from(path);
    if candidate.exists() {
        candidate
            .canonicalize()
            .with_context(|| format!("Failed to resolve path {path}"))
    } else {
        Err(anyhow!("Path '{path}' does not exist"))
    }
}