agentis-ctx 0.3.4

Fast CLI tool that generates AI-ready context from your codebase, with built-in code intelligence
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
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
//! Shared git helpers for quality commands.
//!
//! All helpers shell out to `git` (matching the style of [`crate::diff`]) and
//! operate on the process working directory. Paths returned by these helpers
//! are relative to the working directory (the repo prefix is stripped), so
//! they line up with index-relative paths in `.ctx/codebase.sqlite`.

use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::{Command, Output};

use crate::error::{CtxError, Result};

/// Check if the current directory is inside a git repository.
pub fn is_git_repo() -> bool {
    is_git_repo_in(Path::new("."))
}

/// Get the path of the current directory relative to the repository root.
///
/// Returns `""` at the repo root, or a prefix like `"sub/dir/"` (with a
/// trailing slash) inside a subdirectory.
pub fn repo_prefix() -> Result<String> {
    repo_prefix_in(Path::new("."))
}

/// Get the set of files changed relative to `reference`.
///
/// The result is the union of:
/// - `git diff --name-only <reference>...HEAD` (committed changes since the
///   merge base with `reference`)
/// - `git diff --name-only HEAD` (uncommitted working-tree changes)
/// - `git ls-files --others --exclude-standard` (untracked files)
///
/// Paths are relative to the current directory; files outside it are dropped.
pub fn changed_files_against(reference: &str) -> Result<HashSet<String>> {
    changed_files_against_in(Path::new("."), reference)
}

/// Count how many commits touched each file since `since` (a `git log --since`
/// date spec, e.g. `"6 months ago"` or `"2025-01-01"`).
///
/// Paths are relative to the current directory; only files under it are
/// counted.
pub fn churn_since(since: &str) -> Result<HashMap<String, u32>> {
    churn_since_in(Path::new("."), since)
}

/// Get the contents of `path` (relative to the current directory) at
/// `reference`, or `None` if the file does not exist at that revision.
pub fn show_file(reference: &str, path: &str) -> Result<Option<String>> {
    show_file_in(Path::new("."), reference, path)
}

// ============================================================================
// Directory-explicit implementations (used directly by tests)
// ============================================================================

/// Dir-explicit variant of [`is_git_repo`], for commands and tests that
/// operate on an explicit project root instead of the process cwd.
pub fn is_git_repo_in(dir: &Path) -> bool {
    Command::new("git")
        .args(["rev-parse", "--git-dir"])
        .current_dir(dir)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn repo_prefix_in(dir: &Path) -> Result<String> {
    let output = run_git(dir, &["rev-parse", "--show-prefix"])?;
    let stdout = stdout_or_err(output, None)?;
    Ok(stdout.trim_end_matches(['\n', '\r']).to_string())
}

/// Dir-explicit variant of [`changed_files_against`], for commands and tests
/// that operate on an explicit project root instead of the process cwd.
pub fn changed_files_against_in(dir: &Path, reference: &str) -> Result<HashSet<String>> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    let prefix = repo_prefix_in(dir)?;
    let mut files = HashSet::new();

    // Committed changes since the merge base with the reference.
    let range = format!("{}...HEAD", reference);
    let output = run_git(dir, &["diff", "--name-only", &range])?;
    let committed = stdout_or_err(output, Some(reference))?;
    collect_paths(&committed, &prefix, &mut files);

    // Uncommitted (staged + unstaged) changes.
    let output = run_git(dir, &["diff", "--name-only", "HEAD"])?;
    let uncommitted = stdout_or_err(output, None)?;
    collect_paths(&uncommitted, &prefix, &mut files);

    // Untracked files (--full-name makes paths repo-root-relative like diff).
    let output = run_git(
        dir,
        &["ls-files", "--others", "--exclude-standard", "--full-name"],
    )?;
    let untracked = stdout_or_err(output, None)?;
    collect_paths(&untracked, &prefix, &mut files);

    Ok(files)
}

fn churn_since_in(dir: &Path, since: &str) -> Result<HashMap<String, u32>> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    let prefix = repo_prefix_in(dir)?;
    let since_arg = format!("--since={}", since);
    let output = run_git(
        dir,
        &[
            "log",
            &since_arg,
            "--format=",
            "--name-only",
            "--no-renames",
            "--",
            ".",
        ],
    )?;
    let log = stdout_or_err(output, None)?;

    let mut churn = HashMap::new();
    for (path, count) in parse_name_only_log(&log) {
        if let Some(local) = strip_repo_prefix(&path, &prefix) {
            *churn.entry(local).or_insert(0) += count;
        }
    }
    Ok(churn)
}

/// Count how many commits touched each file since `since`, optionally
/// anchored with `--until=<until>` (any `git log` date spec).
///
/// Like [`churn_since`] but dir-explicit and with an optional upper bound,
/// so historical snapshots can measure churn as of a commit's date instead
/// of wall-clock now.
pub fn churn_between_in(
    dir: &Path,
    since: &str,
    until: Option<&str>,
) -> Result<HashMap<String, u32>> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    let prefix = repo_prefix_in(dir)?;
    let since_arg = format!("--since={}", since);
    let until_arg = until.map(|u| format!("--until={}", u));
    let mut args = vec!["log", &since_arg];
    if let Some(ref until_arg) = until_arg {
        args.push(until_arg);
    }
    args.extend(["--format=", "--name-only", "--no-renames", "--", "."]);
    let output = run_git(dir, &args)?;
    let log = stdout_or_err(output, None)?;

    let mut churn = HashMap::new();
    for (path, count) in parse_name_only_log(&log) {
        if let Some(local) = strip_repo_prefix(&path, &prefix) {
            *churn.entry(local).or_insert(0) += count;
        }
    }
    Ok(churn)
}

/// The current HEAD commit as `(full sha, committer date)`.
///
/// The committer date is strict ISO 8601 (`git log --format=%cI`, e.g.
/// `2026-07-09T12:00:00+02:00`).
pub fn head_commit_in(dir: &Path) -> Result<(String, String)> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    let output = run_git(dir, &["log", "-1", "--format=%H%x00%cI"])?;
    let stdout = stdout_or_err(output, Some("HEAD"))?;
    let line = stdout.trim();
    let (sha, date) = line
        .split_once('\0')
        .ok_or_else(|| CtxError::git(format!("unexpected `git log -1` output: {:?}", line)))?;
    Ok((sha.to_string(), date.to_string()))
}

/// First-parent commit shas in `range` (e.g. `abc123..HEAD`), oldest first.
pub fn rev_list_first_parent_in(dir: &Path, range: &str) -> Result<Vec<String>> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    let output = run_git(dir, &["rev-list", "--first-parent", "--reverse", range])?;
    let stdout = stdout_or_err(output, Some(range))?;
    Ok(stdout
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect())
}

/// Whether the working tree has uncommitted changes (staged, unstaged, or
/// untracked), per `git status --porcelain`.
pub fn is_dirty_in(dir: &Path) -> Result<bool> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    let output = run_git(dir, &["status", "--porcelain"])?;
    let stdout = stdout_or_err(output, None)?;
    Ok(stdout.lines().any(|l| !l.trim().is_empty()))
}

/// Dir-explicit variant of [`show_file`], for commands and tests that
/// operate on an explicit project root instead of the process cwd.
pub fn show_file_in(dir: &Path, reference: &str, path: &str) -> Result<Option<String>> {
    if !is_git_repo_in(dir) {
        return Err(CtxError::NotGitRepo);
    }

    // "REF:./path" makes git resolve the path relative to the current
    // directory, matching index-relative paths.
    let spec = format!("{}:./{}", reference, path);
    let output = run_git(dir, &["show", &spec])?;

    if output.status.success() {
        return Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()));
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.contains("does not exist") || stderr.contains("exists on disk, but not in") {
        return Ok(None);
    }
    // Reuse the shared error mapping for bad revisions and other failures.
    stdout_or_err(output, Some(reference)).map(Some)
}

// ============================================================================
// Helpers
// ============================================================================

/// Run a git command in `dir`, returning the raw output.
fn run_git(dir: &Path, args: &[&str]) -> Result<Output> {
    Ok(Command::new("git").args(args).current_dir(dir).output()?)
}

/// Convert a git `Output` into its stdout, mapping failures to `CtxError`.
///
/// If `revision` is given, revision-related failures map to
/// [`CtxError::InvalidRevision`] with that revision.
fn stdout_or_err(output: Output, revision: Option<&str>) -> Result<String> {
    if output.status.success() {
        return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.contains("not a git repository") {
        return Err(CtxError::NotGitRepo);
    }
    if let Some(rev) = revision {
        if stderr.contains("unknown revision")
            || stderr.contains("bad revision")
            || stderr.contains("invalid object name")
            || stderr.contains("bad object")
        {
            return Err(CtxError::InvalidRevision(rev.to_string()));
        }
    }
    Err(CtxError::git(stderr.trim().to_string()))
}

/// Parse `git log --format= --name-only` output into per-path commit counts.
///
/// Blank lines (commit separators) are skipped; each non-blank line is a path
/// that was touched by one commit.
fn parse_name_only_log(s: &str) -> HashMap<String, u32> {
    let mut counts = HashMap::new();
    for line in s.lines() {
        let line = line.trim_end_matches('\r');
        if line.trim().is_empty() {
            continue;
        }
        *counts.entry(line.to_string()).or_insert(0) += 1;
    }
    counts
}

/// Strip the repo prefix from a repo-root-relative path.
///
/// Returns `None` for paths outside the prefix (i.e. outside the current
/// directory).
fn strip_repo_prefix(path: &str, prefix: &str) -> Option<String> {
    if prefix.is_empty() {
        Some(path.to_string())
    } else {
        path.strip_prefix(prefix).map(|p| p.to_string())
    }
}

/// Add each non-blank, prefix-local path in `raw` to `files`.
fn collect_paths(raw: &str, prefix: &str, files: &mut HashSet<String>) {
    for line in raw.lines() {
        let line = line.trim_end_matches('\r');
        if line.trim().is_empty() {
            continue;
        }
        if let Some(local) = strip_repo_prefix(line, prefix) {
            files.insert(local);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testutil::GitRepo;

    #[test]
    fn test_parse_name_only_log() {
        let log = "src/a.rs\nsrc/b.rs\n\nsrc/a.rs\n\n\nsrc/c.rs\n";
        let counts = parse_name_only_log(log);
        assert_eq!(counts.len(), 3);
        assert_eq!(counts.get("src/a.rs"), Some(&2));
        assert_eq!(counts.get("src/b.rs"), Some(&1));
        assert_eq!(counts.get("src/c.rs"), Some(&1));
    }

    #[test]
    fn test_parse_name_only_log_empty() {
        assert!(parse_name_only_log("").is_empty());
        assert!(parse_name_only_log("\n\n\n").is_empty());
    }

    #[test]
    fn test_strip_repo_prefix() {
        assert_eq!(
            strip_repo_prefix("src/a.rs", ""),
            Some("src/a.rs".to_string())
        );
        assert_eq!(
            strip_repo_prefix("sub/src/a.rs", "sub/"),
            Some("src/a.rs".to_string())
        );
        assert_eq!(strip_repo_prefix("other/a.rs", "sub/"), None);
    }

    #[test]
    fn test_is_git_repo() {
        let dir = tempfile::tempdir().unwrap();
        assert!(!is_git_repo_in(dir.path()));

        let repo = GitRepo::init(dir.path());
        assert!(is_git_repo_in(&repo.root));
    }

    #[test]
    fn test_changed_files_against() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.commit_file("src/a.rs", "fn a() {}", "initial");

        repo.branch("feature");
        repo.commit_file("src/b.rs", "fn b() {}", "add b");

        // Uncommitted modification + untracked file.
        repo.write("src/a.rs", "fn a() { /* changed */ }");
        repo.write("src/c.rs", "fn c() {}");

        let changed = changed_files_against_in(&repo.root, "main").unwrap();
        assert_eq!(changed.len(), 3);
        assert!(changed.contains("src/a.rs"));
        assert!(changed.contains("src/b.rs"));
        assert!(changed.contains("src/c.rs"));
    }

    #[test]
    fn test_changed_files_strips_prefix_in_subdir() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.write("top.rs", "fn top() {}");
        repo.write("sub/x.rs", "fn x() {}");
        repo.commit_all("initial");

        repo.branch("feature");
        repo.write("top.rs", "fn top() { /* changed */ }");
        repo.write("sub/x.rs", "fn x() { /* changed */ }");
        repo.commit_all("change both");

        let subdir = repo.root.join("sub");
        let changed = changed_files_against_in(&subdir, "main").unwrap();
        // Only files under sub/, with the prefix stripped.
        assert_eq!(changed.len(), 1);
        assert!(changed.contains("x.rs"));
    }

    #[test]
    fn test_changed_files_bad_reference() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.commit_file("a.rs", "fn a() {}", "initial");

        let err = changed_files_against_in(&repo.root, "no-such-ref").unwrap_err();
        assert!(
            matches!(err, CtxError::InvalidRevision(ref r) if r == "no-such-ref"),
            "expected InvalidRevision, got: {}",
            err
        );
    }

    #[test]
    fn test_not_a_repo_errors() {
        let dir = tempfile::tempdir().unwrap();
        let err = changed_files_against_in(dir.path(), "main").unwrap_err();
        assert!(matches!(err, CtxError::NotGitRepo));
        let err = churn_since_in(dir.path(), "1 week ago").unwrap_err();
        assert!(matches!(err, CtxError::NotGitRepo));
    }

    #[test]
    fn test_churn_since() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.commit_file("src/a.rs", "v1", "one");
        repo.commit_file("src/a.rs", "v2", "two");
        repo.commit_file("src/b.rs", "v1", "three");

        let churn = churn_since_in(&repo.root, "2000-01-01").unwrap();
        assert_eq!(churn.get("src/a.rs"), Some(&2));
        assert_eq!(churn.get("src/b.rs"), Some(&1));
    }

    #[test]
    fn test_churn_between() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.write("src/a.rs", "v1");
        repo.commit_all_with_date("one", "2020-01-01T12:00:00 +0000");
        repo.write("src/a.rs", "v2");
        repo.commit_all_with_date("two", "2021-01-01T12:00:00 +0000");
        repo.write("src/b.rs", "v1");
        repo.commit_all_with_date("three", "2022-01-01T12:00:00 +0000");

        // Unbounded: all three commits count.
        let churn = churn_between_in(&repo.root, "2000-01-01", None).unwrap();
        assert_eq!(churn.get("src/a.rs"), Some(&2));
        assert_eq!(churn.get("src/b.rs"), Some(&1));

        // Anchored at mid-2021: the 2022 commit is excluded.
        let churn = churn_between_in(&repo.root, "2000-01-01", Some("2021-06-01")).unwrap();
        assert_eq!(churn.get("src/a.rs"), Some(&2));
        assert_eq!(churn.get("src/b.rs"), None);
    }

    #[test]
    fn test_churn_between_not_a_repo() {
        let dir = tempfile::tempdir().unwrap();
        let err = churn_between_in(dir.path(), "1 week ago", None).unwrap_err();
        assert!(matches!(err, CtxError::NotGitRepo));
    }

    #[test]
    fn test_head_commit() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.write("a.rs", "fn a() {}");
        repo.commit_all_with_date("initial", "2020-01-02T03:04:05 +0000");

        let (sha, date) = head_commit_in(&repo.root).unwrap();
        assert_eq!(sha.len(), 40, "expected a full sha: {}", sha);
        assert!(sha.chars().all(|c| c.is_ascii_hexdigit()));
        assert!(date.starts_with("2020-01-02T03:04:05"), "date: {}", date);

        // Not a repo -> error.
        let empty = tempfile::tempdir().unwrap();
        let err = head_commit_in(empty.path()).unwrap_err();
        assert!(matches!(err, CtxError::NotGitRepo));
    }

    #[test]
    fn test_rev_list_first_parent() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.commit_file("a.rs", "v1", "one");
        let (first, _) = head_commit_in(&repo.root).unwrap();
        repo.commit_file("a.rs", "v2", "two");
        repo.commit_file("a.rs", "v3", "three");
        let (head, _) = head_commit_in(&repo.root).unwrap();

        let shas = rev_list_first_parent_in(&repo.root, &format!("{}..HEAD", first)).unwrap();
        assert_eq!(shas.len(), 2, "expected the two commits after the first");
        assert_eq!(shas.last(), Some(&head), "oldest-first order");

        let err = rev_list_first_parent_in(&repo.root, "no-such..HEAD").unwrap_err();
        assert!(matches!(
            err,
            CtxError::InvalidRevision(_) | CtxError::Git(_)
        ));
    }

    #[test]
    fn test_is_dirty() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.commit_file("a.rs", "fn a() {}", "initial");
        assert!(!is_dirty_in(&repo.root).unwrap());

        // Untracked file counts as dirty.
        repo.write("b.rs", "fn b() {}");
        assert!(is_dirty_in(&repo.root).unwrap());

        // Modified tracked file counts as dirty.
        std::fs::remove_file(repo.root.join("b.rs")).unwrap();
        assert!(!is_dirty_in(&repo.root).unwrap());
        repo.write("a.rs", "fn a() { /* changed */ }");
        assert!(is_dirty_in(&repo.root).unwrap());
    }

    #[test]
    fn test_show_file() {
        let dir = tempfile::tempdir().unwrap();
        let repo = GitRepo::init(dir.path());
        repo.commit_file("src/a.rs", "fn a() {}", "initial");

        let content = show_file_in(&repo.root, "HEAD", "src/a.rs").unwrap();
        assert_eq!(content.as_deref(), Some("fn a() {}"));

        // Missing file at the revision -> None.
        let missing = show_file_in(&repo.root, "HEAD", "src/nope.rs").unwrap();
        assert!(missing.is_none());

        // Bad revision -> error.
        let err = show_file_in(&repo.root, "no-such-ref", "src/a.rs").unwrap_err();
        assert!(matches!(err, CtxError::InvalidRevision(_)));
    }
}