git-prism 0.9.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
/// Agent detection module.
///
/// Answers "is the current process running on behalf of an AI coding agent?"
/// using only environment variables. No process inspection, no terminal-program
/// sniffing — those have too-high false-positive rates and are out of scope.
///
/// Call `detect_calling_agent` with an `EnvSource` implementation. The
/// production path uses `StdEnvSource`; tests inject a `HashMap`-backed stub.
/// **Do not call `std::env::var` inside the detection logic itself** — only
/// through `EnvSource`. That contract is what keeps tests hermetic.
use schemars::JsonSchema;
use serde::Serialize;

/// Abstracts environment-variable lookup so detection logic is hermetic in tests.
pub trait EnvSource {
    fn get(&self, key: &str) -> Option<String>;
}

/// Production `EnvSource` that reads from the real process environment.
pub struct StdEnvSource;

impl EnvSource for StdEnvSource {
    fn get(&self, key: &str) -> Option<String> {
        std::env::var(key).ok()
    }
}

/// Which agent was detected.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub enum AgentName {
    ClaudeCode,
    Cursor,
    Gemini,
    Codex,
    Cline,
    Augment,
    OpenCode,
    Trae,
    Goose,
    Amp,
    Unknown,
}

/// Which detection signal fired.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub enum DetectionSignal {
    /// Matched via the cross-tool `AI_AGENT=<tool>_<version>_agent` convention.
    AiAgent,
    /// Matched via `AGENT=<name>` from the agents.md proposal.
    Agent,
    /// Matched via a tool-specific env var (e.g. `CLAUDECODE`, `CURSOR_AGENT`).
    ToolSpecific,
}

/// The result of a successful agent detection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct DetectedAgent {
    /// Which agent was identified.
    pub name: AgentName,
    /// Which detection signal fired.
    pub signal: DetectionSignal,
    /// The raw env var value that matched, for debugging.
    pub raw_value: String,
}

/// Detect the calling agent from environment variables.
///
/// Returns `None` when:
/// - `CI` is set (CI tooling wins over all agent signals), or
/// - no known agent markers are present.
///
/// Detection priority order (per research doc §5):
/// 1. `AI_AGENT` non-empty
/// 2. `AGENT` with value in the allowlist (`goose`, `amp`)
/// 3. Tool-specific markers
/// 4. `CI` set → `None` regardless of the above
pub fn detect_calling_agent(env: &dyn EnvSource) -> Option<DetectedAgent> {
    // CI wins over all agent signals — check first. Empty CI="" is treated
    // as unset, consistent with the empty-value handling for other markers.
    if env.get("CI").is_some_and(|v| !v.is_empty()) {
        return None;
    }

    // Priority 1: AI_AGENT (Vercel cross-tool convention)
    if let Some(value) = env.get("AI_AGENT").filter(|v| !v.is_empty()) {
        let name = parse_ai_agent_value(&value);
        return Some(DetectedAgent {
            name,
            signal: DetectionSignal::AiAgent,
            raw_value: value,
        });
    }

    // Priority 2: AGENT with allowlisted value. Trim whitespace before
    // matching so .env files with trailing spaces work correctly.
    // raw_value preserves the original (untrimmed) value for debugging.
    if let Some(value) = env.get("AGENT") {
        let agent_name = match value.trim() {
            "goose" => Some(AgentName::Goose),
            "amp" => Some(AgentName::Amp),
            _ => None,
        };
        if let Some(name) = agent_name {
            return Some(DetectedAgent {
                name,
                signal: DetectionSignal::Agent,
                raw_value: value,
            });
        }
    }

    // Priority 3: Tool-specific markers
    let tool_specific: &[(&str, AgentName)] = &[
        ("CLAUDECODE", AgentName::ClaudeCode),
        ("CURSOR_AGENT", AgentName::Cursor),
        ("GEMINI_CLI", AgentName::Gemini),
        ("CODEX_SANDBOX", AgentName::Codex),
        ("CLINE_ACTIVE", AgentName::Cline),
        ("AUGMENT_AGENT", AgentName::Augment),
        ("OPENCODE_CLIENT", AgentName::OpenCode),
        ("TRAE_AI_SHELL_ID", AgentName::Trae),
    ];

    for (var, name) in tool_specific {
        if let Some(value) = env.get(var).filter(|v| !v.is_empty()) {
            return Some(DetectedAgent {
                name: name.clone(),
                signal: DetectionSignal::ToolSpecific,
                raw_value: value,
            });
        }
    }

    None
}

/// Parse the `AI_AGENT` value.
///
/// Expected format: `<tool>_<version>_agent`, e.g. `claude-code_2-1-141_agent`.
/// The tool segment maps to a known `AgentName`. Unknown tools produce
/// `AgentName::Unknown`. The original `AI_AGENT` value is preserved on
/// `DetectedAgent.raw_value` if callers need to parse the tool name themselves.
fn parse_ai_agent_value(value: &str) -> AgentName {
    // Strip trailing `_agent` suffix if present
    let tool_version = value.strip_suffix("_agent").unwrap_or(value);

    // Collect underscore-delimited segments until a version segment (starts with a
    // digit) is found. e.g. "claude-code_2-1-141" splits as ["claude-code", "2-1-141"];
    // the version segment is dropped, leaving ["claude-code"] joined with "-".
    // Multi-word tool names (e.g. "open_code_1-0") would join as "open-code".
    let tool = tool_version
        .split('_')
        .take_while(|seg| !seg.starts_with(|c: char| c.is_ascii_digit()))
        .collect::<Vec<_>>()
        .join("-");

    match tool.as_str() {
        "claude-code" => AgentName::ClaudeCode,
        "cursor" => AgentName::Cursor,
        "gemini-cli" => AgentName::Gemini,
        "codex" => AgentName::Codex,
        "cline" => AgentName::Cline,
        "augment" => AgentName::Augment,
        "opencode" => AgentName::OpenCode,
        "trae" => AgentName::Trae,
        "goose" => AgentName::Goose,
        "amp" => AgentName::Amp,
        _ => AgentName::Unknown,
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    struct StubEnv(HashMap<&'static str, &'static str>);

    impl EnvSource for StubEnv {
        fn get(&self, key: &str) -> Option<String> {
            self.0.get(key).map(|v| v.to_string())
        }
    }

    fn env(pairs: &[(&'static str, &'static str)]) -> StubEnv {
        StubEnv(pairs.iter().copied().collect())
    }

    fn empty() -> StubEnv {
        StubEnv(HashMap::new())
    }

    // --- CLAUDECODE ---

    #[test]
    fn it_detects_claude_code_via_claudecode_var() {
        let result = detect_calling_agent(&env(&[("CLAUDECODE", "1")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::ClaudeCode,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "1".to_string(),
            })
        );
    }

    // --- CURSOR_AGENT ---

    #[test]
    fn it_detects_cursor_via_cursor_agent_var() {
        let result = detect_calling_agent(&env(&[("CURSOR_AGENT", "1")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Cursor,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "1".to_string(),
            })
        );
    }

    // --- GEMINI_CLI ---

    #[test]
    fn it_detects_gemini_via_gemini_cli_var() {
        let result = detect_calling_agent(&env(&[("GEMINI_CLI", "1")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Gemini,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "1".to_string(),
            })
        );
    }

    // --- CODEX_SANDBOX ---

    #[test]
    fn it_detects_codex_via_codex_sandbox_var() {
        let result = detect_calling_agent(&env(&[("CODEX_SANDBOX", "seatbelt")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Codex,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "seatbelt".to_string(),
            })
        );
    }

    // --- CLINE_ACTIVE ---

    #[test]
    fn it_detects_cline_via_cline_active_var() {
        let result = detect_calling_agent(&env(&[("CLINE_ACTIVE", "true")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Cline,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "true".to_string(),
            })
        );
    }

    // --- AUGMENT_AGENT ---

    #[test]
    fn it_detects_augment_via_augment_agent_var() {
        let result = detect_calling_agent(&env(&[("AUGMENT_AGENT", "1")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Augment,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "1".to_string(),
            })
        );
    }

    // --- OPENCODE_CLIENT ---

    #[test]
    fn it_detects_opencode_via_opencode_client_var() {
        let result = detect_calling_agent(&env(&[("OPENCODE_CLIENT", "1")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::OpenCode,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "1".to_string(),
            })
        );
    }

    // --- TRAE_AI_SHELL_ID ---

    #[test]
    fn it_detects_trae_via_trae_ai_shell_id_var() {
        let result = detect_calling_agent(&env(&[("TRAE_AI_SHELL_ID", "session-123")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Trae,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "session-123".to_string(),
            })
        );
    }

    // --- AGENT allowlist ---

    #[test]
    fn it_detects_goose_via_agent_var() {
        let result = detect_calling_agent(&env(&[("AGENT", "goose")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Goose,
                signal: DetectionSignal::Agent,
                raw_value: "goose".to_string(),
            })
        );
    }

    #[test]
    fn it_detects_amp_via_agent_var() {
        let result = detect_calling_agent(&env(&[("AGENT", "amp")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Amp,
                signal: DetectionSignal::Agent,
                raw_value: "amp".to_string(),
            })
        );
    }

    #[test]
    fn it_tolerates_whitespace_in_agent_var_value() {
        // .env files frequently produce trailing spaces; the allowlist match
        // should be whitespace-tolerant. raw_value preserves the ORIGINAL
        // (untrimmed) value so debugging surfaces the actual env contents.
        let result = detect_calling_agent(&env(&[("AGENT", "goose ")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::Goose,
                signal: DetectionSignal::Agent,
                raw_value: "goose ".to_string(),
            })
        );
    }

    #[test]
    fn it_ignores_agent_var_with_non_allowlisted_value() {
        let result = detect_calling_agent(&env(&[("AGENT", "1")]));
        assert_eq!(result, None);
    }

    // --- AI_AGENT ---

    #[test]
    fn it_detects_claude_code_via_ai_agent_var() {
        let result = detect_calling_agent(&env(&[("AI_AGENT", "claude-code_2-1-141_agent")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::ClaudeCode,
                signal: DetectionSignal::AiAgent,
                raw_value: "claude-code_2-1-141_agent".to_string(),
            })
        );
    }

    #[test]
    fn it_prefers_ai_agent_over_tool_specific_markers() {
        // When both AI_AGENT and CLAUDECODE are set, AI_AGENT wins — and the
        // returned raw_value must come from AI_AGENT, not CLAUDECODE.
        let result = detect_calling_agent(&env(&[
            ("AI_AGENT", "claude-code_2-1-141_agent"),
            ("CLAUDECODE", "1"),
        ]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::ClaudeCode,
                signal: DetectionSignal::AiAgent,
                raw_value: "claude-code_2-1-141_agent".to_string(),
            })
        );
    }

    #[test]
    fn it_produces_unknown_agent_for_unrecognized_ai_agent_tool() {
        let result = detect_calling_agent(&env(&[("AI_AGENT", "sometool_1-0_agent")]));
        let detected = result.expect("should detect an agent");
        assert_eq!(detected.signal, DetectionSignal::AiAgent);
        assert!(matches!(detected.name, AgentName::Unknown));
    }

    // --- CI override ---

    #[test]
    fn it_treats_empty_ci_var_as_not_set() {
        // Empty CI="" should NOT override agent detection — only meaningful
        // values do, mirroring the empty-value handling for other markers.
        let result = detect_calling_agent(&env(&[("CI", ""), ("CLAUDECODE", "1")]));
        assert_eq!(
            result,
            Some(DetectedAgent {
                name: AgentName::ClaudeCode,
                signal: DetectionSignal::ToolSpecific,
                raw_value: "1".to_string(),
            })
        );
    }

    #[test]
    fn it_returns_none_when_ci_is_set_alongside_claudecode() {
        let result = detect_calling_agent(&env(&[("CI", "true"), ("CLAUDECODE", "1")]));
        assert_eq!(result, None);
    }

    #[test]
    fn it_returns_none_when_ci_is_set_alongside_ai_agent() {
        let result = detect_calling_agent(&env(&[
            ("CI", "true"),
            ("AI_AGENT", "claude-code_2-1-141_agent"),
        ]));
        assert_eq!(result, None);
    }

    // --- empty environment ---

    #[test]
    fn it_returns_none_in_empty_environment() {
        let result = detect_calling_agent(&empty());
        assert_eq!(result, None);
    }

    // --- triangulation: edge cases ---

    #[test]
    fn it_ignores_empty_claudecode_var() {
        let result = detect_calling_agent(&env(&[("CLAUDECODE", "")]));
        assert_eq!(result, None);
    }

    #[test]
    fn it_ignores_empty_ai_agent_var() {
        let result = detect_calling_agent(&env(&[("AI_AGENT", "")]));
        assert_eq!(result, None);
    }

    #[test]
    fn it_ignores_agent_var_with_uppercase_goose() {
        // Allowlist match is case-sensitive
        let result = detect_calling_agent(&env(&[("AGENT", "GOOSE")]));
        assert_eq!(result, None);
    }

    #[test]
    fn it_detects_ai_agent_without_agent_suffix() {
        // Value without _agent suffix still works — tool is parsed from full value
        let result = detect_calling_agent(&env(&[("AI_AGENT", "claude-code")]));
        let detected = result.expect("should detect an agent");
        assert_eq!(detected.name, AgentName::ClaudeCode);
        assert_eq!(detected.signal, DetectionSignal::AiAgent);
    }

    // --- JSON contract: agent name must always serialize as a string ---

    #[test]
    fn it_serializes_unknown_agent_name_as_a_json_string() {
        // CLI `agent-detect` output contract is `agent: string | null` (issue #278
        // acceptance criterion #4). The `Unknown` variant must serialize as a string,
        // not a nested object.
        let name = AgentName::Unknown;
        let value = serde_json::to_value(&name).expect("serialize");
        assert!(
            value.is_string(),
            "AgentName::Unknown must serialize as a JSON string, got: {value}"
        );
        assert_eq!(value.as_str(), Some("Unknown"));
    }

    // --- explicit JSON shape tests ---

    #[test]
    fn it_serializes_detected_agent_to_json_with_expected_fields() {
        // DetectedAgent serializes to a flat JSON object with three string fields.
        // Explicit assertion (not snapshot) so the contract is visible in the test.
        let detected = DetectedAgent {
            name: AgentName::ClaudeCode,
            signal: DetectionSignal::ToolSpecific,
            raw_value: "1".to_string(),
        };
        let value = serde_json::to_value(&detected).expect("serialize");
        assert_eq!(
            value,
            serde_json::json!({
                "name": "ClaudeCode",
                "signal": "ToolSpecific",
                "raw_value": "1",
            })
        );
    }

    #[test]
    fn it_serializes_unknown_agent_to_json_with_expected_fields() {
        let detected = DetectedAgent {
            name: AgentName::Unknown,
            signal: DetectionSignal::AiAgent,
            raw_value: "sometool_1-0_agent".to_string(),
        };
        let value = serde_json::to_value(&detected).expect("serialize");
        assert_eq!(
            value,
            serde_json::json!({
                "name": "Unknown",
                "signal": "AiAgent",
                "raw_value": "sometool_1-0_agent",
            })
        );
    }
}