Skip to main content

code_system_graph_core/codegraph/
mod.rs

1mod cli;
2mod contract;
3mod mcp;
4
5use std::collections::BTreeMap;
6use std::ffi::OsString;
7use std::path::{Component, Path};
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
10use std::time::Duration;
11
12use async_trait::async_trait;
13use code_system_graph_model::RepoId;
14use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
15
16use self::cli::CodeGraphCli;
17use self::contract::{cli_operations, map_mcp_tools, supports_cli_contract};
18use self::mcp::{CodeGraphMcp, McpProbe};
19use crate::{
20    AffectedTestsRequest, AffectedTestsResult, LocalCodeIntelligenceProvider, LocalContextRequest, LocalContextResult, LocalImpactRequest, LocalImpactResult, LocalNeighborResult, LocalNeighborsRequest, ProviderCapability, ProviderDegradation, ProviderError, ProviderRequest, ProviderStatus, ResolveSymbolsRequest, ResolveSymbolsResult
21};
22
23static DIAGNOSTIC_SEQUENCE: AtomicU64 = AtomicU64::new(1);
24const MAX_QUERY_BYTES: usize = 4096;
25const MAX_LOCAL_DEPTH: usize = 64;
26const MAX_CHANGED_FILES: usize = 1024;
27
28/// Process and circuit-breaker settings for the production `CodeGraph` adapter.
29#[derive(Debug, Clone)]
30pub struct CodeGraphConfig {
31    /// Executable path or `PATH`-resolved binary name.
32    pub binary: OsString,
33    /// Maximum concurrent `CodeGraph` child processes.
34    pub max_concurrent_processes: usize,
35    /// Time that MCP is bypassed for one repository after an MCP timeout.
36    pub circuit_breaker_cooldown: Duration,
37}
38
39impl Default for CodeGraphConfig {
40    fn default() -> Self {
41        Self {
42            binary: OsString::from("codegraph"),
43            max_concurrent_processes: 2,
44            circuit_breaker_cooldown: Duration::from_secs(30),
45        }
46    }
47}
48
49/// Production local-intelligence provider using public `CodeGraph` MCP and CLI interfaces.
50pub struct CodeGraphProvider {
51    cli: CodeGraphCli,
52    mcp: CodeGraphMcp,
53    permits: Arc<Semaphore>,
54    circuit_breaker_cooldown: Duration,
55    mcp_circuits: Mutex<BTreeMap<RepoId, tokio::time::Instant>>,
56    cli_version: Mutex<Option<String>>,
57    closed: AtomicBool,
58    active_processes: Arc<AtomicUsize>,
59    maximum_concurrency_observed: Arc<AtomicUsize>,
60}
61
62struct ProviderPermit {
63    _permit: OwnedSemaphorePermit,
64    active_processes: Arc<AtomicUsize>,
65}
66
67impl Drop for ProviderPermit {
68    fn drop(&mut self) {
69        self.active_processes.fetch_sub(1, Ordering::AcqRel);
70    }
71}
72
73struct CliProbe {
74    version: String,
75    status: ProviderStatus,
76    degradations: Vec<ProviderDegradation>,
77}
78
79enum CliProbeOutcome {
80    Ready(CliProbe),
81    Degraded(ProviderCapability),
82}
83
84impl CodeGraphProvider {
85    /// Builds a production adapter without starting or modifying any `CodeGraph` index.
86    ///
87    /// # Errors
88    ///
89    /// Returns [`ProviderError::InvalidRequest`] when child-process concurrency is zero.
90    pub fn new(config: CodeGraphConfig) -> Result<Self, ProviderError> {
91        if config.max_concurrent_processes == 0 {
92            return Err(ProviderError::InvalidRequest(
93                "max_concurrent_processes must be greater than zero".to_owned(),
94            ));
95        }
96        Ok(Self {
97            cli: CodeGraphCli::new(config.binary.clone()),
98            mcp: CodeGraphMcp::new(config.binary),
99            permits: Arc::new(Semaphore::new(config.max_concurrent_processes)),
100            circuit_breaker_cooldown: config.circuit_breaker_cooldown,
101            mcp_circuits: Mutex::new(BTreeMap::new()),
102            cli_version: Mutex::new(None),
103            closed: AtomicBool::new(false),
104            active_processes: Arc::new(AtomicUsize::new(0)),
105            maximum_concurrency_observed: Arc::new(AtomicUsize::new(0)),
106        })
107    }
108
109    /// Returns the maximum number of provider operations that simultaneously held process permits.
110    #[must_use]
111    pub fn maximum_concurrency_observed(&self) -> usize {
112        self.maximum_concurrency_observed.load(Ordering::Acquire)
113    }
114
115    /// Reads one repository-relative file through `CodeGraph`'s bounded public CLI contract.
116    ///
117    /// This is used only when semantic Explore resolves an exact file but the broader context
118    /// query cannot select source for it. The path must remain inside the indexed repository.
119    ///
120    /// # Errors
121    ///
122    /// Returns [`ProviderError`] for unsafe paths, cancellation, timeout, or invalid output.
123    pub async fn build_local_file_context(
124        &self,
125        mut input: LocalContextRequest,
126        file_path: &str,
127    ) -> Result<LocalContextResult, ProviderError> {
128        let path = Path::new(file_path);
129        if file_path.is_empty()
130            || !path.is_relative()
131            || path
132                .components()
133                .any(|component| !matches!(component, Component::Normal(_) | Component::CurDir))
134        {
135            return Err(ProviderError::InvalidRequest(
136                "file path must be a safe repository-relative path".to_owned(),
137            ));
138        }
139        let deadline = tokio::time::Instant::now() + input.request.budget.timeout;
140        let _permit = self.enter(&input.request, deadline).await?;
141        self.compatible_cli_version(&mut input.request, deadline)
142            .await?;
143        update_remaining_timeout(&mut input.request, deadline)?;
144        self.cli.local_file_context(&input, file_path).await
145    }
146
147    /// Reads the structured local-index status without starting MCP or modifying the index.
148    ///
149    /// # Errors
150    ///
151    /// Returns [`ProviderError`] when the request is invalid, the compatible CLI cannot be
152    /// executed, or its bounded JSON status does not satisfy the validated contract.
153    pub async fn index_status(
154        &self,
155        mut request: ProviderRequest,
156    ) -> Result<ProviderStatus, ProviderError> {
157        let deadline = tokio::time::Instant::now() + request.budget.timeout;
158        let _permit = self.enter(&request, deadline).await?;
159        self.compatible_cli_version(&mut request, deadline).await?;
160        update_remaining_timeout(&mut request, deadline)?;
161        self.cli
162            .status(&request)
163            .await
164            .map(|status| status.status())
165    }
166
167    async fn enter(
168        &self,
169        request: &ProviderRequest,
170        deadline: tokio::time::Instant,
171    ) -> Result<ProviderPermit, ProviderError> {
172        validate_request(request)?;
173        if self.closed.load(Ordering::Acquire) {
174            return Err(ProviderError::InvalidRequest(
175                "provider has already been shut down".to_owned(),
176            ));
177        }
178        tokio::select! {
179            biased;
180            () = request.cancellation.cancelled() => Err(ProviderError::Cancelled),
181            () = tokio::time::sleep_until(deadline) => Err(timeout_error()),
182            permit = self.permits.clone().acquire_owned() => {
183                let permit = permit.map_err(|_| {
184                    ProviderError::InvalidRequest("provider has already been shut down".to_owned())
185                })?;
186                let active = self.active_processes.fetch_add(1, Ordering::AcqRel) + 1;
187                self.maximum_concurrency_observed.fetch_max(active, Ordering::AcqRel);
188                Ok(ProviderPermit {
189                    _permit: permit,
190                    active_processes: self.active_processes.clone(),
191                })
192            },
193        }
194    }
195
196    async fn compatible_cli_version(
197        &self,
198        request: &mut ProviderRequest,
199        deadline: tokio::time::Instant,
200    ) -> Result<String, ProviderError> {
201        if let Some(version) = self.cli_version.lock().await.clone() {
202            if supports_cli_contract(&version) {
203                return Ok(version);
204            }
205            return Err(invalid_response(format!(
206                "CodeGraph CLI {version} has no validated structured-output adapter"
207            )));
208        }
209        update_remaining_timeout(request, deadline)?;
210        let version = self.cli.version(request).await?;
211        *self.cli_version.lock().await = Some(version.clone());
212        if !supports_cli_contract(&version) {
213            return Err(invalid_response(format!(
214                "CodeGraph CLI {version} has no validated structured-output adapter"
215            )));
216        }
217        Ok(version)
218    }
219
220    async fn mcp_is_available(&self, repo_id: &RepoId) -> bool {
221        let now = tokio::time::Instant::now();
222        let mut circuits = self.mcp_circuits.lock().await;
223        circuits.retain(|_, until| *until > now);
224        !circuits.contains_key(repo_id)
225    }
226
227    async fn open_mcp_circuit(&self, repo_id: RepoId) {
228        self.mcp_circuits.lock().await.insert(
229            repo_id,
230            tokio::time::Instant::now() + self.circuit_breaker_cooldown,
231        );
232    }
233
234    async fn probe_cli(
235        &self,
236        request: &mut ProviderRequest,
237        deadline: tokio::time::Instant,
238    ) -> Result<CliProbeOutcome, ProviderError> {
239        update_remaining_timeout(request, deadline)?;
240        let version = match self.cli.version(request).await {
241            Ok(version) => version,
242            Err(ProviderError::Cancelled) => return Err(ProviderError::Cancelled),
243            Err(error) => return Ok(CliProbeOutcome::Degraded(unavailable_capability(&error))),
244        };
245        *self.cli_version.lock().await = Some(version.clone());
246        if !supports_cli_contract(&version) {
247            return Ok(CliProbeOutcome::Ready(CliProbe {
248                status: ProviderStatus::Incompatible,
249                degradations: vec![ProviderDegradation {
250                    kind: "unsupported_cli_version".to_owned(),
251                    message: format!(
252                        "CodeGraph CLI {version} is outside the validated structured-output matrix."
253                    ),
254                    diagnostics_id: None,
255                }],
256                version,
257            }));
258        }
259        update_remaining_timeout(request, deadline)?;
260        let mut degradations = Vec::new();
261        let status = match self.cli.status(request).await {
262            Ok(status) => {
263                if status
264                    .version
265                    .as_deref()
266                    .is_some_and(|value| value != version)
267                {
268                    degradations.push(ProviderDegradation {
269                        kind: "version_mismatch".to_owned(),
270                        message:
271                            "CodeGraph version and status contracts reported different versions."
272                                .to_owned(),
273                        diagnostics_id: None,
274                    });
275                }
276                status.status()
277            }
278            Err(error) => {
279                let status = if matches!(error, ProviderError::Timeout { .. }) {
280                    ProviderStatus::TimedOut
281                } else {
282                    ProviderStatus::InvalidResponse
283                };
284                degradations.push(degradation_from_error(&error));
285                status
286            }
287        };
288        Ok(CliProbeOutcome::Ready(CliProbe {
289            version,
290            status,
291            degradations,
292        }))
293    }
294
295    async fn probe_mcp(
296        &self,
297        request: &mut ProviderRequest,
298        deadline: tokio::time::Instant,
299        degradations: &mut Vec<ProviderDegradation>,
300    ) -> Result<Option<McpProbe>, ProviderError> {
301        if !self.mcp_is_available(&request.repo_id).await {
302            degradations.push(ProviderDegradation {
303                kind: "mcp_circuit_open".to_owned(),
304                message: "MCP was bypassed after a recent timeout; compatible CLI fallback remains available.".to_owned(),
305                diagnostics_id: None,
306            });
307            return Ok(None);
308        }
309        update_remaining_timeout(request, deadline)?;
310        match self.mcp.probe(request).await {
311            Ok(probe) => Ok(Some(probe)),
312            Err(ProviderError::Cancelled) => Err(ProviderError::Cancelled),
313            Err(error) => {
314                if matches!(error, ProviderError::Timeout { .. }) {
315                    self.open_mcp_circuit(request.repo_id.clone()).await;
316                }
317                degradations.push(degradation_from_error(&error));
318                Ok(None)
319            }
320        }
321    }
322
323    fn assemble_capability(
324        request: &ProviderRequest,
325        mut cli_probe: CliProbe,
326        mcp_probe: Option<McpProbe>,
327    ) -> ProviderCapability {
328        if mcp_probe
329            .as_ref()
330            .and_then(|probe| probe.version.as_deref())
331            .is_some_and(|version| version != cli_probe.version)
332        {
333            cli_probe.degradations.push(ProviderDegradation {
334                kind: "mcp_cli_version_mismatch".to_owned(),
335                message: "CodeGraph MCP and CLI reported different public implementation versions."
336                    .to_owned(),
337                diagnostics_id: None,
338            });
339        }
340        let mut operations = BTreeMap::new();
341        if let Some(probe) = &mcp_probe {
342            for operation in map_mcp_tools(&probe.tools) {
343                operations.insert(operation.operation, operation);
344            }
345        }
346        for operation in cli_operations(&cli_probe.version) {
347            operations.entry(operation.operation).or_insert(operation);
348        }
349        let status = if operations.is_empty() && cli_probe.status == ProviderStatus::Available {
350            ProviderStatus::Incompatible
351        } else {
352            cli_probe.status
353        };
354        ProviderCapability {
355            provider: "codegraph".to_owned(),
356            version: Some(cli_probe.version),
357            status,
358            tools: mcp_tool_names(mcp_probe.as_ref()),
359            protocol_version: mcp_probe.map(|probe| probe.protocol_version),
360            operations: operations.into_values().collect(),
361            degradations: cli_probe.degradations,
362            remediation: remediation(status, &request.project_path),
363        }
364    }
365}
366
367#[async_trait]
368impl LocalCodeIntelligenceProvider for CodeGraphProvider {
369    fn provider_name(&self) -> &'static str {
370        "codegraph"
371    }
372
373    async fn probe(
374        &self,
375        mut request: ProviderRequest,
376    ) -> Result<ProviderCapability, ProviderError> {
377        let deadline = tokio::time::Instant::now() + request.budget.timeout;
378        let _permit = self.enter(&request, deadline).await?;
379        let mut cli_probe = match self.probe_cli(&mut request, deadline).await? {
380            CliProbeOutcome::Ready(probe) => probe,
381            CliProbeOutcome::Degraded(capability) => return Ok(capability),
382        };
383        let mcp_probe = self
384            .probe_mcp(&mut request, deadline, &mut cli_probe.degradations)
385            .await?;
386        Ok(Self::assemble_capability(&request, cli_probe, mcp_probe))
387    }
388
389    async fn resolve_symbols(
390        &self,
391        mut input: ResolveSymbolsRequest,
392    ) -> Result<ResolveSymbolsResult, ProviderError> {
393        validate_query(&input.query)?;
394        let deadline = tokio::time::Instant::now() + input.request.budget.timeout;
395        let _permit = self.enter(&input.request, deadline).await?;
396        self.compatible_cli_version(&mut input.request, deadline)
397            .await?;
398        update_remaining_timeout(&mut input.request, deadline)?;
399        self.cli.resolve_symbols(&input).await
400    }
401
402    async fn get_local_neighbors(
403        &self,
404        mut input: LocalNeighborsRequest,
405    ) -> Result<LocalNeighborResult, ProviderError> {
406        validate_query(&input.symbol)?;
407        let deadline = tokio::time::Instant::now() + input.request.budget.timeout;
408        let _permit = self.enter(&input.request, deadline).await?;
409        self.compatible_cli_version(&mut input.request, deadline)
410            .await?;
411        update_remaining_timeout(&mut input.request, deadline)?;
412        self.cli.local_neighbors(&input).await
413    }
414
415    async fn get_local_impact(
416        &self,
417        mut input: LocalImpactRequest,
418    ) -> Result<LocalImpactResult, ProviderError> {
419        validate_query(&input.symbol)?;
420        validate_depth(input.max_depth)?;
421        let deadline = tokio::time::Instant::now() + input.request.budget.timeout;
422        let _permit = self.enter(&input.request, deadline).await?;
423        self.compatible_cli_version(&mut input.request, deadline)
424            .await?;
425        update_remaining_timeout(&mut input.request, deadline)?;
426        self.cli.local_impact(&input).await
427    }
428
429    async fn build_local_context(
430        &self,
431        mut input: LocalContextRequest,
432    ) -> Result<LocalContextResult, ProviderError> {
433        validate_query(&input.query)?;
434        if input.max_files == 0 || input.max_files > input.request.budget.max_items {
435            return Err(ProviderError::InvalidRequest(format!(
436                "max_files must be between 1 and max_items ({})",
437                input.request.budget.max_items
438            )));
439        }
440        let deadline = tokio::time::Instant::now() + input.request.budget.timeout;
441        let _permit = self.enter(&input.request, deadline).await?;
442        let mut degradations = Vec::new();
443        if self.mcp_is_available(&input.request.repo_id).await {
444            update_remaining_timeout(&mut input.request, deadline)?;
445            match self.mcp.local_context(&input).await {
446                Ok(result) => return Ok(result),
447                Err(ProviderError::Cancelled) => return Err(ProviderError::Cancelled),
448                Err(error) => {
449                    if matches!(error, ProviderError::Timeout { .. }) {
450                        self.open_mcp_circuit(input.request.repo_id.clone()).await;
451                    }
452                    degradations.push(degradation_from_error(&error));
453                }
454            }
455        } else {
456            degradations.push(ProviderDegradation {
457                kind: "mcp_circuit_open".to_owned(),
458                message: "MCP was bypassed after a recent timeout.".to_owned(),
459                diagnostics_id: None,
460            });
461        }
462        self.compatible_cli_version(&mut input.request, deadline)
463            .await?;
464        update_remaining_timeout(&mut input.request, deadline)?;
465        let mut result = self.cli.local_context(&input).await?;
466        result.execution.degradations = degradations;
467        Ok(result)
468    }
469
470    async fn get_affected_tests(
471        &self,
472        mut input: AffectedTestsRequest,
473    ) -> Result<Option<AffectedTestsResult>, ProviderError> {
474        validate_depth(input.max_depth)?;
475        validate_changed_files(&input.changed_files)?;
476        let deadline = tokio::time::Instant::now() + input.request.budget.timeout;
477        let _permit = self.enter(&input.request, deadline).await?;
478        match self
479            .compatible_cli_version(&mut input.request, deadline)
480            .await
481        {
482            Ok(_) => {}
483            Err(ProviderError::InvalidResponse { .. }) => return Ok(None),
484            Err(error) => return Err(error),
485        }
486        update_remaining_timeout(&mut input.request, deadline)?;
487        self.cli.affected_tests(&input).await.map(Some)
488    }
489
490    async fn shutdown(&self) -> Result<(), ProviderError> {
491        self.closed.store(true, Ordering::Release);
492        self.permits.close();
493        Ok(())
494    }
495}
496
497fn unavailable_capability(error: &ProviderError) -> ProviderCapability {
498    let status = match error {
499        ProviderError::Timeout { .. } => ProviderStatus::TimedOut,
500        ProviderError::InvalidResponse { .. } => ProviderStatus::InvalidResponse,
501        _ => ProviderStatus::Unavailable,
502    };
503    ProviderCapability {
504        provider: "codegraph".to_owned(),
505        version: None,
506        status,
507        tools: Vec::new(),
508        protocol_version: None,
509        operations: Vec::new(),
510        degradations: vec![degradation_from_error(error)],
511        remediation: Some("Install CodeGraph or configure its public executable path.".to_owned()),
512    }
513}
514
515fn mcp_tool_names(probe: Option<&McpProbe>) -> Vec<String> {
516    let mut names = probe
517        .map(|probe| {
518            probe
519                .tools
520                .iter()
521                .map(|tool| tool.name.clone())
522                .collect::<Vec<_>>()
523        })
524        .unwrap_or_default();
525    names.sort();
526    names
527}
528
529fn remediation(status: ProviderStatus, project_path: &Path) -> Option<String> {
530    match status {
531        ProviderStatus::IndexMissing => Some(format!("Create the index explicitly with `codegraph init {}`.", project_path.display())),
532        ProviderStatus::Stale => Some(format!("Refresh the index explicitly with `codegraph sync {}`.", project_path.display())),
533        ProviderStatus::Incompatible => Some("Use a CodeGraph version listed in the compatibility matrix or rely on federated boundaries without local enrichment.".to_owned()),
534        _ => None,
535    }
536}
537
538fn validate_request(request: &ProviderRequest) -> Result<(), ProviderError> {
539    if request.cancellation.is_cancelled() {
540        return Err(ProviderError::Cancelled);
541    }
542    if request.budget.timeout.is_zero() {
543        return Err(ProviderError::InvalidRequest(
544            "timeout must be greater than zero".to_owned(),
545        ));
546    }
547    if request.budget.max_output_bytes == 0 {
548        return Err(ProviderError::InvalidRequest(
549            "max_output_bytes must be greater than zero".to_owned(),
550        ));
551    }
552    if request.budget.max_items == 0 {
553        return Err(ProviderError::InvalidRequest(
554            "max_items must be greater than zero".to_owned(),
555        ));
556    }
557    if !request.project_path.is_absolute() {
558        return Err(ProviderError::InvalidRequest(
559            "project_path must be absolute".to_owned(),
560        ));
561    }
562    if !request.project_path.is_dir() {
563        return Err(ProviderError::InvalidRequest(
564            "project_path must identify an existing directory".to_owned(),
565        ));
566    }
567    Ok(())
568}
569
570fn validate_query(query: &str) -> Result<(), ProviderError> {
571    if query.trim().is_empty() {
572        return Err(ProviderError::InvalidRequest(
573            "provider query must not be empty".to_owned(),
574        ));
575    }
576    if query.len() > MAX_QUERY_BYTES {
577        return Err(ProviderError::InvalidRequest(format!(
578            "provider query exceeds {MAX_QUERY_BYTES} bytes"
579        )));
580    }
581    Ok(())
582}
583
584fn validate_depth(depth: usize) -> Result<(), ProviderError> {
585    if depth == 0 || depth > MAX_LOCAL_DEPTH {
586        return Err(ProviderError::InvalidRequest(format!(
587            "local depth must be between 1 and {MAX_LOCAL_DEPTH}"
588        )));
589    }
590    Ok(())
591}
592
593fn validate_changed_files(files: &[String]) -> Result<(), ProviderError> {
594    if files.is_empty() || files.len() > MAX_CHANGED_FILES {
595        return Err(ProviderError::InvalidRequest(format!(
596            "changed_files must contain between 1 and {MAX_CHANGED_FILES} paths"
597        )));
598    }
599    for file in files {
600        let path = Path::new(file);
601        if file.is_empty()
602            || path.is_absolute()
603            || path
604                .components()
605                .any(|component| matches!(component, Component::ParentDir | Component::RootDir))
606        {
607            return Err(ProviderError::InvalidRequest(format!(
608                "changed file path must be non-empty and repository-relative: {file}"
609            )));
610        }
611    }
612    Ok(())
613}
614
615fn update_remaining_timeout(
616    request: &mut ProviderRequest,
617    deadline: tokio::time::Instant,
618) -> Result<(), ProviderError> {
619    request.budget.timeout = deadline
620        .checked_duration_since(tokio::time::Instant::now())
621        .ok_or_else(timeout_error)?;
622    if request.budget.timeout.is_zero() {
623        return Err(timeout_error());
624    }
625    Ok(())
626}
627
628pub(crate) fn diagnostic_id() -> String {
629    format!(
630        "cg-{:016x}",
631        DIAGNOSTIC_SEQUENCE.fetch_add(1, Ordering::Relaxed)
632    )
633}
634
635pub(crate) fn timeout_error() -> ProviderError {
636    ProviderError::Timeout {
637        diagnostics_id: diagnostic_id(),
638    }
639}
640
641pub(crate) fn output_limit(limit_bytes: usize) -> ProviderError {
642    ProviderError::OutputLimit {
643        limit_bytes,
644        diagnostics_id: diagnostic_id(),
645    }
646}
647
648pub(crate) fn invalid_response(message: impl Into<String>) -> ProviderError {
649    ProviderError::InvalidResponse {
650        message: message.into(),
651        diagnostics_id: diagnostic_id(),
652    }
653}
654
655pub(crate) fn transport_error(message: impl Into<String>) -> ProviderError {
656    ProviderError::Transport {
657        message: message.into(),
658        diagnostics_id: diagnostic_id(),
659    }
660}
661
662fn degradation_from_error(error: &ProviderError) -> ProviderDegradation {
663    let (kind, diagnostics_id) = match error {
664        ProviderError::Cancelled => ("cancelled", None),
665        ProviderError::Timeout { diagnostics_id } => ("timeout", Some(diagnostics_id.clone())),
666        ProviderError::OutputLimit { diagnostics_id, .. } => {
667            ("output_limit", Some(diagnostics_id.clone()))
668        }
669        ProviderError::CircuitOpen => ("circuit_open", None),
670        ProviderError::InvalidRequest(_) => ("invalid_request", None),
671        ProviderError::InvalidResponse { diagnostics_id, .. } => {
672            ("invalid_response", Some(diagnostics_id.clone()))
673        }
674        ProviderError::Transport { diagnostics_id, .. } => {
675            ("transport", Some(diagnostics_id.clone()))
676        }
677    };
678    ProviderDegradation {
679        kind: kind.to_owned(),
680        message: error.to_string(),
681        diagnostics_id,
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use std::path::PathBuf;
688    use std::sync::atomic::Ordering;
689
690    use code_system_graph_model::RepoId;
691    use tokio_util::sync::CancellationToken;
692
693    use super::{CodeGraphConfig, CodeGraphProvider, validate_changed_files};
694    use crate::{ProviderBudget, ProviderError, ProviderRequest};
695
696    fn absolute_project_path() -> PathBuf {
697        std::env::current_dir().expect("test process should expose an absolute current directory")
698    }
699
700    #[test]
701    fn provider_should_reject_zero_process_budget() {
702        let result = CodeGraphProvider::new(CodeGraphConfig {
703            max_concurrent_processes: 0,
704            ..CodeGraphConfig::default()
705        });
706
707        assert!(matches!(result, Err(ProviderError::InvalidRequest(_))));
708    }
709
710    #[test]
711    fn changed_files_should_reject_parent_escape() {
712        let result = validate_changed_files(&["../outside.rs".to_owned()]);
713
714        assert!(matches!(result, Err(ProviderError::InvalidRequest(_))));
715    }
716
717    #[tokio::test]
718    async fn cancelled_probe_should_not_start_a_child() {
719        let provider =
720            CodeGraphProvider::new(CodeGraphConfig::default()).expect("valid provider config");
721        let cancellation = CancellationToken::new();
722        cancellation.cancel();
723        let result = crate::LocalCodeIntelligenceProvider::probe(
724            &provider,
725            ProviderRequest {
726                repo_id: RepoId::new("repo:test"),
727                project_path: absolute_project_path(),
728                budget: ProviderBudget::default(),
729                cancellation,
730            },
731        )
732        .await;
733
734        assert_eq!(result, Err(ProviderError::Cancelled));
735    }
736
737    #[tokio::test]
738    async fn provider_should_measure_held_process_permits() {
739        let provider = CodeGraphProvider::new(CodeGraphConfig {
740            max_concurrent_processes: 2,
741            ..CodeGraphConfig::default()
742        })
743        .expect("valid provider config");
744        let request = ProviderRequest {
745            repo_id: RepoId::new("repo:test"),
746            project_path: absolute_project_path(),
747            budget: ProviderBudget::default(),
748            cancellation: CancellationToken::new(),
749        };
750        assert_eq!(provider.maximum_concurrency_observed(), 0);
751
752        let first = provider
753            .enter(
754                &request,
755                tokio::time::Instant::now() + std::time::Duration::from_secs(1),
756            )
757            .await
758            .expect("first permit");
759        assert_eq!(provider.maximum_concurrency_observed(), 1);
760        let second = provider
761            .enter(
762                &request,
763                tokio::time::Instant::now() + std::time::Duration::from_secs(1),
764            )
765            .await
766            .expect("second permit");
767        assert_eq!(provider.maximum_concurrency_observed(), 2);
768
769        drop((first, second));
770        assert_eq!(provider.active_processes.load(Ordering::Acquire), 0);
771    }
772}