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
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::git::depfiles::DependencyDiff;
use crate::git::diff::{ChangeScope, ChangeType};
use crate::pagination::PaginationInfo;

// --- FunctionChange ---

#[derive(Debug, Clone, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FunctionChangeType {
    Added,
    Modified,
    Deleted,
    SignatureChanged,
    Renamed,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct FunctionChange {
    pub name: String,
    /// For renames, the original function name. Null otherwise.
    pub old_name: Option<String>,
    pub change_type: FunctionChangeType,
    pub start_line: usize,
    pub end_line: usize,
    pub signature: String,
}

impl FunctionChange {
    /// Build a change entry from a [`Function`] reference.
    pub fn from_function(
        f: &crate::treesitter::Function,
        change_type: FunctionChangeType,
        old_name: Option<String>,
    ) -> Self {
        Self {
            name: f.name.clone(),
            old_name,
            change_type,
            start_line: f.start_line,
            end_line: f.end_line,
            signature: f.signature.clone(),
        }
    }
}

// --- ImportChange ---

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ImportChange {
    pub added: Vec<String>,
    pub removed: Vec<String>,
}

// --- Manifest types ---

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ManifestMetadata {
    pub repo_path: String,
    pub base_ref: String,
    pub head_ref: String,
    pub base_sha: String,
    pub head_sha: String,
    pub generated_at: DateTime<Utc>,
    pub version: String,
    /// Estimated token count of the serialized response, via the ~4-chars-
    /// per-token heuristic in [`crate::tools::size::estimate_response_tokens`].
    /// Agents use this as a cheap pre-flight hint before requesting a follow-
    /// up call (e.g., `get_function_context` on the same range). Populated in
    /// a two-pass build: the response is first constructed with `0`, then the
    /// estimate is computed on that struct and written back. The final value
    /// is therefore a lower bound that undercounts by the single-digit
    /// character delta between `"token_estimate":0` and the real value, which
    /// is acceptable for a budgeting hint.
    pub token_estimate: usize,
    /// Paths of files whose function analysis was trimmed to fit the token
    /// budget. Only includes "tier 1" files (signatures preserved, imports
    /// stripped). Files stripped to bare entries are not listed.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub function_analysis_truncated: Vec<String>,
    /// Token budget that produced this response, when applicable. Set by the
    /// `review_change` orchestration tool, which splits its `max_response_tokens`
    /// 40/60 between the manifest and function-context sub-responses, so each
    /// sub-response carries its share for downstream observability. Standalone
    /// `get_change_manifest` calls leave this `None` (and serde skips the
    /// field) — the standalone tool already records its budget elsewhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget_tokens: Option<usize>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ManifestSummary {
    pub total_files_changed: usize,
    pub files_added: usize,
    pub files_modified: usize,
    pub files_deleted: usize,
    pub files_renamed: usize,
    pub total_lines_added: usize,
    pub total_lines_removed: usize,
    pub total_functions_changed: Option<usize>,
    pub languages_affected: Vec<String>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ManifestFileEntry {
    pub path: String,
    pub old_path: Option<String>,
    pub change_type: ChangeType,
    pub change_scope: ChangeScope,
    pub language: String,
    pub is_binary: bool,
    pub is_generated: bool,
    pub lines_added: usize,
    pub lines_removed: usize,
    pub size_before: usize,
    pub size_after: usize,
    pub functions_changed: Option<Vec<FunctionChange>>,
    pub imports_changed: Option<ImportChange>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ManifestResponse {
    pub metadata: ManifestMetadata,
    pub summary: ManifestSummary,
    pub files: Vec<ManifestFileEntry>,
    pub dependency_changes: Vec<DependencyDiff>,
    pub pagination: PaginationInfo,
}

// --- Snapshot types ---

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SnapshotMetadata {
    pub repo_path: String,
    pub base_ref: String,
    pub head_ref: String,
    pub generated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct FileContent {
    pub content: String,
    pub line_count: usize,
    pub size_bytes: usize,
    pub truncated: bool,
}

/// Unified diff hunk boundaries, mirroring the `@@ -old_start,old_lines +new_start,new_lines @@` header.
#[derive(Debug, Clone, Serialize, JsonSchema, PartialEq, Eq)]
pub struct DiffHunk {
    /// 1-based starting line number in the old (before) file.
    pub old_start: usize,
    /// Number of context+removed lines shown for the old side.
    pub old_lines: usize,
    /// 1-based starting line number in the new (after) file.
    pub new_start: usize,
    /// Number of context+added lines shown for the new side.
    pub new_lines: usize,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SnapshotFileEntry {
    pub path: String,
    pub language: String,
    pub is_binary: bool,
    pub before: Option<FileContent>,
    pub after: Option<FileContent>,
    /// Diff hunk metadata. Present only when `include_diff_hunks` is true
    /// and the file was modified (both before and after exist).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diff_hunks: Option<Vec<DiffHunk>>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SnapshotResponse {
    pub metadata: SnapshotMetadata,
    pub files: Vec<SnapshotFileEntry>,
    pub token_estimate: usize,
}

// --- MCP tool input types ---

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
pub struct ManifestArgs {
    pub base_ref: String,
    pub head_ref: Option<String>,
    pub repo_path: Option<String>,
    #[serde(default)]
    pub include_patterns: Vec<String>,
    #[serde(default)]
    pub exclude_patterns: Vec<String>,
    #[serde(default)]
    pub include_function_analysis: bool,
    /// Maximum estimated tokens for the full response. When exceeded,
    /// function/import analysis is progressively stripped per file.
    /// Default 8192. Pass 0 to disable budget enforcement.
    #[serde(default = "default_token_budget")]
    pub max_response_tokens: usize,
    /// Opaque pagination cursor from a previous response.
    pub cursor: Option<String>,
    /// Maximum file entries per page (1-500, default 100).
    #[serde(default = "default_page_size")]
    pub page_size: usize,
}

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
pub struct SnapshotArgs {
    pub base_ref: String,
    pub head_ref: Option<String>,
    pub paths: Vec<String>,
    pub repo_path: Option<String>,
    #[serde(default = "default_true")]
    pub include_before: bool,
    #[serde(default = "default_true")]
    pub include_after: bool,
    #[serde(default = "default_max_file_size")]
    pub max_file_size_bytes: usize,
    pub line_range: Option<(usize, usize)>,
    /// When true, include diff hunk metadata for modified files.
    #[serde(default)]
    pub include_diff_hunks: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
pub struct HistoryArgs {
    pub base_ref: String,
    pub head_ref: String,
    pub repo_path: Option<String>,
    /// Opaque pagination cursor from a previous response.
    pub cursor: Option<String>,
    /// Maximum commits per page (1-500, default 100).
    #[serde(default = "default_page_size")]
    pub page_size: usize,
}

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
pub struct ContextArgs {
    /// Base git ref (exclusive). Commits after this are considered.
    pub base_ref: String,
    /// Head git ref (inclusive). Required — this tool does not support working
    /// tree mode because callers/callees are resolved from committed content.
    pub head_ref: String,
    /// Path to the git repository (defaults to the server's working directory).
    pub repo_path: Option<String>,
    /// Opaque pagination cursor from a prior response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// Maximum functions per page (1–500, default 25). Function-context
    /// entries carry caller/callee/test lists that are expensive per entry,
    /// so the default is smaller than the manifest tool's 100-file default.
    #[serde(default = "default_context_page_size")]
    pub page_size: usize,
    /// When set, restrict the response to functions with these names. Useful
    /// for re-querying a function that was clamped on a prior paginated call.
    /// Must be identical across paginated calls (not validated by the cursor).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub function_names: Option<Vec<String>>,
    /// Response-size budget in estimated tokens. `0` disables the budget.
    /// Default 8192.
    #[serde(default = "default_context_max_tokens")]
    pub max_response_tokens: usize,
}

fn default_true() -> bool {
    true
}

fn default_token_budget() -> usize {
    8192
}

fn default_max_file_size() -> usize {
    100_000
}

fn default_page_size() -> usize {
    100
}

fn default_context_max_tokens() -> usize {
    8192
}

fn default_context_page_size() -> usize {
    25
}

// --- History types ---

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct CommitMetadata {
    pub sha: String,
    pub message: String,
    pub author: String,
    pub timestamp: String,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct CommitManifest {
    pub metadata: CommitMetadata,
    pub files: Vec<ManifestFileEntry>,
    pub summary: ManifestSummary,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct HistoryResponse {
    pub commits: Vec<CommitManifest>,
    pub pagination: PaginationInfo,
}

// --- FunctionContext types ---

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct CallerEntry {
    pub file: String,
    pub line: usize,
    pub caller: String,
    pub is_test: bool,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct CalleeEntry {
    pub callee: String,
    pub line: usize,
}

/// How the caller scan was performed for a given function.
///
/// `Scoped` means the scan used import-based filtering and may have excluded
/// files that don't explicitly import the changed module. `Fallback` means the
/// scan parsed every file in the repo (current behavior for languages without
/// import-scoping support). Agents can use this to tell whether a zero-caller
/// result is authoritative or potentially incomplete.
#[derive(Debug, Clone, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScopingMode {
    Scoped,
    Fallback,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct FunctionContextEntry {
    pub name: String,
    pub file: String,
    pub change_type: FunctionChangeType,
    pub blast_radius: BlastRadius,
    pub scoping_mode: ScopingMode,
    pub callers: Vec<CallerEntry>,
    pub callees: Vec<CalleeEntry>,
    pub test_references: Vec<CallerEntry>,
    /// Total callers (production + test) before any budget clamping. Preserved
    /// so agents can compute how many entries were omitted once `truncated`
    /// fires: `omitted = caller_count - callers.len() - test_references.len()`.
    pub caller_count: usize,
    /// True when this entry's caller / callee / test-reference lists were
    /// clamped by the response-size budget. The full lists can be recovered
    /// by re-querying with `function_names: [name]`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
}

/// `skip_serializing_if` predicate used on the `truncated` flag — named so
/// the derive macro reads as intent ("skip when false") instead of the
/// opaque `std::ops::Not::not`. Takes `&bool` because serde's contract
/// requires the predicate accept a reference.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
    !*b
}

#[derive(Debug, Clone, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RiskLevel {
    None,
    Low,
    Medium,
    High,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct BlastRadius {
    pub production_callers: usize,
    pub test_callers: usize,
    pub has_tests: bool,
    pub risk: RiskLevel,
}

impl BlastRadius {
    #[must_use]
    pub fn compute(production_callers: usize, test_callers: usize) -> Self {
        let has_tests = test_callers > 0;
        let risk = match (production_callers, has_tests) {
            (0, _) => RiskLevel::None,
            (1..=2, true) => RiskLevel::Low,
            (1..=2, false) => RiskLevel::Medium,
            (_, true) => RiskLevel::Medium,
            (_, false) => RiskLevel::High,
        };
        Self {
            production_callers,
            test_callers,
            has_tests,
            risk,
        }
    }
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ContextMetadata {
    pub base_ref: String,
    pub head_ref: String,
    pub base_sha: String,
    pub head_sha: String,
    pub generated_at: DateTime<Utc>,
    /// Estimated token count of the serialized response. See
    /// [`ManifestMetadata::token_estimate`] for the semantics and caveats;
    /// the same two-pass construction trick applies.
    pub token_estimate: usize,
    /// Names of function entries whose caller / callee / test-reference lists
    /// were clamped by the response-size budget. Each entry in this list
    /// corresponds to a `FunctionContextEntry` with `truncated = true`; use
    /// `function_names` to re-query individual entries with the full lists.
    ///
    /// Shares the field name with [`ManifestMetadata::function_analysis_truncated`]
    /// so the two budget-bearing tools emit the same shape and a single
    /// telemetry/metric assertion can key on one path across both tools.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub function_analysis_truncated: Vec<String>,
    /// Opaque pagination cursor to request the next page. `None` means this
    /// is the last page. Mirrors `pagination.next_cursor`; duplicated in
    /// metadata so agents reading only the metadata block can see whether
    /// follow-up calls are required.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    /// Token budget that produced this response, when applicable. Set by the
    /// `review_change` orchestration tool, which splits its `max_response_tokens`
    /// 40/60 between the manifest and function-context sub-responses. Mirrors
    /// [`ManifestMetadata::budget_tokens`] so a single agent assertion path
    /// covers both halves of a `review_change` payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget_tokens: Option<usize>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct FunctionContextResponse {
    pub metadata: ContextMetadata,
    pub functions: Vec<FunctionContextEntry>,
    pub pagination: PaginationInfo,
}

// --- Tool options (for internal use) ---

#[derive(Debug, Clone)]
pub struct ManifestOptions {
    pub include_patterns: Vec<String>,
    pub exclude_patterns: Vec<String>,
    pub include_function_analysis: bool,
    /// Token budget for the response. `None` disables enforcement (used by
    /// internal callers like `context.rs` that need full data). `Some(n)`
    /// triggers per-file tiered trimming when the response exceeds `n` tokens.
    pub max_response_tokens: Option<usize>,
}

#[derive(Debug, Clone)]
pub struct SnapshotOptions {
    pub include_before: bool,
    pub include_after: bool,
    pub max_file_size_bytes: usize,
    pub line_range: Option<(usize, usize)>,
    pub include_diff_hunks: bool,
}

// --- ToolError ---

#[derive(Debug, thiserror::Error)]
pub enum ToolError {
    #[error("git error: {0}")]
    Git(#[from] crate::git::reader::GitError),

    #[error("invalid cursor: {0}")]
    InvalidCursor(#[from] crate::pagination::CursorError),
}

// --- Helper ---

pub fn detect_language(path: &str) -> &'static str {
    let ext = path.rsplit('.').next().unwrap_or("");
    match ext {
        "go" => "go",
        "py" => "python",
        "ts" | "tsx" => "typescript",
        "js" | "jsx" => "javascript",
        "rb" => "ruby",
        "rs" => "rust",
        "java" => "java",
        "php" => "php",
        "swift" => "swift",
        "kt" | "kts" => "kotlin",
        "c" | "h" => "c",
        "cpp" | "hpp" | "cc" | "cxx" | "hh" | "hxx" => "cpp",
        "cs" => "csharp",
        _ => "unknown",
    }
}

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

    #[test]
    fn it_detects_go_language_from_extension() {
        assert_eq!(detect_language("main.go"), "go");
    }

    #[test]
    fn it_detects_python_language_from_extension() {
        assert_eq!(detect_language("app.py"), "python");
    }

    #[test]
    fn it_detects_typescript_from_ts_extension() {
        assert_eq!(detect_language("index.ts"), "typescript");
    }

    #[test]
    fn it_detects_typescript_from_tsx_extension() {
        assert_eq!(detect_language("App.tsx"), "typescript");
    }

    #[test]
    fn it_detects_javascript_from_js_extension() {
        assert_eq!(detect_language("util.js"), "javascript");
    }

    #[test]
    fn it_detects_javascript_from_jsx_extension() {
        assert_eq!(detect_language("Component.jsx"), "javascript");
    }

    #[test]
    fn it_detects_rust_from_rs_extension() {
        assert_eq!(detect_language("lib.rs"), "rust");
    }

    #[test]
    fn it_detects_java_from_java_extension() {
        assert_eq!(detect_language("Main.java"), "java");
    }

    #[test]
    fn it_detects_java_from_nested_path() {
        assert_eq!(detect_language("src/com/example/Main.java"), "java");
    }

    #[test]
    fn it_detects_swift_from_swift_extension() {
        assert_eq!(detect_language("App.swift"), "swift");
    }

    #[test]
    fn it_detects_c_from_c_extension() {
        assert_eq!(detect_language("main.c"), "c");
    }

    #[test]
    fn it_detects_c_from_h_extension() {
        assert_eq!(detect_language("utils.h"), "c");
    }

    #[test]
    fn it_detects_cpp_from_cpp_extension() {
        assert_eq!(detect_language("widget.cpp"), "cpp");
    }

    #[test]
    fn it_detects_cpp_from_hpp_extension() {
        assert_eq!(detect_language("widget.hpp"), "cpp");
    }

    #[test]
    fn it_detects_cpp_from_cc_extension() {
        assert_eq!(detect_language("widget.cc"), "cpp");
    }

    #[test]
    fn it_detects_cpp_from_cxx_extension() {
        assert_eq!(detect_language("widget.cxx"), "cpp");
    }

    #[test]
    fn it_detects_cpp_from_hh_extension() {
        assert_eq!(detect_language("widget.hh"), "cpp");
    }

    #[test]
    fn it_detects_cpp_from_hxx_extension() {
        assert_eq!(detect_language("widget.hxx"), "cpp");
    }

    #[test]
    fn it_detects_kotlin_from_kt_extension() {
        assert_eq!(detect_language("Main.kt"), "kotlin");
    }

    #[test]
    fn it_detects_kotlin_from_kts_extension() {
        assert_eq!(detect_language("build.gradle.kts"), "kotlin");
    }

    #[test]
    fn it_detects_ruby_from_rb_extension() {
        // Kills: delete match arm "rb" in detect_language at line 461.
        // Without the arm, detect_language falls through to "unknown".
        assert_eq!(detect_language("script.rb"), "ruby");
    }

    #[test]
    fn it_detects_php_from_php_extension() {
        // Kills: delete match arm "php" in detect_language at line 464.
        // Without the arm, detect_language falls through to "unknown".
        assert_eq!(detect_language("index.php"), "php");
    }

    #[test]
    fn it_detects_csharp_from_cs_extension() {
        // Kills: delete match arm "cs" in detect_language at line 469.
        // Without the arm, detect_language falls through to "unknown".
        assert_eq!(detect_language("Program.cs"), "csharp");
    }

    #[test]
    fn it_returns_unknown_for_unsupported_extension() {
        assert_eq!(detect_language("README.md"), "unknown");
    }

    #[test]
    fn it_returns_unknown_for_no_extension() {
        assert_eq!(detect_language("Makefile"), "unknown");
    }

    #[test]
    fn it_handles_nested_path_with_dots() {
        assert_eq!(detect_language("src/utils/helper.test.ts"), "typescript");
    }

    #[test]
    fn it_returns_unknown_for_empty_string() {
        assert_eq!(detect_language(""), "unknown");
    }

    #[test]
    fn manifest_response_serializes_to_json() {
        let response = ManifestResponse {
            metadata: ManifestMetadata {
                repo_path: "/tmp/repo".into(),
                base_ref: "HEAD~1".into(),
                head_ref: "HEAD".into(),
                base_sha: "abc123".into(),
                head_sha: "def456".into(),
                generated_at: DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
                version: "0.1.0".into(),
                token_estimate: 0,
                function_analysis_truncated: vec![],
                budget_tokens: None,
            },
            summary: ManifestSummary {
                total_files_changed: 1,
                files_added: 1,
                files_modified: 0,
                files_deleted: 0,
                files_renamed: 0,
                total_lines_added: 5,
                total_lines_removed: 0,
                total_functions_changed: None,
                languages_affected: vec!["rust".into()],
            },
            files: vec![],
            dependency_changes: vec![],
            pagination: PaginationInfo {
                total_items: 1,
                page_start: 0,
                page_size: 200,
                next_cursor: None,
            },
        };
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["metadata"]["base_ref"], "HEAD~1");
        assert_eq!(json["summary"]["total_files_changed"], 1);
        assert!(json["summary"]["total_functions_changed"].is_null());
        assert!(json["pagination"]["next_cursor"].is_null());
        assert_eq!(json["metadata"]["token_estimate"], 0);
    }

    #[test]
    fn snapshot_response_serializes_to_json() {
        let response = SnapshotResponse {
            metadata: SnapshotMetadata {
                repo_path: "/tmp/repo".into(),
                base_ref: "HEAD~1".into(),
                head_ref: "HEAD".into(),
                generated_at: DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
            },
            files: vec![SnapshotFileEntry {
                path: "src/main.rs".into(),
                language: "rust".into(),
                is_binary: false,
                before: None,
                after: Some(FileContent {
                    content: "fn main() {}".into(),
                    line_count: 1,
                    size_bytes: 12,
                    truncated: false,
                }),
                diff_hunks: None,
                error: None,
            }],
            token_estimate: 3,
        };
        let json = serde_json::to_value(&response).unwrap();
        assert!(json["files"][0]["before"].is_null());
        assert_eq!(json["files"][0]["after"]["line_count"], 1);
        assert_eq!(json["token_estimate"], 3);
    }

    #[test]
    fn function_change_type_serializes_as_snake_case() {
        let change = FunctionChange {
            name: "foo".into(),
            old_name: None,
            change_type: FunctionChangeType::SignatureChanged,
            start_line: 1,
            end_line: 5,
            signature: "fn foo(x: i32)".into(),
        };
        let json = serde_json::to_value(&change).unwrap();
        assert_eq!(json["change_type"], "signature_changed");
        assert!(json["old_name"].is_null());
    }

    #[test]
    fn renamed_change_type_serializes_with_old_name() {
        let change = FunctionChange {
            name: "new_fn".into(),
            old_name: Some("old_fn".into()),
            change_type: FunctionChangeType::Renamed,
            start_line: 1,
            end_line: 5,
            signature: "fn new_fn()".into(),
        };
        let json = serde_json::to_value(&change).unwrap();
        assert_eq!(json["change_type"], "renamed");
        assert_eq!(json["old_name"], "old_fn");
        assert_eq!(json["name"], "new_fn");
    }

    #[test]
    fn manifest_args_deserializes_with_defaults() {
        let json = r#"{"base_ref": "main"}"#;
        let args: ManifestArgs = serde_json::from_str(json).unwrap();
        assert_eq!(args.base_ref, "main");
        assert!(args.head_ref.is_none());
        assert!(!args.include_function_analysis);
        assert_eq!(args.max_response_tokens, 8192);
        assert!(args.include_patterns.is_empty());
    }

    #[test]
    fn history_response_serializes_commits_array() {
        let response = HistoryResponse {
            commits: vec![CommitManifest {
                metadata: CommitMetadata {
                    sha: "abc123".into(),
                    message: "test commit".into(),
                    author: "Test User".into(),
                    timestamp: "2026-01-01T00:00:00Z".into(),
                },
                files: vec![],
                summary: ManifestSummary {
                    total_files_changed: 0,
                    files_added: 0,
                    files_modified: 0,
                    files_deleted: 0,
                    files_renamed: 0,
                    total_lines_added: 0,
                    total_lines_removed: 0,
                    total_functions_changed: None,
                    languages_affected: vec![],
                },
            }],
            pagination: PaginationInfo {
                total_items: 1,
                page_start: 0,
                page_size: 100,
                next_cursor: None,
            },
        };
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["commits"].as_array().unwrap().len(), 1);
        assert_eq!(json["commits"][0]["metadata"]["sha"], "abc123");
        assert_eq!(json["commits"][0]["metadata"]["author"], "Test User");
        assert_eq!(
            json["commits"][0]["metadata"]["timestamp"],
            "2026-01-01T00:00:00Z"
        );
        assert_eq!(json["commits"][0]["metadata"]["message"], "test commit");
        assert!(json["commits"][0]["files"].as_array().unwrap().is_empty());
    }

    #[test]
    fn snapshot_args_deserializes_with_defaults() {
        let json = r#"{"base_ref": "main", "paths": ["src/main.rs"]}"#;
        let args: SnapshotArgs = serde_json::from_str(json).unwrap();
        assert!(args.include_before);
        assert!(args.include_after);
        assert_eq!(args.max_file_size_bytes, 100_000);
        assert!(args.line_range.is_none());
    }

    #[test]
    fn manifest_args_accepts_pagination_params() {
        let json =
            r#"{"base_ref": "main", "head_ref": "HEAD", "cursor": "abc123", "page_size": 50}"#;
        let args: ManifestArgs = serde_json::from_str(json).unwrap();
        assert_eq!(args.cursor.as_deref(), Some("abc123"));
        assert_eq!(args.page_size, 50);
    }

    #[test]
    fn manifest_args_defaults_pagination_when_omitted() {
        let json = r#"{"base_ref": "main"}"#;
        let args: ManifestArgs = serde_json::from_str(json).unwrap();
        assert!(args.cursor.is_none());
        assert_eq!(args.page_size, 100);
    }

    #[test]
    fn history_args_accepts_pagination_params() {
        let json =
            r#"{"base_ref": "HEAD~5", "head_ref": "HEAD", "cursor": "xyz", "page_size": 25}"#;
        let args: HistoryArgs = serde_json::from_str(json).unwrap();
        assert_eq!(args.cursor.as_deref(), Some("xyz"));
        assert_eq!(args.page_size, 25);
    }

    #[test]
    fn history_args_defaults_pagination_when_omitted() {
        let json = r#"{"base_ref": "HEAD~5", "head_ref": "HEAD"}"#;
        let args: HistoryArgs = serde_json::from_str(json).unwrap();
        assert!(args.cursor.is_none());
        assert_eq!(args.page_size, 100);
    }

    #[test]
    fn blast_radius_zero_callers_is_none_risk() {
        let br = BlastRadius::compute(0, 0);
        assert_eq!(br.risk, RiskLevel::None);
        assert!(!br.has_tests);
    }

    #[test]
    fn blast_radius_zero_production_with_tests_is_none_risk() {
        let br = BlastRadius::compute(0, 3);
        assert_eq!(br.risk, RiskLevel::None);
        assert!(br.has_tests);
    }

    #[test]
    fn blast_radius_low_callers_with_tests_is_low() {
        let br = BlastRadius::compute(2, 1);
        assert_eq!(br.risk, RiskLevel::Low);
        assert!(br.has_tests);
    }

    #[test]
    fn blast_radius_low_callers_no_tests_is_medium() {
        let br = BlastRadius::compute(1, 0);
        assert_eq!(br.risk, RiskLevel::Medium);
        assert!(!br.has_tests);
    }

    #[test]
    fn blast_radius_many_callers_with_tests_is_medium() {
        let br = BlastRadius::compute(5, 2);
        assert_eq!(br.risk, RiskLevel::Medium);
        assert!(br.has_tests);
    }

    #[test]
    fn blast_radius_many_callers_no_tests_is_high() {
        let br = BlastRadius::compute(10, 0);
        assert_eq!(br.risk, RiskLevel::High);
        assert!(!br.has_tests);
    }

    #[test]
    fn blast_radius_serializes_risk_as_snake_case() {
        let br = BlastRadius::compute(5, 0);
        let json = serde_json::to_value(&br).unwrap();
        assert_eq!(json["risk"], "high");
        assert_eq!(json["production_callers"], 5);
        assert_eq!(json["test_callers"], 0);
        assert_eq!(json["has_tests"], false);
    }

    #[test]
    fn blast_radius_boundary_at_three_callers() {
        let low = BlastRadius::compute(2, 1);
        let medium = BlastRadius::compute(3, 1);
        assert_eq!(low.risk, RiskLevel::Low);
        assert_eq!(medium.risk, RiskLevel::Medium);
    }

    #[test]
    fn context_args_deserializes_with_defaults() {
        let json = r#"{"base_ref": "main", "head_ref": "HEAD"}"#;
        let args: ContextArgs = serde_json::from_str(json).unwrap();
        assert_eq!(args.base_ref, "main");
        assert_eq!(args.head_ref, "HEAD");
        assert!(args.cursor.is_none());
        assert_eq!(args.page_size, 25);
        assert!(args.function_names.is_none());
        assert_eq!(args.max_response_tokens, 8192);
    }

    #[test]
    fn context_args_accepts_pagination_params() {
        let json =
            r#"{"base_ref": "main", "head_ref": "HEAD", "cursor": "tok123", "page_size": 10}"#;
        let args: ContextArgs = serde_json::from_str(json).unwrap();
        assert_eq!(args.cursor.as_deref(), Some("tok123"));
        assert_eq!(args.page_size, 10);
    }

    #[test]
    fn context_args_accepts_function_names_filter() {
        let json = r#"{"base_ref": "main", "head_ref": "HEAD", "function_names": ["foo", "bar"]}"#;
        let args: ContextArgs = serde_json::from_str(json).unwrap();
        assert_eq!(
            args.function_names.as_deref(),
            Some(vec!["foo".to_string(), "bar".to_string()].as_slice())
        );
    }

    #[test]
    fn context_args_zero_max_response_tokens_deserializes() {
        // Callers pass 0 to disable budget enforcement; must round-trip cleanly.
        let json = r#"{"base_ref": "main", "head_ref": "HEAD", "max_response_tokens": 0}"#;
        let args: ContextArgs = serde_json::from_str(json).unwrap();
        assert_eq!(args.max_response_tokens, 0);
    }

    #[test]
    fn function_context_response_serializes_to_json() {
        use chrono::Utc;
        let response = FunctionContextResponse {
            metadata: ContextMetadata {
                base_ref: "HEAD~1".into(),
                head_ref: "HEAD".into(),
                base_sha: "abc123".into(),
                head_sha: "def456".into(),
                generated_at: DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
                token_estimate: 42,
                function_analysis_truncated: vec![],
                next_cursor: None,
                budget_tokens: None,
            },
            functions: vec![],
            pagination: PaginationInfo {
                total_items: 0,
                page_start: 0,
                page_size: 25,
                next_cursor: None,
            },
        };
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["metadata"]["base_ref"], "HEAD~1");
        assert_eq!(json["metadata"]["head_ref"], "HEAD");
        assert_eq!(json["metadata"]["token_estimate"], 42);
        assert!(json["metadata"]["next_cursor"].is_null());
        // function_analysis_truncated skipped when empty
        assert!(
            json["metadata"]
                .get("function_analysis_truncated")
                .is_none()
        );
        assert_eq!(json["functions"].as_array().unwrap().len(), 0);
        assert_eq!(json["pagination"]["total_items"], 0);
        assert_eq!(json["pagination"]["page_size"], 25);
    }

    #[test]
    fn function_context_entry_skips_truncated_when_false() {
        // Kills three mutants on `is_false` at line 343:
        //   - replace body with `true`  → field always skipped (truncated=true never serialized)
        //   - replace body with `false` → field never skipped (truncated=false always serialized)
        //   - delete `!`               → predicate becomes "is_true" (inverts skip behavior)
        // Asserts both directions: truncated=false → field absent, truncated=true → field present.
        let mk_entry = |truncated: bool| FunctionContextEntry {
            name: "foo".into(),
            file: "src/lib.rs".into(),
            change_type: FunctionChangeType::Modified,
            blast_radius: BlastRadius::compute(0, 0),
            scoping_mode: ScopingMode::Scoped,
            callers: vec![],
            callees: vec![],
            test_references: vec![],
            caller_count: 0,
            truncated,
        };

        let json_false = serde_json::to_value(mk_entry(false)).unwrap();
        assert!(
            json_false.get("truncated").is_none(),
            "truncated=false must be skipped from output, got: {json_false}"
        );

        let json_true = serde_json::to_value(mk_entry(true)).unwrap();
        assert_eq!(
            json_true["truncated"], true,
            "truncated=true must be present in output as a true boolean"
        );
    }

    #[test]
    fn context_metadata_serializes_next_cursor_when_present() {
        use chrono::Utc;
        let metadata = ContextMetadata {
            base_ref: "main".into(),
            head_ref: "HEAD".into(),
            base_sha: "a".into(),
            head_sha: "b".into(),
            generated_at: Utc::now(),
            token_estimate: 0,
            function_analysis_truncated: vec!["some_fn".into()],
            next_cursor: Some("cursor_opaque_token".into()),
            budget_tokens: None,
        };
        let json = serde_json::to_value(&metadata).unwrap();
        assert_eq!(json["next_cursor"], "cursor_opaque_token");
        assert_eq!(
            json["function_analysis_truncated"]
                .as_array()
                .unwrap()
                .len(),
            1
        );
        assert_eq!(json["function_analysis_truncated"][0], "some_fn");
    }
}