@a2f0/agent-tool 0.1.84 → 0.1.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,47 +5,35 @@
5
5
  * person or agent to inspect and never edits anything.
6
6
  */
7
7
  import { codeLines, MAX_BYTES } from "../stateMachines/scan";
8
-
9
- export { MAX_BYTES };
10
-
11
- export type DeslopSignalKind =
12
- | "duplicate-block"
13
- | "oversized-file"
14
- | "long-function"
15
- | "suppressions"
16
- | "thin-wrapper";
17
-
18
- export interface DeslopSignal {
19
- readonly kind: DeslopSignalKind;
20
- readonly count: number;
21
- /** 1-based line numbers where the signal starts or appears. */
22
- readonly lines: number[];
23
- /** Optional function names, wrapper names, or peer clone locations. */
24
- readonly details?: string[];
25
- }
26
-
27
- export interface DeslopFileReport {
28
- readonly path: string;
29
- readonly score: number;
30
- readonly signals: DeslopSignal[];
31
- }
32
-
33
- export interface DuplicateLocation {
34
- readonly path: string;
35
- readonly start: number;
36
- readonly end: number;
37
- }
38
-
39
- export interface DuplicateCluster {
40
- readonly lines: number;
41
- readonly locations: DuplicateLocation[];
42
- }
43
-
44
- export interface ScannedSource {
45
- readonly path: string;
46
- readonly text: string;
47
- readonly syntax: "c" | "hash";
48
- }
8
+ import {
9
+ type CloneOccurrence,
10
+ collectAndSummarizeClones,
11
+ type DeslopDirectoryReport,
12
+ type DeslopFileReport,
13
+ type DeslopSignal,
14
+ type DeslopSignalKind,
15
+ type DuplicateCluster,
16
+ type DuplicateLocation,
17
+ type DuplicateSpan,
18
+ type FileDuplicateSummary,
19
+ findMicroFiles,
20
+ findParametricClones,
21
+ type NormalizedLine,
22
+ PARAMETRIC_WINDOW,
23
+ type ScannedSource,
24
+ summarizeDirectories,
25
+ } from "./structural";
26
+
27
+ export {
28
+ MAX_BYTES,
29
+ type DeslopDirectoryReport,
30
+ type DeslopFileReport,
31
+ type DeslopSignal,
32
+ type DeslopSignalKind,
33
+ type DuplicateCluster,
34
+ type DuplicateLocation,
35
+ type ScannedSource,
36
+ };
49
37
 
50
38
  const LANGUAGES: Record<string, "c" | "hash"> = {
51
39
  ".ts": "c",
@@ -102,6 +90,11 @@ function readsShebang(firstLine: string): boolean {
102
90
  return INTERPRETER.test(base(tokens[index]));
103
91
  }
104
92
 
93
+ /** Whether a repository-relative path is classified as a test or fixture file. */
94
+ export function isTestPath(file: string): boolean {
95
+ return TEST_SKIPPED.some(pattern => pattern.test(file));
96
+ }
97
+
105
98
  /**
106
99
  * Comment syntax for a tracked source path. Test and fixture files are skipped
107
100
  * unless `includeTests` is true. Extensionless files return `"maybe"` until
@@ -109,7 +102,7 @@ function readsShebang(firstLine: string): boolean {
109
102
  */
110
103
  export function sourceLanguage(file: string, firstLine?: string, includeTests = false): "c" | "hash" | "maybe" | undefined {
111
104
  if (ALWAYS_SKIPPED.some(pattern => pattern.test(file))) return undefined;
112
- if (!includeTests && TEST_SKIPPED.some(pattern => pattern.test(file))) return undefined;
105
+ if (!includeTests && isTestPath(file)) return undefined;
113
106
  const base = file.slice(file.lastIndexOf("/") + 1);
114
107
  const dot = base.lastIndexOf(".");
115
108
  if (dot > 0) return LANGUAGES[base.slice(dot).toLowerCase()];
@@ -545,47 +538,30 @@ function findThinWrappers(lines: string[], syntax: "c" | "hash"): Array<{ name:
545
538
  return found;
546
539
  }
547
540
 
548
- interface NormalizedLine {
549
- readonly line: number;
550
- readonly text: string;
551
- }
552
-
553
541
  const SKIPPED_CLONE_LINE = /^(?:import\b|export\s+(?:type\s+)?\{|from\s+["']|package\s+|using\s+|use\s+|#include\b|[\s{}()[\];,]+$|else\s*\{?$|try\s*\{?$|finally\s*\{?$|break;?$|continue;?$)/;
542
+ const MULTILINE_IMPORT_START = /^(?:import|export)\s+(?:type\s+)?(?:\*\s+as\s+[A-Za-z_$][\w$]*\s+from|[A-Za-z_$][\w$]*\s*,\s*\{|\{)/;
543
+ const IMPORT_END_RE = /\bfrom\s+["'][^"']+["']\s*;?$|;\s*$/;
554
544
 
555
545
  function normalizedCodeLines(stripped: string[]): NormalizedLine[] {
556
546
  const result: NormalizedLine[] = [];
547
+ let inImportBlock = false;
557
548
  for (let index = 0; index < stripped.length; index++) {
558
549
  const collapsed = stripped[index]!.trim().replace(/\s+/g, " ");
559
- if (!collapsed || SKIPPED_CLONE_LINE.test(collapsed)) continue;
550
+ if (!collapsed) continue;
551
+ if (inImportBlock) {
552
+ if (IMPORT_END_RE.test(collapsed) || collapsed.startsWith("}")) inImportBlock = false;
553
+ continue;
554
+ }
555
+ if (MULTILINE_IMPORT_START.test(collapsed) && !IMPORT_END_RE.test(collapsed) && !collapsed.includes("}")) {
556
+ inImportBlock = true;
557
+ continue;
558
+ }
559
+ if (SKIPPED_CLONE_LINE.test(collapsed)) continue;
560
560
  result.push({ line: index + 1, text: collapsed });
561
561
  }
562
562
  return result;
563
563
  }
564
564
 
565
- interface Occurrence {
566
- readonly fileIndex: number;
567
- readonly normIndex: number;
568
- }
569
-
570
- interface DuplicateSpan {
571
- readonly fileA: number;
572
- readonly normStartA: number;
573
- readonly normEndA: number;
574
- readonly fileB: number;
575
- readonly normStartB: number;
576
- readonly normEndB: number;
577
- }
578
-
579
- interface FileDuplicateSummary {
580
- readonly duplicatedLines: number;
581
- readonly startLines: number[];
582
- readonly peers: string[];
583
- }
584
-
585
- function rangesOverlap(startA: number, endA: number, startB: number, endB: number): boolean {
586
- return startA <= endB && startB <= endA;
587
- }
588
-
589
565
  /**
590
566
  * Finds contiguous duplicated normalized code blocks across and within files.
591
567
  * Each distinct window hash is capped at `CLONE_MAX_OCCURRENCES` so boilerplate
@@ -595,8 +571,8 @@ function rangesOverlap(startA: number, endA: number, startB: number, endB: numbe
595
571
  function findDuplicates(
596
572
  sources: ScannedSource[],
597
573
  normalizedByFile: NormalizedLine[][],
598
- ): { perFile: Map<number, FileDuplicateSummary>; clusters: DuplicateCluster[] } {
599
- const buckets = new Map<string, Occurrence[] | null>();
574
+ ): { perFile: Map<number, FileDuplicateSummary>; clusters: DuplicateCluster[]; spans: DuplicateSpan[] } {
575
+ const buckets = new Map<string, CloneOccurrence[] | null>();
600
576
 
601
577
  for (let fileIndex = 0; fileIndex < normalizedByFile.length; fileIndex++) {
602
578
  const lines = normalizedByFile[fileIndex]!;
@@ -624,143 +600,19 @@ function findDuplicates(
624
600
  }
625
601
  }
626
602
 
627
- const pairStarts = new Map<string, Array<{ a: number; b: number }>>();
628
- for (const occurrences of buckets.values()) {
629
- if (!occurrences || occurrences.length < 2) continue;
630
- for (let i = 0; i < occurrences.length; i++) {
631
- for (let j = i + 1; j < occurrences.length; j++) {
632
- const first = occurrences[i]!;
633
- const second = occurrences[j]!;
634
- if (first.fileIndex === second.fileIndex && second.normIndex - first.normIndex < CLONE_WINDOW) continue;
635
- const key = `${first.fileIndex}:${second.fileIndex}`;
636
- const list = pairStarts.get(key);
637
- const item = { a: first.normIndex, b: second.normIndex };
638
- if (list) list.push(item);
639
- else pairStarts.set(key, [item]);
640
- }
641
- }
642
- }
643
-
644
- const rawSpans: DuplicateSpan[] = [];
645
- for (const [pairKey, matches] of pairStarts) {
646
- const [fileA, fileB] = pairKey.split(":").map(Number) as [number, number];
647
- const byDiag = new Map<number, number[]>();
648
- for (const { a, b } of matches) {
649
- const diag = b - a;
650
- const list = byDiag.get(diag);
651
- if (list) list.push(a);
652
- else byDiag.set(diag, [a]);
653
- }
654
- for (const [diag, starts] of byDiag) {
655
- starts.sort((x, y) => x - y);
656
- let runStart = starts[0]!;
657
- let runEnd = runStart + CLONE_WINDOW - 1;
658
- for (let i = 1; i < starts.length; i++) {
659
- const next = starts[i]!;
660
- const candidateEnd = Math.max(runEnd, next + CLONE_WINDOW - 1);
661
- if (next <= runEnd + 1 && (fileA !== fileB || candidateEnd < runStart + diag)) {
662
- runEnd = candidateEnd;
663
- } else {
664
- if (fileA !== fileB || runEnd < runStart + diag) {
665
- rawSpans.push({ fileA, normStartA: runStart, normEndA: runEnd, fileB, normStartB: runStart + diag, normEndB: runEnd + diag });
666
- }
667
- runStart = next;
668
- runEnd = next + CLONE_WINDOW - 1;
669
- }
670
- }
671
- if (fileA !== fileB || runEnd < runStart + diag) {
672
- rawSpans.push({ fileA, normStartA: runStart, normEndA: runEnd, fileB, normStartB: runStart + diag, normEndB: runEnd + diag });
673
- }
674
- }
675
- }
676
-
677
- // Keep the longest non-overlapping spans per file pair, suppressing shifted-diagonal sub-matches.
678
- rawSpans.sort(
679
- (x, y) =>
680
- y.normEndA - y.normStartA - (x.normEndA - x.normStartA) ||
681
- x.fileA - y.fileA ||
682
- x.fileB - y.fileB ||
683
- x.normStartA - y.normStartA ||
684
- x.normStartB - y.normStartB,
685
- );
686
- const acceptedByPair = new Map<string, DuplicateSpan[]>();
687
- const spans: DuplicateSpan[] = [];
688
- for (const span of rawSpans) {
689
- const key = `${span.fileA}:${span.fileB}`;
690
- const accepted = acceptedByPair.get(key) ?? [];
691
- const redundant = accepted.some(
692
- kept =>
693
- rangesOverlap(span.normStartA, span.normEndA, kept.normStartA, kept.normEndA) &&
694
- rangesOverlap(span.normStartB, span.normEndB, kept.normStartB, kept.normEndB),
695
- );
696
- if (redundant) continue;
697
- accepted.push(span);
698
- acceptedByPair.set(key, accepted);
699
- spans.push(span);
700
- }
701
-
702
- const fileLineSets = new Map<number, Set<number>>();
703
- const fileStarts = new Map<number, Set<number>>();
704
- const filePeers = new Map<number, Set<string>>();
705
- const clusters: DuplicateCluster[] = [];
706
-
707
- const record = (fileIndex: number, normStart: number, normEnd: number, peerIndex: number, peerStart: number, peerEnd: number) => {
708
- const norm = normalizedByFile[fileIndex]!;
709
- const peerNorm = normalizedByFile[peerIndex]!;
710
- const covered = fileLineSets.get(fileIndex) ?? new Set<number>();
711
- for (let i = normStart; i <= normEnd; i++) covered.add(norm[i]!.line);
712
- fileLineSets.set(fileIndex, covered);
713
- const starts = fileStarts.get(fileIndex) ?? new Set<number>();
714
- starts.add(norm[normStart]!.line);
715
- fileStarts.set(fileIndex, starts);
716
- const peers = filePeers.get(fileIndex) ?? new Set<string>();
717
- const peerLabel = peerIndex === fileIndex
718
- ? `self:${peerNorm[peerStart]!.line}-${peerNorm[peerEnd]!.line}`
719
- : `${sources[peerIndex]!.path}:${peerNorm[peerStart]!.line}-${peerNorm[peerEnd]!.line}`;
720
- peers.add(peerLabel);
721
- filePeers.set(fileIndex, peers);
722
- };
723
-
724
- for (const span of spans) {
725
- const normA = normalizedByFile[span.fileA]!;
726
- const normB = normalizedByFile[span.fileB]!;
727
- const count = span.normEndA - span.normStartA + 1;
728
- record(span.fileA, span.normStartA, span.normEndA, span.fileB, span.normStartB, span.normEndB);
729
- record(span.fileB, span.normStartB, span.normEndB, span.fileA, span.normStartA, span.normEndA);
730
- clusters.push({
731
- lines: count,
732
- locations: [
733
- { path: sources[span.fileA]!.path, start: normA[span.normStartA]!.line, end: normA[span.normEndA]!.line },
734
- { path: sources[span.fileB]!.path, start: normB[span.normStartB]!.line, end: normB[span.normEndB]!.line },
735
- ],
736
- });
737
- }
738
-
739
- const perFile = new Map<number, FileDuplicateSummary>();
740
- for (const [fileIndex, covered] of fileLineSets) {
741
- perFile.set(fileIndex, {
742
- duplicatedLines: covered.size,
743
- startLines: [...(fileStarts.get(fileIndex) ?? [])].sort((a, b) => a - b),
744
- peers: [...(filePeers.get(fileIndex) ?? [])].sort().slice(0, 5),
745
- });
746
- }
747
-
748
- clusters.sort(
749
- (a, b) =>
750
- b.lines - a.lines ||
751
- a.locations[0]!.path.localeCompare(b.locations[0]!.path) ||
752
- a.locations[0]!.start - b.locations[0]!.start,
753
- );
754
- return { perFile, clusters };
603
+ return collectAndSummarizeClones(sources, normalizedByFile, buckets, CLONE_WINDOW);
755
604
  }
756
605
 
757
- function scoreSignals(signals: DeslopSignal[], longFunctionMax: number): number {
606
+ function scoreSignals(signals: DeslopSignal[], longFunctionMax: number, microIsReexportShim: boolean): number {
758
607
  let total = 0;
759
608
  for (const signal of signals) {
760
609
  switch (signal.kind) {
761
610
  case "duplicate-block":
762
611
  total += Math.min(8, Math.floor(signal.count / 4) + 2);
763
612
  break;
613
+ case "parametric-clone":
614
+ total += Math.min(7, Math.floor(signal.count / 6) + 2);
615
+ break;
764
616
  case "oversized-file":
765
617
  total += signal.count >= OVERSIZED_HIGH ? 7 : signal.count >= OVERSIZED_MEDIUM ? 5 : 3;
766
618
  break;
@@ -773,16 +625,32 @@ function scoreSignals(signals: DeslopSignal[], longFunctionMax: number): number
773
625
  case "thin-wrapper":
774
626
  total += Math.min(6, 2 * signal.count - 1);
775
627
  break;
628
+ case "micro-file":
629
+ total += microIsReexportShim ? 3 : 2;
630
+ break;
776
631
  }
777
632
  }
778
633
  return total;
779
634
  }
780
635
 
781
- /** Scans a set of tracked source files and returns ranked file leads and top duplicate spans. */
782
- export function scanSources(sources: ScannedSource[], minScore = 3): { files: DeslopFileReport[]; duplicates: DuplicateCluster[] } {
636
+ /** Scans a set of tracked source files and returns ranked file leads, duplicate spans, and directory hotspots. */
637
+ export function scanSources(sources: ScannedSource[], minScore = 3, includeTests?: boolean): {
638
+ files: DeslopFileReport[];
639
+ duplicates: DuplicateCluster[];
640
+ parametricDuplicates: DuplicateCluster[];
641
+ directories: DeslopDirectoryReport[];
642
+ } {
643
+ const hasTests = includeTests ?? sources.some(source => isTestPath(source.path));
783
644
  const strippedByFile = sources.map(source => codeLines(source.text, source.syntax));
645
+ const codeLineCounts = strippedByFile.map(stripped => stripped.filter(line => line.trim().length > 0).length);
784
646
  const normalizedByFile = strippedByFile.map(normalizedCodeLines);
785
- const { perFile, clusters } = findDuplicates(sources, normalizedByFile);
647
+ const { perFile, clusters, spans: exactSpans } = findDuplicates(sources, normalizedByFile);
648
+ const { perFile: parametricPerFile, clusters: parametricClusters } = findParametricClones(
649
+ sources,
650
+ normalizedByFile,
651
+ exactSpans,
652
+ );
653
+ const microFiles = findMicroFiles(sources, strippedByFile, codeLineCounts, isTestPath);
786
654
 
787
655
  const files: DeslopFileReport[] = [];
788
656
  for (let index = 0; index < sources.length; index++) {
@@ -801,7 +669,17 @@ export function scanSources(sources: ScannedSource[], minScore = 3): { files: De
801
669
  });
802
670
  }
803
671
 
804
- const nonBlankCode = stripped.filter(line => line.trim().length > 0).length;
672
+ const parametric = parametricPerFile.get(index);
673
+ if (parametric && parametric.duplicatedLines >= PARAMETRIC_WINDOW) {
674
+ signals.push({
675
+ kind: "parametric-clone",
676
+ count: parametric.duplicatedLines,
677
+ lines: parametric.startLines,
678
+ details: parametric.peers,
679
+ });
680
+ }
681
+
682
+ const nonBlankCode = codeLineCounts[index]!;
805
683
  if (nonBlankCode >= OVERSIZED_LOW) {
806
684
  signals.push({ kind: "oversized-file", count: nonBlankCode, lines: [1] });
807
685
  }
@@ -832,11 +710,22 @@ export function scanSources(sources: ScannedSource[], minScore = 3): { files: De
832
710
  });
833
711
  }
834
712
 
713
+ const micro = microFiles.get(index);
714
+ if (micro) {
715
+ signals.push({
716
+ kind: "micro-file",
717
+ count: micro.codeLines,
718
+ lines: [1],
719
+ details: [micro.detail],
720
+ });
721
+ }
722
+
835
723
  if (signals.length === 0) continue;
836
- const score = scoreSignals(signals, maxLongFn);
724
+ const score = scoreSignals(signals, maxLongFn, micro?.isReexportShim ?? false);
837
725
  if (score >= minScore) files.push({ path: source.path, score, signals });
838
726
  }
839
727
 
840
728
  files.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
841
- return { files, duplicates: clusters };
729
+ const directories = summarizeDirectories(sources, codeLineCounts, files, isTestPath, hasTests);
730
+ return { files, duplicates: clusters, parametricDuplicates: parametricClusters, directories };
842
731
  }