Skip to main content

fallow_api/runtime/
similar_code.rs

1//! Programmatic orchestration for local advisory similar-code discovery.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt::Write as _;
5use std::io::Read as _;
6use std::path::{Path, PathBuf};
7use std::time::Instant;
8
9use fallow_engine::session::AnalysisSession;
10use fallow_engine::similar_code::{
11    FunctionVector, SimilarCodeCorpusSelection, SimilarCodeLimits as EngineLimits,
12    SimilarCodeSelectionInput, SimilarCodeSkipReason as EngineSkipReason,
13    evaluate_selected_similar_code, select_similar_code_corpus,
14};
15use fallow_engine::source::similar_code::{
16    ExtractedSimilarCodeFunction, SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION,
17    SimilarCodeExtractionLimits, SimilarCodeExtractionSkipReason,
18};
19use fallow_engine::test_paths::is_test_code_path_str;
20use fallow_engine::{
21    codeowners::CodeOwners,
22    project_analysis::ProjectAnalysisArtifactOptions,
23    trace::{trace_file, trace_impact_closure_without_search},
24};
25use fallow_output::{
26    SimilarCodeAction, SimilarCodeActionType, SimilarCodeCacheStatus, SimilarCodeCacheSummary,
27    SimilarCodeCandidate, SimilarCodeCandidateSnapshot, SimilarCodeCompletion,
28    SimilarCodeCompletionStatus, SimilarCodeDiagnostic, SimilarCodeDiagnosticDomain,
29    SimilarCodeDomainOutcome, SimilarCodeEnrichmentAvailability, SimilarCodeEnrichmentState,
30    SimilarCodeGeneration, SimilarCodeGenerationParameters, SimilarCodeInspectOutput,
31    SimilarCodeInspectPacket, SimilarCodeInspectSchemaVersion, SimilarCodeLimits,
32    SimilarCodeLocation, SimilarCodeModelProvenance, SimilarCodeNamedReference, SimilarCodeOutput,
33    SimilarCodePhase, SimilarCodePhaseCompletion, SimilarCodePhaseStatus, SimilarCodeProvider,
34    SimilarCodeProviderProvenance, SimilarCodeReviewOutput, SimilarCodeReviewProvenance,
35    SimilarCodeReviewSchemaVersion, SimilarCodeReviewedCandidate, SimilarCodeSchemaVersion,
36    SimilarCodeScopeProvenance, SimilarCodeSideEffectHint, SimilarCodeSideEvidence,
37    SimilarCodeSimilarityBand, SimilarCodeSkip, SimilarCodeSkipReason, SimilarCodeVerdictInput,
38    SimilarCodeVerdictMatch, SimilarCodeVerificationStatus,
39};
40use fallow_types::envelope::{ElapsedMs, ToolVersion};
41use globset::{GlobSet, GlobSetBuilder};
42use rustc_hash::{FxHashMap, FxHashSet};
43use serde_json::Value;
44use sha2::{Digest, Sha256};
45
46use crate::analysis_context::{
47    ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
48    workspace_roots_for_session,
49};
50use crate::similar_code::{
51    self, EmbeddingInput, EmbeddingResult, ProviderError, ReadyProvider, SimilarCodeProviderStatus,
52};
53use crate::{ProgrammaticError, SimilarCodeInspectOptions, SimilarCodeOptions};
54
55use super::ProgrammaticResult;
56
57const MAX_FILES: usize = 20_000;
58const MAX_RUN_TIMEOUT_MS: u64 = 15 * 60 * 1_000;
59const HIGH_SIMILARITY: f64 = 0.88;
60const VERY_HIGH_SIMILARITY: f64 = 0.95;
61const MAX_REVIEW_INPUT_BYTES: usize = 16 * 1024 * 1024;
62const MAX_RATIONALE_CHARS: usize = 4_000;
63const MAX_SOURCE_WINDOW_CHARS: usize = 16_000;
64const MAX_INSPECT_SOURCE_BYTES: u64 = fallow_config::DEFAULT_MAX_FILE_SIZE_BYTES;
65const MAX_INSPECT_GRAPH_REFERENCES: usize = 50;
66const MAX_INSPECT_RELATED_TESTS: usize = 50;
67const MODULE_REFERENCE_NAME: &str = "<module>";
68const INSPECT_CHURN_WINDOW_MONTHS: u64 = 6;
69
70#[derive(Clone, Copy)]
71struct PhaseCompleteness {
72    discovery: bool,
73    extraction: bool,
74    embedding: bool,
75    comparison: bool,
76}
77
78trait RuntimeEmbedder {
79    fn embed(
80        &mut self,
81        project_root: &Path,
82        no_cache: bool,
83        inputs: &[EmbeddingInput<'_>],
84    ) -> Result<EmbeddingResult, ProviderError>;
85}
86
87struct VerifiedProviderEmbedder<'a> {
88    provider: &'a ReadyProvider,
89}
90
91impl RuntimeEmbedder for VerifiedProviderEmbedder<'_> {
92    fn embed(
93        &mut self,
94        project_root: &Path,
95        no_cache: bool,
96        inputs: &[EmbeddingInput<'_>],
97    ) -> Result<EmbeddingResult, ProviderError> {
98        similar_code::embed_selected(self.provider, project_root, no_cache, inputs)
99    }
100}
101
102impl PhaseCompleteness {
103    const fn all_complete(self) -> bool {
104        self.discovery && self.extraction && self.embedding && self.comparison
105    }
106}
107
108/// Run opt-in semantic similar-code discovery through the verified local provider.
109///
110/// Candidate presence never changes success status. Missing local setup uses
111/// exit code 3, while invalid inputs and provider failures use exit code 2.
112///
113/// # Errors
114///
115/// Returns a structured error for invalid analysis options, unavailable local
116/// setup, source discovery failures, or unusable provider output.
117pub fn run_similar_code(options: &SimilarCodeOptions) -> ProgrammaticResult<SimilarCodeOutput> {
118    validate_options(options)?;
119    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
120    let provider = options
121        .adapter_provider_path
122        .as_deref()
123        .map_or_else(
124            || similar_code::ready_provider(resolved.root()),
125            similar_code::ready_provider_from_adapter_path,
126        )
127        .map_err(provider_error)?;
128    resolved.install(|| run_similar_code_inner(options, &resolved, &provider))
129}
130
131/// Select one bounded candidate snapshot from raw discovery JSON.
132///
133/// # Errors
134///
135/// Returns an error for oversized or malformed discovery JSON, duplicate
136/// candidate identities, or an unknown requested candidate.
137pub fn select_similar_code_candidate_snapshot(
138    candidate_json: &[u8],
139    candidate_id: &str,
140) -> ProgrammaticResult<SimilarCodeCandidateSnapshot> {
141    if candidate_json.len() > MAX_REVIEW_INPUT_BYTES {
142        return Err(candidate_input_error(
143            "similar-code candidate input exceeded the 16 MiB limit",
144        ));
145    }
146    if candidate_id.trim().is_empty() {
147        return Err(candidate_input_error("candidate_id must not be empty"));
148    }
149    let raw = parse_candidate_document(candidate_json).map_err(|error| {
150        candidate_input_error(format!(
151            "invalid similar-code candidate document: {}",
152            error.message
153        ))
154    })?;
155    let mut candidates = raw
156        .candidates
157        .into_iter()
158        .filter(|candidate| candidate.candidate_id == candidate_id);
159    let candidate = candidates.next().ok_or_else(|| {
160        candidate_input_error("candidate_id was not present in the discovery document")
161    })?;
162    if candidates.next().is_some() {
163        return Err(candidate_input_error(
164            "candidate document contains duplicate candidate_id values",
165        ));
166    }
167    Ok(SimilarCodeCandidateSnapshot {
168        schema_version: raw.schema_version,
169        generation: raw.generation,
170        candidate,
171        completion: raw.completion,
172        diagnostics: raw.diagnostics,
173    })
174}
175
176/// Validate one inline bounded candidate snapshot.
177///
178/// # Errors
179///
180/// Returns an error for oversized, malformed, or identity-mismatched input.
181pub fn parse_similar_code_candidate_snapshot(
182    snapshot_json: &[u8],
183    candidate_id: &str,
184) -> ProgrammaticResult<SimilarCodeCandidateSnapshot> {
185    if snapshot_json.len() > MAX_REVIEW_INPUT_BYTES {
186        return Err(candidate_input_error(
187            "similar-code candidate snapshot exceeded the 16 MiB limit",
188        ));
189    }
190    let snapshot: SimilarCodeCandidateSnapshot = serde_json::from_slice(snapshot_json)
191        .map_err(|error| candidate_input_error(format!("invalid candidate snapshot: {error}")))?;
192    if candidate_id.trim().is_empty() || snapshot.candidate.candidate_id != candidate_id {
193        return Err(candidate_input_error(
194            "candidate snapshot identity does not match candidate_id",
195        ));
196    }
197    Ok(snapshot)
198}
199
200/// Validate and inspect one exact candidate snapshot without rerunning global
201/// provider retrieval or ranking.
202///
203/// # Errors
204///
205/// Returns an error when the candidate is stale or source cannot be reproduced.
206pub fn inspect_similar_code(
207    options: &SimilarCodeInspectOptions,
208) -> ProgrammaticResult<SimilarCodeInspectOutput> {
209    let started = Instant::now();
210    let candidate = options.snapshot.candidate.clone();
211    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
212    let root = resolved.root().to_path_buf();
213    let mut left = inspect_side(&root, &candidate.left)?;
214    let mut right = inspect_side(&root, &candidate.right)?;
215    let session = load_session(&options.analysis)?;
216    let enrichment = resolved.install(|| {
217        enrich_inspect(
218            &session,
219            &candidate.left,
220            &candidate.right,
221            &mut left,
222            &mut right,
223        )
224    });
225    let mut diagnostics = options.snapshot.diagnostics.clone();
226    diagnostics.extend(enrichment.diagnostics);
227    Ok(SimilarCodeInspectOutput {
228        schema_version: SimilarCodeInspectSchemaVersion::V1,
229        version: ToolVersion(env!("CARGO_PKG_VERSION").to_owned()),
230        elapsed_ms: ElapsedMs(duration_ms(started)),
231        generation: options.snapshot.generation.clone(),
232        packet: SimilarCodeInspectPacket {
233            candidate_id: candidate.candidate_id.clone(),
234            review_key: candidate.review_key.clone(),
235            availability: enrichment.availability,
236            graph_relationship: enrichment.graph_relationship,
237            left,
238            right,
239        },
240        candidate,
241        completion: options.snapshot.completion.clone(),
242        diagnostics,
243    })
244}
245
246/// Join immutable candidate JSON with a separately authored verdict document.
247///
248/// # Errors
249///
250/// Returns a fail-closed error for malformed envelopes, invalid judgment
251/// implications, duplicate or stale verdicts, or missing required verdicts.
252#[expect(
253    clippy::too_many_lines,
254    reason = "the review join keeps fail-closed verdict validation in one auditable boundary"
255)]
256pub fn review_similar_code(
257    candidate_json: &[u8],
258    verdict_json: &[u8],
259    require_verdict_for_each_candidate: bool,
260) -> ProgrammaticResult<SimilarCodeReviewOutput> {
261    let started = Instant::now();
262    if candidate_json.len() > MAX_REVIEW_INPUT_BYTES || verdict_json.len() > MAX_REVIEW_INPUT_BYTES
263    {
264        return Err(review_error(
265            "similar-code review input exceeded the 16 MiB limit",
266        ));
267    }
268    let raw = parse_candidate_document(candidate_json)?;
269    let verdicts: SimilarCodeVerdictInput = serde_json::from_slice(verdict_json)
270        .map_err(|error| review_error(format!("invalid similar-code verdict document: {error}")))?;
271    let mut by_candidate_id = FxHashMap::default();
272    let mut by_review_key: FxHashMap<&str, Vec<usize>> = FxHashMap::default();
273    for (index, candidate) in raw.candidates.iter().enumerate() {
274        if by_candidate_id
275            .insert(candidate.candidate_id.as_str(), index)
276            .is_some()
277        {
278            return Err(review_error(
279                "candidate document contains duplicate candidate_id values",
280            ));
281        }
282        by_review_key
283            .entry(candidate.review_key.as_str())
284            .or_default()
285            .push(index);
286    }
287
288    let mut matched = vec![None; raw.candidates.len()];
289    let mut match_kind = vec![SimilarCodeVerdictMatch::Unverified; raw.candidates.len()];
290    let mut diagnostics = raw.diagnostics;
291    let mut seen_candidate_ids = FxHashSet::default();
292    let mut seen_review_keys = FxHashSet::default();
293    for verdict in verdicts.verdicts {
294        validate_verdict(&verdict)?;
295        if !seen_candidate_ids.insert(verdict.candidate_id.clone()) {
296            return Err(duplicate_verdict_identity_error());
297        }
298        if let Some(&index) = by_candidate_id.get(verdict.candidate_id.as_str()) {
299            if raw.candidates[index].review_key != verdict.review_key {
300                return Err(review_error(
301                    "verdict review_key does not match its candidate_id",
302                ));
303            }
304            if matched[index].is_some() {
305                return Err(review_error(
306                    "multiple verdicts resolve to the same candidate",
307                ));
308            }
309            matched[index] = Some(verdict);
310            match_kind[index] = SimilarCodeVerdictMatch::CandidateId;
311            continue;
312        }
313        // Two candidates can share a review_key when one function is copied
314        // verbatim, so the key is unique only among verdicts that match by it.
315        if !seen_review_keys.insert(verdict.review_key.clone()) {
316            return Err(duplicate_verdict_identity_error());
317        }
318        let Some(indices) = by_review_key.get(verdict.review_key.as_str()) else {
319            return Err(review_error(
320                "verdict references a stale or unknown candidate",
321            ));
322        };
323        if indices.len() == 1 {
324            let index = indices[0];
325            if matched[index].is_some() {
326                return Err(review_error(
327                    "multiple verdicts resolve to the same candidate",
328                ));
329            }
330            matched[index] = Some(verdict);
331            match_kind[index] = SimilarCodeVerdictMatch::ReviewKey;
332        } else {
333            for &index in indices {
334                if matched[index].is_none() {
335                    match_kind[index] = SimilarCodeVerdictMatch::AmbiguousReviewKey;
336                }
337            }
338            diagnostics.push(SimilarCodeDiagnostic {
339                domain: SimilarCodeDiagnosticDomain::Review,
340                code: "FALLOW_SIMILAR_CODE_REVIEW_KEY_AMBIGUOUS".to_owned(),
341                message:
342                    "a verdict review_key matched multiple current candidates and was not applied"
343                        .to_owned(),
344                path: None,
345            });
346        }
347    }
348    if require_verdict_for_each_candidate && matched.iter().any(Option::is_none) {
349        return Err(review_error("a verdict is required for every candidate"));
350    }
351    let candidates = raw
352        .candidates
353        .into_iter()
354        .zip(matched)
355        .zip(match_kind)
356        .map(|((candidate, verdict), verdict_match)| {
357            let outcome = verdict
358                .as_ref()
359                .map_or(SimilarCodeDomainOutcome::NeedsHumanReview, |verdict| {
360                    verdict.outcome
361                });
362            SimilarCodeReviewedCandidate {
363                candidate,
364                verdict,
365                verdict_match,
366                outcome,
367            }
368        })
369        .collect();
370    Ok(SimilarCodeReviewOutput {
371        schema_version: SimilarCodeReviewSchemaVersion::V1,
372        version: ToolVersion(env!("CARGO_PKG_VERSION").to_owned()),
373        elapsed_ms: ElapsedMs(duration_ms(started)),
374        generation: raw.generation,
375        review: SimilarCodeReviewProvenance {
376            candidates_sha256: sha256_hex(candidate_json),
377            verdicts_sha256: sha256_hex(verdict_json),
378        },
379        candidates,
380        completion: raw.completion,
381        diagnostics,
382    })
383}
384
385fn run_similar_code_inner(
386    options: &SimilarCodeOptions,
387    resolved: &ProgrammaticAnalysisContext,
388    provider: &ReadyProvider,
389) -> ProgrammaticResult<SimilarCodeOutput> {
390    let mut embedder = VerifiedProviderEmbedder { provider };
391    run_similar_code_inner_with_embedder(options, resolved, &provider.status, &mut embedder)
392}
393
394struct FileAdmission<'a> {
395    files: Vec<(&'a fallow_types::discover::DiscoveredFile, String)>,
396    total_eligible_files: usize,
397    scope: SimilarCodeScopeProvenance,
398}
399
400struct ExtractedCorpus {
401    functions: Vec<ExtractedSimilarCodeFunction>,
402    limits: SimilarCodeExtractionLimits,
403    skips: BTreeMap<SimilarCodeSkipReason, usize>,
404    source_read_failures: usize,
405}
406
407fn run_similar_code_inner_with_embedder(
408    options: &SimilarCodeOptions,
409    resolved: &ProgrammaticAnalysisContext,
410    provider: &SimilarCodeProviderStatus,
411    embedder: &mut dyn RuntimeEmbedder,
412) -> ProgrammaticResult<SimilarCodeOutput> {
413    let started = Instant::now();
414    let session = load_session(&options.analysis)?;
415    let (threshold, min_lines) = detection_parameters(options, &session)?;
416    let changed_files = changed_files_for_run(resolved)?;
417    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
418    let scope_active = similar_code_scope_active(
419        options,
420        resolved,
421        changed_files.as_ref(),
422        workspace_roots.as_deref(),
423    );
424    let in_scope = |path: &str| {
425        !scope_active
426            || similar_code_path_in_scope(
427                path,
428                options,
429                resolved,
430                changed_files.as_ref(),
431                workspace_roots.as_deref(),
432            )
433    };
434    let ignore = build_ignore_set(&session.config().similar_code.ignore)?;
435    let mut diagnostics = Vec::new();
436    let admission = admit_source_files(&session, &ignore, scope_active, in_scope);
437    let extraction = extract_corpus(&admission, min_lines, &mut diagnostics);
438    let engine_limits = EngineLimits::for_dimensions(provider.dimensions);
439    let selection = select_corpus(
440        &extraction.functions,
441        engine_limits,
442        scope_active,
443        in_scope,
444        &mut diagnostics,
445    )?;
446    let selected = selection
447        .selected_indices
448        .iter()
449        .map(|index| &extraction.functions[*index])
450        .collect::<Vec<_>>();
451    let mut embedding = embed_corpus(session.root(), resolved.no_cache(), &selected, embedder)?;
452    let (vectors, effective_selection) = comparison_inputs(&selected, &selection, &mut embedding)?;
453    let evaluation = evaluate_selected_similar_code(
454        &vectors,
455        &effective_selection,
456        threshold,
457        engine_limits,
458        SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION,
459    )
460    .map_err(engine_error)?;
461    let candidates = output_candidates(
462        evaluation.candidates,
463        &extraction.functions,
464        in_scope,
465        options.top,
466    );
467    let completion = build_completion(
468        &admission,
469        &extraction,
470        &selection,
471        &mut embedding,
472        &evaluation.completion,
473        &mut diagnostics,
474    );
475    Ok(SimilarCodeOutput {
476        schema_version: SimilarCodeSchemaVersion::V1,
477        version: ToolVersion(env!("CARGO_PKG_VERSION").to_owned()),
478        elapsed_ms: ElapsedMs(duration_ms(started)),
479        generation: generation(provider, threshold, min_lines, admission.scope),
480        candidates,
481        completion,
482        diagnostics,
483    })
484}
485
486fn detection_parameters(
487    options: &SimilarCodeOptions,
488    session: &AnalysisSession,
489) -> ProgrammaticResult<(f64, usize)> {
490    let threshold = options
491        .threshold
492        .unwrap_or_else(|| session.config().similar_code.threshold);
493    let min_lines = options
494        .min_lines
495        .unwrap_or_else(|| session.config().similar_code.min_lines);
496    validate_threshold(threshold)?;
497    if min_lines == 0 {
498        return Err(
499            ProgrammaticError::new("`similar_code.min_lines` must be at least 1", 2)
500                .with_code("FALLOW_INVALID_SIMILAR_CODE_MIN_LINES")
501                .with_context("similarCode.minLines"),
502        );
503    }
504    Ok((threshold, min_lines))
505}
506
507fn admit_source_files<'a>(
508    session: &'a AnalysisSession,
509    ignore: &GlobSet,
510    scope_active: bool,
511    in_scope: impl Fn(&str) -> bool,
512) -> FileAdmission<'a> {
513    let mut eligible_files = session
514        .files()
515        .iter()
516        .filter_map(|file| {
517            let relative = root_relative(session.root(), &file.path);
518            (!ignore.is_match(&relative)).then_some((file, relative))
519        })
520        .collect::<Vec<_>>();
521    eligible_files.sort_by_key(|(_, relative)| usize::from(!in_scope(relative)));
522    let total_eligible_files = eligible_files.len();
523    eligible_files.truncate(total_eligible_files.min(MAX_FILES));
524    let mut effective_scope_paths = if scope_active {
525        eligible_files
526            .iter()
527            .filter(|(_, relative)| in_scope(relative))
528            .map(|(_, relative)| relative.clone())
529            .collect::<Vec<_>>()
530    } else {
531        Vec::new()
532    };
533    effective_scope_paths.sort();
534    effective_scope_paths.dedup();
535    FileAdmission {
536        files: eligible_files,
537        total_eligible_files,
538        scope: SimilarCodeScopeProvenance {
539            active: scope_active,
540            paths: effective_scope_paths,
541        },
542    }
543}
544
545fn extract_corpus(
546    admission: &FileAdmission<'_>,
547    min_lines: usize,
548    diagnostics: &mut Vec<SimilarCodeDiagnostic>,
549) -> ExtractedCorpus {
550    let extraction_limits = SimilarCodeExtractionLimits::default();
551    let mut functions = Vec::new();
552    let mut extracted_source_bytes = 0usize;
553    let mut extraction_skips = BTreeMap::new();
554    let mut source_read_failures = 0usize;
555    for (file_index, (file, relative)) in admission.files.iter().enumerate() {
556        let remaining_functions = extraction_limits
557            .max_functions
558            .saturating_sub(functions.len());
559        let remaining_bytes = extraction_limits
560            .max_total_source_bytes
561            .saturating_sub(extracted_source_bytes);
562        if let Some(reason) = exhausted_extraction_limit(remaining_functions, remaining_bytes) {
563            add_skip(
564                &mut extraction_skips,
565                reason,
566                remaining_extraction_inputs(admission.files.len(), file_index),
567            );
568            break;
569        }
570        let source = match std::fs::read_to_string(&file.path) {
571            Ok(source) => source,
572            Err(error) => {
573                source_read_failures = source_read_failures.saturating_add(1);
574                diagnostics.push(SimilarCodeDiagnostic {
575                    domain: SimilarCodeDiagnosticDomain::Extraction,
576                    code: "FALLOW_SIMILAR_CODE_SOURCE_READ_FAILED".to_owned(),
577                    message: format!("failed to read source: {error}"),
578                    path: Some(relative.clone()),
579                });
580                continue;
581            }
582        };
583        let extracted = fallow_engine::source::similar_code::extract(
584            Path::new(relative),
585            &source,
586            SimilarCodeExtractionLimits {
587                max_functions: remaining_functions,
588                max_source_bytes_per_function: extraction_limits.max_source_bytes_per_function,
589                max_total_source_bytes: remaining_bytes,
590            },
591        );
592        for skip in extracted.skipped {
593            add_skip(
594                &mut extraction_skips,
595                map_extraction_skip(skip.reason),
596                skip.count,
597            );
598        }
599        for function in extracted.functions {
600            let lines = function
601                .location
602                .end_line
603                .saturating_sub(function.location.start_line)
604                .saturating_add(1) as usize;
605            if lines < min_lines {
606                add_skip(
607                    &mut extraction_skips,
608                    SimilarCodeSkipReason::BelowMinimumLines,
609                    1,
610                );
611            } else {
612                extracted_source_bytes =
613                    extracted_source_bytes.saturating_add(function.source.len());
614                functions.push(function);
615            }
616        }
617    }
618    ExtractedCorpus {
619        functions,
620        limits: extraction_limits,
621        skips: extraction_skips,
622        source_read_failures,
623    }
624}
625
626fn select_corpus(
627    functions: &[ExtractedSimilarCodeFunction],
628    engine_limits: EngineLimits,
629    scope_active: bool,
630    in_scope: impl Fn(&str) -> bool,
631    diagnostics: &mut Vec<SimilarCodeDiagnostic>,
632) -> ProgrammaticResult<SimilarCodeCorpusSelection> {
633    let selection_inputs = functions
634        .iter()
635        .map(|function| SimilarCodeSelectionInput {
636            location: &function.location,
637            source_sha256: function.source_sha256,
638            in_scope: in_scope(&function.location.file),
639        })
640        .collect::<Vec<_>>();
641    let selection =
642        select_similar_code_corpus(&selection_inputs, engine_limits).map_err(engine_error)?;
643    let scoped_functions = selection_inputs
644        .iter()
645        .filter(|function| function.in_scope)
646        .count();
647    let selected_scoped_functions = selection
648        .selected_in_scope
649        .iter()
650        .filter(|&&value| value)
651        .count();
652    if scope_active && selected_scoped_functions < scoped_functions {
653        diagnostics.push(SimilarCodeDiagnostic {
654            domain: SimilarCodeDiagnosticDomain::Workspace,
655            code: "FALLOW_SIMILAR_CODE_SCOPE_PARTIAL".to_owned(),
656            message: format!(
657                "scope limits admitted {selected_scoped_functions} of {scoped_functions} eligible scoped functions"
658            ),
659            path: None,
660        });
661    }
662    Ok(selection)
663}
664
665fn embed_corpus(
666    root: &Path,
667    no_cache: bool,
668    selected: &[&ExtractedSimilarCodeFunction],
669    embedder: &mut dyn RuntimeEmbedder,
670) -> ProgrammaticResult<EmbeddingResult> {
671    let embedding_inputs = selected
672        .iter()
673        .map(|function| EmbeddingInput {
674            source_sha256: function.source_sha256,
675            source: &function.source,
676        })
677        .collect::<Vec<_>>();
678    embedder
679        .embed(root, no_cache, &embedding_inputs)
680        .map_err(provider_error)
681}
682
683fn comparison_inputs(
684    selected: &[&ExtractedSimilarCodeFunction],
685    selection: &SimilarCodeCorpusSelection,
686    embedding: &mut EmbeddingResult,
687) -> ProgrammaticResult<(Vec<FunctionVector>, SimilarCodeCorpusSelection)> {
688    let mut vectors = Vec::new();
689    let mut effective_scope = Vec::new();
690    for (selected_index, values) in std::mem::take(&mut embedding.vectors)
691        .into_iter()
692        .enumerate()
693    {
694        if let Some(values) = values {
695            let function = selected[selected_index];
696            vectors.push(FunctionVector {
697                location: function.location.clone(),
698                source_sha256: function.source_sha256,
699                extraction_semantics_version: SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION,
700                values,
701            });
702            effective_scope.push(selection.selected_in_scope[selected_index]);
703        }
704    }
705    if vectors.len() < 2 && selected.len() >= 2 {
706        return Err(ProgrammaticError::new(
707            embedding.provider_problem.take().unwrap_or_else(|| {
708                "the local similar-code provider returned fewer than two usable vectors".to_owned()
709            }),
710            2,
711        )
712        .with_code("FALLOW_SIMILAR_CODE_PROVIDER_FAILED")
713        .with_context("similarCode.provider"));
714    }
715
716    let effective_selection = SimilarCodeCorpusSelection {
717        selected_indices: (0..vectors.len()).collect(),
718        selected_in_scope: effective_scope,
719        skipped: selection.skipped.clone(),
720    };
721    Ok((vectors, effective_selection))
722}
723
724fn output_candidates(
725    candidates: Vec<fallow_engine::similar_code::SimilarCodeCandidate>,
726    functions: &[ExtractedSimilarCodeFunction],
727    in_scope: impl Fn(&str) -> bool,
728    top: Option<usize>,
729) -> Vec<SimilarCodeCandidate> {
730    let metadata = functions
731        .iter()
732        .map(|function| (location_key(&function.location), function))
733        .collect::<FxHashMap<_, _>>();
734    let mut candidates = candidates
735        .into_iter()
736        .filter(|candidate| in_scope(&candidate.left.file) || in_scope(&candidate.right.file))
737        .filter_map(|candidate| map_candidate(candidate, &metadata))
738        .collect::<Vec<_>>();
739    if let Some(top) = top {
740        candidates.truncate(top);
741    }
742    candidates
743}
744
745fn completion_skips(
746    extraction_skips: &BTreeMap<SimilarCodeSkipReason, usize>,
747    omitted_files: usize,
748    comparison: &fallow_engine::similar_code::SimilarCodeCompletion,
749    embedding: &EmbeddingResult,
750    missing_vectors: usize,
751) -> Vec<SimilarCodeSkip> {
752    let mut skips = extraction_skips
753        .iter()
754        .map(|(reason, count)| SimilarCodeSkip {
755            phase: SimilarCodePhase::Extraction,
756            reason: *reason,
757            count: usize_to_u64(*count),
758        })
759        .collect::<Vec<_>>();
760    if omitted_files > 0 {
761        skips.push(SimilarCodeSkip {
762            phase: SimilarCodePhase::Discovery,
763            reason: SimilarCodeSkipReason::InputLimit,
764            count: usize_to_u64(omitted_files),
765        });
766    }
767    skips.extend(comparison.skipped.iter().map(|skip| SimilarCodeSkip {
768        phase: SimilarCodePhase::Comparison,
769        reason: map_engine_skip(skip.reason),
770        count: usize_to_u64(skip.count),
771    }));
772    if missing_vectors > 0 {
773        skips.push(SimilarCodeSkip {
774            phase: SimilarCodePhase::Embedding,
775            reason: if embedding
776                .provider_problem
777                .as_deref()
778                .is_some_and(|problem| problem.contains("timed out"))
779            {
780                SimilarCodeSkipReason::Timeout
781            } else {
782                SimilarCodeSkipReason::ProviderFailure
783            },
784            count: usize_to_u64(missing_vectors),
785        });
786    }
787    if embedding.truncated_functions > 0 {
788        skips.push(SimilarCodeSkip {
789            phase: SimilarCodePhase::Embedding,
790            reason: SimilarCodeSkipReason::TokenTruncation,
791            count: usize_to_u64(embedding.truncated_functions),
792        });
793    }
794    skips.sort_by_key(|skip| (skip.phase as u8, skip.reason as u8));
795    skips
796}
797
798fn build_completion(
799    admission: &FileAdmission<'_>,
800    extraction: &ExtractedCorpus,
801    selection: &SimilarCodeCorpusSelection,
802    embedding: &mut EmbeddingResult,
803    comparison: &fallow_engine::similar_code::SimilarCodeCompletion,
804    diagnostics: &mut Vec<SimilarCodeDiagnostic>,
805) -> SimilarCodeCompletion {
806    let omitted_files = admission
807        .total_eligible_files
808        .saturating_sub(admission.files.len());
809    let embedded_functions = comparison.functions_considered;
810    let missing_vectors = selection
811        .selected_indices
812        .len()
813        .saturating_sub(embedded_functions);
814    let skips = completion_skips(
815        &extraction.skips,
816        omitted_files,
817        comparison,
818        embedding,
819        missing_vectors,
820    );
821    if let Some(problem) = embedding.provider_problem.take() {
822        diagnostics.push(SimilarCodeDiagnostic {
823            domain: SimilarCodeDiagnosticDomain::Provider,
824            code: "FALLOW_SIMILAR_CODE_PROVIDER_PARTIAL".to_owned(),
825            message: problem,
826            path: None,
827        });
828    }
829    if let Some(problem) = embedding.cache_problem.take() {
830        diagnostics.push(SimilarCodeDiagnostic {
831            domain: SimilarCodeDiagnosticDomain::Cache,
832            code: "FALLOW_SIMILAR_CODE_CACHE_ADVISORY".to_owned(),
833            message: problem,
834            path: None,
835        });
836    }
837    let phase_completeness = PhaseCompleteness {
838        discovery: omitted_files == 0,
839        extraction: extraction_is_complete(&extraction.skips, extraction.source_read_failures),
840        embedding: missing_vectors == 0 && embedding.truncated_functions == 0,
841        comparison: comparison.status
842            == fallow_engine::similar_code::SimilarCodeCompletionStatus::Complete,
843    };
844    let complete = phase_completeness.all_complete()
845        && diagnostics
846            .iter()
847            .all(|diagnostic| diagnostic.domain == SimilarCodeDiagnosticDomain::Cache);
848    let cache_status = cache_status(
849        embedding.cache_disabled,
850        embedding.cache_hits,
851        embedding.cache_misses,
852    );
853    SimilarCodeCompletion {
854        status: if complete {
855            SimilarCodeCompletionStatus::Complete
856        } else {
857            SimilarCodeCompletionStatus::Partial
858        },
859        phases: phases(
860            admission.files.len(),
861            admission.total_eligible_files,
862            extraction.functions.len(),
863            selection.selected_indices.len(),
864            embedded_functions,
865            comparison.comparisons_performed,
866            phase_completeness,
867            missing_vectors,
868            embedding.truncated_functions,
869            extraction.source_read_failures,
870        ),
871        limits: output_limits(comparison.limits, extraction.limits),
872        skips,
873        cache: SimilarCodeCacheSummary {
874            status: cache_status,
875            hits: usize_to_u64(embedding.cache_hits),
876            misses: usize_to_u64(embedding.cache_misses),
877            writes: usize_to_u64(embedding.cache_writes),
878            invalid_entries: usize_to_u64(embedding.cache_invalid_entries),
879        },
880        provider_inference_ms: finite_f64_to_u64(embedding.inference_ms),
881    }
882}
883
884fn inspect_side(
885    root: &Path,
886    location: &SimilarCodeLocation,
887) -> ProgrammaticResult<SimilarCodeSideEvidence> {
888    let relative = Path::new(&location.path);
889    if location.path.trim().is_empty()
890        || relative.is_absolute()
891        || relative
892            .components()
893            .any(|component| !matches!(component, std::path::Component::Normal(_)))
894    {
895        return Err(candidate_input_error(
896            "candidate source paths must be normalized project-root-relative paths",
897        ));
898    }
899    let path = dunce::canonicalize(root.join(relative)).map_err(|error| {
900        ProgrammaticError::new(
901            format!(
902                "failed to resolve inspected source {}: {error}",
903                location.path
904            ),
905            2,
906        )
907        .with_code("FALLOW_SIMILAR_CODE_INSPECT_SOURCE_FAILED")
908        .with_context("similarCode.inspect")
909    })?;
910    if !path.starts_with(root) {
911        return Err(candidate_input_error(
912            "candidate source path resolves outside the project root",
913        ));
914    }
915    let source = read_inspect_source(&path, &location.path)?;
916    let extracted = fallow_engine::source::similar_code::extract(
917        Path::new(&location.path),
918        &source,
919        SimilarCodeExtractionLimits::default(),
920    );
921    let function = extracted
922        .functions
923        .into_iter()
924        .find(|function| function_matches_snapshot_location(function, location))
925        .ok_or_else(|| {
926            ProgrammaticError::new(
927                "inspected function no longer matches the candidate snapshot",
928                2,
929            )
930            .with_code("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
931            .with_context("similarCode.inspect")
932        })?;
933    Ok(SimilarCodeSideEvidence {
934        source_window: Some(bound_source_window(&function.source)),
935        parameter_count: Some(function.param_count),
936        is_async: Some(function.is_async),
937        is_generator: Some(function.is_generator),
938        has_await: Some(function.has_await),
939        has_throw: Some(function.has_throw),
940        side_effect_hint: Some(match function.side_effect_hint {
941            fallow_engine::source::similar_code::SimilarCodeSideEffectHint::PureLooking => {
942                SimilarCodeSideEffectHint::PureLooking
943            }
944            fallow_engine::source::similar_code::SimilarCodeSideEffectHint::MayHaveSideEffects => {
945                SimilarCodeSideEffectHint::MayHaveSideEffects
946            }
947            fallow_engine::source::similar_code::SimilarCodeSideEffectHint::Unknown => {
948                SimilarCodeSideEffectHint::Unknown
949            }
950            _ => SimilarCodeSideEffectHint::Unknown,
951        }),
952        entry_point_reachable: None,
953        callers: Vec::new(),
954        callees: Vec::new(),
955        owners: Vec::new(),
956        churn_commits: None,
957        tests: Vec::new(),
958        deterministic_clone_coverage: None,
959        runtime_observations: None,
960    })
961}
962
963fn function_matches_snapshot_location(
964    function: &ExtractedSimilarCodeFunction,
965    location: &SimilarCodeLocation,
966) -> bool {
967    function.location.file == location.path
968        && function.name == location.name
969        && function.location.start_line == location.start_line
970        && function.location.start_column_utf8.saturating_add(1) == location.start_column
971        && function.location.end_line == location.end_line
972        && function.location.end_column_utf8.saturating_add(1) == location.end_column
973        && hex(function.source_sha256.as_bytes()) == location.source_sha256
974}
975
976#[expect(
977    clippy::filetype_is_file,
978    reason = "exact inspect accepts only regular source files and rejects every special file"
979)]
980fn read_inspect_source(path: &Path, display_path: &str) -> ProgrammaticResult<String> {
981    let metadata = std::fs::symlink_metadata(path).map_err(|error| {
982        inspect_source_error(format!("failed to inspect source {display_path}: {error}"))
983    })?;
984    if !metadata.file_type().is_file() || metadata.len() > MAX_INSPECT_SOURCE_BYTES {
985        return Err(stale_candidate_error(format!(
986            "inspected source {display_path} exceeded the {} MiB per-file limit",
987            MAX_INSPECT_SOURCE_BYTES / (1024 * 1024)
988        )));
989    }
990
991    let file = std::fs::File::open(path).map_err(|error| {
992        inspect_source_error(format!(
993            "failed to read inspected source {display_path}: {error}"
994        ))
995    })?;
996    let mut bytes = Vec::new();
997    file.take(MAX_INSPECT_SOURCE_BYTES + 1)
998        .read_to_end(&mut bytes)
999        .map_err(|error| {
1000            inspect_source_error(format!(
1001                "failed to read inspected source {display_path}: {error}"
1002            ))
1003        })?;
1004    if bytes.len() as u64 > MAX_INSPECT_SOURCE_BYTES {
1005        return Err(stale_candidate_error(format!(
1006            "inspected source {display_path} exceeded the {} MiB per-file limit",
1007            MAX_INSPECT_SOURCE_BYTES / (1024 * 1024)
1008        )));
1009    }
1010    String::from_utf8(bytes).map_err(|error| {
1011        inspect_source_error(format!(
1012            "failed to read inspected source {display_path}: {error}"
1013        ))
1014    })
1015}
1016
1017fn inspect_source_error(message: impl Into<String>) -> ProgrammaticError {
1018    ProgrammaticError::new(message, 2)
1019        .with_code("FALLOW_SIMILAR_CODE_INSPECT_SOURCE_FAILED")
1020        .with_context("similarCode.inspect")
1021}
1022
1023fn stale_candidate_error(message: impl Into<String>) -> ProgrammaticError {
1024    ProgrammaticError::new(message, 2)
1025        .with_code("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
1026        .with_context("similarCode.inspect")
1027}
1028
1029struct InspectEnrichment {
1030    availability: SimilarCodeEnrichmentAvailability,
1031    graph_relationship: Option<String>,
1032    diagnostics: Vec<SimilarCodeDiagnostic>,
1033}
1034
1035fn enrich_inspect(
1036    session: &AnalysisSession,
1037    left_location: &SimilarCodeLocation,
1038    right_location: &SimilarCodeLocation,
1039    left: &mut SimilarCodeSideEvidence,
1040    right: &mut SimilarCodeSideEvidence,
1041) -> InspectEnrichment {
1042    let mut result = InspectEnrichment {
1043        availability: unavailable_inspect_enrichment(),
1044        graph_relationship: None,
1045        diagnostics: Vec::new(),
1046    };
1047
1048    if session.files().len() > MAX_FILES {
1049        result.diagnostics.push(enrichment_diagnostic(
1050            "FALLOW_SIMILAR_CODE_ENRICHMENT_INPUT_LIMIT",
1051            format!(
1052                "graph and deterministic clone enrichment require at most {MAX_FILES} discovered files"
1053            ),
1054            None,
1055        ));
1056    } else {
1057        enrich_graph_and_clones(
1058            session,
1059            left_location,
1060            right_location,
1061            left,
1062            right,
1063            &mut result,
1064        );
1065    }
1066
1067    enrich_ownership(
1068        session,
1069        left_location,
1070        right_location,
1071        left,
1072        right,
1073        &mut result,
1074    );
1075    enrich_churn(
1076        session,
1077        left_location,
1078        right_location,
1079        left,
1080        right,
1081        &mut result,
1082    );
1083    result
1084}
1085
1086fn enrich_graph_and_clones(
1087    session: &AnalysisSession,
1088    left_location: &SimilarCodeLocation,
1089    right_location: &SimilarCodeLocation,
1090    left: &mut SimilarCodeSideEvidence,
1091    right: &mut SimilarCodeSideEvidence,
1092    result: &mut InspectEnrichment,
1093) {
1094    let artifacts = match session.analyze_project_with_artifacts(
1095        &session.config().duplicates,
1096        ProjectAnalysisArtifactOptions {
1097            retain_graph: true,
1098            ..ProjectAnalysisArtifactOptions::default()
1099        },
1100    ) {
1101        Ok(artifacts) => artifacts,
1102        Err(error) => {
1103            result.diagnostics.push(enrichment_diagnostic(
1104                "FALLOW_SIMILAR_CODE_ANALYSIS_ENRICHMENT_UNAVAILABLE",
1105                format!("graph and deterministic clone enrichment failed: {error}"),
1106                None,
1107            ));
1108            return;
1109        }
1110    };
1111
1112    left.deterministic_clone_coverage = Some(deterministic_clone_coverage(
1113        &artifacts.duplication,
1114        session.root(),
1115        left_location,
1116    ));
1117    right.deterministic_clone_coverage = Some(deterministic_clone_coverage(
1118        &artifacts.duplication,
1119        session.root(),
1120        right_location,
1121    ));
1122    result.availability.deterministic_clone_coverage = SimilarCodeEnrichmentState::Available;
1123
1124    let Some(graph) = artifacts.dead_code.graph.as_ref() else {
1125        result.diagnostics.push(enrichment_diagnostic(
1126            "FALLOW_SIMILAR_CODE_GRAPH_ENRICHMENT_UNAVAILABLE",
1127            "retained module graph was unavailable",
1128            None,
1129        ));
1130        return;
1131    };
1132    let Some(left_trace) = trace_file(graph, session.root(), &left_location.path) else {
1133        result.diagnostics.push(enrichment_diagnostic(
1134            "FALLOW_SIMILAR_CODE_GRAPH_TARGET_UNAVAILABLE",
1135            "left candidate module was absent from the retained graph",
1136            Some(left_location.path.clone()),
1137        ));
1138        return;
1139    };
1140    let Some(right_trace) = trace_file(graph, session.root(), &right_location.path) else {
1141        result.diagnostics.push(enrichment_diagnostic(
1142            "FALLOW_SIMILAR_CODE_GRAPH_TARGET_UNAVAILABLE",
1143            "right candidate module was absent from the retained graph",
1144            Some(right_location.path.clone()),
1145        ));
1146        return;
1147    };
1148
1149    let left_impact =
1150        trace_impact_closure_without_search(graph, session.root(), &left_location.path);
1151    let right_impact =
1152        trace_impact_closure_without_search(graph, session.root(), &right_location.path);
1153    apply_graph_evidence(
1154        session.root(),
1155        &left_trace,
1156        &right_trace,
1157        left_location,
1158        right_location,
1159        left_impact
1160            .as_ref()
1161            .map_or(&[][..], |impact| impact.affected_not_shown.as_slice()),
1162        right_impact
1163            .as_ref()
1164            .map_or(&[][..], |impact| impact.affected_not_shown.as_slice()),
1165        left,
1166        right,
1167        result,
1168    );
1169}
1170
1171#[expect(
1172    clippy::too_many_arguments,
1173    reason = "the helper applies symmetric evidence for both immutable candidate sides"
1174)]
1175fn apply_graph_evidence(
1176    root: &Path,
1177    left_trace: &fallow_engine::trace::FileTrace,
1178    right_trace: &fallow_engine::trace::FileTrace,
1179    left_location: &SimilarCodeLocation,
1180    right_location: &SimilarCodeLocation,
1181    left_impact_paths: &[String],
1182    right_impact_paths: &[String],
1183    left: &mut SimilarCodeSideEvidence,
1184    right: &mut SimilarCodeSideEvidence,
1185    result: &mut InspectEnrichment,
1186) {
1187    left.entry_point_reachable = Some(left_trace.is_reachable);
1188    right.entry_point_reachable = Some(right_trace.is_reachable);
1189
1190    let (left_callers, left_callers_truncated) =
1191        bounded_module_references(&left_trace.imported_by, MAX_INSPECT_GRAPH_REFERENCES);
1192    let (left_callees, left_callees_truncated) =
1193        bounded_module_references(&left_trace.imports_from, MAX_INSPECT_GRAPH_REFERENCES);
1194    let (right_callers, right_callers_truncated) =
1195        bounded_module_references(&right_trace.imported_by, MAX_INSPECT_GRAPH_REFERENCES);
1196    let (right_callees, right_callees_truncated) =
1197        bounded_module_references(&right_trace.imports_from, MAX_INSPECT_GRAPH_REFERENCES);
1198    left.callers = left_callers;
1199    left.callees = left_callees;
1200    right.callers = right_callers;
1201    right.callees = right_callees;
1202
1203    let (left_tests, left_tests_truncated) =
1204        bounded_related_tests(root, left_impact_paths, MAX_INSPECT_RELATED_TESTS);
1205    let (right_tests, right_tests_truncated) =
1206        bounded_related_tests(root, right_impact_paths, MAX_INSPECT_RELATED_TESTS);
1207    left.tests = left_tests;
1208    right.tests = right_tests;
1209
1210    result.graph_relationship = Some(module_relationship(
1211        left_trace,
1212        right_trace,
1213        left_location,
1214        right_location,
1215    ));
1216    result.availability.graph_relationship = SimilarCodeEnrichmentState::Available;
1217    result.availability.entry_point_reachability = SimilarCodeEnrichmentState::Available;
1218    result.availability.callers = SimilarCodeEnrichmentState::Available;
1219    result.availability.callees = SimilarCodeEnrichmentState::Available;
1220    result.availability.tests = SimilarCodeEnrichmentState::Available;
1221    result.diagnostics.push(enrichment_diagnostic(
1222        "FALLOW_SIMILAR_CODE_GRAPH_REFERENCES_MODULE_LEVEL",
1223        "callers and callees are direct module import relationships; <module> at line 1 is a module anchor, not a function callsite",
1224        None,
1225    ));
1226    if left_callers_truncated
1227        || left_callees_truncated
1228        || right_callers_truncated
1229        || right_callees_truncated
1230        || left_tests_truncated
1231        || right_tests_truncated
1232    {
1233        result.diagnostics.push(enrichment_diagnostic(
1234            "FALLOW_SIMILAR_CODE_GRAPH_ENRICHMENT_TRUNCATED",
1235            "graph references or related tests exceeded inspect output limits",
1236            None,
1237        ));
1238    }
1239}
1240
1241fn bounded_module_references(
1242    paths: &[PathBuf],
1243    limit: usize,
1244) -> (Vec<SimilarCodeNamedReference>, bool) {
1245    let mut paths = paths
1246        .iter()
1247        .map(|path| normalize_path(path))
1248        .collect::<Vec<_>>();
1249    paths.sort();
1250    paths.dedup();
1251    let truncated = paths.len() > limit;
1252    paths.truncate(limit);
1253    (
1254        paths
1255            .into_iter()
1256            .map(|path| SimilarCodeNamedReference {
1257                path,
1258                name: MODULE_REFERENCE_NAME.to_owned(),
1259                line: 1,
1260            })
1261            .collect(),
1262        truncated,
1263    )
1264}
1265
1266fn bounded_related_tests(root: &Path, paths: &[String], limit: usize) -> (Vec<String>, bool) {
1267    let mut tests = paths
1268        .iter()
1269        .map(|path| path.replace('\\', "/"))
1270        .filter(|path| is_test_code_path_str(root, path))
1271        .collect::<Vec<_>>();
1272    tests.sort();
1273    tests.dedup();
1274    let truncated = tests.len() > limit;
1275    tests.truncate(limit);
1276    (tests, truncated)
1277}
1278
1279fn module_relationship(
1280    left_trace: &fallow_engine::trace::FileTrace,
1281    right_trace: &fallow_engine::trace::FileTrace,
1282    left_location: &SimilarCodeLocation,
1283    right_location: &SimilarCodeLocation,
1284) -> String {
1285    if left_location.path == right_location.path {
1286        return "same-module".to_owned();
1287    }
1288    let left_imports_right = trace_imports_path(left_trace, &right_location.path);
1289    let right_imports_left = trace_imports_path(right_trace, &left_location.path);
1290    if left_imports_right && right_imports_left {
1291        return "mutual-direct-module-import".to_owned();
1292    }
1293    if left_imports_right {
1294        return "left-directly-imports-right".to_owned();
1295    }
1296    if right_imports_left {
1297        return "right-directly-imports-left".to_owned();
1298    }
1299
1300    let left_callers = left_trace
1301        .imported_by
1302        .iter()
1303        .map(|path| normalize_path(path))
1304        .collect::<BTreeSet<_>>();
1305    if right_trace
1306        .imported_by
1307        .iter()
1308        .map(|path| normalize_path(path))
1309        .any(|path| left_callers.contains(&path))
1310    {
1311        "shared-direct-importer".to_owned()
1312    } else {
1313        "no-direct-module-relationship".to_owned()
1314    }
1315}
1316
1317fn trace_imports_path(trace: &fallow_engine::trace::FileTrace, target: &str) -> bool {
1318    trace
1319        .imports_from
1320        .iter()
1321        .any(|path| normalize_path(path) == target)
1322}
1323
1324fn enrich_ownership(
1325    session: &AnalysisSession,
1326    left_location: &SimilarCodeLocation,
1327    right_location: &SimilarCodeLocation,
1328    left: &mut SimilarCodeSideEvidence,
1329    right: &mut SimilarCodeSideEvidence,
1330    result: &mut InspectEnrichment,
1331) {
1332    match CodeOwners::load(session.root(), session.config().codeowners.as_deref()) {
1333        Ok(codeowners) => {
1334            left.owners = primary_owner(&codeowners, &left_location.path);
1335            right.owners = primary_owner(&codeowners, &right_location.path);
1336            result.availability.ownership = SimilarCodeEnrichmentState::Available;
1337        }
1338        Err(error) => result.diagnostics.push(enrichment_diagnostic(
1339            "FALLOW_SIMILAR_CODE_OWNERSHIP_UNAVAILABLE",
1340            error,
1341            None,
1342        )),
1343    }
1344}
1345
1346fn primary_owner(codeowners: &CodeOwners, path: &str) -> Vec<String> {
1347    codeowners
1348        .owner_of(Path::new(path))
1349        .map(|owner| vec![owner.to_owned()])
1350        .unwrap_or_default()
1351}
1352
1353fn enrich_churn(
1354    session: &AnalysisSession,
1355    left_location: &SimilarCodeLocation,
1356    right_location: &SimilarCodeLocation,
1357    left: &mut SimilarCodeSideEvidence,
1358    right: &mut SimilarCodeSideEvidence,
1359    result: &mut InspectEnrichment,
1360) {
1361    if !fallow_engine::churn::is_git_repo(session.root()) {
1362        result.diagnostics.push(enrichment_diagnostic(
1363            "FALLOW_SIMILAR_CODE_CHURN_UNAVAILABLE",
1364            "git repository unavailable at project root",
1365            None,
1366        ));
1367        return;
1368    }
1369    let since = fallow_engine::churn::SinceDuration::relative(
1370        INSPECT_CHURN_WINDOW_MONTHS,
1371        fallow_engine::churn::ChurnWindowUnit::Months,
1372        "6 months",
1373    );
1374    let Some((churn, _cache_hit)) = fallow_engine::churn::analyze_churn_cached(
1375        session.root(),
1376        &since,
1377        &session.config().cache_dir,
1378        session.config().no_cache,
1379    ) else {
1380        result.diagnostics.push(enrichment_diagnostic(
1381            "FALLOW_SIMILAR_CODE_CHURN_UNAVAILABLE",
1382            "git churn analysis failed",
1383            None,
1384        ));
1385        return;
1386    };
1387    left.churn_commits = Some(churn_commits_for(
1388        &churn,
1389        &session.root().join(&left_location.path),
1390    ));
1391    right.churn_commits = Some(churn_commits_for(
1392        &churn,
1393        &session.root().join(&right_location.path),
1394    ));
1395    result.availability.churn = SimilarCodeEnrichmentState::Available;
1396    if churn.shallow_clone {
1397        result.diagnostics.push(enrichment_diagnostic(
1398            "FALLOW_SIMILAR_CODE_CHURN_SHALLOW_HISTORY",
1399            "git churn counts may undercount history because the repository is shallow",
1400            None,
1401        ));
1402    }
1403}
1404
1405fn churn_commits_for(churn: &fallow_engine::churn::ChurnResult, path: &Path) -> u64 {
1406    if let Some(file) = churn.files.get(path) {
1407        return u64::from(file.commits);
1408    }
1409    let target = normalize_path(path);
1410    churn
1411        .files
1412        .iter()
1413        .find(|(candidate, _)| normalize_path(candidate) == target)
1414        .map_or(0, |(_, file)| u64::from(file.commits))
1415}
1416
1417fn deterministic_clone_coverage(
1418    report: &fallow_engine::duplicates::DuplicationReport,
1419    root: &Path,
1420    location: &SimilarCodeLocation,
1421) -> f64 {
1422    let start = usize::try_from(location.start_line).unwrap_or(usize::MAX);
1423    let end = usize::try_from(location.end_line).unwrap_or(0);
1424    if start > end {
1425        return 0.0;
1426    }
1427    let mut covered = BTreeSet::new();
1428    for group in &report.clone_groups {
1429        if !matches!(
1430            group.kind(),
1431            fallow_engine::duplicates::CloneGroupKind::Exact
1432        ) {
1433            continue;
1434        }
1435        for instance in &group.instances {
1436            if root_relative(root, &instance.file) != location.path {
1437                continue;
1438            }
1439            let overlap_start = start.max(instance.start_line);
1440            let overlap_end = end.min(instance.end_line);
1441            if overlap_start <= overlap_end {
1442                covered.extend(overlap_start..=overlap_end);
1443            }
1444        }
1445    }
1446    let total = end.saturating_sub(start).saturating_add(1);
1447    covered.len() as f64 / total as f64
1448}
1449
1450fn unavailable_inspect_enrichment() -> SimilarCodeEnrichmentAvailability {
1451    SimilarCodeEnrichmentAvailability {
1452        graph_relationship: SimilarCodeEnrichmentState::Unavailable,
1453        entry_point_reachability: SimilarCodeEnrichmentState::Unavailable,
1454        callers: SimilarCodeEnrichmentState::Unavailable,
1455        callees: SimilarCodeEnrichmentState::Unavailable,
1456        ownership: SimilarCodeEnrichmentState::Unavailable,
1457        churn: SimilarCodeEnrichmentState::Unavailable,
1458        tests: SimilarCodeEnrichmentState::Unavailable,
1459        deterministic_clone_coverage: SimilarCodeEnrichmentState::Unavailable,
1460        runtime: SimilarCodeEnrichmentState::NotRequested,
1461    }
1462}
1463
1464fn enrichment_diagnostic(
1465    code: &'static str,
1466    message: impl Into<String>,
1467    path: Option<String>,
1468) -> SimilarCodeDiagnostic {
1469    SimilarCodeDiagnostic {
1470        domain: SimilarCodeDiagnosticDomain::Enrichment,
1471        code: code.to_owned(),
1472        message: message.into(),
1473        path,
1474    }
1475}
1476
1477fn parse_candidate_document(bytes: &[u8]) -> ProgrammaticResult<SimilarCodeOutput> {
1478    let mut value: Value = serde_json::from_slice(bytes)
1479        .map_err(|error| review_error(format!("invalid similar-code candidate JSON: {error}")))?;
1480    let object = value
1481        .as_object_mut()
1482        .ok_or_else(|| review_error("similar-code candidate document must be a JSON object"))?;
1483    let kind = object
1484        .remove("kind")
1485        .and_then(|kind| kind.as_str().map(str::to_owned))
1486        .ok_or_else(|| review_error("similar-code candidate document is missing kind"))?;
1487    if kind != "similar-code" {
1488        return Err(review_error(
1489            "candidate document kind must be `similar-code`",
1490        ));
1491    }
1492    serde_json::from_value(value)
1493        .map_err(|error| review_error(format!("invalid similar-code candidate envelope: {error}")))
1494}
1495
1496fn validate_verdict(verdict: &fallow_output::SimilarCodeVerdict) -> ProgrammaticResult<()> {
1497    verdict
1498        .validate()
1499        .map_err(|error| review_error(format!("invalid verdict implication: {error}")))?;
1500    let rationale_chars = verdict.rationale.chars().count();
1501    if rationale_chars == 0 || rationale_chars > MAX_RATIONALE_CHARS {
1502        return Err(review_error(
1503            "verdict rationale must contain 1 through 4000 characters",
1504        ));
1505    }
1506    if verdict.rationale.chars().any(char::is_control) {
1507        return Err(review_error(
1508            "verdict rationale must not contain control characters",
1509        ));
1510    }
1511    Ok(())
1512}
1513
1514fn duplicate_verdict_identity_error() -> ProgrammaticError {
1515    review_error("verdict document contains duplicate candidate or review identities")
1516}
1517
1518fn review_error(message: impl Into<String>) -> ProgrammaticError {
1519    ProgrammaticError::new(message, 2)
1520        .with_code("FALLOW_SIMILAR_CODE_REVIEW_INVALID")
1521        .with_context("similarCode.review")
1522}
1523
1524fn candidate_input_error(message: impl Into<String>) -> ProgrammaticError {
1525    ProgrammaticError::new(message, 2)
1526        .with_code("FALLOW_SIMILAR_CODE_CANDIDATE_INPUT_INVALID")
1527        .with_context("similarCode.candidates")
1528}
1529
1530fn bound_source_window(source: &str) -> String {
1531    let mut chars = source.chars();
1532    let bounded = chars
1533        .by_ref()
1534        .take(MAX_SOURCE_WINDOW_CHARS)
1535        .collect::<String>();
1536    if chars.next().is_some() {
1537        format!("{bounded}\n/* source window truncated */")
1538    } else {
1539        bounded
1540    }
1541}
1542
1543fn sha256_hex(bytes: &[u8]) -> String {
1544    hex(&Sha256::digest(bytes))
1545}
1546
1547#[expect(
1548    clippy::cast_sign_loss,
1549    reason = "the guards above leave only finite positive values"
1550)]
1551fn finite_f64_to_u64(value: f64) -> u64 {
1552    if !value.is_finite() || value <= 0.0 {
1553        0
1554    } else if value >= u64::MAX as f64 {
1555        u64::MAX
1556    } else {
1557        value.round() as u64
1558    }
1559}
1560
1561fn load_session(analysis: &crate::AnalysisOptions) -> ProgrammaticResult<AnalysisSession> {
1562    let entry = crate::run::ProgrammaticEntry::SimilarCode;
1563    let run = crate::run::resolve_programmatic_run(analysis, &entry)?;
1564    Ok(crate::run::runnable(&run, fallow_config::PlannedAnalysis::DeadCode)?.open_session())
1565}
1566
1567fn build_ignore_set(patterns: &[String]) -> ProgrammaticResult<GlobSet> {
1568    let mut builder = GlobSetBuilder::new();
1569    for pattern in patterns {
1570        builder.add(fallow_config::compile_path_glob(pattern).map_err(|error| {
1571            ProgrammaticError::new(
1572                format!("invalid `similarCode.ignore` pattern `{pattern}`: {error}"),
1573                2,
1574            )
1575            .with_code("FALLOW_INVALID_SIMILAR_CODE_IGNORE")
1576            .with_context("similarCode.ignore")
1577        })?);
1578    }
1579    builder.build().map_err(|error| {
1580        ProgrammaticError::new(
1581            format!("failed to compile `similarCode.ignore`: {error}"),
1582            2,
1583        )
1584        .with_code("FALLOW_INVALID_SIMILAR_CODE_IGNORE")
1585        .with_context("similarCode.ignore")
1586    })
1587}
1588
1589fn map_candidate(
1590    candidate: fallow_engine::similar_code::SimilarCodeCandidate,
1591    metadata: &FxHashMap<(String, u32, u32), &ExtractedSimilarCodeFunction>,
1592) -> Option<SimilarCodeCandidate> {
1593    let left = metadata.get(&location_key(&candidate.left))?;
1594    let right = metadata.get(&location_key(&candidate.right))?;
1595    Some(SimilarCodeCandidate {
1596        candidate_id: candidate.candidate_id,
1597        review_key: candidate.review_key,
1598        left: output_location(left),
1599        right: output_location(right),
1600        similarity: candidate.similarity,
1601        similarity_band: similarity_band(candidate.similarity),
1602        verification_status: SimilarCodeVerificationStatus::Unverified,
1603        enrichment: raw_enrichment_availability(),
1604        actions: vec![
1605            SimilarCodeAction {
1606                action: SimilarCodeActionType::Inspect,
1607                description: "Inspect bounded source, graph, ownership, churn, test, and deterministic clone evidence".to_owned(),
1608                read_only: true,
1609            },
1610            SimilarCodeAction {
1611                action: SimilarCodeActionType::Review,
1612                description: "Join this immutable candidate with a separate evidence-grounded verdict".to_owned(),
1613                read_only: true,
1614            },
1615        ],
1616    })
1617}
1618
1619fn output_location(function: &ExtractedSimilarCodeFunction) -> SimilarCodeLocation {
1620    SimilarCodeLocation {
1621        path: function.location.file.clone(),
1622        name: function.name.clone(),
1623        start_line: function.location.start_line,
1624        start_column: function.location.start_column_utf8.saturating_add(1),
1625        end_line: function.location.end_line,
1626        end_column: function.location.end_column_utf8.saturating_add(1),
1627        source_sha256: hex(function.source_sha256.as_bytes()),
1628    }
1629}
1630
1631fn similar_code_scope_active(
1632    options: &SimilarCodeOptions,
1633    resolved: &ProgrammaticAnalysisContext,
1634    changed_files: Option<&FxHashSet<PathBuf>>,
1635    workspace_roots: Option<&[PathBuf]>,
1636) -> bool {
1637    !options.files.is_empty()
1638        || changed_files.is_some()
1639        || resolved.diff_index().is_some()
1640        || workspace_roots.is_some()
1641}
1642
1643fn similar_code_path_in_scope(
1644    path: &str,
1645    options: &SimilarCodeOptions,
1646    resolved: &ProgrammaticAnalysisContext,
1647    changed_files: Option<&FxHashSet<PathBuf>>,
1648    workspace_roots: Option<&[PathBuf]>,
1649) -> bool {
1650    if !options.files.is_empty()
1651        && !options
1652            .files
1653            .iter()
1654            .any(|filter| normalize_path(filter) == path)
1655    {
1656        return false;
1657    }
1658    if let Some(changed_files) = changed_files
1659        && !changed_files.contains(Path::new(path))
1660        && !changed_files.contains(&resolved.root().join(path))
1661    {
1662        return false;
1663    }
1664    if let Some(diff) = resolved.diff_index()
1665        && !diff.touches_file(&diff.key_for_root_relative(path))
1666    {
1667        return false;
1668    }
1669    if let Some(workspace_roots) = workspace_roots
1670        && !workspace_roots
1671            .iter()
1672            .any(|workspace| resolved.root().join(path).starts_with(workspace))
1673    {
1674        return false;
1675    }
1676    true
1677}
1678
1679#[expect(
1680    clippy::too_many_arguments,
1681    reason = "each argument maps directly to one public completion-accounting field"
1682)]
1683fn phases(
1684    admitted_files: usize,
1685    total_files: usize,
1686    extracted_functions: usize,
1687    selected_functions: usize,
1688    embedded_functions: usize,
1689    comparisons: usize,
1690    completeness: PhaseCompleteness,
1691    missing_vectors: usize,
1692    truncated_functions: usize,
1693    source_read_failures: usize,
1694) -> Vec<SimilarCodePhaseCompletion> {
1695    vec![
1696        phase(
1697            SimilarCodePhase::Discovery,
1698            phase_status(completeness.discovery),
1699            admitted_files,
1700            Some(total_files),
1701            (!completeness.discovery)
1702                .then(|| "the file admission limit omitted source files".to_owned()),
1703        ),
1704        phase(
1705            SimilarCodePhase::Extraction,
1706            phase_status(completeness.extraction),
1707            extracted_functions,
1708            None,
1709            (!completeness.extraction).then(|| {
1710                if source_read_failures > 0 {
1711                    "one or more admitted source files could not be read".to_owned()
1712                } else {
1713                    "one or more function forms or source fragments were outside extraction limits"
1714                        .to_owned()
1715                }
1716            }),
1717        ),
1718        phase(
1719            SimilarCodePhase::Cache,
1720            SimilarCodePhaseStatus::Complete,
1721            selected_functions,
1722            Some(selected_functions),
1723            None,
1724        ),
1725        phase(
1726            SimilarCodePhase::Embedding,
1727            phase_status(completeness.embedding),
1728            embedded_functions,
1729            Some(selected_functions),
1730            (!completeness.embedding).then(|| {
1731                if missing_vectors > 0 {
1732                    "the provider did not return every selected vector".to_owned()
1733                } else if truncated_functions > 0 {
1734                    "the provider truncated one or more admitted functions".to_owned()
1735                } else {
1736                    "embedding did not complete its admitted scope".to_owned()
1737                }
1738            }),
1739        ),
1740        phase(
1741            SimilarCodePhase::Validation,
1742            SimilarCodePhaseStatus::Complete,
1743            embedded_functions,
1744            Some(embedded_functions),
1745            None,
1746        ),
1747        phase(
1748            SimilarCodePhase::Comparison,
1749            phase_status(completeness.comparison),
1750            comparisons,
1751            None,
1752            (!completeness.comparison)
1753                .then(|| "comparison limits omitted candidate pairs".to_owned()),
1754        ),
1755        phase(
1756            SimilarCodePhase::Enrichment,
1757            SimilarCodePhaseStatus::Skipped,
1758            0,
1759            None,
1760            Some("raw discovery defers source-grounded enrichment to inspect".to_owned()),
1761        ),
1762    ]
1763}
1764
1765const fn phase_status(complete: bool) -> SimilarCodePhaseStatus {
1766    if complete {
1767        SimilarCodePhaseStatus::Complete
1768    } else {
1769        SimilarCodePhaseStatus::Partial
1770    }
1771}
1772
1773fn phase(
1774    phase: SimilarCodePhase,
1775    status: SimilarCodePhaseStatus,
1776    processed: usize,
1777    total: Option<usize>,
1778    reason: Option<String>,
1779) -> SimilarCodePhaseCompletion {
1780    SimilarCodePhaseCompletion {
1781        phase,
1782        status,
1783        processed: usize_to_u64(processed),
1784        total: total.map(usize_to_u64),
1785        reason,
1786    }
1787}
1788
1789fn output_limits(
1790    engine: EngineLimits,
1791    extraction: SimilarCodeExtractionLimits,
1792) -> SimilarCodeLimits {
1793    SimilarCodeLimits {
1794        max_files: usize_to_u64(MAX_FILES),
1795        max_functions: usize_to_u64(engine.max_functions),
1796        max_source_bytes: usize_to_u64(extraction.max_total_source_bytes),
1797        max_function_bytes: usize_to_u64(extraction.max_source_bytes_per_function),
1798        max_batch_size: usize_to_u64(similar_code::embedding_batch_size()),
1799        max_vector_bytes: usize_to_u64(engine.max_vector_bytes),
1800        max_comparisons: usize_to_u64(engine.max_comparisons),
1801        max_candidates: usize_to_u64(engine.max_candidates),
1802        max_neighbors_per_function: usize_to_u64(engine.max_neighbors_per_function),
1803        timeout_ms: MAX_RUN_TIMEOUT_MS,
1804    }
1805}
1806
1807fn generation(
1808    provider: &SimilarCodeProviderStatus,
1809    threshold: f64,
1810    min_lines: usize,
1811    scope: SimilarCodeScopeProvenance,
1812) -> SimilarCodeGeneration {
1813    SimilarCodeGeneration {
1814        extraction_semantics_version: SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION,
1815        embedding_semantics_version: similar_code::embedding_semantics_version(),
1816        provider: SimilarCodeProviderProvenance {
1817            provider: SimilarCodeProvider::OfficialLocalCompanion,
1818            companion_version: provider.sidecar_version.clone(),
1819            protocol_version: provider.protocol_version,
1820            source_left_machine: false,
1821        },
1822        model: SimilarCodeModelProvenance {
1823            model_id: provider.model_id.clone(),
1824            revision: provider.model_revision.clone(),
1825            artifact_sha256: similar_code::model_artifact_sha256().to_owned(),
1826            license: provider.license.clone(),
1827            dimensions: u32::try_from(provider.dimensions).unwrap_or(u32::MAX),
1828        },
1829        parameters: SimilarCodeGenerationParameters {
1830            dtype: "f32".to_owned(),
1831            pooling: "mean".to_owned(),
1832            normalized: true,
1833            batch_size: u32::try_from(similar_code::embedding_batch_size()).unwrap_or(u32::MAX),
1834            max_tokens: u32::try_from(provider.max_tokens).unwrap_or(u32::MAX),
1835            parameter_sha256: similar_code::parameter_sha256(),
1836        },
1837        scope,
1838        threshold,
1839        min_lines: usize_to_u64(min_lines),
1840    }
1841}
1842
1843fn raw_enrichment_availability() -> SimilarCodeEnrichmentAvailability {
1844    SimilarCodeEnrichmentAvailability {
1845        graph_relationship: SimilarCodeEnrichmentState::NotRequested,
1846        entry_point_reachability: SimilarCodeEnrichmentState::NotRequested,
1847        callers: SimilarCodeEnrichmentState::NotRequested,
1848        callees: SimilarCodeEnrichmentState::NotRequested,
1849        ownership: SimilarCodeEnrichmentState::NotRequested,
1850        churn: SimilarCodeEnrichmentState::NotRequested,
1851        tests: SimilarCodeEnrichmentState::NotRequested,
1852        deterministic_clone_coverage: SimilarCodeEnrichmentState::NotRequested,
1853        runtime: SimilarCodeEnrichmentState::NotRequested,
1854    }
1855}
1856
1857fn map_extraction_skip(reason: SimilarCodeExtractionSkipReason) -> SimilarCodeSkipReason {
1858    match reason {
1859        SimilarCodeExtractionSkipReason::GeneratedSource => SimilarCodeSkipReason::GeneratedSource,
1860        SimilarCodeExtractionSkipReason::SourceBytesPerFunctionLimit => {
1861            SimilarCodeSkipReason::FunctionTooLarge
1862        }
1863        SimilarCodeExtractionSkipReason::FunctionLimit => SimilarCodeSkipReason::InputLimit,
1864        SimilarCodeExtractionSkipReason::TotalSourceBytesLimit => {
1865            SimilarCodeSkipReason::SourceBytesLimit
1866        }
1867        _ => SimilarCodeSkipReason::UnsupportedFunction,
1868    }
1869}
1870
1871fn map_engine_skip(reason: EngineSkipReason) -> SimilarCodeSkipReason {
1872    match reason {
1873        EngineSkipReason::VectorMemoryLimit => SimilarCodeSkipReason::VectorMemoryLimit,
1874        EngineSkipReason::ComparisonLimit => SimilarCodeSkipReason::ComparisonLimit,
1875        EngineSkipReason::CandidateLimit => SimilarCodeSkipReason::CandidateLimit,
1876        EngineSkipReason::NeighborLimit => SimilarCodeSkipReason::NeighborLimit,
1877        _ => SimilarCodeSkipReason::InputLimit,
1878    }
1879}
1880
1881fn cache_status(disabled: bool, hits: usize, misses: usize) -> SimilarCodeCacheStatus {
1882    if disabled {
1883        SimilarCodeCacheStatus::Disabled
1884    } else if misses == 0 {
1885        SimilarCodeCacheStatus::Hit
1886    } else if hits == 0 {
1887        SimilarCodeCacheStatus::Miss
1888    } else {
1889        SimilarCodeCacheStatus::Mixed
1890    }
1891}
1892
1893fn similarity_band(similarity: f64) -> SimilarCodeSimilarityBand {
1894    if similarity >= VERY_HIGH_SIMILARITY {
1895        SimilarCodeSimilarityBand::VeryHigh
1896    } else if similarity >= HIGH_SIMILARITY {
1897        SimilarCodeSimilarityBand::High
1898    } else {
1899        SimilarCodeSimilarityBand::Moderate
1900    }
1901}
1902
1903fn validate_options(options: &SimilarCodeOptions) -> ProgrammaticResult<()> {
1904    if let Some(threshold) = options.threshold {
1905        validate_threshold(threshold)?;
1906    }
1907    if options.min_lines == Some(0) {
1908        return Err(ProgrammaticError::new("`min_lines` must be at least 1", 2)
1909            .with_code("FALLOW_INVALID_SIMILAR_CODE_MIN_LINES")
1910            .with_context("similarCode.minLines"));
1911    }
1912    if options.top == Some(0) {
1913        return Err(ProgrammaticError::new("`top` must be at least 1", 2)
1914            .with_code("FALLOW_INVALID_SIMILAR_CODE_TOP")
1915            .with_context("similarCode.top"));
1916    }
1917    for path in &options.files {
1918        if path.is_absolute()
1919            || path
1920                .components()
1921                .any(|part| matches!(part, std::path::Component::ParentDir))
1922        {
1923            return Err(ProgrammaticError::new(
1924                "`file` paths must be project-root-relative and must not contain `..`",
1925                2,
1926            )
1927            .with_code("FALLOW_INVALID_SIMILAR_CODE_FILE")
1928            .with_context("similarCode.files"));
1929        }
1930    }
1931    Ok(())
1932}
1933
1934fn validate_threshold(threshold: f64) -> ProgrammaticResult<()> {
1935    if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) {
1936        return Err(
1937            ProgrammaticError::new("`threshold` must be finite and between 0 and 1", 2)
1938                .with_code("FALLOW_INVALID_SIMILAR_CODE_THRESHOLD")
1939                .with_context("similarCode.threshold"),
1940        );
1941    }
1942    Ok(())
1943}
1944
1945#[expect(
1946    clippy::needless_pass_by_value,
1947    reason = "map_err supplies owned provider failures and the mapper consumes that boundary"
1948)]
1949fn provider_error(error: ProviderError) -> ProgrammaticError {
1950    let exit_code = if matches!(error, ProviderError::NotReady(_)) {
1951        3
1952    } else {
1953        2
1954    };
1955    let code = if exit_code == 3 {
1956        "FALLOW_SIMILAR_CODE_NOT_READY"
1957    } else {
1958        "FALLOW_SIMILAR_CODE_PROVIDER_FAILED"
1959    };
1960    ProgrammaticError::new(error.message(), exit_code)
1961        .with_code(code)
1962        .with_context("similarCode.provider")
1963}
1964
1965fn engine_error(error: impl std::fmt::Display) -> ProgrammaticError {
1966    ProgrammaticError::new(format!("invalid similar-code evaluation: {error}"), 2)
1967        .with_code("FALLOW_SIMILAR_CODE_EVALUATION_FAILED")
1968        .with_context("similarCode.evaluation")
1969}
1970
1971fn location_key(
1972    location: &fallow_engine::source::similar_code::SimilarCodeFunctionLocation,
1973) -> (String, u32, u32) {
1974    (
1975        location.file.clone(),
1976        location.start_byte,
1977        location.end_byte,
1978    )
1979}
1980
1981fn root_relative(root: &Path, path: &Path) -> String {
1982    normalize_path(path.strip_prefix(root).unwrap_or(path))
1983}
1984
1985fn normalize_path(path: &Path) -> String {
1986    path.to_string_lossy().replace('\\', "/")
1987}
1988
1989fn add_skip(
1990    skips: &mut BTreeMap<SimilarCodeSkipReason, usize>,
1991    reason: SimilarCodeSkipReason,
1992    count: usize,
1993) {
1994    *skips.entry(reason).or_default() += count;
1995}
1996
1997fn extraction_is_complete(
1998    skips: &BTreeMap<SimilarCodeSkipReason, usize>,
1999    source_read_failures: usize,
2000) -> bool {
2001    source_read_failures == 0
2002        && skips.iter().all(|(reason, count)| {
2003            *count == 0 || matches!(reason, SimilarCodeSkipReason::BelowMinimumLines)
2004        })
2005}
2006
2007const fn remaining_extraction_inputs(total: usize, current_index: usize) -> usize {
2008    total.saturating_sub(current_index)
2009}
2010
2011const fn exhausted_extraction_limit(
2012    remaining_functions: usize,
2013    remaining_source_bytes: usize,
2014) -> Option<SimilarCodeSkipReason> {
2015    if remaining_functions == 0 {
2016        Some(SimilarCodeSkipReason::InputLimit)
2017    } else if remaining_source_bytes == 0 {
2018        Some(SimilarCodeSkipReason::SourceBytesLimit)
2019    } else {
2020        None
2021    }
2022}
2023
2024fn hex(bytes: &[u8]) -> String {
2025    bytes.iter().fold(
2026        String::with_capacity(bytes.len().saturating_mul(2)),
2027        |mut output, byte| {
2028            let _ = write!(output, "{byte:02x}");
2029            output
2030        },
2031    )
2032}
2033
2034fn duration_ms(started: Instant) -> u64 {
2035    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
2036}
2037
2038fn usize_to_u64(value: usize) -> u64 {
2039    u64::try_from(value).unwrap_or(u64::MAX)
2040}
2041
2042#[cfg(test)]
2043#[expect(
2044    clippy::unwrap_used,
2045    reason = "deterministic fixtures fail immediately"
2046)]
2047mod tests {
2048    use super::*;
2049    use std::sync::{Arc, Mutex};
2050    use std::time::Duration;
2051
2052    use crate::similar_code::{
2053        EmbeddingBatch, EmbeddingBatchVector, EmbeddingSession, EmbeddingSessionFactory,
2054    };
2055
2056    #[test]
2057    fn ignore_glob_single_star_stays_within_one_segment() {
2058        let set = build_ignore_set(&["src/*.ts".to_string()]).unwrap();
2059        assert!(set.is_match("src/a.ts"));
2060        assert!(!set.is_match("src/nested/a.ts"));
2061    }
2062
2063    #[derive(Default)]
2064    struct FakeProviderState {
2065        spawns: usize,
2066        batches: usize,
2067        complete_batches: Option<usize>,
2068    }
2069
2070    struct FakeEmbeddingSession {
2071        state: Arc<Mutex<FakeProviderState>>,
2072        dimensions: usize,
2073    }
2074
2075    impl EmbeddingSession for FakeEmbeddingSession {
2076        #[expect(
2077            clippy::unwrap_in_result,
2078            reason = "test helper: a panic fails the test"
2079        )]
2080        fn embed(&mut self, functions: &[(u32, &str)]) -> Result<EmbeddingBatch, String> {
2081            let should_return_partial = {
2082                let mut state = self.state.lock().unwrap();
2083                state.batches += 1;
2084                state
2085                    .complete_batches
2086                    .is_some_and(|limit| state.batches > limit)
2087            };
2088            if should_return_partial {
2089                return Ok(EmbeddingBatch {
2090                    vectors: Vec::new(),
2091                    inference_ms: 0.0,
2092                    problem: Some("fixture provider returned a bounded partial batch".to_owned()),
2093                });
2094            }
2095            let vectors = functions
2096                .iter()
2097                .map(|(key, _)| {
2098                    let mut values = vec![0.0; self.dimensions];
2099                    values[0] = 1.0;
2100                    EmbeddingBatchVector {
2101                        key: *key,
2102                        values,
2103                        truncated: false,
2104                    }
2105                })
2106                .collect();
2107            Ok(EmbeddingBatch {
2108                vectors,
2109                inference_ms: 0.25,
2110                problem: None,
2111            })
2112        }
2113    }
2114
2115    struct FakeEmbeddingFactory {
2116        state: Arc<Mutex<FakeProviderState>>,
2117        dimensions: usize,
2118    }
2119
2120    impl EmbeddingSessionFactory for FakeEmbeddingFactory {
2121        #[expect(
2122            clippy::unwrap_in_result,
2123            reason = "test helper: a panic fails the test"
2124        )]
2125        fn spawn(&mut self) -> Result<Box<dyn EmbeddingSession>, String> {
2126            self.state.lock().unwrap().spawns += 1;
2127            Ok(Box::new(FakeEmbeddingSession {
2128                state: Arc::clone(&self.state),
2129                dimensions: self.dimensions,
2130            }))
2131        }
2132    }
2133
2134    struct FixtureEmbedder {
2135        provider_cache_dir: PathBuf,
2136        run_timeout: Duration,
2137        factory: FakeEmbeddingFactory,
2138    }
2139
2140    impl RuntimeEmbedder for FixtureEmbedder {
2141        fn embed(
2142            &mut self,
2143            project_root: &Path,
2144            no_cache: bool,
2145            inputs: &[EmbeddingInput<'_>],
2146        ) -> Result<EmbeddingResult, ProviderError> {
2147            similar_code::embed_selected_with_factory(
2148                &self.provider_cache_dir,
2149                project_root,
2150                no_cache,
2151                inputs,
2152                self.run_timeout,
2153                &mut self.factory,
2154            )
2155        }
2156    }
2157
2158    fn similar_code_fixture() -> (tempfile::TempDir, PathBuf, SimilarCodeProviderStatus) {
2159        let temp = tempfile::tempdir().unwrap();
2160        let project = temp.path().join("project");
2161        let cache_root = temp.path().join("user-cache");
2162        let provider_cache_dir = cache_root.join("models").join("fixture-model");
2163        std::fs::create_dir_all(project.join("src")).unwrap();
2164        std::fs::create_dir_all(&cache_root).unwrap();
2165        std::fs::write(
2166            project.join("package.json"),
2167            r#"{"name":"similar-code-runtime-fixture","private":true}"#,
2168        )
2169        .unwrap();
2170        for (name, value) in [("a", 1), ("b", 2), ("c", 3)] {
2171            std::fs::write(
2172                project.join("src").join(format!("{name}.ts")),
2173                format!(
2174                    "export function {name}(input: number) {{\n  const adjusted = input + {value};\n  return adjusted * 2;\n}}\n"
2175                ),
2176            )
2177            .unwrap();
2178        }
2179        let (model_id, model_revision, dimensions, license) = similar_code::provider_identity();
2180        let status = SimilarCodeProviderStatus {
2181            protocol_version: 2,
2182            embedding_semantics_version: similar_code::embedding_semantics_version(),
2183            sidecar_version: env!("CARGO_PKG_VERSION").to_owned(),
2184            model_ready: true,
2185            model_id: model_id.to_owned(),
2186            model_revision: model_revision.to_owned(),
2187            dimensions,
2188            max_tokens: 512,
2189            license: license.to_owned(),
2190            cache_dir: provider_cache_dir.to_string_lossy().into_owned(),
2191            download_bytes: similar_code::model_download_bytes(),
2192            analysis_offline: true,
2193            integrity_verified: true,
2194            problem: None,
2195            downloaded: None,
2196        };
2197        (temp, project, status)
2198    }
2199
2200    fn fixture_options(project: &Path) -> SimilarCodeOptions {
2201        SimilarCodeOptions {
2202            analysis: crate::AnalysisOptions {
2203                root: Some(project.to_path_buf()),
2204                ..crate::AnalysisOptions::default()
2205            },
2206            threshold: Some(0.9),
2207            min_lines: Some(2),
2208            ..SimilarCodeOptions::default()
2209        }
2210    }
2211
2212    fn run_with_fixture(
2213        options: &SimilarCodeOptions,
2214        status: &SimilarCodeProviderStatus,
2215        embedder: &mut FixtureEmbedder,
2216    ) -> ProgrammaticResult<SimilarCodeOutput> {
2217        let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
2218        resolved
2219            .install(|| run_similar_code_inner_with_embedder(options, &resolved, status, embedder))
2220    }
2221
2222    fn find_cache_file(root: &Path) -> Option<PathBuf> {
2223        for entry in std::fs::read_dir(root).ok()? {
2224            let path = entry.ok()?.path();
2225            if path.file_name().is_some_and(|name| name == "vectors.bin") {
2226                return Some(path);
2227            }
2228            if path.is_dir()
2229                && let Some(found) = find_cache_file(&path)
2230            {
2231                return Some(found);
2232            }
2233        }
2234        None
2235    }
2236
2237    #[test]
2238    fn similar_code_runtime_covers_cold_warm_corrupt_cache_scope_and_output_contract() {
2239        let (_temp, project, status) = similar_code_fixture();
2240        let provider_cache_dir = PathBuf::from(&status.cache_dir);
2241        let state = Arc::new(Mutex::new(FakeProviderState::default()));
2242        let mut embedder = FixtureEmbedder {
2243            provider_cache_dir: provider_cache_dir.clone(),
2244            run_timeout: Duration::from_secs(5),
2245            factory: FakeEmbeddingFactory {
2246                state: Arc::clone(&state),
2247                dimensions: status.dimensions,
2248            },
2249        };
2250        let mut options = fixture_options(&project);
2251        options.files = vec![PathBuf::from("src/a.ts")];
2252
2253        let cold = run_with_fixture(&options, &status, &mut embedder).unwrap();
2254        assert!(!cold.candidates.is_empty());
2255        assert!(cold.candidates.iter().all(|candidate| {
2256            candidate.left.path == "src/a.ts" || candidate.right.path == "src/a.ts"
2257        }));
2258        assert_eq!(
2259            cold.completion.status,
2260            SimilarCodeCompletionStatus::Complete
2261        );
2262        assert!(cold.completion.cache.misses > 0);
2263        assert!(cold.completion.cache.writes > 0);
2264        let cold_spawns = state.lock().unwrap().spawns;
2265        let cold_ids = cold
2266            .candidates
2267            .iter()
2268            .map(|candidate| candidate.candidate_id.clone())
2269            .collect::<Vec<_>>();
2270        let json = serde_json::to_value(&cold).unwrap();
2271        assert_eq!(json["generation"]["embedding_semantics_version"], 2);
2272        assert_eq!(json["generation"]["provider"]["source_left_machine"], false);
2273        assert_eq!(json["generation"]["scope"]["active"], true);
2274        assert_eq!(
2275            json["generation"]["scope"]["paths"],
2276            serde_json::json!(["src/a.ts"])
2277        );
2278        assert!(json["completion"]["cache"].is_object());
2279
2280        let warm = run_with_fixture(&options, &status, &mut embedder).unwrap();
2281        assert_eq!(state.lock().unwrap().spawns, cold_spawns);
2282        assert!(warm.completion.cache.hits > 0);
2283        assert_eq!(warm.completion.cache.writes, 0);
2284        assert_eq!(
2285            warm.candidates
2286                .iter()
2287                .map(|candidate| candidate.candidate_id.clone())
2288                .collect::<Vec<_>>(),
2289            cold_ids
2290        );
2291
2292        let cache_root = provider_cache_dir.parent().and_then(Path::parent).unwrap();
2293        let cache_file = find_cache_file(cache_root).unwrap();
2294        std::fs::write(&cache_file, b"corrupt cache fixture").unwrap();
2295        let recovered = run_with_fixture(&options, &status, &mut embedder).unwrap();
2296        assert_eq!(recovered.completion.cache.invalid_entries, 1);
2297        assert!(recovered.completion.cache.writes > 0);
2298        assert!(state.lock().unwrap().spawns > cold_spawns);
2299    }
2300
2301    #[test]
2302    fn snapshot_inspect_survives_ranking_crowd_out_and_rejects_stale_source() {
2303        let (_temp, project, status) = similar_code_fixture();
2304        let state = Arc::new(Mutex::new(FakeProviderState::default()));
2305        let mut embedder = FixtureEmbedder {
2306            provider_cache_dir: PathBuf::from(&status.cache_dir),
2307            run_timeout: Duration::from_secs(5),
2308            factory: FakeEmbeddingFactory {
2309                state,
2310                dimensions: status.dimensions,
2311            },
2312        };
2313        let discovery =
2314            run_with_fixture(&fixture_options(&project), &status, &mut embedder).unwrap();
2315        let candidate_id = discovery.candidates.last().unwrap().candidate_id.clone();
2316        let tagged = fallow_output::serialize_similar_code_json_output(discovery).unwrap();
2317        let snapshot = select_similar_code_candidate_snapshot(
2318            &serde_json::to_vec(&tagged).unwrap(),
2319            &candidate_id,
2320        )
2321        .unwrap();
2322
2323        let mut legacy_options = fixture_options(&project);
2324        legacy_options.files = vec![
2325            PathBuf::from(&snapshot.candidate.left.path),
2326            PathBuf::from(&snapshot.candidate.right.path),
2327        ];
2328        legacy_options.top = Some(1);
2329        let endpoint_reranked = run_with_fixture(&legacy_options, &status, &mut embedder).unwrap();
2330        assert_eq!(endpoint_reranked.candidates.len(), 1);
2331        assert!(
2332            endpoint_reranked
2333                .candidates
2334                .iter()
2335                .all(|candidate| candidate.candidate_id != candidate_id),
2336            "the endpoint-only legacy rerank must reproduce the crowd-out condition"
2337        );
2338
2339        let inspect_options = SimilarCodeInspectOptions {
2340            analysis: crate::AnalysisOptions {
2341                root: Some(project.clone()),
2342                ..crate::AnalysisOptions::default()
2343            },
2344            snapshot: snapshot.clone(),
2345        };
2346        let inspected = inspect_similar_code(&inspect_options).unwrap();
2347        assert_eq!(inspected.candidate.candidate_id, candidate_id);
2348
2349        let stale_path = project.join(&snapshot.candidate.left.path);
2350        let stale_source = std::fs::read_to_string(&stale_path).unwrap();
2351        std::fs::write(
2352            &stale_path,
2353            stale_source.replace("return adjusted * 2", "return adjusted * 3"),
2354        )
2355        .unwrap();
2356        let error = inspect_similar_code(&inspect_options).unwrap_err();
2357        assert_eq!(
2358            error.code.as_deref(),
2359            Some("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
2360        );
2361    }
2362
2363    #[test]
2364    fn snapshot_inspect_rejects_oversized_endpoint_before_source_allocation() {
2365        let temp = tempfile::tempdir().unwrap();
2366        let project = dunce::canonicalize(temp.path()).unwrap();
2367        let source_path = project.join("src/endpoint.ts");
2368        std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
2369        std::fs::write(
2370            &source_path,
2371            "export function candidate() {\n  return true;\n}\n",
2372        )
2373        .unwrap();
2374        std::fs::OpenOptions::new()
2375            .write(true)
2376            .open(&source_path)
2377            .unwrap()
2378            .set_len(MAX_INSPECT_SOURCE_BYTES + 1)
2379            .unwrap();
2380
2381        let error = inspect_side(&project, &location("src/endpoint.ts", 1, 3)).unwrap_err();
2382        assert_eq!(
2383            error.code.as_deref(),
2384            Some("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
2385        );
2386        assert!(error.message.contains("5 MiB per-file limit"));
2387    }
2388
2389    #[test]
2390    fn snapshot_inspect_does_not_rebind_an_identical_same_line_function() {
2391        let temp = tempfile::tempdir().unwrap();
2392        let project = dunce::canonicalize(temp.path()).unwrap();
2393        let relative = Path::new("src/duplicates.js");
2394        let source_path = project.join(relative);
2395        std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
2396        let function = "function duplicate() { return 1; }";
2397        let original = format!("{function} {function}\n");
2398        std::fs::write(&source_path, &original).unwrap();
2399
2400        let extracted = fallow_engine::source::similar_code::extract(
2401            relative,
2402            &original,
2403            SimilarCodeExtractionLimits::default(),
2404        );
2405        assert_eq!(extracted.functions.len(), 2);
2406        let snapshot = output_location(&extracted.functions[0]);
2407        assert_eq!(
2408            snapshot.source_sha256,
2409            output_location(&extracted.functions[1]).source_sha256
2410        );
2411        assert_ne!(
2412            snapshot.start_column,
2413            output_location(&extracted.functions[1]).start_column
2414        );
2415
2416        let second_start = function.len() + 1;
2417        std::fs::write(
2418            &source_path,
2419            format!("{}{function}\n", " ".repeat(second_start)),
2420        )
2421        .unwrap();
2422
2423        let error = inspect_side(&project, &snapshot).unwrap_err();
2424        assert_eq!(
2425            error.code.as_deref(),
2426            Some("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
2427        );
2428    }
2429
2430    #[test]
2431    fn similar_code_runtime_reports_partial_provider_output_and_bounded_timeout() {
2432        let (_temp, project, status) = similar_code_fixture();
2433        let provider_cache_dir = PathBuf::from(&status.cache_dir);
2434        let partial_state = Arc::new(Mutex::new(FakeProviderState {
2435            complete_batches: Some(2),
2436            ..FakeProviderState::default()
2437        }));
2438        let mut partial_embedder = FixtureEmbedder {
2439            provider_cache_dir: provider_cache_dir.clone(),
2440            run_timeout: Duration::from_secs(5),
2441            factory: FakeEmbeddingFactory {
2442                state: partial_state,
2443                dimensions: status.dimensions,
2444            },
2445        };
2446        let mut options = fixture_options(&project);
2447        options.analysis.no_cache = true;
2448
2449        let partial = run_with_fixture(&options, &status, &mut partial_embedder).unwrap();
2450        assert_eq!(
2451            partial.completion.status,
2452            SimilarCodeCompletionStatus::Partial
2453        );
2454        assert!(partial.completion.skips.iter().any(|skip| {
2455            skip.phase == SimilarCodePhase::Embedding
2456                && skip.reason == SimilarCodeSkipReason::ProviderFailure
2457        }));
2458        assert!(
2459            partial
2460                .diagnostics
2461                .iter()
2462                .any(|diagnostic| { diagnostic.code == "FALLOW_SIMILAR_CODE_PROVIDER_PARTIAL" })
2463        );
2464
2465        let timeout_state = Arc::new(Mutex::new(FakeProviderState::default()));
2466        let mut timeout_embedder = FixtureEmbedder {
2467            provider_cache_dir,
2468            run_timeout: Duration::ZERO,
2469            factory: FakeEmbeddingFactory {
2470                state: Arc::clone(&timeout_state),
2471                dimensions: status.dimensions,
2472            },
2473        };
2474        let error = run_with_fixture(&options, &status, &mut timeout_embedder).unwrap_err();
2475        assert_eq!(
2476            error.code.as_deref(),
2477            Some("FALLOW_SIMILAR_CODE_PROVIDER_FAILED")
2478        );
2479        assert_eq!(timeout_state.lock().unwrap().spawns, 0);
2480    }
2481
2482    fn location(path: &str, start_line: u32, end_line: u32) -> SimilarCodeLocation {
2483        SimilarCodeLocation {
2484            path: path.to_owned(),
2485            name: "candidate".to_owned(),
2486            start_line,
2487            start_column: 1,
2488            end_line,
2489            end_column: 1,
2490            source_sha256: "00".repeat(32),
2491        }
2492    }
2493
2494    fn file_trace(imports_from: &[&str], imported_by: &[&str]) -> fallow_engine::trace::FileTrace {
2495        fallow_engine::trace::FileTrace {
2496            file: PathBuf::from("src/current.ts"),
2497            is_reachable: true,
2498            is_entry_point: false,
2499            exports: Vec::new(),
2500            imports_from: imports_from.iter().map(PathBuf::from).collect(),
2501            imported_by: imported_by.iter().map(PathBuf::from).collect(),
2502            re_exports: Vec::new(),
2503            ..Default::default()
2504        }
2505    }
2506
2507    fn side_evidence() -> SimilarCodeSideEvidence {
2508        SimilarCodeSideEvidence {
2509            source_window: None,
2510            parameter_count: None,
2511            is_async: None,
2512            is_generator: None,
2513            has_await: None,
2514            has_throw: None,
2515            side_effect_hint: None,
2516            entry_point_reachable: None,
2517            callers: Vec::new(),
2518            callees: Vec::new(),
2519            owners: Vec::new(),
2520            churn_commits: None,
2521            tests: Vec::new(),
2522            deterministic_clone_coverage: None,
2523            runtime_observations: None,
2524        }
2525    }
2526
2527    #[test]
2528    fn similar_code_phase_statuses_identify_only_the_incomplete_phase() {
2529        let phases = phases(
2530            5,
2531            5,
2532            3,
2533            3,
2534            3,
2535            3,
2536            PhaseCompleteness {
2537                discovery: true,
2538                extraction: false,
2539                embedding: true,
2540                comparison: true,
2541            },
2542            0,
2543            0,
2544            0,
2545        );
2546
2547        assert_eq!(phases[0].status, SimilarCodePhaseStatus::Complete);
2548        assert_eq!(phases[1].status, SimilarCodePhaseStatus::Partial);
2549        assert!(phases[1].reason.is_some());
2550        assert_eq!(phases[3].status, SimilarCodePhaseStatus::Complete);
2551        assert_eq!(phases[4].status, SimilarCodePhaseStatus::Complete);
2552        assert_eq!(phases[5].status, SimilarCodePhaseStatus::Complete);
2553    }
2554
2555    #[test]
2556    fn similar_code_extraction_completion_counts_limits_and_read_failures_honestly() {
2557        let mut skips = BTreeMap::from([(SimilarCodeSkipReason::BelowMinimumLines, 2)]);
2558        assert!(extraction_is_complete(&skips, 0));
2559        assert!(!extraction_is_complete(&skips, 1));
2560
2561        skips.insert(SimilarCodeSkipReason::InputLimit, 3);
2562        assert!(!extraction_is_complete(&skips, 0));
2563        assert_eq!(remaining_extraction_inputs(7, 3), 4);
2564    }
2565
2566    #[test]
2567    fn similar_code_exhausted_extraction_budget_uses_the_specific_skip_reason() {
2568        assert_eq!(
2569            exhausted_extraction_limit(0, 1),
2570            Some(SimilarCodeSkipReason::InputLimit)
2571        );
2572        assert_eq!(
2573            exhausted_extraction_limit(1, 0),
2574            Some(SimilarCodeSkipReason::SourceBytesLimit)
2575        );
2576        assert_eq!(exhausted_extraction_limit(1, 1), None);
2577    }
2578
2579    #[test]
2580    fn similar_code_scope_requires_one_endpoint_to_match_every_active_filter() {
2581        let root = tempfile::tempdir().unwrap();
2582        let resolved = resolve_programmatic_analysis_context(&crate::AnalysisOptions {
2583            root: Some(root.path().to_path_buf()),
2584            ..crate::AnalysisOptions::default()
2585        })
2586        .unwrap();
2587        let options = SimilarCodeOptions {
2588            files: vec![PathBuf::from("src/file-scoped.ts")],
2589            ..SimilarCodeOptions::default()
2590        };
2591        let changed = FxHashSet::from_iter([PathBuf::from("src/changed.ts")]);
2592
2593        assert!(similar_code_scope_active(
2594            &options,
2595            &resolved,
2596            Some(&changed),
2597            None,
2598        ));
2599        assert!(!similar_code_path_in_scope(
2600            "src/file-scoped.ts",
2601            &options,
2602            &resolved,
2603            Some(&changed),
2604            None,
2605        ));
2606        assert!(!similar_code_path_in_scope(
2607            "src/changed.ts",
2608            &options,
2609            &resolved,
2610            Some(&changed),
2611            None,
2612        ));
2613
2614        let changed = FxHashSet::from_iter([PathBuf::from("src/file-scoped.ts")]);
2615        assert!(similar_code_path_in_scope(
2616            "src/file-scoped.ts",
2617            &options,
2618            &resolved,
2619            Some(&changed),
2620            None,
2621        ));
2622    }
2623
2624    #[test]
2625    fn similar_code_module_references_are_sorted_deduplicated_and_bounded() {
2626        let paths = vec![
2627            PathBuf::from("src/z.ts"),
2628            PathBuf::from("src/a.ts"),
2629            PathBuf::from("src/a.ts"),
2630        ];
2631
2632        let (references, truncated) = bounded_module_references(&paths, 1);
2633
2634        assert!(truncated);
2635        assert_eq!(references.len(), 1);
2636        assert_eq!(references[0].path, "src/a.ts");
2637        assert_eq!(references[0].name, MODULE_REFERENCE_NAME);
2638        assert_eq!(references[0].line, 1);
2639    }
2640
2641    #[test]
2642    fn similar_code_related_tests_are_transitive_path_filtered_and_bounded() {
2643        let paths = vec![
2644            "src/helper.ts".to_owned(),
2645            "tests/z.spec.ts".to_owned(),
2646            "src/a.test.ts".to_owned(),
2647            "src/a.test.ts".to_owned(),
2648        ];
2649
2650        let (tests, truncated) = bounded_related_tests(Path::new("/project"), &paths, 1);
2651
2652        assert!(truncated);
2653        assert_eq!(tests, vec!["src/a.test.ts"]);
2654    }
2655
2656    #[test]
2657    fn similar_code_related_tests_leave_out_test_support_files() {
2658        let paths = vec![
2659            "src/__mocks__/api.ts".to_owned(),
2660            "src/__fixtures__/user.ts".to_owned(),
2661            "src/__snapshots__/api.ts.snap".to_owned(),
2662            "src/user.fixture.ts".to_owned(),
2663            "src/api.test.ts".to_owned(),
2664        ];
2665
2666        let (tests, truncated) = bounded_related_tests(Path::new("/project"), &paths, 10);
2667
2668        assert!(!truncated);
2669        assert_eq!(tests, vec!["src/api.test.ts"]);
2670    }
2671
2672    #[test]
2673    fn similar_code_module_relationship_uses_direct_edges_then_shared_importers() {
2674        let left_location = location("src/left.ts", 1, 3);
2675        let right_location = location("src/right.ts", 1, 3);
2676        let left = file_trace(&["src/right.ts"], &["src/shared.ts"]);
2677        let right = file_trace(&[], &["src/shared.ts"]);
2678
2679        assert_eq!(
2680            module_relationship(&left, &right, &left_location, &right_location),
2681            "left-directly-imports-right"
2682        );
2683
2684        let left = file_trace(&[], &["src/shared.ts"]);
2685        assert_eq!(
2686            module_relationship(&left, &right, &left_location, &right_location),
2687            "shared-direct-importer"
2688        );
2689    }
2690
2691    #[test]
2692    fn similar_code_primary_owner_uses_the_codeowners_winning_rule() {
2693        let codeowners = CodeOwners::parse("/src/* @team/base\n/src/special.ts @team/special")
2694            .expect("CODEOWNERS parses");
2695
2696        assert_eq!(
2697            primary_owner(&codeowners, "src/special.ts"),
2698            vec!["@team/special"]
2699        );
2700        assert!(primary_owner(&codeowners, "test/a.ts").is_empty());
2701    }
2702
2703    #[test]
2704    fn similar_code_churn_lookup_normalizes_path_separators_and_defaults_to_zero() {
2705        let mut files = FxHashMap::default();
2706        files.insert(
2707            PathBuf::from("C:/repo/src/a.ts"),
2708            fallow_engine::churn::FileChurn {
2709                path: PathBuf::from("C:/repo/src/a.ts"),
2710                commits: 7,
2711                weighted_commits: 0.0,
2712                lines_added: 0,
2713                lines_deleted: 0,
2714                trend: fallow_engine::churn::ChurnTrend::Stable,
2715                authors: FxHashMap::default(),
2716            },
2717        );
2718        let churn = fallow_engine::churn::ChurnResult {
2719            files,
2720            shallow_clone: false,
2721            author_pool: Vec::new(),
2722            clock: fallow_engine::clock::AnalysisClock::pinned(1_788_782_400),
2723            git_log_bytes: 0,
2724            commits: Vec::new(),
2725        };
2726
2727        assert_eq!(churn_commits_for(&churn, Path::new(r"C:\repo\src\a.ts")), 7);
2728        assert_eq!(churn_commits_for(&churn, Path::new("src/missing.ts")), 0);
2729    }
2730
2731    #[test]
2732    fn similar_code_clone_coverage_counts_unique_exact_lines_only() {
2733        let root = Path::new("/repo");
2734        let exact = fallow_engine::duplicates::CloneGroup {
2735            instances: vec![
2736                clone_instance("/repo/src/a.ts", 2, 4),
2737                clone_instance("/repo/src/a.ts", 4, 6),
2738            ],
2739            token_count: 10,
2740            line_count: 3,
2741            similarity: None,
2742        };
2743        let near = fallow_engine::duplicates::CloneGroup {
2744            instances: vec![clone_instance("/repo/src/a.ts", 7, 9)],
2745            token_count: 10,
2746            line_count: 3,
2747            similarity: Some(0.9),
2748        };
2749        let report = fallow_engine::duplicates::DuplicationReport {
2750            clone_groups: vec![exact, near],
2751            ..fallow_engine::duplicates::DuplicationReport::default()
2752        };
2753
2754        assert_eq!(
2755            deterministic_clone_coverage(&report, root, &location("src/a.ts", 1, 10)),
2756            0.5
2757        );
2758    }
2759
2760    #[test]
2761    fn similar_code_project_artifacts_enrich_both_sides_deterministically() {
2762        let project = tempfile::tempdir().expect("temporary project");
2763        let root = project.path();
2764        std::fs::create_dir_all(root.join("src")).expect("source directory");
2765        std::fs::create_dir_all(root.join("tests")).expect("test directory");
2766        std::fs::write(
2767            root.join("package.json"),
2768            r#"{"name":"inspect-enrichment","main":"src/index.ts"}"#,
2769        )
2770        .expect("package manifest");
2771        let repeated = "export function candidate(values: number[]) {\n  const positive = values.filter((value) => value > 0);\n  const doubled = positive.map((value) => value * 2);\n  const total = doubled.reduce((sum, value) => sum + value, 0);\n  return { total, count: doubled.length };\n}\n";
2772        std::fs::write(root.join("src/left.ts"), repeated).expect("left source");
2773        std::fs::write(root.join("src/right.ts"), repeated).expect("right source");
2774        std::fs::write(
2775            root.join("src/index.ts"),
2776            "import { candidate as left } from './left';\nimport { candidate as right } from './right';\nconsole.log(left([1]), right([2]));\n",
2777        )
2778        .expect("entry source");
2779        std::fs::write(
2780            root.join("tests/left.test.ts"),
2781            "import { candidate } from '../src/left';\ntest('candidate', () => expect(candidate([1])).toBeTruthy());\n",
2782        )
2783        .expect("test source");
2784
2785        let session = AnalysisSession::load_with_config(root, None, |config| {
2786            config.duplicates.min_tokens = 5;
2787            config.duplicates.min_lines = 2;
2788        })
2789        .expect("analysis session");
2790        let left_location = location("src/left.ts", 1, 6);
2791        let right_location = location("src/right.ts", 1, 6);
2792        let mut left = side_evidence();
2793        let mut right = side_evidence();
2794        let mut result = InspectEnrichment {
2795            availability: unavailable_inspect_enrichment(),
2796            graph_relationship: None,
2797            diagnostics: Vec::new(),
2798        };
2799
2800        enrich_graph_and_clones(
2801            &session,
2802            &left_location,
2803            &right_location,
2804            &mut left,
2805            &mut right,
2806            &mut result,
2807        );
2808
2809        assert_eq!(
2810            result.graph_relationship.as_deref(),
2811            Some("shared-direct-importer")
2812        );
2813        assert_eq!(
2814            result.availability.entry_point_reachability,
2815            SimilarCodeEnrichmentState::Available
2816        );
2817        assert_eq!(left.entry_point_reachable, Some(true));
2818        assert!(
2819            left.callers
2820                .iter()
2821                .any(|reference| reference.path == "src/index.ts")
2822        );
2823        assert_eq!(left.tests, vec!["tests/left.test.ts"]);
2824        assert!(
2825            left.deterministic_clone_coverage
2826                .is_some_and(|value| value > 0.0)
2827        );
2828        assert!(
2829            right
2830                .deterministic_clone_coverage
2831                .is_some_and(|value| value > 0.0)
2832        );
2833    }
2834
2835    fn clone_instance(
2836        file: &str,
2837        start_line: usize,
2838        end_line: usize,
2839    ) -> fallow_engine::duplicates::CloneInstance {
2840        fallow_engine::duplicates::CloneInstance {
2841            is_symlink: false,
2842            file: PathBuf::from(file),
2843            start_line,
2844            end_line,
2845            start_col: 0,
2846            end_col: 0,
2847            fragment: String::new(),
2848        }
2849    }
2850
2851    fn shared_review_key_candidates() -> (Vec<u8>, Vec<SimilarCodeCandidate>) {
2852        let (_temp, project, status) = similar_code_fixture();
2853        std::fs::copy(project.join("src/a.ts"), project.join("src/d.ts")).unwrap();
2854        let mut embedder = FixtureEmbedder {
2855            provider_cache_dir: PathBuf::from(&status.cache_dir),
2856            run_timeout: Duration::from_secs(5),
2857            factory: FakeEmbeddingFactory {
2858                state: Arc::new(Mutex::new(FakeProviderState::default())),
2859                dimensions: status.dimensions,
2860            },
2861        };
2862        let output = run_with_fixture(&fixture_options(&project), &status, &mut embedder).unwrap();
2863        let mut document = serde_json::to_value(&output).unwrap();
2864        document["kind"] = Value::from("similar-code");
2865        (serde_json::to_vec(&document).unwrap(), output.candidates)
2866    }
2867
2868    fn abstaining_verdict(candidate_id: &str, review_key: &str) -> Value {
2869        serde_json::json!({
2870            "candidate_id": candidate_id,
2871            "review_key": review_key,
2872            "candidate_worthy": null,
2873            "behaviorally_equivalent": null,
2874            "refactor_safe": null,
2875            "outcome": "needs-human-review",
2876            "rationale": "Evidence is incomplete."
2877        })
2878    }
2879
2880    fn verdict_document(verdicts: &[Value]) -> Vec<u8> {
2881        serde_json::to_vec(&serde_json::json!({
2882            "schema_version": "1",
2883            "verdicts": verdicts,
2884        }))
2885        .unwrap()
2886    }
2887
2888    /// Returns the shared review key and the candidates that carry it.
2889    fn shared_key_group(
2890        candidates: &[SimilarCodeCandidate],
2891    ) -> (String, Vec<&SimilarCodeCandidate>) {
2892        let mut groups: BTreeMap<&str, Vec<&SimilarCodeCandidate>> = BTreeMap::new();
2893        for candidate in candidates {
2894            groups
2895                .entry(candidate.review_key.as_str())
2896                .or_default()
2897                .push(candidate);
2898        }
2899        let (key, group) = groups
2900            .into_iter()
2901            .find(|(_, group)| group.len() > 1)
2902            .expect("a copied function gives two candidates with one review_key");
2903        (key.to_owned(), group)
2904    }
2905
2906    #[test]
2907    fn review_accepts_candidate_id_verdicts_that_share_a_review_key() {
2908        let (candidate_json, candidates) = shared_review_key_candidates();
2909        shared_key_group(&candidates);
2910        let verdicts = verdict_document(
2911            &candidates
2912                .iter()
2913                .map(|candidate| abstaining_verdict(&candidate.candidate_id, &candidate.review_key))
2914                .collect::<Vec<_>>(),
2915        );
2916
2917        let reviewed = review_similar_code(&candidate_json, &verdicts, true).unwrap();
2918
2919        assert_eq!(reviewed.candidates.len(), candidates.len());
2920        assert!(reviewed.candidates.iter().all(|reviewed| {
2921            reviewed.verdict.is_some()
2922                && reviewed.verdict_match == SimilarCodeVerdictMatch::CandidateId
2923        }));
2924    }
2925
2926    #[test]
2927    fn review_does_not_apply_a_review_key_verdict_that_matches_several_candidates() {
2928        let (candidate_json, candidates) = shared_review_key_candidates();
2929        let (key, group) = shared_key_group(&candidates);
2930        let verdicts = verdict_document(&[abstaining_verdict("sc_stale", &key)]);
2931
2932        let reviewed = review_similar_code(&candidate_json, &verdicts, false).unwrap();
2933        assert!(
2934            reviewed.diagnostics.iter().any(|diagnostic| {
2935                diagnostic.code == "FALLOW_SIMILAR_CODE_REVIEW_KEY_AMBIGUOUS"
2936            })
2937        );
2938        for candidate in &group {
2939            let joined = reviewed
2940                .candidates
2941                .iter()
2942                .find(|reviewed| reviewed.candidate.candidate_id == candidate.candidate_id)
2943                .unwrap();
2944            assert!(joined.verdict.is_none());
2945            assert_eq!(
2946                joined.verdict_match,
2947                SimilarCodeVerdictMatch::AmbiguousReviewKey
2948            );
2949        }
2950
2951        let error = review_similar_code(&candidate_json, &verdicts, true).unwrap_err();
2952        assert_eq!(error.message, "a verdict is required for every candidate");
2953    }
2954
2955    #[test]
2956    fn review_keeps_candidate_id_matches_next_to_an_ambiguous_review_key_verdict() {
2957        let (candidate_json, candidates) = shared_review_key_candidates();
2958        let (key, group) = shared_key_group(&candidates);
2959        let first = group[0];
2960        for verdicts in [
2961            vec![
2962                abstaining_verdict(&first.candidate_id, &key),
2963                abstaining_verdict("sc_stale", &key),
2964            ],
2965            vec![
2966                abstaining_verdict("sc_stale", &key),
2967                abstaining_verdict(&first.candidate_id, &key),
2968            ],
2969        ] {
2970            let reviewed =
2971                review_similar_code(&candidate_json, &verdict_document(&verdicts), false).unwrap();
2972            let joined = reviewed
2973                .candidates
2974                .iter()
2975                .find(|reviewed| reviewed.candidate.candidate_id == first.candidate_id)
2976                .unwrap();
2977            assert!(joined.verdict.is_some());
2978            assert_eq!(joined.verdict_match, SimilarCodeVerdictMatch::CandidateId);
2979        }
2980    }
2981
2982    #[test]
2983    fn review_rejects_repeated_identities_that_do_not_identify_one_candidate() {
2984        let (candidate_json, candidates) = shared_review_key_candidates();
2985        let (key, _) = shared_key_group(&candidates);
2986        let unique = candidates
2987            .iter()
2988            .find(|candidate| {
2989                candidates
2990                    .iter()
2991                    .filter(|other| other.review_key == candidate.review_key)
2992                    .count()
2993                    == 1
2994            })
2995            .expect("the fixture has a candidate with a unique review_key");
2996        let cases = [
2997            (
2998                vec![
2999                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
3000                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
3001                ],
3002                "verdict document contains duplicate candidate or review identities",
3003            ),
3004            (
3005                vec![
3006                    abstaining_verdict("sc_stale_one", &key),
3007                    abstaining_verdict("sc_stale_two", &key),
3008                ],
3009                "verdict document contains duplicate candidate or review identities",
3010            ),
3011            (
3012                vec![
3013                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
3014                    abstaining_verdict("sc_stale", &unique.review_key),
3015                ],
3016                "multiple verdicts resolve to the same candidate",
3017            ),
3018            (
3019                vec![
3020                    abstaining_verdict("sc_stale", &unique.review_key),
3021                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
3022                ],
3023                "multiple verdicts resolve to the same candidate",
3024            ),
3025            (
3026                vec![abstaining_verdict(&unique.candidate_id, &key)],
3027                "verdict review_key does not match its candidate_id",
3028            ),
3029        ];
3030        for (verdicts, message) in cases {
3031            let error = review_similar_code(&candidate_json, &verdict_document(&verdicts), false)
3032                .unwrap_err();
3033            assert_eq!(error.message, message);
3034        }
3035    }
3036}