Skip to main content

code_system_graph_core/
changes.rs

1//! Bounded, cancellable local Git change discovery and commit gating.
2
3use std::collections::{BTreeMap, BTreeSet};
4#[cfg(unix)]
5use std::ffi::OsStr;
6use std::ffi::OsString;
7use std::path::{Path, PathBuf};
8use std::process::Stdio;
9use std::time::Duration;
10
11use async_trait::async_trait;
12use code_system_graph_model::{CheckoutId, NativePath, NativePathEncoding, RepoId};
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16use tokio::io::AsyncReadExt;
17use tokio::process::Command;
18use tokio_util::sync::CancellationToken;
19
20const DEFAULT_OUTPUT_CAP: usize = 16 * 1024 * 1024;
21const DEFAULT_STDERR_CAP: usize = 256 * 1024;
22const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
23
24/// Selects the repository state represented by a [`ChangeSet`].
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
26#[serde(tag = "kind", rename_all = "snake_case")]
27pub enum ChangeScope {
28    /// Tracked worktree changes not present in the index.
29    Unstaged,
30    /// Changes currently present in the index.
31    Staged,
32    /// Staged, tracked worktree, and untracked changes as separate layers.
33    All,
34    /// Changes from the merge base of a validated ref to `HEAD`.
35    Compare {
36        /// Branch, tag, or other non-expression Git ref.
37        reference: String,
38    },
39    /// The changes introduced by one full hexadecimal commit object ID.
40    Commit {
41        /// Full SHA-1 or SHA-256 commit object ID.
42        sha: String,
43    },
44    /// Changes between two validated refs, equivalent to `base..head`.
45    Range {
46        /// Older endpoint.
47        base: String,
48        /// Newer endpoint.
49        head: String,
50    },
51    /// A provider-specific pull request.
52    PullRequest {
53        /// External provider identifier, such as `github`.
54        provider: String,
55        /// Provider-local pull-request number.
56        number: u64,
57    },
58}
59
60/// Identifies the layer from which a changed file was discovered.
61#[derive(
62    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
63)]
64#[serde(rename_all = "snake_case")]
65pub enum ChangeSourceLayer {
66    /// The Git index.
67    Staged,
68    /// Tracked files in the working tree.
69    Worktree,
70    /// Untracked worktree entries.
71    Untracked,
72    /// A committed tree comparison.
73    Commit,
74}
75
76/// Git-level classification of a changed file.
77#[derive(
78    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
79)]
80#[serde(rename_all = "snake_case")]
81pub enum ChangedFileStatus {
82    /// A newly added tracked file.
83    Added,
84    /// A modified tracked file.
85    Modified,
86    /// A deleted tracked file.
87    Deleted,
88    /// A renamed tracked file.
89    Renamed,
90    /// A copied tracked file.
91    Copied,
92    /// An untracked file whose body was not read.
93    Untracked,
94}
95
96/// Kind of one changed line in a zero-context hunk.
97#[derive(
98    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
99)]
100#[serde(rename_all = "snake_case")]
101pub enum ChangedLineKind {
102    /// A line removed from the old side.
103    Removed,
104    /// A line added to the new side.
105    Added,
106}
107
108/// Position-only changed-line evidence.
109///
110/// Source text is deliberately excluded so a persisted [`ChangeSet`] cannot retain diff bodies.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
112pub struct ChangedLine {
113    /// Whether this line was added or removed.
114    pub kind: ChangedLineKind,
115    /// One-based line on the old side, when applicable.
116    pub old_line: Option<u32>,
117    /// One-based line on the new side, when applicable.
118    pub new_line: Option<u32>,
119}
120
121/// One zero-context unified-diff hunk.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
123pub struct ChangeHunk {
124    /// One-based old-side starting line.
125    pub old_start: u32,
126    /// Number of old-side lines covered.
127    pub old_count: u32,
128    /// One-based new-side starting line.
129    pub new_start: u32,
130    /// Number of new-side lines covered.
131    pub new_count: u32,
132    /// Changed line positions, without source text.
133    pub lines: Vec<ChangedLine>,
134}
135
136/// One changed file, preserving native path bytes where the platform permits it.
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
138pub struct ChangedFile {
139    /// Git change classification.
140    pub status: ChangedFileStatus,
141    /// Original repository-relative path, when one exists.
142    pub old_path: Option<NativePath>,
143    /// Resulting repository-relative path, when one exists.
144    pub new_path: Option<NativePath>,
145    /// Whether Git reported a binary numstat.
146    pub binary: bool,
147    /// Position-only zero-context hunks.
148    pub hunks: Vec<ChangeHunk>,
149    /// State layer that supplied this record.
150    pub source: ChangeSourceLayer,
151}
152
153/// Version map for analyzers whose output is tied to a change set.
154pub type AnalyzerVersions = BTreeMap<String, String>;
155
156/// Immutable, fingerprinted description of a repository change.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
158pub struct ChangeSet {
159    /// Stable registered repository identity.
160    pub repo_id: RepoId,
161    /// Stable concrete checkout identity.
162    pub checkout_id: CheckoutId,
163    /// Canonical, lossless worktree root.
164    pub worktree: NativePath,
165    /// Canonical, lossless common Git directory.
166    pub git_common_dir: NativePath,
167    /// Requested scope.
168    pub scope: ChangeScope,
169    /// Symbolic checkout `HEAD`, when attached.
170    pub checkout_head_ref: Option<String>,
171    /// Commit currently checked out, or the empty-tree object for an unborn checkout.
172    pub checkout_head_sha: String,
173    /// Scope base ref or object ID, when applicable.
174    pub base_ref: Option<String>,
175    /// Scope head ref or object ID, when applicable.
176    pub head_ref: Option<String>,
177    /// Resolved scope head, or the empty-tree object for an unborn local scope.
178    pub head_sha: String,
179    /// BLAKE3 hash of exact bounded staged Git output.
180    pub staged_hash: String,
181    /// BLAKE3 hash of exact bounded tracked and untracked worktree output.
182    pub worktree_hash: String,
183    /// BLAKE3 fingerprint of exact bounded Git output and identity metadata.
184    pub exact_diff_fingerprint: String,
185    /// Workspace manifest fingerprint used by analysis.
186    pub workspace_manifest_hash: String,
187    /// Contract registry fingerprint used by analysis.
188    pub contract_registry_hash: String,
189    /// Analyzer names and exact versions used by analysis.
190    pub analyzer_versions: AnalyzerVersions,
191    /// Deterministically ordered changed files.
192    pub files: Vec<ChangedFile>,
193}
194
195/// Input required to collect one local change set.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
197pub struct ChangeRequest {
198    /// Registered repository identity.
199    pub repo_id: RepoId,
200    /// Concrete checkout identity.
201    pub checkout_id: CheckoutId,
202    /// Any path accepted by `git -C`, normally the expected worktree root.
203    pub worktree: PathBuf,
204    /// State to collect.
205    pub scope: ChangeScope,
206    /// Current workspace manifest fingerprint.
207    pub workspace_manifest_hash: String,
208    /// Current contract registry fingerprint.
209    pub contract_registry_hash: String,
210    /// Current analyzer versions.
211    pub analyzer_versions: AnalyzerVersions,
212}
213
214/// Read-only source of repository changes.
215#[allow(clippy::double_must_use)]
216#[async_trait]
217pub trait ChangeProvider: Send + Sync {
218    /// Collects a bounded and fingerprinted change set.
219    ///
220    /// # Errors
221    ///
222    /// Returns [`ChangeError`] for invalid input, unsupported scopes, Git failures, cancellation,
223    /// timeouts, malformed output, and output-budget exhaustion.
224    async fn changes(
225        &self,
226        request: &ChangeRequest,
227        cancellation: &CancellationToken,
228    ) -> Result<ChangeSet, ChangeError>;
229}
230
231/// Configuration for the production local Git provider.
232#[derive(Debug, Clone)]
233pub struct GitCliChangeProvider {
234    git_binary: OsString,
235    timeout: Duration,
236    stdout_cap: usize,
237    stderr_cap: usize,
238}
239
240impl Default for GitCliChangeProvider {
241    fn default() -> Self {
242        Self {
243            git_binary: OsString::from("git"),
244            timeout: DEFAULT_TIMEOUT,
245            stdout_cap: DEFAULT_OUTPUT_CAP,
246            stderr_cap: DEFAULT_STDERR_CAP,
247        }
248    }
249}
250
251impl GitCliChangeProvider {
252    /// Creates a provider using `git` from the process search path and conservative budgets.
253    #[must_use]
254    pub fn new() -> Self {
255        Self::default()
256    }
257
258    /// Creates a provider with explicit executable and process budgets.
259    ///
260    /// Zero output limits are rejected when [`ChangeProvider::changes`] is called.
261    #[must_use]
262    pub fn with_limits(
263        git_binary: impl Into<OsString>,
264        timeout: Duration,
265        stdout_cap: usize,
266        stderr_cap: usize,
267    ) -> Self {
268        Self {
269            git_binary: git_binary.into(),
270            timeout,
271            stdout_cap,
272            stderr_cap,
273        }
274    }
275
276    async fn git(
277        &self,
278        worktree: &Path,
279        args: &[OsString],
280        cancellation: &CancellationToken,
281    ) -> Result<Vec<u8>, ChangeError> {
282        if self.stdout_cap == 0 || self.stderr_cap == 0 {
283            return Err(ChangeError::InvalidLimit);
284        }
285        if cancellation.is_cancelled() {
286            return Err(ChangeError::Cancelled);
287        }
288
289        let mut command = Command::new(&self.git_binary);
290        command
291            .arg("-C")
292            .arg(worktree)
293            .args(args)
294            .env("GIT_OPTIONAL_LOCKS", "0")
295            .stdin(Stdio::null())
296            .stdout(Stdio::piped())
297            .stderr(Stdio::piped())
298            .kill_on_drop(true);
299        let mut child = command
300            .spawn()
301            .map_err(|source| ChangeError::Spawn { source })?;
302        let stdout = child.stdout.take().ok_or(ChangeError::MissingPipe)?;
303        let stderr = child.stderr.take().ok_or(ChangeError::MissingPipe)?;
304        let stdout_cap = self.stdout_cap;
305        let stderr_cap = self.stderr_cap;
306        let stdout_task = tokio::spawn(async move { read_bounded(stdout, stdout_cap).await });
307        let stderr_task = tokio::spawn(async move { read_bounded(stderr, stderr_cap).await });
308
309        let status = tokio::select! {
310            () = cancellation.cancelled() => {
311                terminate(&mut child).await;
312                stdout_task.abort();
313                stderr_task.abort();
314                return Err(ChangeError::Cancelled);
315            }
316            () = tokio::time::sleep(self.timeout) => {
317                terminate(&mut child).await;
318                stdout_task.abort();
319                stderr_task.abort();
320                return Err(ChangeError::Timeout { timeout: self.timeout });
321            }
322            result = child.wait() => result.map_err(|source| ChangeError::Wait { source })?,
323        };
324        let stdout = stdout_task
325            .await
326            .map_err(|source| ChangeError::ReaderTask { source })??;
327        let stderr = stderr_task
328            .await
329            .map_err(|source| ChangeError::ReaderTask { source })??;
330        if !status.success() {
331            return Err(ChangeError::GitFailed {
332                status: status.code(),
333                stderr: String::from_utf8_lossy(&stderr).into_owned(),
334            });
335        }
336        Ok(stdout)
337    }
338
339    async fn text_query(
340        &self,
341        worktree: &Path,
342        args: &[&str],
343        cancellation: &CancellationToken,
344    ) -> Result<String, ChangeError> {
345        let args = args.iter().map(OsString::from).collect::<Vec<_>>();
346        let bytes = self.git(worktree, &args, cancellation).await?;
347        let value = std::str::from_utf8(&bytes).map_err(|_| ChangeError::NonUtf8Metadata)?;
348        Ok(value.trim_end_matches(['\r', '\n']).to_owned())
349    }
350
351    async fn collect_layer(
352        &self,
353        worktree: &Path,
354        source: ChangeSourceLayer,
355        revision_args: &[OsString],
356        cancellation: &CancellationToken,
357    ) -> Result<LayerResult, ChangeError> {
358        let mut raw_args = diff_prefix("--raw");
359        raw_args.extend_from_slice(revision_args);
360        let raw = self.git(worktree, &raw_args, cancellation).await?;
361
362        let mut numstat_args = diff_prefix("--numstat");
363        numstat_args.extend_from_slice(revision_args);
364        let numstat = self.git(worktree, &numstat_args, cancellation).await?;
365
366        let mut patch_args = diff_prefix("--patch");
367        patch_args.push(OsString::from("--unified=0"));
368        patch_args.push(OsString::from("--no-prefix"));
369        patch_args.extend_from_slice(revision_args);
370        let patch = self.git(worktree, &patch_args, cancellation).await?;
371
372        let mut files = parse_raw(&raw, source)?;
373        apply_numstat(&numstat, &mut files)?;
374        apply_patch(&patch, &mut files)?;
375        let material = framed_material(&[&raw, &numstat, &patch]);
376        Ok(LayerResult { files, material })
377    }
378
379    async fn collect_untracked(
380        &self,
381        worktree: &Path,
382        cancellation: &CancellationToken,
383    ) -> Result<LayerResult, ChangeError> {
384        let args = [
385            OsString::from("ls-files"),
386            OsString::from("--others"),
387            OsString::from("--exclude-standard"),
388            OsString::from("-z"),
389        ];
390        let output = self.git(worktree, &args, cancellation).await?;
391        let files = output
392            .split(|byte| *byte == 0)
393            .filter(|path| !path.is_empty())
394            .map(|path| ChangedFile {
395                status: ChangedFileStatus::Untracked,
396                old_path: None,
397                new_path: Some(native_path_bytes(path)),
398                binary: false,
399                hunks: Vec::new(),
400                source: ChangeSourceLayer::Untracked,
401            })
402            .collect();
403        Ok(LayerResult {
404            files,
405            material: framed_material(&[&output]),
406        })
407    }
408}
409
410#[async_trait]
411impl ChangeProvider for GitCliChangeProvider {
412    #[expect(
413        clippy::too_many_lines,
414        reason = "scope orchestration remains linear so every Git layer is auditable"
415    )]
416    async fn changes(
417        &self,
418        request: &ChangeRequest,
419        cancellation: &CancellationToken,
420    ) -> Result<ChangeSet, ChangeError> {
421        validate_scope(&request.scope)?;
422        let top = self
423            .text_query(
424                &request.worktree,
425                &["rev-parse", "--show-toplevel"],
426                cancellation,
427            )
428            .await?;
429        let canonical_worktree = canonicalize(Path::new(&top))?;
430        let common = self
431            .text_query(
432                &canonical_worktree,
433                &["rev-parse", "--git-common-dir"],
434                cancellation,
435            )
436            .await?;
437        let common_path = Path::new(&common);
438        let common_path = if common_path.is_absolute() {
439            common_path.to_path_buf()
440        } else {
441            canonical_worktree.join(common_path)
442        };
443        let canonical_common = canonicalize(&common_path)?;
444        let symbolic = self
445            .text_query(
446                &canonical_worktree,
447                &["symbolic-ref", "-q", "HEAD"],
448                cancellation,
449            )
450            .await;
451        let checkout_head_ref = match symbolic {
452            Ok(value) => Some(value),
453            Err(ChangeError::GitFailed { .. }) => None,
454            Err(error) => return Err(error),
455        };
456        let checkout_head_sha = match self
457            .text_query(
458                &canonical_worktree,
459                &["rev-parse", "--verify", "HEAD^{commit}"],
460                cancellation,
461            )
462            .await
463        {
464            Ok(commit) => commit,
465            Err(ChangeError::GitFailed { .. })
466                if checkout_head_ref.is_some()
467                    && matches!(
468                        &request.scope,
469                        ChangeScope::Unstaged | ChangeScope::Staged | ChangeScope::All
470                    ) =>
471            {
472                self.text_query(
473                    &canonical_worktree,
474                    &["hash-object", "-t", "tree", "--stdin"],
475                    cancellation,
476                )
477                .await?
478            }
479            Err(error) => return Err(error),
480        };
481
482        let mut staged = LayerResult::default();
483        let mut worktree = LayerResult::default();
484        let mut committed = LayerResult::default();
485        let (base_ref, head_ref, head_sha) = match &request.scope {
486            ChangeScope::Unstaged => {
487                worktree = self
488                    .collect_layer(
489                        &canonical_worktree,
490                        ChangeSourceLayer::Worktree,
491                        &[],
492                        cancellation,
493                    )
494                    .await?;
495                (None, Some("HEAD".to_owned()), checkout_head_sha.clone())
496            }
497            ChangeScope::Staged => {
498                staged = self
499                    .collect_layer(
500                        &canonical_worktree,
501                        ChangeSourceLayer::Staged,
502                        &[OsString::from("--cached")],
503                        cancellation,
504                    )
505                    .await?;
506                (None, Some("HEAD".to_owned()), checkout_head_sha.clone())
507            }
508            ChangeScope::All => {
509                staged = self
510                    .collect_layer(
511                        &canonical_worktree,
512                        ChangeSourceLayer::Staged,
513                        &[OsString::from("--cached")],
514                        cancellation,
515                    )
516                    .await?;
517                worktree = self
518                    .collect_layer(
519                        &canonical_worktree,
520                        ChangeSourceLayer::Worktree,
521                        &[],
522                        cancellation,
523                    )
524                    .await?;
525                let untracked = self
526                    .collect_untracked(&canonical_worktree, cancellation)
527                    .await?;
528                worktree.files.extend(untracked.files);
529                worktree.material.extend(untracked.material);
530                (None, Some("HEAD".to_owned()), checkout_head_sha.clone())
531            }
532            ChangeScope::Compare { reference } => {
533                let expression = OsString::from(format!("{reference}...HEAD"));
534                committed = self
535                    .collect_layer(
536                        &canonical_worktree,
537                        ChangeSourceLayer::Commit,
538                        &[expression],
539                        cancellation,
540                    )
541                    .await?;
542                (
543                    Some(reference.clone()),
544                    Some("HEAD".to_owned()),
545                    checkout_head_sha.clone(),
546                )
547            }
548            ChangeScope::Commit { sha } => {
549                committed = self
550                    .collect_layer(
551                        &canonical_worktree,
552                        ChangeSourceLayer::Commit,
553                        &[OsString::from(format!("{sha}^!"))],
554                        cancellation,
555                    )
556                    .await?;
557                let resolved = self
558                    .text_query(
559                        &canonical_worktree,
560                        &["rev-parse", "--verify", &format!("{sha}^{{commit}}")],
561                        cancellation,
562                    )
563                    .await?;
564                (None, Some(sha.clone()), resolved)
565            }
566            ChangeScope::Range { base, head } => {
567                committed = self
568                    .collect_layer(
569                        &canonical_worktree,
570                        ChangeSourceLayer::Commit,
571                        &[OsString::from(format!("{base}..{head}"))],
572                        cancellation,
573                    )
574                    .await?;
575                let resolved = self
576                    .text_query(
577                        &canonical_worktree,
578                        &["rev-parse", "--verify", &format!("{head}^{{commit}}")],
579                        cancellation,
580                    )
581                    .await?;
582                (Some(base.clone()), Some(head.clone()), resolved)
583            }
584            ChangeScope::PullRequest { .. } => return Err(ChangeError::PullRequestUnsupported),
585        };
586
587        let staged_hash = hash_material(b"code-system-graph-staged-v1", &staged.material);
588        let worktree_hash = hash_material(b"code-system-graph-worktree-v1", &worktree.material);
589        let mut files = staged.files;
590        files.extend(worktree.files);
591        files.extend(committed.files);
592        sort_and_deduplicate(&mut files);
593
594        let worktree_native = native_path(&canonical_worktree);
595        let common_native = native_path(&canonical_common);
596        let exact_diff_fingerprint = exact_fingerprint(
597            request,
598            &worktree_native,
599            &common_native,
600            &checkout_head_sha,
601            base_ref.as_deref(),
602            head_ref.as_deref(),
603            &head_sha,
604            &[&staged.material, &worktree.material, &committed.material],
605        )?;
606        Ok(ChangeSet {
607            repo_id: request.repo_id.clone(),
608            checkout_id: request.checkout_id.clone(),
609            worktree: worktree_native,
610            git_common_dir: common_native,
611            scope: request.scope.clone(),
612            checkout_head_ref,
613            checkout_head_sha,
614            base_ref,
615            head_ref,
616            head_sha,
617            staged_hash,
618            worktree_hash,
619            exact_diff_fingerprint,
620            workspace_manifest_hash: request.workspace_manifest_hash.clone(),
621            contract_registry_hash: request.contract_registry_hash.clone(),
622            analyzer_versions: request.analyzer_versions.clone(),
623            files,
624        })
625    }
626}
627
628/// Current fingerprints used to determine whether analysis remains valid.
629#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
630pub struct ChangeValidityInput {
631    /// Current repository identity.
632    pub repo_id: RepoId,
633    /// Current checkout identity.
634    pub checkout_id: CheckoutId,
635    /// Current canonical worktree.
636    pub worktree: NativePath,
637    /// Current canonical common Git directory.
638    pub git_common_dir: NativePath,
639    /// Current checked-out commit.
640    pub checkout_head_sha: String,
641    /// Current staged output hash.
642    pub staged_hash: String,
643    /// Current worktree output hash.
644    pub worktree_hash: String,
645    /// Current exact diff fingerprint.
646    pub exact_diff_fingerprint: String,
647    /// Current workspace manifest hash.
648    pub workspace_manifest_hash: String,
649    /// Current contract registry hash.
650    pub contract_registry_hash: String,
651    /// Current analyzer versions.
652    pub analyzer_versions: AnalyzerVersions,
653}
654
655impl From<&ChangeSet> for ChangeValidityInput {
656    fn from(value: &ChangeSet) -> Self {
657        Self {
658            repo_id: value.repo_id.clone(),
659            checkout_id: value.checkout_id.clone(),
660            worktree: value.worktree.clone(),
661            git_common_dir: value.git_common_dir.clone(),
662            checkout_head_sha: value.checkout_head_sha.clone(),
663            staged_hash: value.staged_hash.clone(),
664            worktree_hash: value.worktree_hash.clone(),
665            exact_diff_fingerprint: value.exact_diff_fingerprint.clone(),
666            workspace_manifest_hash: value.workspace_manifest_hash.clone(),
667            contract_registry_hash: value.contract_registry_hash.clone(),
668            analyzer_versions: value.analyzer_versions.clone(),
669        }
670    }
671}
672
673/// Machine-readable cause of stale change analysis.
674#[derive(
675    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
676)]
677#[serde(rename_all = "snake_case")]
678pub enum StaleReason {
679    /// Repository registration changed.
680    RepositoryChanged,
681    /// Checkout identity changed.
682    CheckoutChanged,
683    /// Canonical worktree changed.
684    WorktreeChanged,
685    /// Common Git directory changed.
686    GitCommonDirectoryChanged,
687    /// Checked-out commit changed.
688    HeadChanged,
689    /// Git index changed.
690    StagedChangesChanged,
691    /// Tracked or untracked worktree state changed.
692    WorktreeChangesChanged,
693    /// Exact diff fingerprint changed.
694    ExactDiffChanged,
695    /// Workspace manifest changed.
696    WorkspaceManifestChanged,
697    /// Contract registry changed.
698    ContractRegistryChanged,
699    /// Analyzer version set changed.
700    AnalyzerVersionsChanged,
701}
702
703/// Result of validating a previously analyzed change set.
704#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
705#[serde(tag = "status", rename_all = "snake_case")]
706pub enum ChangeValidity {
707    /// Every relevant fingerprint still matches.
708    Valid,
709    /// One or more inputs changed and analysis must not be reused.
710    Stale {
711        /// Deterministically ordered stale causes.
712        reasons: Vec<StaleReason>,
713        /// Safe operator action.
714        remediation: String,
715    },
716}
717
718/// Compares every analysis-relevant identity and fingerprint.
719#[must_use]
720pub fn validate_change_set(
721    change_set: &ChangeSet,
722    current: &ChangeValidityInput,
723) -> ChangeValidity {
724    let mut reasons = Vec::new();
725    compare(
726        &change_set.repo_id,
727        &current.repo_id,
728        StaleReason::RepositoryChanged,
729        &mut reasons,
730    );
731    compare(
732        &change_set.checkout_id,
733        &current.checkout_id,
734        StaleReason::CheckoutChanged,
735        &mut reasons,
736    );
737    compare(
738        &change_set.worktree,
739        &current.worktree,
740        StaleReason::WorktreeChanged,
741        &mut reasons,
742    );
743    compare(
744        &change_set.git_common_dir,
745        &current.git_common_dir,
746        StaleReason::GitCommonDirectoryChanged,
747        &mut reasons,
748    );
749    compare(
750        &change_set.checkout_head_sha,
751        &current.checkout_head_sha,
752        StaleReason::HeadChanged,
753        &mut reasons,
754    );
755    compare(
756        &change_set.staged_hash,
757        &current.staged_hash,
758        StaleReason::StagedChangesChanged,
759        &mut reasons,
760    );
761    compare(
762        &change_set.worktree_hash,
763        &current.worktree_hash,
764        StaleReason::WorktreeChangesChanged,
765        &mut reasons,
766    );
767    compare(
768        &change_set.exact_diff_fingerprint,
769        &current.exact_diff_fingerprint,
770        StaleReason::ExactDiffChanged,
771        &mut reasons,
772    );
773    compare(
774        &change_set.workspace_manifest_hash,
775        &current.workspace_manifest_hash,
776        StaleReason::WorkspaceManifestChanged,
777        &mut reasons,
778    );
779    compare(
780        &change_set.contract_registry_hash,
781        &current.contract_registry_hash,
782        StaleReason::ContractRegistryChanged,
783        &mut reasons,
784    );
785    compare(
786        &change_set.analyzer_versions,
787        &current.analyzer_versions,
788        StaleReason::AnalyzerVersionsChanged,
789        &mut reasons,
790    );
791    reasons.sort_unstable();
792    reasons.dedup();
793    if reasons.is_empty() {
794        ChangeValidity::Valid
795    } else {
796        ChangeValidity::Stale {
797            reasons,
798            remediation: "Recollect the change set and rerun analysis before committing."
799                .to_owned(),
800        }
801    }
802}
803
804/// Git commit selection semantics modeled without executing a commit.
805#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
806#[serde(tag = "kind", rename_all = "snake_case")]
807pub enum CommitSelection {
808    /// Default `git commit`: commit the index exactly as represented.
809    Default,
810    /// `git commit -a`: stage and commit all tracked modifications and deletions.
811    AllTracked,
812    /// `git commit --only -- <pathspecs>`: commit only selected worktree paths.
813    Only {
814        /// Validated literal repository-relative pathspecs.
815        pathspecs: Vec<String>,
816    },
817    /// `git commit --include -- <pathspecs>`: add selected paths to the existing index.
818    Include {
819        /// Validated literal repository-relative pathspecs.
820        pathspecs: Vec<String>,
821    },
822}
823
824/// Commit command intent evaluated against an analyzed change set.
825#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
826pub struct CommitIntent {
827    /// Selection behavior requested by the caller.
828    pub selection: CommitSelection,
829}
830
831/// Explicit file/layer subset a modeled commit would select.
832#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
833pub struct CommitFileSelection {
834    /// Resulting path, or the old path for a deletion.
835    pub path: NativePath,
836    /// Included source layers.
837    pub layers: Vec<ChangeSourceLayer>,
838}
839
840/// Safety decision for a modeled commit command.
841#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
842pub struct CommitGate {
843    /// Whether the selected subset is explicit and unambiguous.
844    pub allowed: bool,
845    /// Explicit selected paths and layers.
846    pub selected: Vec<CommitFileSelection>,
847    /// Reasons the gate failed closed.
848    pub reasons: Vec<String>,
849}
850
851/// Evaluates commit selection semantics without mutating Git state.
852///
853/// # Errors
854///
855/// Returns [`ChangeError::InvalidPathspec`] when a pathspec could be interpreted as an option,
856/// revision expression, pathspec magic, glob, absolute path, or control-bearing input.
857pub fn evaluate_commit_gate(
858    change_set: &ChangeSet,
859    intent: &CommitIntent,
860) -> Result<CommitGate, ChangeError> {
861    let pathspecs = match &intent.selection {
862        CommitSelection::Only { pathspecs } | CommitSelection::Include { pathspecs } => {
863            for pathspec in pathspecs {
864                validate_pathspec(pathspec)?;
865            }
866            Some(pathspecs.as_slice())
867        }
868        CommitSelection::Default | CommitSelection::AllTracked => None,
869    };
870    let mut selected = BTreeMap::<NativePath, BTreeSet<ChangeSourceLayer>>::new();
871    for file in &change_set.files {
872        let Some(path) = effective_path(file) else {
873            continue;
874        };
875        let matched = pathspecs.is_none_or(|specs| {
876            specs
877                .iter()
878                .any(|spec| literal_pathspec_matches(spec, &path.bytes))
879        });
880        let include = match intent.selection {
881            CommitSelection::Default => file.source == ChangeSourceLayer::Staged,
882            CommitSelection::AllTracked => {
883                matches!(
884                    file.source,
885                    ChangeSourceLayer::Staged | ChangeSourceLayer::Worktree
886                )
887            }
888            CommitSelection::Only { .. } => {
889                matched
890                    && matches!(
891                        file.source,
892                        ChangeSourceLayer::Staged
893                            | ChangeSourceLayer::Worktree
894                            | ChangeSourceLayer::Untracked
895                    )
896            }
897            CommitSelection::Include { .. } => {
898                file.source == ChangeSourceLayer::Staged
899                    || (matched
900                        && matches!(
901                            file.source,
902                            ChangeSourceLayer::Worktree | ChangeSourceLayer::Untracked
903                        ))
904            }
905        };
906        if include {
907            selected
908                .entry(path.clone())
909                .or_default()
910                .insert(file.source);
911        }
912    }
913
914    let mut reasons = Vec::new();
915    if selected.is_empty() {
916        reasons.push("The modeled command selects no analyzed changes.".to_owned());
917    }
918    if matches!(intent.selection, CommitSelection::Only { .. })
919        && selected.values().any(|layers| layers.len() > 1)
920    {
921        reasons.push(
922            "`--only` overlaps staged and worktree layers; the exact committed blob is ambiguous."
923                .to_owned(),
924        );
925    }
926    let selected = selected
927        .into_iter()
928        .map(|(path, layers)| CommitFileSelection {
929            path,
930            layers: layers.into_iter().collect(),
931        })
932        .collect();
933    Ok(CommitGate {
934        allowed: reasons.is_empty(),
935        selected,
936        reasons,
937    })
938}
939
940/// Failures produced by local Git change discovery and commit modeling.
941#[derive(Debug, Error)]
942pub enum ChangeError {
943    /// Pull-request scopes require an external provider.
944    #[error("the local Git provider does not support pull-request scopes")]
945    PullRequestUnsupported,
946    /// A ref contains revision-expression or option syntax.
947    #[error("invalid Git ref `{0}`")]
948    InvalidRef(String),
949    /// A commit ID is not a full hexadecimal SHA-1 or SHA-256 object ID.
950    #[error("invalid full commit SHA `{0}`")]
951    InvalidSha(String),
952    /// A pathspec is unsafe or cannot be modeled literally.
953    #[error("invalid literal pathspec `{0}`")]
954    InvalidPathspec(String),
955    /// An output budget was configured as zero.
956    #[error("Git output limits must be greater than zero")]
957    InvalidLimit,
958    /// Git could not be started.
959    #[error("failed to spawn Git")]
960    Spawn {
961        /// Underlying process error.
962        #[source]
963        source: std::io::Error,
964    },
965    /// A required child pipe was unavailable.
966    #[error("Git child process did not expose a required pipe")]
967    MissingPipe,
968    /// Waiting for Git failed.
969    #[error("failed while waiting for Git")]
970    Wait {
971        /// Underlying process error.
972        #[source]
973        source: std::io::Error,
974    },
975    /// Reading bounded process output failed.
976    #[error("failed while reading bounded Git output")]
977    Read {
978        /// Underlying I/O error.
979        #[source]
980        source: std::io::Error,
981    },
982    /// A process reader task failed.
983    #[error("Git output reader task failed")]
984    ReaderTask {
985        /// Tokio task failure.
986        #[source]
987        source: tokio::task::JoinError,
988    },
989    /// Git exceeded the configured stream budget.
990    #[error("Git {stream} exceeded its {limit}-byte output limit")]
991    OutputLimit {
992        /// Stream whose budget was exhausted.
993        stream: &'static str,
994        /// Configured maximum bytes.
995        limit: usize,
996    },
997    /// Git returned a non-success status.
998    #[error("Git failed with status {status:?}: {stderr}")]
999    GitFailed {
1000        /// Exit status code, if the platform supplied one.
1001        status: Option<i32>,
1002        /// Bounded, lossy diagnostic stderr.
1003        stderr: String,
1004    },
1005    /// The operation exceeded its deadline.
1006    #[error("Git operation timed out after {timeout:?}")]
1007    Timeout {
1008        /// Configured deadline.
1009        timeout: Duration,
1010    },
1011    /// The caller cancelled the operation.
1012    #[error("Git operation was cancelled")]
1013    Cancelled,
1014    /// Git identity metadata was unexpectedly non-UTF-8.
1015    #[error("Git returned non-UTF-8 identity metadata")]
1016    NonUtf8Metadata,
1017    /// A canonical repository path could not be resolved.
1018    #[error("failed to canonicalize `{path}`")]
1019    Canonicalize {
1020        /// Path being resolved.
1021        path: PathBuf,
1022        /// Underlying filesystem error.
1023        #[source]
1024        source: std::io::Error,
1025    },
1026    /// Git raw output was malformed or inconsistent.
1027    #[error("malformed bounded Git output: {0}")]
1028    MalformedGitOutput(String),
1029    /// Fingerprint identity serialization failed.
1030    #[error("failed to encode change identity")]
1031    FingerprintEncoding {
1032        /// Underlying serialization error.
1033        #[source]
1034        source: serde_json::Error,
1035    },
1036}
1037
1038#[derive(Debug, Default)]
1039struct LayerResult {
1040    files: Vec<ChangedFile>,
1041    material: Vec<u8>,
1042}
1043
1044fn diff_prefix(mode: &str) -> Vec<OsString> {
1045    vec![
1046        OsString::from("diff"),
1047        OsString::from(mode),
1048        OsString::from("-z"),
1049        OsString::from("--find-renames"),
1050        OsString::from("--find-copies"),
1051        OsString::from("--no-ext-diff"),
1052        OsString::from("--no-color"),
1053    ]
1054}
1055
1056async fn read_bounded<R>(reader: R, limit: usize) -> Result<Vec<u8>, ChangeError>
1057where
1058    R: tokio::io::AsyncRead + Unpin,
1059{
1060    let maximum = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1);
1061    let mut output = Vec::new();
1062    reader
1063        .take(maximum)
1064        .read_to_end(&mut output)
1065        .await
1066        .map_err(|source| ChangeError::Read { source })?;
1067    if output.len() > limit {
1068        return Err(ChangeError::OutputLimit {
1069            stream: "stream",
1070            limit,
1071        });
1072    }
1073    Ok(output)
1074}
1075
1076async fn terminate(child: &mut tokio::process::Child) {
1077    let _ignored = child.start_kill();
1078    let _ignored = child.wait().await;
1079}
1080
1081fn canonicalize(path: &Path) -> Result<PathBuf, ChangeError> {
1082    std::fs::canonicalize(path).map_err(|source| ChangeError::Canonicalize {
1083        path: path.to_path_buf(),
1084        source,
1085    })
1086}
1087
1088fn validate_scope(scope: &ChangeScope) -> Result<(), ChangeError> {
1089    match scope {
1090        ChangeScope::Compare { reference } => validate_ref(reference),
1091        ChangeScope::Commit { sha } => validate_sha(sha),
1092        ChangeScope::Range { base, head } => {
1093            validate_ref(base)?;
1094            validate_ref(head)
1095        }
1096        ChangeScope::PullRequest { provider, .. } => {
1097            if provider.is_empty() || provider.chars().any(char::is_control) {
1098                return Err(ChangeError::InvalidRef(provider.clone()));
1099            }
1100            Err(ChangeError::PullRequestUnsupported)
1101        }
1102        ChangeScope::Unstaged | ChangeScope::Staged | ChangeScope::All => Ok(()),
1103    }
1104}
1105
1106fn validate_ref(reference: &str) -> Result<(), ChangeError> {
1107    let valid_chars = reference
1108        .bytes()
1109        .all(|byte| byte.is_ascii_alphanumeric() || b"._/-".contains(&byte));
1110    let invalid = reference.is_empty()
1111        || reference.starts_with('-')
1112        || reference.starts_with('/')
1113        || reference.ends_with('/')
1114        || reference.contains("..")
1115        || reference.contains("//")
1116        || reference.contains("@{")
1117        || reference.ends_with('.')
1118        || Path::new(reference)
1119            .extension()
1120            .is_some_and(|extension| extension.eq_ignore_ascii_case("lock"))
1121        || !valid_chars;
1122    if invalid {
1123        Err(ChangeError::InvalidRef(reference.to_owned()))
1124    } else {
1125        Ok(())
1126    }
1127}
1128
1129fn validate_sha(sha: &str) -> Result<(), ChangeError> {
1130    if matches!(sha.len(), 40 | 64) && sha.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1131        Ok(())
1132    } else {
1133        Err(ChangeError::InvalidSha(sha.to_owned()))
1134    }
1135}
1136
1137fn validate_pathspec(pathspec: &str) -> Result<(), ChangeError> {
1138    let path = Path::new(pathspec);
1139    let invalid = pathspec.is_empty()
1140        || pathspec.starts_with('-')
1141        || pathspec.starts_with(":(")
1142        || pathspec.contains("..")
1143        || pathspec.contains(['*', '?', '[', ']'])
1144        || pathspec.chars().any(char::is_control)
1145        || path.is_absolute()
1146        || path
1147            .components()
1148            .any(|component| matches!(component, std::path::Component::ParentDir));
1149    if invalid {
1150        Err(ChangeError::InvalidPathspec(pathspec.to_owned()))
1151    } else {
1152        Ok(())
1153    }
1154}
1155
1156fn parse_raw(raw: &[u8], source: ChangeSourceLayer) -> Result<Vec<ChangedFile>, ChangeError> {
1157    let mut files = Vec::new();
1158    let mut cursor = 0;
1159    while cursor < raw.len() {
1160        let header = take_nul(raw, &mut cursor)?;
1161        if header.is_empty() {
1162            continue;
1163        }
1164        if header.first() != Some(&b':') {
1165            return Err(ChangeError::MalformedGitOutput(
1166                "raw record does not start with ':'".to_owned(),
1167            ));
1168        }
1169        let status_byte = header
1170            .split(u8::is_ascii_whitespace)
1171            .next_back()
1172            .and_then(|field| field.first())
1173            .copied()
1174            .ok_or_else(|| ChangeError::MalformedGitOutput("missing raw status".to_owned()))?;
1175        let first_path = take_nul(raw, &mut cursor)?;
1176        let (status, old_path, new_path) = match status_byte {
1177            b'A' => (ChangedFileStatus::Added, None, Some(first_path)),
1178            b'M' | b'T' | b'U' => (
1179                ChangedFileStatus::Modified,
1180                Some(first_path),
1181                Some(first_path),
1182            ),
1183            b'D' => (ChangedFileStatus::Deleted, Some(first_path), None),
1184            b'R' => (
1185                ChangedFileStatus::Renamed,
1186                Some(first_path),
1187                Some(take_nul(raw, &mut cursor)?),
1188            ),
1189            b'C' => (
1190                ChangedFileStatus::Copied,
1191                Some(first_path),
1192                Some(take_nul(raw, &mut cursor)?),
1193            ),
1194            other => {
1195                return Err(ChangeError::MalformedGitOutput(format!(
1196                    "unsupported raw status `{}`",
1197                    char::from(other)
1198                )));
1199            }
1200        };
1201        files.push(ChangedFile {
1202            status,
1203            old_path: old_path.map(native_path_bytes),
1204            new_path: new_path.map(native_path_bytes),
1205            binary: false,
1206            hunks: Vec::new(),
1207            source,
1208        });
1209    }
1210    Ok(files)
1211}
1212
1213fn take_nul<'a>(bytes: &'a [u8], cursor: &mut usize) -> Result<&'a [u8], ChangeError> {
1214    let remaining = bytes
1215        .get(*cursor..)
1216        .ok_or_else(|| ChangeError::MalformedGitOutput("cursor exceeds output".to_owned()))?;
1217    let length = remaining
1218        .iter()
1219        .position(|byte| *byte == 0)
1220        .ok_or_else(|| ChangeError::MalformedGitOutput("missing NUL delimiter".to_owned()))?;
1221    let value = &remaining[..length];
1222    *cursor = cursor.saturating_add(length).saturating_add(1);
1223    Ok(value)
1224}
1225
1226fn apply_numstat(numstat: &[u8], files: &mut [ChangedFile]) -> Result<(), ChangeError> {
1227    let mut cursor = 0;
1228    let mut index = 0;
1229    while cursor < numstat.len() {
1230        let record = take_nul(numstat, &mut cursor)?;
1231        if record.is_empty() {
1232            continue;
1233        }
1234        let mut fields = record.splitn(3, |byte| *byte == b'\t');
1235        let added = fields.next();
1236        let removed = fields.next();
1237        let path = fields.next();
1238        let (Some(added), Some(removed), Some(path)) = (added, removed, path) else {
1239            return Err(ChangeError::MalformedGitOutput(
1240                "invalid numstat record".to_owned(),
1241            ));
1242        };
1243        let file = files.get_mut(index).ok_or_else(|| {
1244            ChangeError::MalformedGitOutput("numstat has too many records".to_owned())
1245        })?;
1246        file.binary = added == b"-" || removed == b"-";
1247        if path.is_empty() {
1248            let _old = take_nul(numstat, &mut cursor)?;
1249            let _new = take_nul(numstat, &mut cursor)?;
1250        }
1251        index = index.saturating_add(1);
1252    }
1253    if index != files.len() {
1254        return Err(ChangeError::MalformedGitOutput(
1255            "raw and numstat record counts differ".to_owned(),
1256        ));
1257    }
1258    Ok(())
1259}
1260
1261fn apply_patch(patch: &[u8], files: &mut [ChangedFile]) -> Result<(), ChangeError> {
1262    let mut file_index: Option<usize> = None;
1263    let mut current_hunk: Option<ChangeHunk> = None;
1264    let mut old_line = 0_u32;
1265    let mut new_line = 0_u32;
1266    for line in patch.split_inclusive(|byte| *byte == b'\n') {
1267        if line.starts_with(b"diff --git ") {
1268            finish_hunk(files, file_index, current_hunk.take())?;
1269            file_index = Some(file_index.map_or(0, |index| index.saturating_add(1)));
1270            continue;
1271        }
1272        if line.starts_with(b"@@ ") {
1273            finish_hunk(files, file_index, current_hunk.take())?;
1274            let hunk = parse_hunk_header(line)?;
1275            old_line = hunk.old_start;
1276            new_line = hunk.new_start;
1277            current_hunk = Some(hunk);
1278            continue;
1279        }
1280        let Some(hunk) = current_hunk.as_mut() else {
1281            continue;
1282        };
1283        if line.starts_with(b"+") && !line.starts_with(b"+++") {
1284            hunk.lines.push(ChangedLine {
1285                kind: ChangedLineKind::Added,
1286                old_line: None,
1287                new_line: Some(new_line),
1288            });
1289            new_line = new_line.saturating_add(1);
1290        } else if line.starts_with(b"-") && !line.starts_with(b"---") {
1291            hunk.lines.push(ChangedLine {
1292                kind: ChangedLineKind::Removed,
1293                old_line: Some(old_line),
1294                new_line: None,
1295            });
1296            old_line = old_line.saturating_add(1);
1297        } else if line.starts_with(b" ") {
1298            old_line = old_line.saturating_add(1);
1299            new_line = new_line.saturating_add(1);
1300        }
1301    }
1302    finish_hunk(files, file_index, current_hunk)?;
1303    if file_index.is_some_and(|index| index >= files.len()) {
1304        return Err(ChangeError::MalformedGitOutput(
1305            "patch has more file sections than raw output".to_owned(),
1306        ));
1307    }
1308    Ok(())
1309}
1310
1311fn finish_hunk(
1312    files: &mut [ChangedFile],
1313    file_index: Option<usize>,
1314    hunk: Option<ChangeHunk>,
1315) -> Result<(), ChangeError> {
1316    if let Some(hunk) = hunk {
1317        let index = file_index.ok_or_else(|| {
1318            ChangeError::MalformedGitOutput("hunk precedes file header".to_owned())
1319        })?;
1320        files
1321            .get_mut(index)
1322            .ok_or_else(|| {
1323                ChangeError::MalformedGitOutput("patch file index exceeds raw output".to_owned())
1324            })?
1325            .hunks
1326            .push(hunk);
1327    }
1328    Ok(())
1329}
1330
1331fn parse_hunk_header(line: &[u8]) -> Result<ChangeHunk, ChangeError> {
1332    let text = std::str::from_utf8(line)
1333        .map_err(|_| ChangeError::MalformedGitOutput("non-ASCII hunk header".to_owned()))?;
1334    let mut fields = text.split_ascii_whitespace();
1335    if fields.next() != Some("@@") {
1336        return Err(ChangeError::MalformedGitOutput(
1337            "invalid hunk marker".to_owned(),
1338        ));
1339    }
1340    let old = fields
1341        .next()
1342        .ok_or_else(|| ChangeError::MalformedGitOutput("missing old hunk range".to_owned()))?;
1343    let new = fields
1344        .next()
1345        .ok_or_else(|| ChangeError::MalformedGitOutput("missing new hunk range".to_owned()))?;
1346    let (old_start, old_count) = parse_range(old, '-')?;
1347    let (new_start, new_count) = parse_range(new, '+')?;
1348    Ok(ChangeHunk {
1349        old_start,
1350        old_count,
1351        new_start,
1352        new_count,
1353        lines: Vec::new(),
1354    })
1355}
1356
1357fn parse_range(value: &str, prefix: char) -> Result<(u32, u32), ChangeError> {
1358    let value = value
1359        .strip_prefix(prefix)
1360        .ok_or_else(|| ChangeError::MalformedGitOutput("invalid hunk range prefix".to_owned()))?;
1361    let (start, count) = value.split_once(',').unwrap_or((value, "1"));
1362    let start = start
1363        .parse()
1364        .map_err(|_| ChangeError::MalformedGitOutput("invalid hunk start".to_owned()))?;
1365    let count = count
1366        .parse()
1367        .map_err(|_| ChangeError::MalformedGitOutput("invalid hunk count".to_owned()))?;
1368    Ok((start, count))
1369}
1370
1371fn sort_and_deduplicate(files: &mut Vec<ChangedFile>) {
1372    files.sort_by(|left, right| {
1373        left.source
1374            .cmp(&right.source)
1375            .then_with(|| effective_path(left).cmp(&effective_path(right)))
1376            .then_with(|| left.status.cmp(&right.status))
1377            .then_with(|| left.old_path.cmp(&right.old_path))
1378    });
1379    files.dedup();
1380}
1381
1382fn effective_path(file: &ChangedFile) -> Option<&NativePath> {
1383    file.new_path.as_ref().or(file.old_path.as_ref())
1384}
1385
1386fn literal_pathspec_matches(pathspec: &str, path: &[u8]) -> bool {
1387    let spec = pathspec.trim_end_matches('/').as_bytes();
1388    path == spec
1389        || (path.starts_with(spec)
1390            && path
1391                .get(spec.len())
1392                .is_some_and(|separator| *separator == b'/'))
1393}
1394
1395fn framed_material(parts: &[&[u8]]) -> Vec<u8> {
1396    let capacity = parts.iter().map(|part| part.len().saturating_add(8)).sum();
1397    let mut output = Vec::with_capacity(capacity);
1398    for part in parts {
1399        output.extend_from_slice(&u64::try_from(part.len()).unwrap_or(u64::MAX).to_le_bytes());
1400        output.extend_from_slice(part);
1401    }
1402    output
1403}
1404
1405fn hash_material(namespace: &[u8], material: &[u8]) -> String {
1406    let mut hasher = blake3::Hasher::new();
1407    hasher.update(namespace);
1408    hasher.update(&[0]);
1409    hasher.update(material);
1410    hasher.finalize().to_hex().to_string()
1411}
1412
1413#[expect(
1414    clippy::too_many_arguments,
1415    reason = "all identity inputs are fingerprint material"
1416)]
1417fn exact_fingerprint(
1418    request: &ChangeRequest,
1419    worktree: &NativePath,
1420    common: &NativePath,
1421    checkout_head_sha: &str,
1422    base_ref: Option<&str>,
1423    head_ref: Option<&str>,
1424    head_sha: &str,
1425    materials: &[&[u8]],
1426) -> Result<String, ChangeError> {
1427    let identity = serde_json::to_vec(&(
1428        &request.repo_id,
1429        &request.checkout_id,
1430        worktree,
1431        common,
1432        &request.scope,
1433        checkout_head_sha,
1434        base_ref,
1435        head_ref,
1436        head_sha,
1437        &request.workspace_manifest_hash,
1438        &request.contract_registry_hash,
1439        &request.analyzer_versions,
1440    ))
1441    .map_err(|source| ChangeError::FingerprintEncoding { source })?;
1442    let mut hasher = blake3::Hasher::new();
1443    hasher.update(b"code-system-graph-exact-diff-v1");
1444    hasher.update(
1445        &u64::try_from(identity.len())
1446            .unwrap_or(u64::MAX)
1447            .to_le_bytes(),
1448    );
1449    hasher.update(&identity);
1450    for material in materials {
1451        hasher.update(
1452            &u64::try_from(material.len())
1453                .unwrap_or(u64::MAX)
1454                .to_le_bytes(),
1455        );
1456        hasher.update(material);
1457    }
1458    Ok(hasher.finalize().to_hex().to_string())
1459}
1460
1461fn compare<T: PartialEq>(stored: &T, current: &T, reason: StaleReason, out: &mut Vec<StaleReason>) {
1462    if stored != current {
1463        out.push(reason);
1464    }
1465}
1466
1467#[cfg(unix)]
1468fn native_path(path: &Path) -> NativePath {
1469    use std::os::unix::ffi::OsStrExt;
1470
1471    NativePath {
1472        encoding: NativePathEncoding::UnixBytes,
1473        bytes: path.as_os_str().as_bytes().to_vec(),
1474        display: path.to_string_lossy().into_owned(),
1475    }
1476}
1477
1478#[cfg(windows)]
1479fn native_path(path: &Path) -> NativePath {
1480    use std::os::windows::ffi::OsStrExt;
1481
1482    NativePath {
1483        encoding: NativePathEncoding::WindowsWide,
1484        bytes: path
1485            .as_os_str()
1486            .encode_wide()
1487            .flat_map(u16::to_le_bytes)
1488            .collect(),
1489        display: path.to_string_lossy().into_owned(),
1490    }
1491}
1492
1493#[cfg(not(any(unix, windows)))]
1494fn native_path(path: &Path) -> NativePath {
1495    NativePath {
1496        encoding: NativePathEncoding::Utf8,
1497        bytes: path.to_string_lossy().as_bytes().to_vec(),
1498        display: path.to_string_lossy().into_owned(),
1499    }
1500}
1501
1502fn native_path_bytes(bytes: &[u8]) -> NativePath {
1503    #[cfg(unix)]
1504    {
1505        use std::os::unix::ffi::OsStrExt;
1506
1507        let value = OsStr::from_bytes(bytes);
1508        NativePath {
1509            encoding: NativePathEncoding::UnixBytes,
1510            bytes: bytes.to_vec(),
1511            display: value.to_string_lossy().into_owned(),
1512        }
1513    }
1514    #[cfg(not(unix))]
1515    {
1516        NativePath {
1517            encoding: NativePathEncoding::Utf8,
1518            bytes: bytes.to_vec(),
1519            display: String::from_utf8_lossy(bytes).into_owned(),
1520        }
1521    }
1522}
1523
1524#[cfg(test)]
1525mod tests {
1526    use std::fs;
1527    use std::process::Command as StdCommand;
1528
1529    use tempfile::TempDir;
1530
1531    use super::*;
1532
1533    type TestResult = Result<(), Box<dyn std::error::Error>>;
1534
1535    fn path(value: &str) -> NativePath {
1536        native_path_bytes(value.as_bytes())
1537    }
1538
1539    fn file(name: &str, source: ChangeSourceLayer) -> ChangedFile {
1540        ChangedFile {
1541            status: ChangedFileStatus::Modified,
1542            old_path: Some(path(name)),
1543            new_path: Some(path(name)),
1544            binary: false,
1545            hunks: Vec::new(),
1546            source,
1547        }
1548    }
1549
1550    fn sample_set(files: Vec<ChangedFile>) -> ChangeSet {
1551        ChangeSet {
1552            repo_id: RepoId::new("repo:test"),
1553            checkout_id: CheckoutId::new("checkout:test"),
1554            worktree: path("/tmp/repo"),
1555            git_common_dir: path("/tmp/repo/.git"),
1556            scope: ChangeScope::All,
1557            checkout_head_ref: Some("refs/heads/main".to_owned()),
1558            checkout_head_sha: "a".repeat(40),
1559            base_ref: None,
1560            head_ref: Some("HEAD".to_owned()),
1561            head_sha: "a".repeat(40),
1562            staged_hash: "staged".to_owned(),
1563            worktree_hash: "worktree".to_owned(),
1564            exact_diff_fingerprint: "exact".to_owned(),
1565            workspace_manifest_hash: "manifest".to_owned(),
1566            contract_registry_hash: "contracts".to_owned(),
1567            analyzer_versions: BTreeMap::from([("core".to_owned(), "1".to_owned())]),
1568            files,
1569        }
1570    }
1571
1572    fn git(repo: &Path, args: &[&str]) -> TestResult {
1573        let status = StdCommand::new("git")
1574            .arg("-C")
1575            .arg(repo)
1576            .args(args)
1577            .stdin(Stdio::null())
1578            .status()?;
1579        if status.success() {
1580            Ok(())
1581        } else {
1582            Err(format!("git failed with {status}").into())
1583        }
1584    }
1585
1586    fn repo() -> Result<TempDir, Box<dyn std::error::Error>> {
1587        let temp = tempfile::tempdir()?;
1588        git(temp.path(), &["init", "-q"])?;
1589        git(temp.path(), &["config", "core.autocrlf", "false"])?;
1590        git(
1591            temp.path(),
1592            &["config", "user.name", "Code System Graph Test"],
1593        )?;
1594        git(
1595            temp.path(),
1596            &["config", "user.email", "test@example.invalid"],
1597        )?;
1598        fs::write(temp.path().join("tracked.txt"), "one\n")?;
1599        git(temp.path(), &["add", "tracked.txt"])?;
1600        git(temp.path(), &["commit", "-qm", "initial"])?;
1601        Ok(temp)
1602    }
1603
1604    fn request(repo: &Path, scope: ChangeScope) -> ChangeRequest {
1605        ChangeRequest {
1606            repo_id: RepoId::new("repo:test"),
1607            checkout_id: CheckoutId::new("checkout:test"),
1608            worktree: repo.to_path_buf(),
1609            scope,
1610            workspace_manifest_hash: "manifest".to_owned(),
1611            contract_registry_hash: "contracts".to_owned(),
1612            analyzer_versions: BTreeMap::from([("core".to_owned(), "1".to_owned())]),
1613        }
1614    }
1615
1616    async fn collect(repo: &Path, scope: ChangeScope) -> Result<ChangeSet, ChangeError> {
1617        GitCliChangeProvider::new()
1618            .changes(&request(repo, scope), &CancellationToken::new())
1619            .await
1620    }
1621
1622    #[test]
1623    fn ref_validation_accepts_simple_names() {
1624        assert!(validate_ref("refs/heads/feature-x").is_ok());
1625    }
1626
1627    #[test]
1628    fn ref_validation_rejects_option_injection() {
1629        assert!(validate_ref("--output=/tmp/pwn").is_err());
1630    }
1631
1632    #[test]
1633    fn ref_validation_rejects_range_injection() {
1634        assert!(validate_ref("main..evil").is_err());
1635    }
1636
1637    #[test]
1638    fn sha_validation_accepts_full_sha1() {
1639        assert!(validate_sha(&"a".repeat(40)).is_ok());
1640    }
1641
1642    #[test]
1643    fn sha_validation_rejects_short_object_id() {
1644        assert!(validate_sha("deadbeef").is_err());
1645    }
1646
1647    #[test]
1648    fn pathspec_validation_rejects_options() {
1649        assert!(validate_pathspec("-a").is_err());
1650    }
1651
1652    #[test]
1653    fn pathspec_validation_rejects_magic() {
1654        assert!(validate_pathspec(":(top)src").is_err());
1655    }
1656
1657    #[test]
1658    fn pathspec_matching_includes_directory_children() {
1659        assert!(literal_pathspec_matches("src", b"src/lib.rs"));
1660    }
1661
1662    #[test]
1663    fn raw_parser_handles_rename() -> TestResult {
1664        let raw = b":100644 100644 aaaaaaa bbbbbbb R100\0old.rs\0new.rs\0";
1665        let parsed = parse_raw(raw, ChangeSourceLayer::Staged)?;
1666        assert_eq!(parsed[0].status, ChangedFileStatus::Renamed);
1667        Ok(())
1668    }
1669
1670    #[test]
1671    fn raw_parser_preserves_non_utf8_path() -> TestResult {
1672        let raw = b":000000 100644 0000000 bbbbbbb A\0bad-\xff\0";
1673        let parsed = parse_raw(raw, ChangeSourceLayer::Staged)?;
1674        assert_eq!(
1675            parsed[0]
1676                .new_path
1677                .as_ref()
1678                .map(|value| value.bytes.as_slice()),
1679            Some(&b"bad-\xff"[..])
1680        );
1681        Ok(())
1682    }
1683
1684    #[test]
1685    fn numstat_marks_binary() -> TestResult {
1686        let mut files = vec![file("image.bin", ChangeSourceLayer::Staged)];
1687        apply_numstat(b"-\t-\timage.bin\0", &mut files)?;
1688        assert!(files[0].binary);
1689        Ok(())
1690    }
1691
1692    #[test]
1693    fn patch_parser_records_positions_without_text() -> TestResult {
1694        let mut files = vec![file("a.txt", ChangeSourceLayer::Worktree)];
1695        apply_patch(
1696            b"diff --git a.txt a.txt\n@@ -1 +1,2 @@\n-old secret\n+new secret\n+second\n",
1697            &mut files,
1698        )?;
1699        assert_eq!(files[0].hunks[0].lines.len(), 3);
1700        Ok(())
1701    }
1702
1703    #[test]
1704    fn validity_is_valid_for_identical_input() {
1705        let set = sample_set(Vec::new());
1706        assert_eq!(
1707            validate_change_set(&set, &ChangeValidityInput::from(&set)),
1708            ChangeValidity::Valid
1709        );
1710    }
1711
1712    #[test]
1713    fn validity_reports_manifest_change() {
1714        let set = sample_set(Vec::new());
1715        let mut input = ChangeValidityInput::from(&set);
1716        input.workspace_manifest_hash = "new".to_owned();
1717        assert!(matches!(
1718            validate_change_set(&set, &input),
1719            ChangeValidity::Stale { reasons, .. }
1720                if reasons == vec![StaleReason::WorkspaceManifestChanged]
1721        ));
1722    }
1723
1724    #[test]
1725    fn default_commit_gate_selects_only_staged() -> TestResult {
1726        let set = sample_set(vec![
1727            file("a", ChangeSourceLayer::Staged),
1728            file("b", ChangeSourceLayer::Worktree),
1729        ]);
1730        let gate = evaluate_commit_gate(
1731            &set,
1732            &CommitIntent {
1733                selection: CommitSelection::Default,
1734            },
1735        )?;
1736        assert_eq!(gate.selected.len(), 1);
1737        Ok(())
1738    }
1739
1740    #[test]
1741    fn all_tracked_commit_gate_excludes_untracked() -> TestResult {
1742        let set = sample_set(vec![
1743            file("a", ChangeSourceLayer::Worktree),
1744            file("b", ChangeSourceLayer::Untracked),
1745        ]);
1746        let gate = evaluate_commit_gate(
1747            &set,
1748            &CommitIntent {
1749                selection: CommitSelection::AllTracked,
1750            },
1751        )?;
1752        assert_eq!(gate.selected.len(), 1);
1753        Ok(())
1754    }
1755
1756    #[test]
1757    fn only_commit_gate_fails_on_layer_ambiguity() -> TestResult {
1758        let set = sample_set(vec![
1759            file("a", ChangeSourceLayer::Staged),
1760            file("a", ChangeSourceLayer::Worktree),
1761        ]);
1762        let gate = evaluate_commit_gate(
1763            &set,
1764            &CommitIntent {
1765                selection: CommitSelection::Only {
1766                    pathspecs: vec!["a".to_owned()],
1767                },
1768            },
1769        )?;
1770        assert!(!gate.allowed);
1771        Ok(())
1772    }
1773
1774    #[test]
1775    fn include_commit_gate_keeps_existing_index() -> TestResult {
1776        let set = sample_set(vec![
1777            file("staged", ChangeSourceLayer::Staged),
1778            file("src/new", ChangeSourceLayer::Worktree),
1779        ]);
1780        let gate = evaluate_commit_gate(
1781            &set,
1782            &CommitIntent {
1783                selection: CommitSelection::Include {
1784                    pathspecs: vec!["src".to_owned()],
1785                },
1786            },
1787        )?;
1788        assert_eq!(gate.selected.len(), 2);
1789        Ok(())
1790    }
1791
1792    #[tokio::test]
1793    async fn unstaged_scope_reports_tracked_modification() -> TestResult {
1794        let repo = repo()?;
1795        fs::write(repo.path().join("tracked.txt"), "two\n")?;
1796        let set = collect(repo.path(), ChangeScope::Unstaged).await?;
1797        assert_eq!(set.files[0].source, ChangeSourceLayer::Worktree);
1798        Ok(())
1799    }
1800
1801    #[tokio::test]
1802    async fn staged_scope_reports_index_addition() -> TestResult {
1803        let repo = repo()?;
1804        fs::write(repo.path().join("added.txt"), "added\n")?;
1805        git(repo.path(), &["add", "added.txt"])?;
1806        let set = collect(repo.path(), ChangeScope::Staged).await?;
1807        assert_eq!(set.files[0].status, ChangedFileStatus::Added);
1808        Ok(())
1809    }
1810
1811    #[tokio::test]
1812    async fn staged_scope_supports_an_unborn_checkout() -> TestResult {
1813        let repo = tempfile::tempdir()?;
1814        git(repo.path(), &["init", "-q"])?;
1815        fs::write(repo.path().join("first.txt"), "first commit\n")?;
1816        git(repo.path(), &["add", "first.txt"])?;
1817
1818        let set = collect(repo.path(), ChangeScope::Staged).await?;
1819
1820        assert!(
1821            set.checkout_head_ref
1822                .as_deref()
1823                .is_some_and(|head| head.starts_with("refs/heads/"))
1824        );
1825        assert_eq!(set.checkout_head_sha, set.head_sha);
1826        assert!(matches!(set.checkout_head_sha.len(), 40 | 64));
1827        assert_eq!(set.files.len(), 1);
1828        assert_eq!(set.files[0].status, ChangedFileStatus::Added);
1829        assert_eq!(set.files[0].source, ChangeSourceLayer::Staged);
1830        Ok(())
1831    }
1832
1833    #[tokio::test]
1834    async fn all_scope_keeps_layers_distinct() -> TestResult {
1835        let repo = repo()?;
1836        fs::write(repo.path().join("tracked.txt"), "staged\n")?;
1837        git(repo.path(), &["add", "tracked.txt"])?;
1838        fs::write(repo.path().join("tracked.txt"), "worktree\n")?;
1839        fs::write(repo.path().join("untracked.txt"), "untracked body\n")?;
1840        let set = collect(repo.path(), ChangeScope::All).await?;
1841        assert_eq!(set.files.len(), 3);
1842        Ok(())
1843    }
1844
1845    #[tokio::test]
1846    async fn delete_is_classified() -> TestResult {
1847        let repo = repo()?;
1848        fs::remove_file(repo.path().join("tracked.txt"))?;
1849        let set = collect(repo.path(), ChangeScope::Unstaged).await?;
1850        assert_eq!(set.files[0].status, ChangedFileStatus::Deleted);
1851        Ok(())
1852    }
1853
1854    #[tokio::test]
1855    async fn rename_is_classified() -> TestResult {
1856        let repo = repo()?;
1857        git(repo.path(), &["mv", "tracked.txt", "renamed.txt"])?;
1858        let set = collect(repo.path(), ChangeScope::Staged).await?;
1859        assert_eq!(set.files[0].status, ChangedFileStatus::Renamed);
1860        Ok(())
1861    }
1862
1863    #[tokio::test]
1864    async fn compare_scope_uses_merge_base() -> TestResult {
1865        let repo = repo()?;
1866        let initial = String::from_utf8(
1867            StdCommand::new("git")
1868                .arg("-C")
1869                .arg(repo.path())
1870                .args(["rev-parse", "HEAD"])
1871                .output()?
1872                .stdout,
1873        )?;
1874        fs::write(repo.path().join("later.txt"), "later\n")?;
1875        git(repo.path(), &["add", "later.txt"])?;
1876        git(repo.path(), &["commit", "-qm", "later"])?;
1877        let set = collect(
1878            repo.path(),
1879            ChangeScope::Compare {
1880                reference: initial.trim().to_owned(),
1881            },
1882        )
1883        .await?;
1884        assert_eq!(set.files.len(), 1);
1885        Ok(())
1886    }
1887
1888    #[tokio::test]
1889    async fn commit_scope_reports_one_commit() -> TestResult {
1890        let repo = repo()?;
1891        fs::write(repo.path().join("later.txt"), "later\n")?;
1892        git(repo.path(), &["add", "later.txt"])?;
1893        git(repo.path(), &["commit", "-qm", "later"])?;
1894        let sha = String::from_utf8(
1895            StdCommand::new("git")
1896                .arg("-C")
1897                .arg(repo.path())
1898                .args(["rev-parse", "HEAD"])
1899                .output()?
1900                .stdout,
1901        )?;
1902        let set = collect(
1903            repo.path(),
1904            ChangeScope::Commit {
1905                sha: sha.trim().to_owned(),
1906            },
1907        )
1908        .await?;
1909        assert_eq!(set.files.len(), 1);
1910        Ok(())
1911    }
1912
1913    #[tokio::test]
1914    async fn range_scope_reports_endpoint_difference() -> TestResult {
1915        let repo = repo()?;
1916        let base = String::from_utf8(
1917            StdCommand::new("git")
1918                .arg("-C")
1919                .arg(repo.path())
1920                .args(["rev-parse", "HEAD"])
1921                .output()?
1922                .stdout,
1923        )?;
1924        fs::write(repo.path().join("later.txt"), "later\n")?;
1925        git(repo.path(), &["add", "later.txt"])?;
1926        git(repo.path(), &["commit", "-qm", "later"])?;
1927        let head = String::from_utf8(
1928            StdCommand::new("git")
1929                .arg("-C")
1930                .arg(repo.path())
1931                .args(["rev-parse", "HEAD"])
1932                .output()?
1933                .stdout,
1934        )?;
1935        let set = collect(
1936            repo.path(),
1937            ChangeScope::Range {
1938                base: base.trim().to_owned(),
1939                head: head.trim().to_owned(),
1940            },
1941        )
1942        .await?;
1943        assert_eq!(set.files.len(), 1);
1944        Ok(())
1945    }
1946
1947    #[tokio::test]
1948    async fn pull_request_scope_is_rejected_locally() -> TestResult {
1949        let repo = repo()?;
1950        let result = collect(
1951            repo.path(),
1952            ChangeScope::PullRequest {
1953                provider: "github".to_owned(),
1954                number: 1,
1955            },
1956        )
1957        .await;
1958        assert!(matches!(result, Err(ChangeError::PullRequestUnsupported)));
1959        Ok(())
1960    }
1961
1962    #[tokio::test]
1963    async fn cancelled_request_fails_before_spawn() -> TestResult {
1964        let repo = repo()?;
1965        let token = CancellationToken::new();
1966        token.cancel();
1967        let result = GitCliChangeProvider::new()
1968            .changes(&request(repo.path(), ChangeScope::All), &token)
1969            .await;
1970        assert!(matches!(result, Err(ChangeError::Cancelled)));
1971        Ok(())
1972    }
1973
1974    #[tokio::test]
1975    async fn output_cap_is_enforced() -> TestResult {
1976        let repo = repo()?;
1977        fs::write(repo.path().join("large.txt"), "x".repeat(4096))?;
1978        git(repo.path(), &["add", "large.txt"])?;
1979        let provider = GitCliChangeProvider::with_limits("git", Duration::from_secs(5), 64, 1024);
1980        let result = provider
1981            .changes(
1982                &request(repo.path(), ChangeScope::Staged),
1983                &CancellationToken::new(),
1984            )
1985            .await;
1986        assert!(matches!(result, Err(ChangeError::OutputLimit { .. })));
1987        Ok(())
1988    }
1989
1990    #[cfg(unix)]
1991    #[tokio::test]
1992    async fn linked_worktree_uses_shared_common_directory() -> TestResult {
1993        let repo = repo()?;
1994        let linked_parent = tempfile::tempdir()?;
1995        let linked = linked_parent.path().join("linked");
1996        let linked_text = linked.to_string_lossy().into_owned();
1997        git(
1998            repo.path(),
1999            &["worktree", "add", "-q", "-b", "linked-test", &linked_text],
2000        )?;
2001        let set = collect(&linked, ChangeScope::All).await?;
2002        assert_ne!(set.worktree.bytes, set.git_common_dir.bytes);
2003        Ok(())
2004    }
2005}