Skip to main content

fallow_api/runtime/
trace.rs

1use fallow_engine::session::AnalysisSession;
2use fallow_types::duplicates::DuplicationReport;
3use rustc_hash::FxHashSet;
4
5use crate::{
6    DependencyUsageQuery, ProgrammaticAnalysisContext, ProgrammaticError, TraceCloneOptions,
7    TraceCloneProgrammaticOutput, TraceCloneTarget, TraceDependencyOptions,
8    TraceDependencyProgrammaticOutput, TraceErrorOptions, TraceErrorProgrammaticOutput,
9    TraceExportOptions, TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOptions,
10    TraceFileProgrammaticOutput, TraceImportPathOptions, TraceImportPathProgrammaticOutput,
11};
12
13use super::{ProgrammaticResult, duplication, resolve_programmatic_analysis_context};
14use crate::analysis_context::validate_workspace_selection;
15
16struct TraceArtifacts {
17    graph: fallow_engine::module_graph::RetainedModuleGraph,
18    script_used_packages: FxHashSet<String>,
19    trace_provenance: fallow_engine::trace::TraceProvenance,
20    /// The findings of the analysis, which name the manifests that the
21    /// unused-dependency check flags.
22    results: fallow_types::results::AnalysisResults,
23}
24
25/// Trace why an export is considered used or unused.
26///
27/// # Errors
28///
29/// Returns a structured programmatic error for invalid options, config load
30/// failures, graph construction failures, or missing trace targets. When the
31/// `type_aware` option, `FALLOW_TYPE_AWARE` or `typeAware.enabled` turns on
32/// type-aware analysis, it returns [`super::TYPE_AWARE_CONFIG_UNSUPPORTED`]:
33/// the CLI trace then adds semantic evidence that this trace cannot.
34pub fn run_trace_export(
35    options: &TraceExportOptions,
36) -> ProgrammaticResult<TraceExportProgrammaticOutput> {
37    validate_non_empty("file", &options.file)?;
38    validate_non_empty("export_name", &options.export_name)?;
39    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
40    super::type_aware_config::reject_type_aware_trace(&options.analysis.type_aware, &resolved)?;
41    resolved.install(|| {
42        let session = load_trace_session(&resolved)?;
43        let artifacts = trace_artifacts(&session)?;
44        // Resolve a top-level export first; on a miss fall back to a class /
45        // enum / store member trace so the MCP tool and Code Mode match the
46        // CLI's `--trace FILE:MEMBER` behavior instead of a hard not-found
47        // (issue #1744).
48        let output = if let Some(mut export) = fallow_engine::trace::trace_export(
49            &artifacts.graph,
50            session.root(),
51            &options.file,
52            &options.export_name,
53        ) {
54            export.apply_plugin_credits(&artifacts.trace_provenance);
55            TraceExportTargetOutput::Export(export)
56        } else if let Some(member) = fallow_engine::trace::trace_class_member(
57            &artifacts.graph,
58            session.root(),
59            &options.file,
60            &options.export_name,
61        ) {
62            TraceExportTargetOutput::Member(member)
63        } else {
64            return Err(ProgrammaticError::new(
65                format!(
66                    "export or member '{}' not found in '{}'",
67                    options.export_name, options.file
68                ),
69                2,
70            )
71            .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
72            .with_help(
73                "The name is neither a top-level export nor a class / enum / store member of this \
74                 file. Run trace_file on the file to list its exports, or project_info for the \
75                 project symbol set; confirm the file path is project-relative.",
76            )
77            .with_context("trace_export"));
78        };
79        Ok(TraceExportProgrammaticOutput { output })
80    })
81}
82
83/// Trace all graph edges for a file.
84///
85/// # Errors
86///
87/// Returns a structured programmatic error for invalid options, config load
88/// failures, graph construction failures, or missing trace targets.
89pub fn run_trace_file(
90    options: &TraceFileOptions,
91) -> ProgrammaticResult<TraceFileProgrammaticOutput> {
92    validate_non_empty("file", &options.file)?;
93    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
94    resolved.install(|| {
95        let session = load_trace_session(&resolved)?;
96        let artifacts = trace_artifacts(&session)?;
97        let mut output =
98            fallow_engine::trace::trace_file(&artifacts.graph, session.root(), &options.file)
99                .ok_or_else(|| {
100                    ProgrammaticError::new(
101                        format!("file '{}' not found in module graph", options.file),
102                        2,
103                    )
104                    .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
105                    .with_help(
106                        "The file is not in the analyzed module graph. Run project_info to list \
107                         discovered files; the path must be project-relative and not excluded by \
108                         ignore patterns or outside the analyzed roots.",
109                    )
110                    .with_context("trace_file")
111                })?;
112        output.sources = artifacts.trace_provenance.file_sources(&output.file);
113        output.apply_plugin_credits(&artifacts.trace_provenance);
114        output.apply_entry_script(&artifacts.trace_provenance);
115        Ok(TraceFileProgrammaticOutput { output })
116    })
117}
118
119/// Trace the shortest import path between two modules.
120///
121/// An unreachable pair is a RESULT, not an error: the output reports
122/// `reachable: false` with zero hops. A missing or ambiguous endpoint is an error.
123///
124/// # Errors
125///
126/// Returns a structured programmatic error for invalid options, config load
127/// failures, graph construction failures, or a missing or ambiguous endpoint.
128pub fn run_trace_import_path(
129    options: &TraceImportPathOptions,
130) -> ProgrammaticResult<TraceImportPathProgrammaticOutput> {
131    validate_non_empty("from", &options.from)?;
132    validate_non_empty("to", &options.to)?;
133    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
134    resolved.install(|| {
135        let session = load_trace_session(&resolved)?;
136        let artifacts = trace_artifacts(&session)?;
137        let trace = if options.eager_only {
138            fallow_engine::trace::trace_eager_import_path
139        } else {
140            fallow_engine::trace::trace_import_path
141        };
142        let output = trace(
143            &artifacts.graph,
144            session.root(),
145            &options.from,
146            &options.to,
147        )
148        .map_err(|endpoint| {
149            let label = endpoint.label();
150            let value = match endpoint {
151                fallow_engine::trace::ImportPathEndpoint::From
152                | fallow_engine::trace::ImportPathEndpoint::AmbiguousFrom => &options.from,
153                fallow_engine::trace::ImportPathEndpoint::To
154                | fallow_engine::trace::ImportPathEndpoint::AmbiguousTo => &options.to,
155            };
156            if endpoint.is_ambiguous() {
157                return ProgrammaticError::new(format!("'{value}' ({label}) matches multiple modules"), 2)
158                    .with_code("FALLOW_TRACE_TARGET_AMBIGUOUS")
159                    .with_help("Use the full project-relative path; run project_info to list discovered files.")
160                    .with_context("trace_import_path");
161            }
162            ProgrammaticError::new(format!("'{value}' ({label}) not found in module graph"), 2)
163                .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
164                .with_help(
165                    "The module is not in the analyzed module graph. Run project_info to list \
166                 discovered files; both paths must be project-relative and not excluded by \
167                 ignore patterns or outside the analyzed roots.",
168                )
169                .with_context("trace_import_path")
170        })?;
171        Ok(TraceImportPathProgrammaticOutput { output })
172    })
173}
174
175/// Resolve a runtime stack trace's frames against the project graph.
176///
177/// A trace in which nothing resolves is a RESULT, not an error: the output
178/// reports every frame with the origin and resolution that explain why. Only
179/// an empty trace argument, a config load failure, or a failed analysis is an
180/// error.
181///
182/// # Errors
183///
184/// Returns a structured programmatic error for an empty or oversized trace,
185/// config load failures, or graph construction failures.
186pub fn run_trace_error(
187    options: &TraceErrorOptions,
188) -> ProgrammaticResult<TraceErrorProgrammaticOutput> {
189    if options.trace.trim().is_empty() {
190        // Typed like the oversized-trace refusal below rather than through
191        // `validate_non_empty`: both are the same tool refusing the same
192        // argument, so both carry a `code`, a `help` and a `context`.
193        return Err(ProgrammaticError::new("trace must not be empty", 2)
194            .with_code("FALLOW_INVALID_TRACE_OPTIONS")
195            .with_help(
196                "Paste the stack trace text into `trace`, as your runtime printed it. \
197                 trace_error resolves frames against the project graph, so it has nothing \
198                 to resolve without them.",
199            )
200            .with_context("trace_error"));
201    }
202    if options.trace.len() as u64 > fallow_engine::trace_error::MAX_STACK_TRACE_BYTES {
203        let limit = fallow_engine::trace_error::MAX_STACK_TRACE_BYTES;
204        return Err(ProgrammaticError::new(
205            format!("stack trace exceeds the {limit}-byte limit"),
206            2,
207        )
208        .with_code("FALLOW_INVALID_TRACE_OPTIONS")
209        .with_help(
210            "A stack trace is a handful of kilobytes. Pass the trace itself rather than a \
211             redirected log file, and cut it to the frames that matter.",
212        )
213        .with_context("trace_error"));
214    }
215    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
216    resolved.install(|| {
217        let session = load_trace_session(&resolved)?;
218        let output = fallow_engine::trace_error::trace_error_with_session(
219            &session,
220            &options.trace,
221            options.source.clone(),
222        )
223        .map_err(|err| {
224            ProgrammaticError::new(format!("stack-trace resolution failed: {err}"), 2)
225                .with_code("FALLOW_ANALYSIS_FAILED")
226                .with_context("trace_error")
227        })?;
228        Ok(TraceErrorProgrammaticOutput { output })
229    })
230}
231
232/// Trace where a dependency is used.
233///
234/// # Errors
235///
236/// Returns a structured programmatic error for invalid options, config load, or
237/// graph construction failures.
238pub fn run_trace_dependency(
239    options: &TraceDependencyOptions,
240) -> ProgrammaticResult<TraceDependencyProgrammaticOutput> {
241    validate_non_empty("package_name", &options.package_name)?;
242    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
243    resolved.install(|| {
244        let session = load_trace_session(&resolved)?;
245        if let Some(query) = &options.usage {
246            return trace_dependency_usage(&session, &options.package_name, query);
247        }
248        let artifacts = trace_artifacts(&session)?;
249        let workspace_roots: Vec<&std::path::Path> = session
250            .workspaces()
251            .iter()
252            .map(|ws| ws.root.as_path())
253            .collect();
254        let output = fallow_engine::trace::build_dependency_trace(
255            &fallow_engine::trace::DependencyTraceInputs {
256                graph: &artifacts.graph,
257                root: session.root(),
258                workspace_roots: &workspace_roots,
259                ignore_patterns: &session.config().ignore_patterns,
260                script_used_packages: &artifacts.script_used_packages,
261                provenance: &artifacts.trace_provenance,
262                results: &artifacts.results,
263            },
264            &options.package_name,
265        );
266        Ok(TraceDependencyProgrammaticOutput { output })
267    })
268}
269
270/// Trace a dependency with its per-specifier usage.
271fn trace_dependency_usage(
272    session: &AnalysisSession,
273    package_name: &str,
274    query: &DependencyUsageQuery,
275) -> ProgrammaticResult<TraceDependencyProgrammaticOutput> {
276    let result = fallow_engine::trace::trace_dependency_with_session(session, package_name, query)
277        .map_err(|err| {
278            super::dead_code::map_engine_error(
279                &err,
280                "trace analysis failed",
281                "FALLOW_TRACE_FAILED",
282                "trace",
283            )
284        })?;
285    result
286        .map(|output| TraceDependencyProgrammaticOutput { output })
287        .map_err(|err| {
288            ProgrammaticError::new(err.to_string(), 2)
289                .with_code("FALLOW_TRACE_INVALID_CURSOR")
290                .with_context("cursor")
291        })
292}
293
294/// Trace duplicate-code groups by location or stable fingerprint.
295///
296/// # Errors
297///
298/// Returns a structured programmatic error for invalid options, config load
299/// failures, duplicate detection failures, or missing trace targets.
300pub fn run_trace_clone(
301    options: &TraceCloneOptions,
302) -> ProgrammaticResult<TraceCloneProgrammaticOutput> {
303    validate_trace_clone_target(&options.target)?;
304    let resolved = resolve_programmatic_analysis_context(&options.duplication.analysis)?;
305    resolved.install(|| {
306        resolved.ensure_not_cancelled("config load and file discovery")?;
307        let session = duplication::load_duplication_session(&options.duplication, &resolved)?;
308        validate_workspace_selection(&resolved, session.workspaces())?;
309        resolved.ensure_not_cancelled("duplication detection")?;
310        let dupes_config =
311            duplication::build_dupes_config(&options.duplication, &session.config().duplicates);
312        let cache_dir = (!resolved.no_cache).then_some(session.config().cache_dir.as_path());
313        let report = session
314            .find_duplicates_with_defaults(&dupes_config, cache_dir)
315            .report;
316        // Duplication detection is infallible, so the cancelled run has to be
317        // reported before the report is traced as a complete one.
318        resolved.ensure_not_cancelled("the clone trace")?;
319        let (trace, not_found) = match &options.target {
320            TraceCloneTarget::Location { file, line } => (
321                fallow_engine::trace::trace_clone(&report, session.root(), file, *line),
322                format!("no clone found at {file}:{line}"),
323            ),
324            TraceCloneTarget::Fingerprint(fingerprint) => (
325                fallow_engine::trace::trace_clone_by_fingerprint(
326                    &report,
327                    session.root(),
328                    fingerprint,
329                ),
330                format!("no clone group with fingerprint {fingerprint}"),
331            ),
332        };
333        if trace.matched_instance.is_none() {
334            return Err(ProgrammaticError::new(not_found, 2)
335                .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
336                .with_help(
337                    "No clone matched. Run find_dupes to list clone groups and their fingerprints; \
338                     a location must fall inside a reported clone instance, and a fingerprint must \
339                     be a find_dupes clone_groups[].fingerprint (a dup:<id> value).",
340                )
341                .with_context("trace_clone"));
342        }
343        Ok(TraceCloneProgrammaticOutput { output: trace })
344    })
345}
346
347/// Exercise the retained-graph trace family and compact JSON boundary without
348/// repeating project discovery, parsing, or graph construction.
349///
350/// # Errors
351///
352/// Returns a structured error when a fixture target is missing or compact JSON
353/// serialization fails.
354#[doc(hidden)]
355#[expect(
356    clippy::implicit_hasher,
357    reason = "the engine trace boundary intentionally accepts the workspace-standard FxHashSet"
358)]
359pub fn benchmark_trace_graph_family_compact_json(
360    graph: &fallow_engine::module_graph::RetainedModuleGraph,
361    root: &std::path::Path,
362    script_used_packages: &FxHashSet<String>,
363) -> ProgrammaticResult<(usize, usize, usize, usize, usize)> {
364    let export =
365        fallow_engine::trace::trace_export(graph, root, "src/000-shared.ts", "sharedValue")
366            .ok_or_else(|| benchmark_trace_target_missing("src/000-shared.ts:sharedValue"))?;
367    let export_reference_count = export.direct_references.len();
368    let export_json =
369        crate::serialize_trace_export_programmatic_json(TraceExportProgrammaticOutput {
370            output: TraceExportTargetOutput::Export(export),
371        })?;
372
373    let file = fallow_engine::trace::trace_file(graph, root, "src/000-shared.ts")
374        .ok_or_else(|| benchmark_trace_target_missing("src/000-shared.ts"))?;
375    let file_export_count = file.exports.len();
376    let file_imported_by_count = file.imported_by.len();
377    let file_json = crate::serialize_trace_file_programmatic_json(TraceFileProgrammaticOutput {
378        output: file,
379    })?;
380
381    let dependency = fallow_engine::trace::trace_dependency(
382        graph,
383        root,
384        &[],
385        &fallow_config::IgnorePatternSet::empty(),
386        "trace-package",
387        script_used_packages,
388    );
389    let dependency_import_count = dependency.import_count;
390    let dependency_json =
391        crate::serialize_trace_dependency_programmatic_json(TraceDependencyProgrammaticOutput {
392            output: dependency,
393        })?;
394
395    let rendered_bytes = compact_json_len(&[export_json, file_json, dependency_json])?;
396    Ok((
397        export_reference_count,
398        file_export_count,
399        file_imported_by_count,
400        dependency_import_count,
401        rendered_bytes,
402    ))
403}
404
405/// Stable facts returned by the clone trace benchmark boundary.
406#[doc(hidden)]
407#[derive(Debug, PartialEq, Eq)]
408pub struct TraceCloneBenchmarkResult {
409    /// Location identity returned by the location trace.
410    pub location_file: std::path::PathBuf,
411    /// Location line returned by the location trace.
412    pub location_line: usize,
413    /// Group fingerprint returned by the location trace.
414    pub location_fingerprint: String,
415    /// Group fingerprint returned by the fingerprint trace.
416    pub fingerprint_fingerprint: String,
417    /// Groups returned by the location trace.
418    pub location_group_count: usize,
419    /// Groups returned by the fingerprint trace.
420    pub fingerprint_group_count: usize,
421    /// Instances returned by the location trace.
422    pub location_instance_count: usize,
423    /// Instances returned by the fingerprint trace.
424    pub fingerprint_instance_count: usize,
425    /// Total compact JSON bytes for both trace responses.
426    pub rendered_bytes: usize,
427}
428
429/// Exercise both supported clone trace identities from one retained report.
430///
431/// # Errors
432///
433/// Returns a structured error when either identity misses or compact JSON
434/// serialization fails.
435#[doc(hidden)]
436pub fn benchmark_trace_clone_compact_json(
437    report: &DuplicationReport,
438    root: &std::path::Path,
439    file: &str,
440    line: usize,
441    fingerprint: &str,
442) -> ProgrammaticResult<TraceCloneBenchmarkResult> {
443    let location_trace = fallow_engine::trace::trace_clone(report, root, file, line);
444    let matched_location = location_trace
445        .matched_instance
446        .as_ref()
447        .ok_or_else(|| benchmark_trace_target_missing(&format!("{file}:{line}")))?;
448    let location_file = matched_location.file.clone();
449    let location_line = matched_location.start_line;
450    let location_fingerprint = location_trace
451        .clone_groups
452        .first()
453        .map(|group| group.fingerprint.clone())
454        .ok_or_else(|| benchmark_trace_target_missing(&format!("{file}:{line}")))?;
455    let location_group_count = location_trace.clone_groups.len();
456    let location_instance_count = location_trace
457        .clone_groups
458        .iter()
459        .map(|group| group.instances.len())
460        .sum();
461    let location_json =
462        crate::serialize_trace_clone_programmatic_json(TraceCloneProgrammaticOutput {
463            output: location_trace,
464        })?;
465
466    let fingerprint_trace =
467        fallow_engine::trace::trace_clone_by_fingerprint(report, root, fingerprint);
468    if fingerprint_trace.matched_instance.is_none() {
469        return Err(benchmark_trace_target_missing(fingerprint));
470    }
471    let fingerprint_fingerprint = fingerprint_trace
472        .clone_groups
473        .first()
474        .map(|group| group.fingerprint.clone())
475        .ok_or_else(|| benchmark_trace_target_missing(fingerprint))?;
476    let fingerprint_group_count = fingerprint_trace.clone_groups.len();
477    let fingerprint_instance_count = fingerprint_trace
478        .clone_groups
479        .iter()
480        .map(|group| group.instances.len())
481        .sum();
482    let fingerprint_json =
483        crate::serialize_trace_clone_programmatic_json(TraceCloneProgrammaticOutput {
484            output: fingerprint_trace,
485        })?;
486
487    let rendered_bytes = compact_json_len(&[location_json, fingerprint_json])?;
488    Ok(TraceCloneBenchmarkResult {
489        location_file,
490        location_line,
491        location_fingerprint,
492        fingerprint_fingerprint,
493        location_group_count,
494        fingerprint_group_count,
495        location_instance_count,
496        fingerprint_instance_count,
497        rendered_bytes,
498    })
499}
500
501fn compact_json_len(values: &[serde_json::Value]) -> ProgrammaticResult<usize> {
502    serde_json::to_vec(values)
503        .map(|json| json.len())
504        .map_err(|err| {
505            ProgrammaticError::new(
506                format!("failed to serialize benchmark trace JSON: {err}"),
507                2,
508            )
509            .with_code("FALLOW_SERIALIZE_BENCHMARK_TRACE")
510            .with_context("benchmark_trace")
511        })
512}
513
514fn benchmark_trace_target_missing(target: &str) -> ProgrammaticError {
515    ProgrammaticError::new(format!("benchmark trace target not found: {target}"), 2)
516        .with_code("FALLOW_BENCHMARK_TRACE_TARGET_NOT_FOUND")
517        .with_context("benchmark_trace")
518}
519
520fn validate_non_empty(field: &str, value: &str) -> ProgrammaticResult<()> {
521    if value.trim().is_empty() {
522        return Err(
523            ProgrammaticError::new(format!("{field} must not be empty"), 2)
524                .with_code("FALLOW_INVALID_TRACE_OPTIONS")
525                .with_context(field.to_string()),
526        );
527    }
528    Ok(())
529}
530
531fn validate_trace_clone_target(target: &TraceCloneTarget) -> ProgrammaticResult<()> {
532    match target {
533        TraceCloneTarget::Location { file, line } => {
534            validate_non_empty("file", file)?;
535            if *line == 0 {
536                return Err(ProgrammaticError::new("line must be greater than 0", 2)
537                    .with_code("FALLOW_INVALID_TRACE_OPTIONS")
538                    .with_context("trace_clone.line"));
539            }
540        }
541        TraceCloneTarget::Fingerprint(fingerprint) => {
542            validate_non_empty("fingerprint", fingerprint)?;
543        }
544    }
545    Ok(())
546}
547
548fn load_trace_session(
549    resolved: &ProgrammaticAnalysisContext,
550) -> ProgrammaticResult<AnalysisSession> {
551    let session = super::dead_code::load_dead_code_session(
552        &super::dead_code::default_dead_code_options_for_context(resolved),
553        resolved,
554    )?;
555    validate_workspace_selection(resolved, session.workspaces())?;
556    Ok(session)
557}
558
559fn trace_artifacts(session: &AnalysisSession) -> ProgrammaticResult<TraceArtifacts> {
560    let artifacts = session
561        .analyze_dead_code_with_session_artifacts(false, true, None)
562        .map_err(|err| {
563            super::dead_code::map_engine_error(
564                &err,
565                "trace analysis failed",
566                "FALLOW_TRACE_FAILED",
567                "trace",
568            )
569        })?;
570    let graph = artifacts.analysis.graph.ok_or_else(|| {
571        ProgrammaticError::new("trace requires a retained module graph", 2)
572            .with_code("FALLOW_TRACE_GRAPH_UNAVAILABLE")
573            .with_context("trace.graph")
574    })?;
575    Ok(TraceArtifacts {
576        graph,
577        script_used_packages: artifacts.analysis.script_used_packages,
578        trace_provenance: artifacts.analysis.trace_provenance,
579        results: artifacts.analysis.results,
580    })
581}
582
583#[cfg(test)]
584mod benchmark_tests {
585    use std::fmt::Write as _;
586    use std::fs;
587
588    use fallow_engine::duplicates::CloneFingerprintSet;
589
590    use super::*;
591
592    const FIXTURE_SIZE: usize = 4;
593
594    fn write_file(root: &std::path::Path, path: &str, source: impl AsRef<str>) {
595        let path = root.join(path);
596        fs::create_dir_all(path.parent().expect("fixture file has parent"))
597            .expect("fixture directory is created");
598        fs::write(path, source.as_ref()).expect("fixture file is written");
599    }
600
601    #[test]
602    fn graph_family_benchmark_boundary_uses_only_retained_artifacts() {
603        let temp_dir = tempfile::TempDir::new().expect("temporary project is created");
604        let root = temp_dir.path().to_path_buf();
605        write_file(
606            &root,
607            "package.json",
608            r#"{"name":"trace-test","type":"module","main":"src/index.ts"}"#,
609        );
610        write_file(
611            &root,
612            "src/000-shared.ts",
613            "export const sharedValue = 42;\n",
614        );
615
616        let mut index_source = String::new();
617        for index in 0..FIXTURE_SIZE {
618            write_file(
619                &root,
620                &format!("src/consumer{index}.ts"),
621                format!(
622                    "import {{ sharedValue }} from './000-shared';\nimport {{ traceHelper }} from 'trace-package';\nexport const value{index} = traceHelper(sharedValue + {index});\n"
623                ),
624            );
625            writeln!(
626                index_source,
627                "import {{ value{index} }} from './consumer{index}';\nconsole.log(value{index});"
628            )
629            .expect("index source is built");
630        }
631        write_file(&root, "src/index.ts", index_source);
632
633        let session = AnalysisSession::load(&root, None).expect("trace session loads");
634        let target = session
635            .files()
636            .iter()
637            .find(|file| file.path.ends_with("src/000-shared.ts"))
638            .expect("trace target is discovered");
639        assert_eq!(
640            target.id.0, 0,
641            "the retained trace target must precede every non-matching importer"
642        );
643        let trace_root = session.root().to_path_buf();
644        let artifacts = session
645            .analyze_dead_code_with_artifacts(false, true)
646            .expect("trace graph analysis succeeds");
647        drop(session);
648        temp_dir.close().expect("temporary project is removed");
649
650        let result = benchmark_trace_graph_family_compact_json(
651            artifacts.graph.as_ref().expect("trace graph is retained"),
652            &trace_root,
653            &artifacts.script_used_packages,
654        )
655        .expect("retained trace graph serializes without project IO");
656        assert_eq!(result.0, FIXTURE_SIZE);
657        assert_eq!(result.1, 1);
658        assert_eq!(result.2, FIXTURE_SIZE);
659        assert_eq!(result.3, FIXTURE_SIZE);
660        assert!(result.4 > 0);
661    }
662
663    #[test]
664    fn clone_benchmark_boundary_uses_only_the_retained_report() {
665        let temp_dir = tempfile::TempDir::new().expect("temporary project is created");
666        let root = temp_dir.path().to_path_buf();
667        write_file(
668            &root,
669            "package.json",
670            r#"{"name":"trace-clone-test","type":"module"}"#,
671        );
672        for index in 0..FIXTURE_SIZE {
673            write_file(
674                &root,
675                &format!("src/clone{index}.ts"),
676                format!(
677                    "export function normalizeRecords(records: Array<{{ active: boolean; value: number }}>) {{\n  const active = records.filter((record) => record.active);\n  const values = active.map((record) => record.value);\n  const total = values.reduce((sum, value) => sum + value, 0);\n  const average = values.length === 0 ? 0 : total / values.length;\n  const maximum = values.reduce((current, value) => Math.max(current, value), 0);\n  return {{ total, average, maximum, count: values.length }};\n}}\n\nexport const cloneId = {index};\n"
678                ),
679            );
680        }
681
682        let session = AnalysisSession::load(&root, None).expect("clone session loads");
683        let trace_root = session.root().to_path_buf();
684        let mut config = session.config().duplicates.clone();
685        config.min_tokens = 35;
686        config.min_lines = 5;
687        config.min_occurrences = FIXTURE_SIZE;
688        let report = session.find_duplicates_with_defaults(&config, None).report;
689        let group = report
690            .clone_groups
691            .iter()
692            .max_by_key(|group| group.instances.len())
693            .expect("clone group exists");
694        let target = group.instances.last().expect("clone instance exists");
695        let target_file = target
696            .file
697            .strip_prefix(&trace_root)
698            .expect("clone path is project-relative")
699            .to_string_lossy()
700            .replace('\\', "/");
701        let target_line = target.start_line;
702        let expected_fingerprint =
703            CloneFingerprintSet::from_groups(&report.clone_groups).fingerprint_for_group(group);
704        drop(session);
705        temp_dir.close().expect("temporary project is removed");
706
707        let result = benchmark_trace_clone_compact_json(
708            &report,
709            &trace_root,
710            &target_file,
711            target_line,
712            &expected_fingerprint,
713        )
714        .expect("retained clone report serializes without project IO");
715        assert_eq!(result.location_file, std::path::PathBuf::from(&target_file));
716        assert_eq!(result.location_line, target_line);
717        assert_eq!(result.location_fingerprint, expected_fingerprint);
718        assert_eq!(result.fingerprint_fingerprint, expected_fingerprint);
719        assert_eq!(result.location_group_count, 1);
720        assert_eq!(result.fingerprint_group_count, 1);
721        assert_eq!(result.location_instance_count, FIXTURE_SIZE);
722        assert_eq!(result.fingerprint_instance_count, FIXTURE_SIZE);
723        assert!(result.rendered_bytes > 0);
724    }
725}