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_ref(),
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_ref(),
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<&fallow_engine::workspace_scope::WorkspaceScope>,
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<&fallow_engine::workspace_scope::WorkspaceScope>,
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.contains(&resolved.root().join(path))
1671    {
1672        return false;
1673    }
1674    true
1675}
1676
1677#[expect(
1678    clippy::too_many_arguments,
1679    reason = "each argument maps directly to one public completion-accounting field"
1680)]
1681fn phases(
1682    admitted_files: usize,
1683    total_files: usize,
1684    extracted_functions: usize,
1685    selected_functions: usize,
1686    embedded_functions: usize,
1687    comparisons: usize,
1688    completeness: PhaseCompleteness,
1689    missing_vectors: usize,
1690    truncated_functions: usize,
1691    source_read_failures: usize,
1692) -> Vec<SimilarCodePhaseCompletion> {
1693    vec![
1694        phase(
1695            SimilarCodePhase::Discovery,
1696            phase_status(completeness.discovery),
1697            admitted_files,
1698            Some(total_files),
1699            (!completeness.discovery)
1700                .then(|| "the file admission limit omitted source files".to_owned()),
1701        ),
1702        phase(
1703            SimilarCodePhase::Extraction,
1704            phase_status(completeness.extraction),
1705            extracted_functions,
1706            None,
1707            (!completeness.extraction).then(|| {
1708                if source_read_failures > 0 {
1709                    "one or more admitted source files could not be read".to_owned()
1710                } else {
1711                    "one or more function forms or source fragments were outside extraction limits"
1712                        .to_owned()
1713                }
1714            }),
1715        ),
1716        phase(
1717            SimilarCodePhase::Cache,
1718            SimilarCodePhaseStatus::Complete,
1719            selected_functions,
1720            Some(selected_functions),
1721            None,
1722        ),
1723        phase(
1724            SimilarCodePhase::Embedding,
1725            phase_status(completeness.embedding),
1726            embedded_functions,
1727            Some(selected_functions),
1728            (!completeness.embedding).then(|| {
1729                if missing_vectors > 0 {
1730                    "the provider did not return every selected vector".to_owned()
1731                } else if truncated_functions > 0 {
1732                    "the provider truncated one or more admitted functions".to_owned()
1733                } else {
1734                    "embedding did not complete its admitted scope".to_owned()
1735                }
1736            }),
1737        ),
1738        phase(
1739            SimilarCodePhase::Validation,
1740            SimilarCodePhaseStatus::Complete,
1741            embedded_functions,
1742            Some(embedded_functions),
1743            None,
1744        ),
1745        phase(
1746            SimilarCodePhase::Comparison,
1747            phase_status(completeness.comparison),
1748            comparisons,
1749            None,
1750            (!completeness.comparison)
1751                .then(|| "comparison limits omitted candidate pairs".to_owned()),
1752        ),
1753        phase(
1754            SimilarCodePhase::Enrichment,
1755            SimilarCodePhaseStatus::Skipped,
1756            0,
1757            None,
1758            Some("raw discovery defers source-grounded enrichment to inspect".to_owned()),
1759        ),
1760    ]
1761}
1762
1763const fn phase_status(complete: bool) -> SimilarCodePhaseStatus {
1764    if complete {
1765        SimilarCodePhaseStatus::Complete
1766    } else {
1767        SimilarCodePhaseStatus::Partial
1768    }
1769}
1770
1771fn phase(
1772    phase: SimilarCodePhase,
1773    status: SimilarCodePhaseStatus,
1774    processed: usize,
1775    total: Option<usize>,
1776    reason: Option<String>,
1777) -> SimilarCodePhaseCompletion {
1778    SimilarCodePhaseCompletion {
1779        phase,
1780        status,
1781        processed: usize_to_u64(processed),
1782        total: total.map(usize_to_u64),
1783        reason,
1784    }
1785}
1786
1787fn output_limits(
1788    engine: EngineLimits,
1789    extraction: SimilarCodeExtractionLimits,
1790) -> SimilarCodeLimits {
1791    SimilarCodeLimits {
1792        max_files: usize_to_u64(MAX_FILES),
1793        max_functions: usize_to_u64(engine.max_functions),
1794        max_source_bytes: usize_to_u64(extraction.max_total_source_bytes),
1795        max_function_bytes: usize_to_u64(extraction.max_source_bytes_per_function),
1796        max_batch_size: usize_to_u64(similar_code::embedding_batch_size()),
1797        max_vector_bytes: usize_to_u64(engine.max_vector_bytes),
1798        max_comparisons: usize_to_u64(engine.max_comparisons),
1799        max_candidates: usize_to_u64(engine.max_candidates),
1800        max_neighbors_per_function: usize_to_u64(engine.max_neighbors_per_function),
1801        timeout_ms: MAX_RUN_TIMEOUT_MS,
1802    }
1803}
1804
1805fn generation(
1806    provider: &SimilarCodeProviderStatus,
1807    threshold: f64,
1808    min_lines: usize,
1809    scope: SimilarCodeScopeProvenance,
1810) -> SimilarCodeGeneration {
1811    SimilarCodeGeneration {
1812        extraction_semantics_version: SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION,
1813        embedding_semantics_version: similar_code::embedding_semantics_version(),
1814        provider: SimilarCodeProviderProvenance {
1815            provider: SimilarCodeProvider::OfficialLocalCompanion,
1816            companion_version: provider.sidecar_version.clone(),
1817            protocol_version: provider.protocol_version,
1818            source_left_machine: false,
1819        },
1820        model: SimilarCodeModelProvenance {
1821            model_id: provider.model_id.clone(),
1822            revision: provider.model_revision.clone(),
1823            artifact_sha256: similar_code::model_artifact_sha256().to_owned(),
1824            license: provider.license.clone(),
1825            dimensions: u32::try_from(provider.dimensions).unwrap_or(u32::MAX),
1826        },
1827        parameters: SimilarCodeGenerationParameters {
1828            dtype: "f32".to_owned(),
1829            pooling: "mean".to_owned(),
1830            normalized: true,
1831            batch_size: u32::try_from(similar_code::embedding_batch_size()).unwrap_or(u32::MAX),
1832            max_tokens: u32::try_from(provider.max_tokens).unwrap_or(u32::MAX),
1833            parameter_sha256: similar_code::parameter_sha256(),
1834        },
1835        scope,
1836        threshold,
1837        min_lines: usize_to_u64(min_lines),
1838    }
1839}
1840
1841fn raw_enrichment_availability() -> SimilarCodeEnrichmentAvailability {
1842    SimilarCodeEnrichmentAvailability {
1843        graph_relationship: SimilarCodeEnrichmentState::NotRequested,
1844        entry_point_reachability: SimilarCodeEnrichmentState::NotRequested,
1845        callers: SimilarCodeEnrichmentState::NotRequested,
1846        callees: SimilarCodeEnrichmentState::NotRequested,
1847        ownership: SimilarCodeEnrichmentState::NotRequested,
1848        churn: SimilarCodeEnrichmentState::NotRequested,
1849        tests: SimilarCodeEnrichmentState::NotRequested,
1850        deterministic_clone_coverage: SimilarCodeEnrichmentState::NotRequested,
1851        runtime: SimilarCodeEnrichmentState::NotRequested,
1852    }
1853}
1854
1855fn map_extraction_skip(reason: SimilarCodeExtractionSkipReason) -> SimilarCodeSkipReason {
1856    match reason {
1857        SimilarCodeExtractionSkipReason::GeneratedSource => SimilarCodeSkipReason::GeneratedSource,
1858        SimilarCodeExtractionSkipReason::SourceBytesPerFunctionLimit => {
1859            SimilarCodeSkipReason::FunctionTooLarge
1860        }
1861        SimilarCodeExtractionSkipReason::FunctionLimit => SimilarCodeSkipReason::InputLimit,
1862        SimilarCodeExtractionSkipReason::TotalSourceBytesLimit => {
1863            SimilarCodeSkipReason::SourceBytesLimit
1864        }
1865        _ => SimilarCodeSkipReason::UnsupportedFunction,
1866    }
1867}
1868
1869fn map_engine_skip(reason: EngineSkipReason) -> SimilarCodeSkipReason {
1870    match reason {
1871        EngineSkipReason::VectorMemoryLimit => SimilarCodeSkipReason::VectorMemoryLimit,
1872        EngineSkipReason::ComparisonLimit => SimilarCodeSkipReason::ComparisonLimit,
1873        EngineSkipReason::CandidateLimit => SimilarCodeSkipReason::CandidateLimit,
1874        EngineSkipReason::NeighborLimit => SimilarCodeSkipReason::NeighborLimit,
1875        _ => SimilarCodeSkipReason::InputLimit,
1876    }
1877}
1878
1879fn cache_status(disabled: bool, hits: usize, misses: usize) -> SimilarCodeCacheStatus {
1880    if disabled {
1881        SimilarCodeCacheStatus::Disabled
1882    } else if misses == 0 {
1883        SimilarCodeCacheStatus::Hit
1884    } else if hits == 0 {
1885        SimilarCodeCacheStatus::Miss
1886    } else {
1887        SimilarCodeCacheStatus::Mixed
1888    }
1889}
1890
1891fn similarity_band(similarity: f64) -> SimilarCodeSimilarityBand {
1892    if similarity >= VERY_HIGH_SIMILARITY {
1893        SimilarCodeSimilarityBand::VeryHigh
1894    } else if similarity >= HIGH_SIMILARITY {
1895        SimilarCodeSimilarityBand::High
1896    } else {
1897        SimilarCodeSimilarityBand::Moderate
1898    }
1899}
1900
1901fn validate_options(options: &SimilarCodeOptions) -> ProgrammaticResult<()> {
1902    if let Some(threshold) = options.threshold {
1903        validate_threshold(threshold)?;
1904    }
1905    if options.min_lines == Some(0) {
1906        return Err(ProgrammaticError::new("`min_lines` must be at least 1", 2)
1907            .with_code("FALLOW_INVALID_SIMILAR_CODE_MIN_LINES")
1908            .with_context("similarCode.minLines"));
1909    }
1910    if options.top == Some(0) {
1911        return Err(ProgrammaticError::new("`top` must be at least 1", 2)
1912            .with_code("FALLOW_INVALID_SIMILAR_CODE_TOP")
1913            .with_context("similarCode.top"));
1914    }
1915    for path in &options.files {
1916        if path.is_absolute()
1917            || path
1918                .components()
1919                .any(|part| matches!(part, std::path::Component::ParentDir))
1920        {
1921            return Err(ProgrammaticError::new(
1922                "`file` paths must be project-root-relative and must not contain `..`",
1923                2,
1924            )
1925            .with_code("FALLOW_INVALID_SIMILAR_CODE_FILE")
1926            .with_context("similarCode.files"));
1927        }
1928    }
1929    Ok(())
1930}
1931
1932fn validate_threshold(threshold: f64) -> ProgrammaticResult<()> {
1933    if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) {
1934        return Err(
1935            ProgrammaticError::new("`threshold` must be finite and between 0 and 1", 2)
1936                .with_code("FALLOW_INVALID_SIMILAR_CODE_THRESHOLD")
1937                .with_context("similarCode.threshold"),
1938        );
1939    }
1940    Ok(())
1941}
1942
1943#[expect(
1944    clippy::needless_pass_by_value,
1945    reason = "map_err supplies owned provider failures and the mapper consumes that boundary"
1946)]
1947fn provider_error(error: ProviderError) -> ProgrammaticError {
1948    let exit_code = if matches!(error, ProviderError::NotReady(_)) {
1949        3
1950    } else {
1951        2
1952    };
1953    let code = if exit_code == 3 {
1954        "FALLOW_SIMILAR_CODE_NOT_READY"
1955    } else {
1956        "FALLOW_SIMILAR_CODE_PROVIDER_FAILED"
1957    };
1958    ProgrammaticError::new(error.message(), exit_code)
1959        .with_code(code)
1960        .with_context("similarCode.provider")
1961}
1962
1963fn engine_error(error: impl std::fmt::Display) -> ProgrammaticError {
1964    ProgrammaticError::new(format!("invalid similar-code evaluation: {error}"), 2)
1965        .with_code("FALLOW_SIMILAR_CODE_EVALUATION_FAILED")
1966        .with_context("similarCode.evaluation")
1967}
1968
1969fn location_key(
1970    location: &fallow_engine::source::similar_code::SimilarCodeFunctionLocation,
1971) -> (String, u32, u32) {
1972    (
1973        location.file.clone(),
1974        location.start_byte,
1975        location.end_byte,
1976    )
1977}
1978
1979fn root_relative(root: &Path, path: &Path) -> String {
1980    normalize_path(path.strip_prefix(root).unwrap_or(path))
1981}
1982
1983fn normalize_path(path: &Path) -> String {
1984    path.to_string_lossy().replace('\\', "/")
1985}
1986
1987fn add_skip(
1988    skips: &mut BTreeMap<SimilarCodeSkipReason, usize>,
1989    reason: SimilarCodeSkipReason,
1990    count: usize,
1991) {
1992    *skips.entry(reason).or_default() += count;
1993}
1994
1995fn extraction_is_complete(
1996    skips: &BTreeMap<SimilarCodeSkipReason, usize>,
1997    source_read_failures: usize,
1998) -> bool {
1999    source_read_failures == 0
2000        && skips.iter().all(|(reason, count)| {
2001            *count == 0 || matches!(reason, SimilarCodeSkipReason::BelowMinimumLines)
2002        })
2003}
2004
2005const fn remaining_extraction_inputs(total: usize, current_index: usize) -> usize {
2006    total.saturating_sub(current_index)
2007}
2008
2009const fn exhausted_extraction_limit(
2010    remaining_functions: usize,
2011    remaining_source_bytes: usize,
2012) -> Option<SimilarCodeSkipReason> {
2013    if remaining_functions == 0 {
2014        Some(SimilarCodeSkipReason::InputLimit)
2015    } else if remaining_source_bytes == 0 {
2016        Some(SimilarCodeSkipReason::SourceBytesLimit)
2017    } else {
2018        None
2019    }
2020}
2021
2022fn hex(bytes: &[u8]) -> String {
2023    bytes.iter().fold(
2024        String::with_capacity(bytes.len().saturating_mul(2)),
2025        |mut output, byte| {
2026            let _ = write!(output, "{byte:02x}");
2027            output
2028        },
2029    )
2030}
2031
2032fn duration_ms(started: Instant) -> u64 {
2033    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
2034}
2035
2036fn usize_to_u64(value: usize) -> u64 {
2037    u64::try_from(value).unwrap_or(u64::MAX)
2038}
2039
2040#[cfg(test)]
2041#[expect(
2042    clippy::unwrap_used,
2043    reason = "deterministic fixtures fail immediately"
2044)]
2045mod tests {
2046    use super::*;
2047    use std::sync::{Arc, Mutex};
2048    use std::time::Duration;
2049
2050    use crate::similar_code::{
2051        EmbeddingBatch, EmbeddingBatchVector, EmbeddingSession, EmbeddingSessionFactory,
2052    };
2053
2054    #[test]
2055    fn ignore_glob_single_star_stays_within_one_segment() {
2056        let set = build_ignore_set(&["src/*.ts".to_string()]).unwrap();
2057        assert!(set.is_match("src/a.ts"));
2058        assert!(!set.is_match("src/nested/a.ts"));
2059    }
2060
2061    #[derive(Default)]
2062    struct FakeProviderState {
2063        spawns: usize,
2064        batches: usize,
2065        complete_batches: Option<usize>,
2066    }
2067
2068    struct FakeEmbeddingSession {
2069        state: Arc<Mutex<FakeProviderState>>,
2070        dimensions: usize,
2071    }
2072
2073    impl EmbeddingSession for FakeEmbeddingSession {
2074        #[expect(
2075            clippy::unwrap_in_result,
2076            reason = "test helper: a panic fails the test"
2077        )]
2078        fn embed(&mut self, functions: &[(u32, &str)]) -> Result<EmbeddingBatch, String> {
2079            let should_return_partial = {
2080                let mut state = self.state.lock().unwrap();
2081                state.batches += 1;
2082                state
2083                    .complete_batches
2084                    .is_some_and(|limit| state.batches > limit)
2085            };
2086            if should_return_partial {
2087                return Ok(EmbeddingBatch {
2088                    vectors: Vec::new(),
2089                    inference_ms: 0.0,
2090                    problem: Some("fixture provider returned a bounded partial batch".to_owned()),
2091                });
2092            }
2093            let vectors = functions
2094                .iter()
2095                .map(|(key, _)| {
2096                    let mut values = vec![0.0; self.dimensions];
2097                    values[0] = 1.0;
2098                    EmbeddingBatchVector {
2099                        key: *key,
2100                        values,
2101                        truncated: false,
2102                    }
2103                })
2104                .collect();
2105            Ok(EmbeddingBatch {
2106                vectors,
2107                inference_ms: 0.25,
2108                problem: None,
2109            })
2110        }
2111    }
2112
2113    struct FakeEmbeddingFactory {
2114        state: Arc<Mutex<FakeProviderState>>,
2115        dimensions: usize,
2116    }
2117
2118    impl EmbeddingSessionFactory for FakeEmbeddingFactory {
2119        #[expect(
2120            clippy::unwrap_in_result,
2121            reason = "test helper: a panic fails the test"
2122        )]
2123        fn spawn(&mut self) -> Result<Box<dyn EmbeddingSession>, String> {
2124            self.state.lock().unwrap().spawns += 1;
2125            Ok(Box::new(FakeEmbeddingSession {
2126                state: Arc::clone(&self.state),
2127                dimensions: self.dimensions,
2128            }))
2129        }
2130    }
2131
2132    struct FixtureEmbedder {
2133        provider_cache_dir: PathBuf,
2134        run_timeout: Duration,
2135        factory: FakeEmbeddingFactory,
2136    }
2137
2138    impl RuntimeEmbedder for FixtureEmbedder {
2139        fn embed(
2140            &mut self,
2141            project_root: &Path,
2142            no_cache: bool,
2143            inputs: &[EmbeddingInput<'_>],
2144        ) -> Result<EmbeddingResult, ProviderError> {
2145            similar_code::embed_selected_with_factory(
2146                &self.provider_cache_dir,
2147                project_root,
2148                no_cache,
2149                inputs,
2150                self.run_timeout,
2151                &mut self.factory,
2152            )
2153        }
2154    }
2155
2156    fn similar_code_fixture() -> (tempfile::TempDir, PathBuf, SimilarCodeProviderStatus) {
2157        let temp = tempfile::tempdir().unwrap();
2158        let project = temp.path().join("project");
2159        let cache_root = temp.path().join("user-cache");
2160        let provider_cache_dir = cache_root.join("models").join("fixture-model");
2161        std::fs::create_dir_all(project.join("src")).unwrap();
2162        std::fs::create_dir_all(&cache_root).unwrap();
2163        std::fs::write(
2164            project.join("package.json"),
2165            r#"{"name":"similar-code-runtime-fixture","private":true}"#,
2166        )
2167        .unwrap();
2168        for (name, value) in [("a", 1), ("b", 2), ("c", 3)] {
2169            std::fs::write(
2170                project.join("src").join(format!("{name}.ts")),
2171                format!(
2172                    "export function {name}(input: number) {{\n  const adjusted = input + {value};\n  return adjusted * 2;\n}}\n"
2173                ),
2174            )
2175            .unwrap();
2176        }
2177        let (model_id, model_revision, dimensions, license) = similar_code::provider_identity();
2178        let status = SimilarCodeProviderStatus {
2179            protocol_version: 2,
2180            embedding_semantics_version: similar_code::embedding_semantics_version(),
2181            sidecar_version: env!("CARGO_PKG_VERSION").to_owned(),
2182            model_ready: true,
2183            model_id: model_id.to_owned(),
2184            model_revision: model_revision.to_owned(),
2185            dimensions,
2186            max_tokens: 512,
2187            license: license.to_owned(),
2188            cache_dir: provider_cache_dir.to_string_lossy().into_owned(),
2189            download_bytes: similar_code::model_download_bytes(),
2190            analysis_offline: true,
2191            integrity_verified: true,
2192            problem: None,
2193            downloaded: None,
2194        };
2195        (temp, project, status)
2196    }
2197
2198    fn fixture_options(project: &Path) -> SimilarCodeOptions {
2199        SimilarCodeOptions {
2200            analysis: crate::AnalysisOptions {
2201                root: Some(project.to_path_buf()),
2202                ..crate::AnalysisOptions::default()
2203            },
2204            threshold: Some(0.9),
2205            min_lines: Some(2),
2206            ..SimilarCodeOptions::default()
2207        }
2208    }
2209
2210    fn run_with_fixture(
2211        options: &SimilarCodeOptions,
2212        status: &SimilarCodeProviderStatus,
2213        embedder: &mut FixtureEmbedder,
2214    ) -> ProgrammaticResult<SimilarCodeOutput> {
2215        let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
2216        resolved
2217            .install(|| run_similar_code_inner_with_embedder(options, &resolved, status, embedder))
2218    }
2219
2220    fn find_cache_file(root: &Path) -> Option<PathBuf> {
2221        for entry in std::fs::read_dir(root).ok()? {
2222            let path = entry.ok()?.path();
2223            if path.file_name().is_some_and(|name| name == "vectors.bin") {
2224                return Some(path);
2225            }
2226            if path.is_dir()
2227                && let Some(found) = find_cache_file(&path)
2228            {
2229                return Some(found);
2230            }
2231        }
2232        None
2233    }
2234
2235    #[test]
2236    fn similar_code_runtime_covers_cold_warm_corrupt_cache_scope_and_output_contract() {
2237        let (_temp, project, status) = similar_code_fixture();
2238        let provider_cache_dir = PathBuf::from(&status.cache_dir);
2239        let state = Arc::new(Mutex::new(FakeProviderState::default()));
2240        let mut embedder = FixtureEmbedder {
2241            provider_cache_dir: provider_cache_dir.clone(),
2242            run_timeout: Duration::from_secs(5),
2243            factory: FakeEmbeddingFactory {
2244                state: Arc::clone(&state),
2245                dimensions: status.dimensions,
2246            },
2247        };
2248        let mut options = fixture_options(&project);
2249        options.files = vec![PathBuf::from("src/a.ts")];
2250
2251        let cold = run_with_fixture(&options, &status, &mut embedder).unwrap();
2252        assert!(!cold.candidates.is_empty());
2253        assert!(cold.candidates.iter().all(|candidate| {
2254            candidate.left.path == "src/a.ts" || candidate.right.path == "src/a.ts"
2255        }));
2256        assert_eq!(
2257            cold.completion.status,
2258            SimilarCodeCompletionStatus::Complete
2259        );
2260        assert!(cold.completion.cache.misses > 0);
2261        assert!(cold.completion.cache.writes > 0);
2262        let cold_spawns = state.lock().unwrap().spawns;
2263        let cold_ids = cold
2264            .candidates
2265            .iter()
2266            .map(|candidate| candidate.candidate_id.clone())
2267            .collect::<Vec<_>>();
2268        let json = serde_json::to_value(&cold).unwrap();
2269        assert_eq!(json["generation"]["embedding_semantics_version"], 2);
2270        assert_eq!(json["generation"]["provider"]["source_left_machine"], false);
2271        assert_eq!(json["generation"]["scope"]["active"], true);
2272        assert_eq!(
2273            json["generation"]["scope"]["paths"],
2274            serde_json::json!(["src/a.ts"])
2275        );
2276        assert!(json["completion"]["cache"].is_object());
2277
2278        let warm = run_with_fixture(&options, &status, &mut embedder).unwrap();
2279        assert_eq!(state.lock().unwrap().spawns, cold_spawns);
2280        assert!(warm.completion.cache.hits > 0);
2281        assert_eq!(warm.completion.cache.writes, 0);
2282        assert_eq!(
2283            warm.candidates
2284                .iter()
2285                .map(|candidate| candidate.candidate_id.clone())
2286                .collect::<Vec<_>>(),
2287            cold_ids
2288        );
2289
2290        let cache_root = provider_cache_dir.parent().and_then(Path::parent).unwrap();
2291        let cache_file = find_cache_file(cache_root).unwrap();
2292        std::fs::write(&cache_file, b"corrupt cache fixture").unwrap();
2293        let recovered = run_with_fixture(&options, &status, &mut embedder).unwrap();
2294        assert_eq!(recovered.completion.cache.invalid_entries, 1);
2295        assert!(recovered.completion.cache.writes > 0);
2296        assert!(state.lock().unwrap().spawns > cold_spawns);
2297    }
2298
2299    #[test]
2300    fn snapshot_inspect_survives_ranking_crowd_out_and_rejects_stale_source() {
2301        let (_temp, project, status) = similar_code_fixture();
2302        let state = Arc::new(Mutex::new(FakeProviderState::default()));
2303        let mut embedder = FixtureEmbedder {
2304            provider_cache_dir: PathBuf::from(&status.cache_dir),
2305            run_timeout: Duration::from_secs(5),
2306            factory: FakeEmbeddingFactory {
2307                state,
2308                dimensions: status.dimensions,
2309            },
2310        };
2311        let discovery =
2312            run_with_fixture(&fixture_options(&project), &status, &mut embedder).unwrap();
2313        let candidate_id = discovery.candidates.last().unwrap().candidate_id.clone();
2314        let tagged = fallow_output::serialize_similar_code_json_output(discovery).unwrap();
2315        let snapshot = select_similar_code_candidate_snapshot(
2316            &serde_json::to_vec(&tagged).unwrap(),
2317            &candidate_id,
2318        )
2319        .unwrap();
2320
2321        let mut legacy_options = fixture_options(&project);
2322        legacy_options.files = vec![
2323            PathBuf::from(&snapshot.candidate.left.path),
2324            PathBuf::from(&snapshot.candidate.right.path),
2325        ];
2326        legacy_options.top = Some(1);
2327        let endpoint_reranked = run_with_fixture(&legacy_options, &status, &mut embedder).unwrap();
2328        assert_eq!(endpoint_reranked.candidates.len(), 1);
2329        assert!(
2330            endpoint_reranked
2331                .candidates
2332                .iter()
2333                .all(|candidate| candidate.candidate_id != candidate_id),
2334            "the endpoint-only legacy rerank must reproduce the crowd-out condition"
2335        );
2336
2337        let inspect_options = SimilarCodeInspectOptions {
2338            analysis: crate::AnalysisOptions {
2339                root: Some(project.clone()),
2340                ..crate::AnalysisOptions::default()
2341            },
2342            snapshot: snapshot.clone(),
2343        };
2344        let inspected = inspect_similar_code(&inspect_options).unwrap();
2345        assert_eq!(inspected.candidate.candidate_id, candidate_id);
2346
2347        let stale_path = project.join(&snapshot.candidate.left.path);
2348        let stale_source = std::fs::read_to_string(&stale_path).unwrap();
2349        std::fs::write(
2350            &stale_path,
2351            stale_source.replace("return adjusted * 2", "return adjusted * 3"),
2352        )
2353        .unwrap();
2354        let error = inspect_similar_code(&inspect_options).unwrap_err();
2355        assert_eq!(
2356            error.code.as_deref(),
2357            Some("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
2358        );
2359    }
2360
2361    #[test]
2362    fn snapshot_inspect_rejects_oversized_endpoint_before_source_allocation() {
2363        let temp = tempfile::tempdir().unwrap();
2364        let project = dunce::canonicalize(temp.path()).unwrap();
2365        let source_path = project.join("src/endpoint.ts");
2366        std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
2367        std::fs::write(
2368            &source_path,
2369            "export function candidate() {\n  return true;\n}\n",
2370        )
2371        .unwrap();
2372        std::fs::OpenOptions::new()
2373            .write(true)
2374            .open(&source_path)
2375            .unwrap()
2376            .set_len(MAX_INSPECT_SOURCE_BYTES + 1)
2377            .unwrap();
2378
2379        let error = inspect_side(&project, &location("src/endpoint.ts", 1, 3)).unwrap_err();
2380        assert_eq!(
2381            error.code.as_deref(),
2382            Some("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
2383        );
2384        assert!(error.message.contains("5 MiB per-file limit"));
2385    }
2386
2387    #[test]
2388    fn snapshot_inspect_does_not_rebind_an_identical_same_line_function() {
2389        let temp = tempfile::tempdir().unwrap();
2390        let project = dunce::canonicalize(temp.path()).unwrap();
2391        let relative = Path::new("src/duplicates.js");
2392        let source_path = project.join(relative);
2393        std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
2394        let function = "function duplicate() { return 1; }";
2395        let original = format!("{function} {function}\n");
2396        std::fs::write(&source_path, &original).unwrap();
2397
2398        let extracted = fallow_engine::source::similar_code::extract(
2399            relative,
2400            &original,
2401            SimilarCodeExtractionLimits::default(),
2402        );
2403        assert_eq!(extracted.functions.len(), 2);
2404        let snapshot = output_location(&extracted.functions[0]);
2405        assert_eq!(
2406            snapshot.source_sha256,
2407            output_location(&extracted.functions[1]).source_sha256
2408        );
2409        assert_ne!(
2410            snapshot.start_column,
2411            output_location(&extracted.functions[1]).start_column
2412        );
2413
2414        let second_start = function.len() + 1;
2415        std::fs::write(
2416            &source_path,
2417            format!("{}{function}\n", " ".repeat(second_start)),
2418        )
2419        .unwrap();
2420
2421        let error = inspect_side(&project, &snapshot).unwrap_err();
2422        assert_eq!(
2423            error.code.as_deref(),
2424            Some("FALLOW_SIMILAR_CODE_CANDIDATE_STALE")
2425        );
2426    }
2427
2428    #[test]
2429    fn similar_code_runtime_reports_partial_provider_output_and_bounded_timeout() {
2430        let (_temp, project, status) = similar_code_fixture();
2431        let provider_cache_dir = PathBuf::from(&status.cache_dir);
2432        let partial_state = Arc::new(Mutex::new(FakeProviderState {
2433            complete_batches: Some(2),
2434            ..FakeProviderState::default()
2435        }));
2436        let mut partial_embedder = FixtureEmbedder {
2437            provider_cache_dir: provider_cache_dir.clone(),
2438            run_timeout: Duration::from_secs(5),
2439            factory: FakeEmbeddingFactory {
2440                state: partial_state,
2441                dimensions: status.dimensions,
2442            },
2443        };
2444        let mut options = fixture_options(&project);
2445        options.analysis.no_cache = true;
2446
2447        let partial = run_with_fixture(&options, &status, &mut partial_embedder).unwrap();
2448        assert_eq!(
2449            partial.completion.status,
2450            SimilarCodeCompletionStatus::Partial
2451        );
2452        assert!(partial.completion.skips.iter().any(|skip| {
2453            skip.phase == SimilarCodePhase::Embedding
2454                && skip.reason == SimilarCodeSkipReason::ProviderFailure
2455        }));
2456        assert!(
2457            partial
2458                .diagnostics
2459                .iter()
2460                .any(|diagnostic| { diagnostic.code == "FALLOW_SIMILAR_CODE_PROVIDER_PARTIAL" })
2461        );
2462
2463        let timeout_state = Arc::new(Mutex::new(FakeProviderState::default()));
2464        let mut timeout_embedder = FixtureEmbedder {
2465            provider_cache_dir,
2466            run_timeout: Duration::ZERO,
2467            factory: FakeEmbeddingFactory {
2468                state: Arc::clone(&timeout_state),
2469                dimensions: status.dimensions,
2470            },
2471        };
2472        let error = run_with_fixture(&options, &status, &mut timeout_embedder).unwrap_err();
2473        assert_eq!(
2474            error.code.as_deref(),
2475            Some("FALLOW_SIMILAR_CODE_PROVIDER_FAILED")
2476        );
2477        assert_eq!(timeout_state.lock().unwrap().spawns, 0);
2478    }
2479
2480    fn location(path: &str, start_line: u32, end_line: u32) -> SimilarCodeLocation {
2481        SimilarCodeLocation {
2482            path: path.to_owned(),
2483            name: "candidate".to_owned(),
2484            start_line,
2485            start_column: 1,
2486            end_line,
2487            end_column: 1,
2488            source_sha256: "00".repeat(32),
2489        }
2490    }
2491
2492    fn file_trace(imports_from: &[&str], imported_by: &[&str]) -> fallow_engine::trace::FileTrace {
2493        fallow_engine::trace::FileTrace {
2494            file: PathBuf::from("src/current.ts"),
2495            is_reachable: true,
2496            is_entry_point: false,
2497            exports: Vec::new(),
2498            imports_from: imports_from.iter().map(PathBuf::from).collect(),
2499            imported_by: imported_by.iter().map(PathBuf::from).collect(),
2500            re_exports: Vec::new(),
2501            ..Default::default()
2502        }
2503    }
2504
2505    fn side_evidence() -> SimilarCodeSideEvidence {
2506        SimilarCodeSideEvidence {
2507            source_window: None,
2508            parameter_count: None,
2509            is_async: None,
2510            is_generator: None,
2511            has_await: None,
2512            has_throw: None,
2513            side_effect_hint: None,
2514            entry_point_reachable: None,
2515            callers: Vec::new(),
2516            callees: Vec::new(),
2517            owners: Vec::new(),
2518            churn_commits: None,
2519            tests: Vec::new(),
2520            deterministic_clone_coverage: None,
2521            runtime_observations: None,
2522        }
2523    }
2524
2525    #[test]
2526    fn similar_code_phase_statuses_identify_only_the_incomplete_phase() {
2527        let phases = phases(
2528            5,
2529            5,
2530            3,
2531            3,
2532            3,
2533            3,
2534            PhaseCompleteness {
2535                discovery: true,
2536                extraction: false,
2537                embedding: true,
2538                comparison: true,
2539            },
2540            0,
2541            0,
2542            0,
2543        );
2544
2545        assert_eq!(phases[0].status, SimilarCodePhaseStatus::Complete);
2546        assert_eq!(phases[1].status, SimilarCodePhaseStatus::Partial);
2547        assert!(phases[1].reason.is_some());
2548        assert_eq!(phases[3].status, SimilarCodePhaseStatus::Complete);
2549        assert_eq!(phases[4].status, SimilarCodePhaseStatus::Complete);
2550        assert_eq!(phases[5].status, SimilarCodePhaseStatus::Complete);
2551    }
2552
2553    #[test]
2554    fn similar_code_extraction_completion_counts_limits_and_read_failures_honestly() {
2555        let mut skips = BTreeMap::from([(SimilarCodeSkipReason::BelowMinimumLines, 2)]);
2556        assert!(extraction_is_complete(&skips, 0));
2557        assert!(!extraction_is_complete(&skips, 1));
2558
2559        skips.insert(SimilarCodeSkipReason::InputLimit, 3);
2560        assert!(!extraction_is_complete(&skips, 0));
2561        assert_eq!(remaining_extraction_inputs(7, 3), 4);
2562    }
2563
2564    #[test]
2565    fn similar_code_exhausted_extraction_budget_uses_the_specific_skip_reason() {
2566        assert_eq!(
2567            exhausted_extraction_limit(0, 1),
2568            Some(SimilarCodeSkipReason::InputLimit)
2569        );
2570        assert_eq!(
2571            exhausted_extraction_limit(1, 0),
2572            Some(SimilarCodeSkipReason::SourceBytesLimit)
2573        );
2574        assert_eq!(exhausted_extraction_limit(1, 1), None);
2575    }
2576
2577    #[test]
2578    fn similar_code_scope_requires_one_endpoint_to_match_every_active_filter() {
2579        let root = tempfile::tempdir().unwrap();
2580        let resolved = resolve_programmatic_analysis_context(&crate::AnalysisOptions {
2581            root: Some(root.path().to_path_buf()),
2582            ..crate::AnalysisOptions::default()
2583        })
2584        .unwrap();
2585        let options = SimilarCodeOptions {
2586            files: vec![PathBuf::from("src/file-scoped.ts")],
2587            ..SimilarCodeOptions::default()
2588        };
2589        let changed = FxHashSet::from_iter([PathBuf::from("src/changed.ts")]);
2590
2591        assert!(similar_code_scope_active(
2592            &options,
2593            &resolved,
2594            Some(&changed),
2595            None,
2596        ));
2597        assert!(!similar_code_path_in_scope(
2598            "src/file-scoped.ts",
2599            &options,
2600            &resolved,
2601            Some(&changed),
2602            None,
2603        ));
2604        assert!(!similar_code_path_in_scope(
2605            "src/changed.ts",
2606            &options,
2607            &resolved,
2608            Some(&changed),
2609            None,
2610        ));
2611
2612        let changed = FxHashSet::from_iter([PathBuf::from("src/file-scoped.ts")]);
2613        assert!(similar_code_path_in_scope(
2614            "src/file-scoped.ts",
2615            &options,
2616            &resolved,
2617            Some(&changed),
2618            None,
2619        ));
2620    }
2621
2622    #[test]
2623    fn similar_code_module_references_are_sorted_deduplicated_and_bounded() {
2624        let paths = vec![
2625            PathBuf::from("src/z.ts"),
2626            PathBuf::from("src/a.ts"),
2627            PathBuf::from("src/a.ts"),
2628        ];
2629
2630        let (references, truncated) = bounded_module_references(&paths, 1);
2631
2632        assert!(truncated);
2633        assert_eq!(references.len(), 1);
2634        assert_eq!(references[0].path, "src/a.ts");
2635        assert_eq!(references[0].name, MODULE_REFERENCE_NAME);
2636        assert_eq!(references[0].line, 1);
2637    }
2638
2639    #[test]
2640    fn similar_code_related_tests_are_transitive_path_filtered_and_bounded() {
2641        let paths = vec![
2642            "src/helper.ts".to_owned(),
2643            "tests/z.spec.ts".to_owned(),
2644            "src/a.test.ts".to_owned(),
2645            "src/a.test.ts".to_owned(),
2646        ];
2647
2648        let (tests, truncated) = bounded_related_tests(Path::new("/project"), &paths, 1);
2649
2650        assert!(truncated);
2651        assert_eq!(tests, vec!["src/a.test.ts"]);
2652    }
2653
2654    #[test]
2655    fn similar_code_related_tests_leave_out_test_support_files() {
2656        let paths = vec![
2657            "src/__mocks__/api.ts".to_owned(),
2658            "src/__fixtures__/user.ts".to_owned(),
2659            "src/__snapshots__/api.ts.snap".to_owned(),
2660            "src/user.fixture.ts".to_owned(),
2661            "src/api.test.ts".to_owned(),
2662        ];
2663
2664        let (tests, truncated) = bounded_related_tests(Path::new("/project"), &paths, 10);
2665
2666        assert!(!truncated);
2667        assert_eq!(tests, vec!["src/api.test.ts"]);
2668    }
2669
2670    #[test]
2671    fn similar_code_module_relationship_uses_direct_edges_then_shared_importers() {
2672        let left_location = location("src/left.ts", 1, 3);
2673        let right_location = location("src/right.ts", 1, 3);
2674        let left = file_trace(&["src/right.ts"], &["src/shared.ts"]);
2675        let right = file_trace(&[], &["src/shared.ts"]);
2676
2677        assert_eq!(
2678            module_relationship(&left, &right, &left_location, &right_location),
2679            "left-directly-imports-right"
2680        );
2681
2682        let left = file_trace(&[], &["src/shared.ts"]);
2683        assert_eq!(
2684            module_relationship(&left, &right, &left_location, &right_location),
2685            "shared-direct-importer"
2686        );
2687    }
2688
2689    #[test]
2690    fn similar_code_primary_owner_uses_the_codeowners_winning_rule() {
2691        let codeowners = CodeOwners::parse("/src/* @team/base\n/src/special.ts @team/special")
2692            .expect("CODEOWNERS parses");
2693
2694        assert_eq!(
2695            primary_owner(&codeowners, "src/special.ts"),
2696            vec!["@team/special"]
2697        );
2698        assert!(primary_owner(&codeowners, "test/a.ts").is_empty());
2699    }
2700
2701    #[test]
2702    fn similar_code_churn_lookup_normalizes_path_separators_and_defaults_to_zero() {
2703        let mut files = FxHashMap::default();
2704        files.insert(
2705            PathBuf::from("C:/repo/src/a.ts"),
2706            fallow_engine::churn::FileChurn {
2707                path: PathBuf::from("C:/repo/src/a.ts"),
2708                commits: 7,
2709                weighted_commits: 0.0,
2710                lines_added: 0,
2711                lines_deleted: 0,
2712                trend: fallow_engine::churn::ChurnTrend::Stable,
2713                authors: FxHashMap::default(),
2714            },
2715        );
2716        let churn = fallow_engine::churn::ChurnResult {
2717            files,
2718            shallow_clone: false,
2719            author_pool: Vec::new(),
2720            clock: fallow_engine::clock::AnalysisClock::pinned(1_788_782_400),
2721            git_log_bytes: 0,
2722            commits: Vec::new(),
2723        };
2724
2725        assert_eq!(churn_commits_for(&churn, Path::new(r"C:\repo\src\a.ts")), 7);
2726        assert_eq!(churn_commits_for(&churn, Path::new("src/missing.ts")), 0);
2727    }
2728
2729    #[test]
2730    fn similar_code_clone_coverage_counts_unique_exact_lines_only() {
2731        let root = Path::new("/repo");
2732        let exact = fallow_engine::duplicates::CloneGroup {
2733            instances: vec![
2734                clone_instance("/repo/src/a.ts", 2, 4),
2735                clone_instance("/repo/src/a.ts", 4, 6),
2736            ],
2737            token_count: 10,
2738            line_count: 3,
2739            similarity: None,
2740        };
2741        let near = fallow_engine::duplicates::CloneGroup {
2742            instances: vec![clone_instance("/repo/src/a.ts", 7, 9)],
2743            token_count: 10,
2744            line_count: 3,
2745            similarity: Some(0.9),
2746        };
2747        let report = fallow_engine::duplicates::DuplicationReport {
2748            clone_groups: vec![exact, near],
2749            ..fallow_engine::duplicates::DuplicationReport::default()
2750        };
2751
2752        assert_eq!(
2753            deterministic_clone_coverage(&report, root, &location("src/a.ts", 1, 10)),
2754            0.5
2755        );
2756    }
2757
2758    #[test]
2759    fn similar_code_project_artifacts_enrich_both_sides_deterministically() {
2760        let project = tempfile::tempdir().expect("temporary project");
2761        let root = project.path();
2762        std::fs::create_dir_all(root.join("src")).expect("source directory");
2763        std::fs::create_dir_all(root.join("tests")).expect("test directory");
2764        std::fs::write(
2765            root.join("package.json"),
2766            r#"{"name":"inspect-enrichment","main":"src/index.ts"}"#,
2767        )
2768        .expect("package manifest");
2769        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";
2770        std::fs::write(root.join("src/left.ts"), repeated).expect("left source");
2771        std::fs::write(root.join("src/right.ts"), repeated).expect("right source");
2772        std::fs::write(
2773            root.join("src/index.ts"),
2774            "import { candidate as left } from './left';\nimport { candidate as right } from './right';\nconsole.log(left([1]), right([2]));\n",
2775        )
2776        .expect("entry source");
2777        std::fs::write(
2778            root.join("tests/left.test.ts"),
2779            "import { candidate } from '../src/left';\ntest('candidate', () => expect(candidate([1])).toBeTruthy());\n",
2780        )
2781        .expect("test source");
2782
2783        let session = AnalysisSession::load_with_config(root, None, |config| {
2784            config.duplicates.min_tokens = 5;
2785            config.duplicates.min_lines = 2;
2786        })
2787        .expect("analysis session");
2788        let left_location = location("src/left.ts", 1, 6);
2789        let right_location = location("src/right.ts", 1, 6);
2790        let mut left = side_evidence();
2791        let mut right = side_evidence();
2792        let mut result = InspectEnrichment {
2793            availability: unavailable_inspect_enrichment(),
2794            graph_relationship: None,
2795            diagnostics: Vec::new(),
2796        };
2797
2798        enrich_graph_and_clones(
2799            &session,
2800            &left_location,
2801            &right_location,
2802            &mut left,
2803            &mut right,
2804            &mut result,
2805        );
2806
2807        assert_eq!(
2808            result.graph_relationship.as_deref(),
2809            Some("shared-direct-importer")
2810        );
2811        assert_eq!(
2812            result.availability.entry_point_reachability,
2813            SimilarCodeEnrichmentState::Available
2814        );
2815        assert_eq!(left.entry_point_reachable, Some(true));
2816        assert!(
2817            left.callers
2818                .iter()
2819                .any(|reference| reference.path == "src/index.ts")
2820        );
2821        assert_eq!(left.tests, vec!["tests/left.test.ts"]);
2822        assert!(
2823            left.deterministic_clone_coverage
2824                .is_some_and(|value| value > 0.0)
2825        );
2826        assert!(
2827            right
2828                .deterministic_clone_coverage
2829                .is_some_and(|value| value > 0.0)
2830        );
2831    }
2832
2833    fn clone_instance(
2834        file: &str,
2835        start_line: usize,
2836        end_line: usize,
2837    ) -> fallow_engine::duplicates::CloneInstance {
2838        fallow_engine::duplicates::CloneInstance {
2839            is_symlink: false,
2840            file: PathBuf::from(file),
2841            start_line,
2842            end_line,
2843            start_col: 0,
2844            end_col: 0,
2845            fragment: String::new(),
2846        }
2847    }
2848
2849    fn shared_review_key_candidates() -> (Vec<u8>, Vec<SimilarCodeCandidate>) {
2850        let (_temp, project, status) = similar_code_fixture();
2851        std::fs::copy(project.join("src/a.ts"), project.join("src/d.ts")).unwrap();
2852        let mut embedder = FixtureEmbedder {
2853            provider_cache_dir: PathBuf::from(&status.cache_dir),
2854            run_timeout: Duration::from_secs(5),
2855            factory: FakeEmbeddingFactory {
2856                state: Arc::new(Mutex::new(FakeProviderState::default())),
2857                dimensions: status.dimensions,
2858            },
2859        };
2860        let output = run_with_fixture(&fixture_options(&project), &status, &mut embedder).unwrap();
2861        let mut document = serde_json::to_value(&output).unwrap();
2862        document["kind"] = Value::from("similar-code");
2863        (serde_json::to_vec(&document).unwrap(), output.candidates)
2864    }
2865
2866    fn abstaining_verdict(candidate_id: &str, review_key: &str) -> Value {
2867        serde_json::json!({
2868            "candidate_id": candidate_id,
2869            "review_key": review_key,
2870            "candidate_worthy": null,
2871            "behaviorally_equivalent": null,
2872            "refactor_safe": null,
2873            "outcome": "needs-human-review",
2874            "rationale": "Evidence is incomplete."
2875        })
2876    }
2877
2878    fn verdict_document(verdicts: &[Value]) -> Vec<u8> {
2879        serde_json::to_vec(&serde_json::json!({
2880            "schema_version": "1",
2881            "verdicts": verdicts,
2882        }))
2883        .unwrap()
2884    }
2885
2886    /// Returns the shared review key and the candidates that carry it.
2887    fn shared_key_group(
2888        candidates: &[SimilarCodeCandidate],
2889    ) -> (String, Vec<&SimilarCodeCandidate>) {
2890        let mut groups: BTreeMap<&str, Vec<&SimilarCodeCandidate>> = BTreeMap::new();
2891        for candidate in candidates {
2892            groups
2893                .entry(candidate.review_key.as_str())
2894                .or_default()
2895                .push(candidate);
2896        }
2897        let (key, group) = groups
2898            .into_iter()
2899            .find(|(_, group)| group.len() > 1)
2900            .expect("a copied function gives two candidates with one review_key");
2901        (key.to_owned(), group)
2902    }
2903
2904    #[test]
2905    fn review_accepts_candidate_id_verdicts_that_share_a_review_key() {
2906        let (candidate_json, candidates) = shared_review_key_candidates();
2907        shared_key_group(&candidates);
2908        let verdicts = verdict_document(
2909            &candidates
2910                .iter()
2911                .map(|candidate| abstaining_verdict(&candidate.candidate_id, &candidate.review_key))
2912                .collect::<Vec<_>>(),
2913        );
2914
2915        let reviewed = review_similar_code(&candidate_json, &verdicts, true).unwrap();
2916
2917        assert_eq!(reviewed.candidates.len(), candidates.len());
2918        assert!(reviewed.candidates.iter().all(|reviewed| {
2919            reviewed.verdict.is_some()
2920                && reviewed.verdict_match == SimilarCodeVerdictMatch::CandidateId
2921        }));
2922    }
2923
2924    #[test]
2925    fn review_does_not_apply_a_review_key_verdict_that_matches_several_candidates() {
2926        let (candidate_json, candidates) = shared_review_key_candidates();
2927        let (key, group) = shared_key_group(&candidates);
2928        let verdicts = verdict_document(&[abstaining_verdict("sc_stale", &key)]);
2929
2930        let reviewed = review_similar_code(&candidate_json, &verdicts, false).unwrap();
2931        assert!(
2932            reviewed.diagnostics.iter().any(|diagnostic| {
2933                diagnostic.code == "FALLOW_SIMILAR_CODE_REVIEW_KEY_AMBIGUOUS"
2934            })
2935        );
2936        for candidate in &group {
2937            let joined = reviewed
2938                .candidates
2939                .iter()
2940                .find(|reviewed| reviewed.candidate.candidate_id == candidate.candidate_id)
2941                .unwrap();
2942            assert!(joined.verdict.is_none());
2943            assert_eq!(
2944                joined.verdict_match,
2945                SimilarCodeVerdictMatch::AmbiguousReviewKey
2946            );
2947        }
2948
2949        let error = review_similar_code(&candidate_json, &verdicts, true).unwrap_err();
2950        assert_eq!(error.message, "a verdict is required for every candidate");
2951    }
2952
2953    #[test]
2954    fn review_keeps_candidate_id_matches_next_to_an_ambiguous_review_key_verdict() {
2955        let (candidate_json, candidates) = shared_review_key_candidates();
2956        let (key, group) = shared_key_group(&candidates);
2957        let first = group[0];
2958        for verdicts in [
2959            vec![
2960                abstaining_verdict(&first.candidate_id, &key),
2961                abstaining_verdict("sc_stale", &key),
2962            ],
2963            vec![
2964                abstaining_verdict("sc_stale", &key),
2965                abstaining_verdict(&first.candidate_id, &key),
2966            ],
2967        ] {
2968            let reviewed =
2969                review_similar_code(&candidate_json, &verdict_document(&verdicts), false).unwrap();
2970            let joined = reviewed
2971                .candidates
2972                .iter()
2973                .find(|reviewed| reviewed.candidate.candidate_id == first.candidate_id)
2974                .unwrap();
2975            assert!(joined.verdict.is_some());
2976            assert_eq!(joined.verdict_match, SimilarCodeVerdictMatch::CandidateId);
2977        }
2978    }
2979
2980    #[test]
2981    fn review_rejects_repeated_identities_that_do_not_identify_one_candidate() {
2982        let (candidate_json, candidates) = shared_review_key_candidates();
2983        let (key, _) = shared_key_group(&candidates);
2984        let unique = candidates
2985            .iter()
2986            .find(|candidate| {
2987                candidates
2988                    .iter()
2989                    .filter(|other| other.review_key == candidate.review_key)
2990                    .count()
2991                    == 1
2992            })
2993            .expect("the fixture has a candidate with a unique review_key");
2994        let cases = [
2995            (
2996                vec![
2997                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
2998                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
2999                ],
3000                "verdict document contains duplicate candidate or review identities",
3001            ),
3002            (
3003                vec![
3004                    abstaining_verdict("sc_stale_one", &key),
3005                    abstaining_verdict("sc_stale_two", &key),
3006                ],
3007                "verdict document contains duplicate candidate or review identities",
3008            ),
3009            (
3010                vec![
3011                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
3012                    abstaining_verdict("sc_stale", &unique.review_key),
3013                ],
3014                "multiple verdicts resolve to the same candidate",
3015            ),
3016            (
3017                vec![
3018                    abstaining_verdict("sc_stale", &unique.review_key),
3019                    abstaining_verdict(&unique.candidate_id, &unique.review_key),
3020                ],
3021                "multiple verdicts resolve to the same candidate",
3022            ),
3023            (
3024                vec![abstaining_verdict(&unique.candidate_id, &key)],
3025                "verdict review_key does not match its candidate_id",
3026            ),
3027        ];
3028        for (verdicts, message) in cases {
3029            let error = review_similar_code(&candidate_json, &verdict_document(&verdicts), false)
3030                .unwrap_err();
3031            assert_eq!(error.message, message);
3032        }
3033    }
3034}