git-prism 0.8.0

Agent-optimized git data MCP server — structured change manifests and full file snapshots for LLM agents
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
pub mod context;
pub mod history;
pub mod import_scope;
pub mod manifest;
pub mod review_change;
pub mod size;
pub mod snapshots;
pub mod types;

pub use context::{ContextOptions, build_function_context_with_options};
pub use history::build_history;
pub use manifest::{build_manifest, build_worktree_manifest, enforce_token_budget};
pub use review_change::{ReviewChangeArgs, ReviewChangeResponse, build_review_change};
pub use snapshots::build_snapshots;
pub use types::{
    ContextArgs, FunctionContextResponse, HistoryArgs, HistoryResponse, ManifestArgs,
    ManifestOptions, ManifestResponse, SnapshotArgs, SnapshotOptions, SnapshotResponse,
};

use std::path::Path;

use crate::pagination::{self, decode_cursor};

/// Assemble paginated manifest pages into a single combined [`ManifestResponse`],
/// then apply token-budget enforcement on the combined result.
///
/// `fetch_page` is called with `(offset, page_size)` and must return one page.
/// The first call is always at offset 0; subsequent calls use the cursor offset
/// from the previous page's `pagination.next_cursor`.
///
/// Budget enforcement is intentionally deferred to the combined response:
/// per-page enforcement would cap each page individually but the caller would
/// re-assemble them all, defeating the budget.
pub fn collect_manifest_pages(
    fetch_page: impl Fn(usize, usize) -> anyhow::Result<ManifestResponse>,
    options: &ManifestOptions,
    page_size: usize,
) -> anyhow::Result<ManifestResponse> {
    let page_size = pagination::clamp_page_size(page_size);

    let mut all_files = Vec::new();

    let first_page = fetch_page(0, page_size)?;
    all_files.extend(first_page.files);

    let mut next_cursor = first_page.pagination.next_cursor.clone();
    while let Some(ref cursor_str) = next_cursor {
        let cursor = decode_cursor(cursor_str)?;
        let page = fetch_page(cursor.offset, page_size)?;
        all_files.extend(page.files);
        next_cursor = page.pagination.next_cursor.clone();
    }

    let total_items = all_files.len();
    let mut response = ManifestResponse {
        metadata: first_page.metadata,
        summary: first_page.summary,
        files: all_files,
        dependency_changes: first_page.dependency_changes,
        pagination: pagination::PaginationInfo {
            total_items,
            page_start: 0,
            page_size: total_items,
            next_cursor: None,
        },
    };

    if let Some(budget) = options.max_response_tokens.filter(|&b| b > 0)
        && options.include_function_analysis
    {
        let trimmed = enforce_token_budget(&mut response, budget);
        response.metadata.function_analysis_truncated = trimmed;
        response.pagination.page_size = response.files.len();
    }
    response.metadata.token_estimate = size::estimate_response_tokens(&response);

    Ok(response)
}

/// Collect all manifest pages for a commit-to-commit range into a single
/// combined response.
pub fn collect_all_manifest_pages(
    repo_path: &Path,
    base: &str,
    head: &str,
    options: &ManifestOptions,
    page_size: usize,
) -> anyhow::Result<ManifestResponse> {
    let collection_options = ManifestOptions {
        max_response_tokens: None,
        ..options.clone()
    };
    collect_manifest_pages(
        |offset, ps| {
            build_manifest(repo_path, base, head, &collection_options, offset, ps)
                .map_err(anyhow::Error::from)
        },
        options,
        page_size,
    )
}

/// Collect all manifest pages in worktree mode into a single combined response.
pub fn collect_all_worktree_manifest_pages(
    repo_path: &Path,
    base: &str,
    options: &ManifestOptions,
    page_size: usize,
) -> anyhow::Result<ManifestResponse> {
    let collection_options = ManifestOptions {
        max_response_tokens: None,
        ..options.clone()
    };
    collect_manifest_pages(
        |offset, ps| {
            build_worktree_manifest(repo_path, base, &collection_options, offset, ps)
                .map_err(anyhow::Error::from)
        },
        options,
        page_size,
    )
}

/// Collect all history pages into a single combined response.
pub fn collect_all_history_pages(
    repo_path: &Path,
    base: &str,
    head: &str,
    options: &ManifestOptions,
    page_size: usize,
) -> anyhow::Result<HistoryResponse> {
    let page_size = pagination::clamp_page_size(page_size);
    let mut all_commits = Vec::new();

    let first_page = build_history(repo_path, base, head, options, 0, page_size)?;
    all_commits.extend(first_page.commits);

    let mut next_cursor = first_page.pagination.next_cursor.clone();
    while let Some(ref cursor_str) = next_cursor {
        let cursor = decode_cursor(cursor_str)?;
        let page = build_history(repo_path, base, head, options, cursor.offset, page_size)?;
        all_commits.extend(page.commits);
        next_cursor = page.pagination.next_cursor.clone();
    }

    let total_items = all_commits.len();
    Ok(HistoryResponse {
        commits: all_commits,
        pagination: pagination::PaginationInfo {
            total_items,
            page_start: 0,
            page_size: total_items,
            next_cursor: None,
        },
    })
}

/// Extract the file extension from a path.
///
/// Returns the substring after the final `.`, or `""` when the path has no
/// extension or the "extension" is actually a dotfile basename like
/// `.gitignore`. The `path.len() > ext.len() + 1` guard rejects the
/// dotfile case: `.gitignore` splits as `("", "gitignore")` but the full
/// path length equals the candidate extension length plus one character
/// for the leading dot, which means there's no real basename before it.
///
/// Used by the manifest and context tools to look up language analyzers.
/// `pub(crate)` rather than `pub` so the helper stays an internal
/// orchestration detail — downstream MCP clients should not depend on it.
pub(crate) fn extension_from_path(path: &str) -> &str {
    path.rsplit('.')
        .next()
        .filter(|ext| path.len() > ext.len() + 1)
        .unwrap_or("")
}

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

    #[test]
    fn extension_from_path_returns_extension_for_simple_file() {
        assert_eq!(extension_from_path("lib.rs"), "rs");
    }

    #[test]
    fn extension_from_path_returns_last_extension_for_double_extension() {
        assert_eq!(extension_from_path("foo.test.ts"), "ts");
    }

    #[test]
    fn extension_from_path_returns_empty_for_no_extension() {
        assert_eq!(extension_from_path("Makefile"), "");
    }

    #[test]
    fn extension_from_path_returns_empty_for_empty_string() {
        assert_eq!(extension_from_path(""), "");
    }

    #[test]
    fn extension_from_path_handles_nested_path() {
        assert_eq!(extension_from_path("src/tools/context.rs"), "rs");
    }

    #[test]
    fn extension_from_path_returns_empty_for_dotfile() {
        // `.gitignore` splits as ("", "gitignore") but path.len() == ext.len() + 1
        // so the filter rejects it and returns "".
        assert_eq!(extension_from_path(".gitignore"), "");
    }

    // --- collect_all_manifest_pages / collect_all_history_pages tests ---

    use std::process::Command;
    use tempfile::TempDir;

    fn create_repo_with_many_files(file_count: usize) -> (TempDir, std::path::PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().to_path_buf();
        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&path)
            .output()
            .unwrap();
        std::fs::write(path.join("README.md"), "# base\n").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "base commit"])
            .current_dir(&path)
            .output()
            .unwrap();
        for i in 0..file_count {
            std::fs::write(path.join(format!("file_{i}.txt")), format!("content {i}\n")).unwrap();
        }
        Command::new("git")
            .args(["add", "."])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "add many files"])
            .current_dir(&path)
            .output()
            .unwrap();
        (dir, path)
    }

    fn create_repo_with_many_commits(commit_count: usize) -> (TempDir, std::path::PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().to_path_buf();
        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&path)
            .output()
            .unwrap();
        std::fs::write(path.join("README.md"), "# anchor\n").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "anchor"])
            .current_dir(&path)
            .output()
            .unwrap();
        for i in 0..commit_count {
            std::fs::write(path.join(format!("file_{i}.txt")), format!("content {i}\n")).unwrap();
            Command::new("git")
                .args(["add", "."])
                .current_dir(&path)
                .output()
                .unwrap();
            Command::new("git")
                .args(["commit", "-m", &format!("commit {i}")])
                .current_dir(&path)
                .output()
                .unwrap();
        }
        (dir, path)
    }

    #[test]
    fn collect_all_manifest_pages_returns_all_files_when_single_page() {
        let (_dir, path) = create_repo_with_many_files(3);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_manifest_pages(&path, "HEAD~1", "HEAD", &options, 500).unwrap();
        assert_eq!(result.files.len(), 3);
        assert!(result.pagination.next_cursor.is_none());
        assert_eq!(result.pagination.total_items, 3);
    }

    #[test]
    fn collect_all_manifest_pages_collects_across_multiple_pages() {
        let (_dir, path) = create_repo_with_many_files(5);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_manifest_pages(&path, "HEAD~1", "HEAD", &options, 2).unwrap();
        assert_eq!(result.files.len(), 5);
        assert!(result.pagination.next_cursor.is_none());
        assert_eq!(result.pagination.total_items, 5);
    }

    #[test]
    fn collect_all_manifest_pages_preserves_metadata_from_first_page() {
        let (_dir, path) = create_repo_with_many_files(5);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_manifest_pages(&path, "HEAD~1", "HEAD", &options, 2).unwrap();
        assert_eq!(result.metadata.base_ref, "HEAD~1");
        assert_eq!(result.metadata.head_ref, "HEAD");
        assert!(!result.metadata.base_sha.is_empty());
        assert!(!result.metadata.head_sha.is_empty());
    }

    #[test]
    fn collect_all_manifest_pages_with_page_size_1() {
        let (_dir, path) = create_repo_with_many_files(3);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_manifest_pages(&path, "HEAD~1", "HEAD", &options, 1).unwrap();
        assert_eq!(result.files.len(), 3);
        assert!(result.pagination.next_cursor.is_none());
    }

    #[test]
    fn collect_all_history_pages_returns_all_commits_when_single_page() {
        let (_dir, path) = create_repo_with_many_commits(3);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_history_pages(&path, "HEAD~3", "HEAD", &options, 500).unwrap();
        assert_eq!(result.commits.len(), 3);
        assert!(result.pagination.next_cursor.is_none());
        assert_eq!(result.pagination.total_items, 3);
    }

    #[test]
    fn collect_all_history_pages_collects_across_multiple_pages() {
        let (_dir, path) = create_repo_with_many_commits(5);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_history_pages(&path, "HEAD~5", "HEAD", &options, 2).unwrap();
        assert_eq!(result.commits.len(), 5);
        assert!(result.pagination.next_cursor.is_none());
        assert_eq!(result.pagination.total_items, 5);
    }

    #[test]
    fn collect_all_history_pages_preserves_commit_order() {
        let (_dir, path) = create_repo_with_many_commits(4);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_history_pages(&path, "HEAD~4", "HEAD", &options, 2).unwrap();
        assert_eq!(result.commits.len(), 4);
        assert_eq!(result.commits[0].metadata.message, "commit 0");
        assert_eq!(result.commits[1].metadata.message, "commit 1");
        assert_eq!(result.commits[2].metadata.message, "commit 2");
        assert_eq!(result.commits[3].metadata.message, "commit 3");
    }

    #[test]
    fn collect_all_history_pages_with_page_size_1() {
        let (_dir, path) = create_repo_with_many_commits(3);
        let options = ManifestOptions {
            include_patterns: vec![],
            exclude_patterns: vec![],
            include_function_analysis: false,
            max_response_tokens: None,
        };
        let result = collect_all_history_pages(&path, "HEAD~3", "HEAD", &options, 1).unwrap();
        assert_eq!(result.commits.len(), 3);
        assert!(result.pagination.next_cursor.is_none());
    }
}