weavatrix 0.1.1 → 0.1.3

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.
Files changed (42) hide show
  1. package/README.md +117 -21
  2. package/SECURITY.md +31 -0
  3. package/package.json +16 -4
  4. package/skill/SKILL.md +69 -12
  5. package/src/analysis/coverage-reports.js +14 -11
  6. package/src/analysis/dead-check.js +87 -6
  7. package/src/analysis/dep-check.js +84 -8
  8. package/src/analysis/dep-rules.js +74 -8
  9. package/src/analysis/duplicates.compute.js +215 -215
  10. package/src/analysis/duplicates.js +15 -15
  11. package/src/analysis/duplicates.run.js +52 -51
  12. package/src/analysis/duplicates.tokenize.js +182 -182
  13. package/src/analysis/endpoints.js +50 -5
  14. package/src/analysis/graph-analysis.aggregate.js +16 -4
  15. package/src/analysis/internal-audit.collect.js +154 -31
  16. package/src/analysis/internal-audit.reach.js +52 -11
  17. package/src/analysis/internal-audit.run.js +72 -21
  18. package/src/build-graph.js +2 -1
  19. package/src/child-env.js +7 -0
  20. package/src/graph/builder/lang-js.js +66 -23
  21. package/src/graph/internal-builder.build.js +48 -10
  22. package/src/graph/internal-builder.langs.js +49 -3
  23. package/src/graph/internal-builder.resolvers.js +96 -20
  24. package/src/mcp/catalog.mjs +10 -8
  25. package/src/mcp/graph-context.mjs +107 -17
  26. package/src/mcp/sync-payload.mjs +110 -0
  27. package/src/mcp/tools-actions.mjs +42 -18
  28. package/src/mcp/tools-graph.mjs +46 -12
  29. package/src/mcp/tools-health.mjs +42 -18
  30. package/src/mcp/tools-impact.mjs +55 -43
  31. package/src/mcp-rg.mjs +2 -1
  32. package/src/mcp-server.mjs +25 -16
  33. package/src/mcp-source-tools.mjs +16 -5
  34. package/src/process.js +4 -3
  35. package/src/repo-path.js +53 -0
  36. package/src/security/advisory-store.js +51 -7
  37. package/src/security/installed.js +44 -31
  38. package/src/security/malware-heuristics.exclusions.js +134 -134
  39. package/src/security/malware-heuristics.js +15 -15
  40. package/src/security/malware-heuristics.roots.js +142 -142
  41. package/src/security/malware-heuristics.scan.js +85 -85
  42. package/src/security/malware-heuristics.sweep.js +122 -122
@@ -1,215 +1,215 @@
1
- // duplicates.compute.js — fragment extraction, inverted-index pairing, and the computeDuplicates
2
- // pipeline (split from duplicates.js; see the facade there for the full algorithm overview).
3
- import { readFileSync, readdirSync } from "node:fs";
4
- import { join, extname } from "node:path";
5
- import { isTestPath } from "../graph/graph-filter.js";
6
- import { stripNonCode, bodyEndLineCount, tokenize, fingerprints, extractLargeStrings } from "./duplicates.tokenize.js";
7
-
8
- const FLOOR_TOKENS = 30; // fragments below this never enter the index (UI slider min)
9
- const FLOOR_SIM = 0.5; // pairs below this are not reported (UI slider min)
10
- const MAX_BODY_LINES = 400;
11
- // File types with no code SYMBOLS to fragment (stylesheets, markup, docs, single-file components). The
12
- // user still wants them clone-checked ("check the frontend / md too"), so each is sliced into fixed line
13
- // WINDOWS and each window is fingerprinted like a function body a duplicated CSS rule block / HTML
14
- // section / doc passage then clones the same way.
15
- const WINDOW_EXTS = /\.(css|scss|sass|less|styl|html?|md|markdown|mdx|vue|svelte|astro)$/i;
16
- const WINDOW_LINES = 24; // non-overlapping block size for windowed files
17
- // Asset files are DEDUP-ONLY they are NOT put in the code graph (that would score md/css as fake
18
- // "methods" in Health and clutter the GUI board), so the clone scanner finds them by walking the repo.
19
- const WALK_SKIP = new Set(["node_modules", ".git", "dist", "build", "coverage", "vendor", "weavatrix-graphs", ".next", "out", "__pycache__", ".venv", "venv", "site-packages"]);
20
- const MAX_ASSET_FILES = 4000;
21
- function walkAssets(root, dir, acc, depth) {
22
- if (depth > 40 || acc.length >= MAX_ASSET_FILES) return acc;
23
- let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return acc; }
24
- for (const e of entries) {
25
- if (acc.length >= MAX_ASSET_FILES) break;
26
- if (e.name.startsWith(".") || WALK_SKIP.has(e.name)) continue;
27
- const full = join(dir, e.name);
28
- if (e.isDirectory()) walkAssets(root, full, acc, depth + 1);
29
- else if (WINDOW_EXTS.test(e.name)) acc.push(full.slice(root.length + 1).replace(/\\/g, "/"));
30
- }
31
- return acc;
32
- }
33
- // Fingerprints shared by MORE than this many fragments are ubiquitous boilerplate and are excluded
34
- // from BOTH the shared count AND the union (so jaccard stays honest see pairsForMode). Set well
35
- // above realistic clone multiplicity: N byte-identical copies each put all their fingerprints in
36
- // buckets of size N, so the cap must exceed N or the whole clone family is invisible. 120 covers all
37
- // but pathological mass-duplication; the O(n²) pair work per bucket stays bounded by it.
38
- const BUCKET_CAP = 120;
39
- // A clone must share at least this many DISTINCT (non-ubiquitous) fingerprints. Winnowing collapses a
40
- // UNIFORM repetitive body (a constant table where every line is `KEY: 'VALUE',` → renamed `I: <str>`) to a
41
- // handful of fingerprints, so two UNRELATED such tables hit 100% renamed Jaccard on ~3-6 shared fingerprints
42
- // — "same shape, zero shared content". Requiring real shared evidence drops those false positives while a
43
- // genuine clone (which shares dozens of fingerprints) is untouched.
44
- const MIN_SHARED_FP = 8;
45
-
46
- // Same-name symbols across DIFFERENT files — the semantic complement to token clones. A token clone
47
- // says "same body"; a name twin with LOW similarity says "same name, different behavior" — the
48
- // drift-hazard class of duplicate (three divergent uniqueStrings() implementations) that jaccard
49
- // ranks too low to surface. OOP-generic lifecycle names are stoplisted; interface implementations
50
- // still appear, so the caller's report keeps neutral wording.
51
- const TWIN_STOP = new Set(["constructor", "tostring", "valueof", "dispose", "close", "render", "setup", "teardown", "initialize", "destroy", "connect", "disconnect", "update", "reset", "clear", "create", "handle", "execute", "invoke", "main", "start", "stop", "build", "parse", "value", "index"]);
52
- function computeNameTwins(frags) {
53
- const byName = new Map();
54
- frags.forEach((f, i) => {
55
- if (f.kind === "string") return;
56
- const name = String(f.label || "").trim().replace(/\(\)$/, "");
57
- if (name.length < 5 || !/^[A-Za-z_$][\w$]*$/.test(name) || TWIN_STOP.has(name.toLowerCase())) return;
58
- const key = name.toLowerCase();
59
- let a = byName.get(key); if (!a) byName.set(key, (a = []));
60
- a.push(i);
61
- });
62
- const jac = (A, B) => { let inter = 0; for (const h of A) if (B.has(h)) inter++; const u = A.size + B.size - inter; return u ? inter / u : 0; };
63
- const out = [];
64
- for (const idxs of byName.values()) {
65
- const files = new Set(idxs.map((i) => frags[i].file));
66
- if (files.size < 2 || idxs.length > 12) continue; // single-file overloads / framework-name explosions
67
- let simMin = 1, simMax = 0;
68
- for (let a = 0; a < idxs.length; a++) for (let b = a + 1; b < idxs.length; b++) {
69
- if (frags[idxs[a]].file === frags[idxs[b]].file) continue;
70
- const s = jac(frags[idxs[a]].fp.renamed, frags[idxs[b]].fp.renamed);
71
- if (s < simMin) simMin = s;
72
- if (s > simMax) simMax = s;
73
- }
74
- out.push({
75
- label: String(frags[idxs[0]].label || "").replace(/\(\)$/, ""), members: idxs, files: files.size,
76
- simMin: Math.round(simMin * 100), simMax: Math.round(simMax * 100),
77
- tokens: idxs.reduce((n, i) => n + frags[i].n, 0),
78
- });
79
- }
80
- return out.sort((x, y) => y.tokens - x.tokens).slice(0, 200);
81
- }
82
-
83
- function pairsForMode(frags, mode) {
84
- const index = new Map();
85
- frags.forEach((f, i) => { for (const h of f.fp[mode]) { let a = index.get(h); if (!a) index.set(h, (a = [])); a.push(i); } });
86
- // eff[i] = count of i's fingerprints that sit in NON-ubiquitous buckets. Jaccard's numerator (shared)
87
- // and denominator (union) are BOTH computed over this same restricted set, so excluding a boilerplate
88
- // fingerprint never deflates similarity — two real clones sharing a widely-repeated preamble still
89
- // pair at 100% on their unique bodies, and the sim is a true jaccard, not an under-count.
90
- const eff = new Array(frags.length).fill(0);
91
- const shared = new Map();
92
- for (const arr of index.values()) {
93
- if (arr.length > BUCKET_CAP) continue; // ubiquitous k-gram → excluded from count AND size (both sides)
94
- for (const idx of arr) eff[idx]++;
95
- for (let a = 0; a < arr.length; a++) for (let b = a + 1; b < arr.length; b++) {
96
- const key = arr[a] * 1000000 + arr[b]; // frag count is bounded way below 1e6
97
- shared.set(key, (shared.get(key) || 0) + 1);
98
- }
99
- }
100
- const pairs = [];
101
- for (const [key, count] of shared) {
102
- const i = Math.floor(key / 1000000), j = key % 1000000;
103
- const union = eff[i] + eff[j] - count;
104
- const sim = union > 0 ? count / union : 0;
105
- if (sim >= FLOOR_SIM && count >= MIN_SHARED_FP) pairs.push([i, j, Math.round(sim * 100)]);
106
- }
107
- return pairs;
108
- }
109
-
110
- // Parse "L<line>" graph symbol locations into per-file ordered symbol lists.
111
- function symbolRanges(graph) {
112
- const byFile = new Map();
113
- for (const n of graph.nodes || []) {
114
- if (!n.source_file || !String(n.id || "").includes("#")) continue;
115
- const line = Number((String(n.source_location || "").match(/L(\d+)/) || [])[1] || 0);
116
- if (!line) continue;
117
- let arr = byFile.get(n.source_file);
118
- if (!arr) byFile.set(n.source_file, (arr = []));
119
- arr.push({ id: n.id, label: n.label || n.id, line });
120
- }
121
- for (const arr of byFile.values()) arr.sort((a, b) => a.line - b.line);
122
- return byFile;
123
- }
124
-
125
- export function computeDuplicates(repoPath, graphJsonPath, opts = {}) {
126
- const includeStrings = !!opts.includeStrings;
127
- const graph = JSON.parse(readFileSync(graphJsonPath, "utf8"));
128
- const byFile = symbolRanges(graph);
129
- // total symbol nodes in the graph — 0 means a file-only graph (built by an older builder before
130
- // symbol extraction, or a stale graph): clone detection has nothing to work with, and the UI must
131
- // say "rebuild the graph" instead of the misleading "no clones at these thresholds".
132
- let graphSymbols = 0;
133
- for (const arr of byFile.values()) graphSymbols += arr.length;
134
- const frags = [];
135
- for (const [file, syms] of byFile) {
136
- const full = join(repoPath, file);
137
- let lines;
138
- try { lines = readFileSync(full, "utf8").split(/\r?\n/); } catch { continue; }
139
- const py = /\.py$/i.test(file);
140
- for (let i = 0; i < syms.length; i++) {
141
- const start = syms[i].line;
142
- // hard cap first (next symbol, or EOF, whichever comes first, MAX_BODY_LINES)
143
- const hardEnd = Math.min(i + 1 < syms.length ? syms[i + 1].line - 1 : lines.length, start + MAX_BODY_LINES);
144
- if (hardEnd - start < 2) continue; // one-liners can't be meaningful clones
145
- // then shrink to where the construct actually closes, so the last symbol doesn't absorb
146
- // trailing module-level code (module.exports tables, main() calls) up to EOF.
147
- const bodyLines = lines.slice(start - 1, hardEnd);
148
- const body = bodyLines.slice(0, bodyEndLineCount(bodyLines, py));
149
- const end = start + body.length - 1;
150
- if (end - start < 2) continue;
151
- const toks = tokenize(stripNonCode(body.join("\n"), py));
152
- if (toks.strict.length < FLOOR_TOKENS) continue;
153
- frags.push({
154
- id: syms[i].id, label: syms[i].label, file, start, end,
155
- n: toks.strict.length,
156
- test: isTestPath(file),
157
- fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
158
- });
159
- }
160
- // ---- opt-in: large multi-line string literals as their own fragments. The code pass above strips
161
- // string bodies (correctly — content isn't code), which makes embedded DSL templates (inline
162
- // C#/SQL/PowerShell) invisible to clone detection. Tokenized RAW: the content IS the payload.
163
- if (includeStrings) {
164
- const base = file.split("/").pop();
165
- const pushStr = (startLine, endLine, content) => {
166
- const toks = tokenize(content);
167
- if (toks.strict.length < FLOOR_TOKENS) return;
168
- frags.push({
169
- id: `${file}#str@${startLine}`, label: `${base}:${startLine} ~${endLine - startLine + 1}-line string`,
170
- file, start: startLine, end: endLine, n: toks.strict.length, test: isTestPath(file), kind: "string",
171
- fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
172
- });
173
- };
174
- for (const str of extractLargeStrings(lines.join("\n"), { py, cs: /\.cs$/i.test(file) })) {
175
- const strLines = str.content.split(/\r?\n/).slice(0, MAX_BODY_LINES);
176
- // A SECTION shared between two big templates dilutes below the similarity floor when the whole
177
- // literals are compared (70 shared lines inside 220- and 107-line strings ≈ 27% jaccard). Big
178
- // literals therefore get the same WINDOW treatment as CSS/HTML files; small ones stay whole.
179
- if (strLines.length <= WINDOW_LINES * 2) {
180
- pushStr(str.start, str.start + strLines.length - 1, strLines.join("\n"));
181
- } else {
182
- for (let off = 0; off < strLines.length; off += WINDOW_LINES) {
183
- const chunk = strLines.slice(off, off + WINDOW_LINES);
184
- if (chunk.length < 3) break;
185
- pushStr(str.start + off, str.start + off + chunk.length - 1, chunk.join("\n"));
186
- }
187
- }
188
- }
189
- }
190
- }
191
- // ---- windowed fragments for symbol-less file types (CSS/HTML/MD/…), found by walking the repo (NOT the
192
- // graph assets are dedup-only). Each file is sliced into WINDOW_LINES blocks and fingerprinted.
193
- const symFiles = new Set(byFile.keys());
194
- for (const file of walkAssets(repoPath, repoPath, [], 0)) {
195
- if (symFiles.has(file)) continue;
196
- let lines;
197
- try { lines = readFileSync(join(repoPath, file), "utf8").split(/\r?\n/); } catch { continue; }
198
- for (let start = 1; start <= lines.length; start += WINDOW_LINES) {
199
- const end = Math.min(start + WINDOW_LINES - 1, lines.length);
200
- if (end - start < 2) continue;
201
- const toks = tokenize(stripNonCode(lines.slice(start - 1, end).join("\n"), false));
202
- if (toks.strict.length < FLOOR_TOKENS) continue;
203
- frags.push({
204
- id: `${file}#win@${start}`, label: `${file.split("/").pop()}:${start}-${end}`, file, start, end,
205
- n: toks.strict.length, test: isTestPath(file),
206
- fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
207
- });
208
- }
209
- }
210
- const modes = { strict: pairsForMode(frags, "strict"), renamed: pairsForMode(frags, "renamed") };
211
- const nameTwins = opts.nameTwins ? computeNameTwins(frags) : null;
212
- // fp sets are worker-internal — strip them from the payload that crosses the thread boundary
213
- const slim = frags.map(({ fp, ...rest }) => rest);
214
- return { ok: true, frags: slim, modes, ...(nameTwins ? { nameTwins } : {}), graphSymbols, floors: { tokens: FLOOR_TOKENS, sim: FLOOR_SIM * 100 } };
215
- }
1
+ // duplicates.compute.js — fragment extraction, inverted-index pairing, and the computeDuplicates
2
+ // pipeline (split from duplicates.js; see the facade there for the full algorithm overview).
3
+ import { readFileSync } from "node:fs";
4
+ import { isTestPath } from "../graph/graph-filter.js";
5
+ import { createRepoBoundary } from "../repo-path.js";
6
+ import { listRepoFiles } from "./internal-audit.collect.js";
7
+ import { stripNonCode, bodyEndLineCount, tokenize, fingerprints, extractLargeStrings } from "./duplicates.tokenize.js";
8
+
9
+ const FLOOR_TOKENS = 30; // fragments below this never enter the index (UI slider min)
10
+ const FLOOR_SIM = 0.5; // pairs below this are not reported (UI slider min)
11
+ const MAX_BODY_LINES = 400;
12
+ // File types with no code SYMBOLS to fragment (stylesheets, markup, docs, single-file components). The
13
+ // user still wants them clone-checked ("check the frontend / md too"), so each is sliced into fixed line
14
+ // WINDOWS and each window is fingerprinted like a function body — a duplicated CSS rule block / HTML
15
+ // section / doc passage then clones the same way.
16
+ const WINDOW_EXTS = /\.(css|scss|sass|less|styl|html?|md|markdown|mdx|vue|svelte|astro)$/i;
17
+ const WINDOW_LINES = 24; // non-overlapping block size for windowed files
18
+ // Asset files are DEDUP-ONLY they are NOT put in the code graph (that would score md/css as fake
19
+ // "methods" in Health and clutter the GUI board), so the clone scanner finds them by walking the repo.
20
+ const MAX_ASSET_FILES = 4000;
21
+ // Fingerprints shared by MORE than this many fragments are ubiquitous boilerplate and are excluded
22
+ // from BOTH the shared count AND the union (so jaccard stays honest see pairsForMode). Set well
23
+ // above realistic clone multiplicity: N byte-identical copies each put all their fingerprints in
24
+ // buckets of size N, so the cap must exceed N or the whole clone family is invisible. 120 covers all
25
+ // but pathological mass-duplication; the O(n²) pair work per bucket stays bounded by it.
26
+ const BUCKET_CAP = 120;
27
+ // A clone must share at least this many DISTINCT (non-ubiquitous) fingerprints. Winnowing collapses a
28
+ // UNIFORM repetitive body (a constant table where every line is `KEY: 'VALUE',` → renamed `I: <str>`) to a
29
+ // handful of fingerprints, so two UNRELATED such tables hit 100% renamed Jaccard on ~3-6 shared fingerprints
30
+ // — "same shape, zero shared content". Requiring real shared evidence drops those false positives while a
31
+ // genuine clone (which shares dozens of fingerprints) is untouched.
32
+ const MIN_SHARED_FP = 8;
33
+
34
+ // Same-name symbols across DIFFERENT files the semantic complement to token clones. A token clone
35
+ // says "same body"; a name twin with LOW similarity says "same name, different behavior" — the
36
+ // drift-hazard class of duplicate (three divergent uniqueStrings() implementations) that jaccard
37
+ // ranks too low to surface. OOP-generic lifecycle names are stoplisted; interface implementations
38
+ // still appear, so the caller's report keeps neutral wording.
39
+ const TWIN_STOP = new Set(["constructor", "tostring", "valueof", "dispose", "close", "render", "setup", "teardown", "initialize", "destroy", "connect", "disconnect", "update", "reset", "clear", "create", "handle", "execute", "invoke", "main", "start", "stop", "build", "parse", "value", "index"]);
40
+ function computeNameTwins(frags) {
41
+ const byName = new Map();
42
+ frags.forEach((f, i) => {
43
+ if (f.kind === "string") return;
44
+ const name = String(f.label || "").trim().replace(/\(\)$/, "");
45
+ if (name.length < 5 || !/^[A-Za-z_$][\w$]*$/.test(name) || TWIN_STOP.has(name.toLowerCase()) || /^do_(?:get|post|put|patch|delete|head|options)$/i.test(name)) return;
46
+ const key = name.toLowerCase();
47
+ let a = byName.get(key); if (!a) byName.set(key, (a = []));
48
+ a.push(i);
49
+ });
50
+ const jac = (A, B) => { let inter = 0; for (const h of A) if (B.has(h)) inter++; const u = A.size + B.size - inter; return u ? inter / u : 0; };
51
+ const out = [];
52
+ for (const idxs of byName.values()) {
53
+ const files = new Set(idxs.map((i) => frags[i].file));
54
+ if (files.size < 2 || idxs.length > 12) continue; // single-file overloads / framework-name explosions
55
+ let simMin = 1, simMax = 0;
56
+ const pairs = [];
57
+ for (let a = 0; a < idxs.length; a++) for (let b = a + 1; b < idxs.length; b++) {
58
+ if (frags[idxs[a]].file === frags[idxs[b]].file) continue;
59
+ const s = jac(frags[idxs[a]].fp.renamed, frags[idxs[b]].fp.renamed);
60
+ if (s < simMin) simMin = s;
61
+ if (s > simMax) simMax = s;
62
+ pairs.push({ a: idxs[a], b: idxs[b], similarity: Math.round(s * 100) });
63
+ }
64
+ out.push({
65
+ label: String(frags[idxs[0]].label || "").replace(/\(\)$/, ""), members: idxs, files: files.size,
66
+ simMin: Math.round(simMin * 100), simMax: Math.round(simMax * 100),
67
+ pairs,
68
+ tokens: idxs.reduce((n, i) => n + frags[i].n, 0),
69
+ });
70
+ }
71
+ return out.sort((x, y) => y.tokens - x.tokens).slice(0, 200);
72
+ }
73
+
74
+ function pairsForMode(frags, mode) {
75
+ const index = new Map();
76
+ frags.forEach((f, i) => { for (const h of f.fp[mode]) { let a = index.get(h); if (!a) index.set(h, (a = [])); a.push(i); } });
77
+ // eff[i] = count of i's fingerprints that sit in NON-ubiquitous buckets. Jaccard's numerator (shared)
78
+ // and denominator (union) are BOTH computed over this same restricted set, so excluding a boilerplate
79
+ // fingerprint never deflates similarity — two real clones sharing a widely-repeated preamble still
80
+ // pair at 100% on their unique bodies, and the sim is a true jaccard, not an under-count.
81
+ const eff = new Array(frags.length).fill(0);
82
+ const shared = new Map();
83
+ for (const arr of index.values()) {
84
+ if (arr.length > BUCKET_CAP) continue; // ubiquitous k-gram → excluded from count AND size (both sides)
85
+ for (const idx of arr) eff[idx]++;
86
+ for (let a = 0; a < arr.length; a++) for (let b = a + 1; b < arr.length; b++) {
87
+ const key = arr[a] * 1000000 + arr[b]; // frag count is bounded way below 1e6
88
+ shared.set(key, (shared.get(key) || 0) + 1);
89
+ }
90
+ }
91
+ const pairs = [];
92
+ for (const [key, count] of shared) {
93
+ const i = Math.floor(key / 1000000), j = key % 1000000;
94
+ const union = eff[i] + eff[j] - count;
95
+ const sim = union > 0 ? count / union : 0;
96
+ if (sim >= FLOOR_SIM && count >= MIN_SHARED_FP) pairs.push([i, j, Math.round(sim * 100)]);
97
+ }
98
+ return pairs;
99
+ }
100
+
101
+ // Parse "L<line>" graph symbol locations into per-file ordered symbol lists.
102
+ function symbolRanges(graph) {
103
+ const byFile = new Map();
104
+ for (const n of graph.nodes || []) {
105
+ if (!n.source_file || !String(n.id || "").includes("#")) continue;
106
+ const line = Number((String(n.source_location || "").match(/L(\d+)/) || [])[1] || 0);
107
+ if (!line) continue;
108
+ let arr = byFile.get(n.source_file);
109
+ if (!arr) byFile.set(n.source_file, (arr = []));
110
+ arr.push({ id: n.id, label: n.label || n.id, line });
111
+ }
112
+ for (const arr of byFile.values()) arr.sort((a, b) => a.line - b.line);
113
+ return byFile;
114
+ }
115
+
116
+ export function computeDuplicates(repoPath, graphJsonPath, opts = {}) {
117
+ const includeStrings = !!opts.includeStrings;
118
+ const graph = JSON.parse(readFileSync(graphJsonPath, "utf8"));
119
+ const byFile = symbolRanges(graph);
120
+ // total symbol nodes in the graph — 0 means a file-only graph (built by an older builder before
121
+ // symbol extraction, or a stale graph): clone detection has nothing to work with, and the UI must
122
+ // say "rebuild the graph" instead of the misleading "no clones at these thresholds".
123
+ const repoFiles = listRepoFiles(repoPath);
124
+ const allowedFiles = new Set(repoFiles);
125
+ let graphSymbols = 0;
126
+ for (const [file, arr] of byFile) if (allowedFiles.has(file)) graphSymbols += arr.length;
127
+ const frags = [];
128
+ const boundary = createRepoBoundary(repoPath);
129
+ for (const [file, syms] of byFile) {
130
+ if (!allowedFiles.has(file)) continue;
131
+ const resolved = boundary.resolve(file);
132
+ if (!resolved.ok) continue;
133
+ const full = resolved.path;
134
+ let lines;
135
+ try { lines = readFileSync(full, "utf8").split(/\r?\n/); } catch { continue; }
136
+ const py = /\.py$/i.test(file);
137
+ for (let i = 0; i < syms.length; i++) {
138
+ const start = syms[i].line;
139
+ // hard cap first (next symbol, or EOF, whichever comes first, ≤ MAX_BODY_LINES)
140
+ const hardEnd = Math.min(i + 1 < syms.length ? syms[i + 1].line - 1 : lines.length, start + MAX_BODY_LINES);
141
+ if (hardEnd - start < 2) continue; // one-liners can't be meaningful clones
142
+ // then shrink to where the construct actually closes, so the last symbol doesn't absorb
143
+ // trailing module-level code (module.exports tables, main() calls) up to EOF.
144
+ const bodyLines = lines.slice(start - 1, hardEnd);
145
+ const body = bodyLines.slice(0, bodyEndLineCount(bodyLines, py));
146
+ const end = start + body.length - 1;
147
+ if (end - start < 2) continue;
148
+ const toks = tokenize(stripNonCode(body.join("\n"), py));
149
+ if (toks.strict.length < FLOOR_TOKENS) continue;
150
+ frags.push({
151
+ id: syms[i].id, label: syms[i].label, file, start, end,
152
+ n: toks.strict.length,
153
+ test: isTestPath(file),
154
+ fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
155
+ });
156
+ }
157
+ // ---- opt-in: large multi-line string literals as their own fragments. The code pass above strips
158
+ // string bodies (correctly — content isn't code), which makes embedded DSL templates (inline
159
+ // C#/SQL/PowerShell) invisible to clone detection. Tokenized RAW: the content IS the payload.
160
+ if (includeStrings) {
161
+ const base = file.split("/").pop();
162
+ const pushStr = (startLine, endLine, content) => {
163
+ const toks = tokenize(content);
164
+ if (toks.strict.length < FLOOR_TOKENS) return;
165
+ frags.push({
166
+ id: `${file}#str@${startLine}`, label: `${base}:${startLine} ~${endLine - startLine + 1}-line string`,
167
+ file, start: startLine, end: endLine, n: toks.strict.length, test: isTestPath(file), kind: "string",
168
+ fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
169
+ });
170
+ };
171
+ for (const str of extractLargeStrings(lines.join("\n"), { py, cs: /\.cs$/i.test(file) })) {
172
+ const strLines = str.content.split(/\r?\n/).slice(0, MAX_BODY_LINES);
173
+ // A SECTION shared between two big templates dilutes below the similarity floor when the whole
174
+ // literals are compared (70 shared lines inside 220- and 107-line strings ≈ 27% jaccard). Big
175
+ // literals therefore get the same WINDOW treatment as CSS/HTML files; small ones stay whole.
176
+ if (strLines.length <= WINDOW_LINES * 2) {
177
+ pushStr(str.start, str.start + strLines.length - 1, strLines.join("\n"));
178
+ } else {
179
+ for (let off = 0; off < strLines.length; off += WINDOW_LINES) {
180
+ const chunk = strLines.slice(off, off + WINDOW_LINES);
181
+ if (chunk.length < 3) break;
182
+ pushStr(str.start + off, str.start + off + chunk.length - 1, chunk.join("\n"));
183
+ }
184
+ }
185
+ }
186
+ }
187
+ }
188
+ // ---- windowed fragments for symbol-less file types (CSS/HTML/MD/…), found by walking the repo (NOT the
189
+ // graph — assets are dedup-only). Each file is sliced into WINDOW_LINES blocks and fingerprinted.
190
+ const symFiles = new Set(byFile.keys());
191
+ const assetFiles = repoFiles.filter((file) => WINDOW_EXTS.test(file)).slice(0, MAX_ASSET_FILES);
192
+ for (const file of assetFiles) {
193
+ if (symFiles.has(file)) continue;
194
+ const resolved = boundary.resolve(file);
195
+ if (!resolved.ok) continue;
196
+ let lines;
197
+ try { lines = readFileSync(resolved.path, "utf8").split(/\r?\n/); } catch { continue; }
198
+ for (let start = 1; start <= lines.length; start += WINDOW_LINES) {
199
+ const end = Math.min(start + WINDOW_LINES - 1, lines.length);
200
+ if (end - start < 2) continue;
201
+ const toks = tokenize(stripNonCode(lines.slice(start - 1, end).join("\n"), false));
202
+ if (toks.strict.length < FLOOR_TOKENS) continue;
203
+ frags.push({
204
+ id: `${file}#win@${start}`, label: `${file.split("/").pop()}:${start}-${end}`, file, start, end,
205
+ n: toks.strict.length, test: isTestPath(file),
206
+ fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
207
+ });
208
+ }
209
+ }
210
+ const modes = { strict: pairsForMode(frags, "strict"), renamed: pairsForMode(frags, "renamed") };
211
+ const nameTwins = opts.nameTwins ? computeNameTwins(frags) : null;
212
+ // fp sets are worker-internal — strip them from the payload that crosses the thread boundary
213
+ const slim = frags.map(({ fp, ...rest }) => rest);
214
+ return { ok: true, frags: slim, modes, ...(nameTwins ? { nameTwins } : {}), graphSymbols, floors: { tokens: FLOOR_TOKENS, sim: FLOOR_SIM * 100 } };
215
+ }
@@ -1,15 +1,15 @@
1
- // duplicates.js — content-based clone detection over the repo's OWN graph.json symbols (the Health
2
- // tab's engine). MOSS-style pipeline: symbol bodies (line ranges from the graph) → strip comments &
3
- // string bodies → tokenize → k-gram rolling hashes → winnowing fingerprints → inverted index (no
4
- // O(n²) all-pairs) → jaccard similarity. BOTH normalization modes are computed in one pass so every
5
- // UI knob (similarity %, min size, strict/renamed) filters instantly on the renderer side:
6
- // strict — identifiers kept: only literal copy-paste (Type-1 clones)
7
- // renamed — identifiers canonicalized to "I": catches copy-paste-then-rename (Type-2 clones)
8
- // Pairs are reported down to the FLOOR values; the renderer slices from there upward.
9
- //
10
- // Facade: the implementation lives in the sibling modules —
11
- // duplicates.tokenize.js — stripping, body-end detection, tokenization, winnowing fingerprints
12
- // duplicates.compute.js — fragment extraction, inverted-index pairing, computeDuplicates
13
- // duplicates.run.js — worker offload + mtime cache (runDuplicates entry)
14
- export { computeDuplicates } from "./duplicates.compute.js";
15
- export { runDuplicates } from "./duplicates.run.js";
1
+ // duplicates.js — content-based clone detection over the repo's OWN graph.json symbols (the Health
2
+ // tab's engine). MOSS-style pipeline: symbol bodies (line ranges from the graph) → strip comments &
3
+ // string bodies → tokenize → k-gram rolling hashes → winnowing fingerprints → inverted index (no
4
+ // O(n²) all-pairs) → jaccard similarity. BOTH normalization modes are computed in one pass so every
5
+ // UI knob (similarity %, min size, strict/renamed) filters instantly on the renderer side:
6
+ // strict — identifiers kept: only literal copy-paste (Type-1 clones)
7
+ // renamed — identifiers canonicalized to "I": catches copy-paste-then-rename (Type-2 clones)
8
+ // Pairs are reported down to the FLOOR values; the renderer slices from there upward.
9
+ //
10
+ // Facade: the implementation lives in the sibling modules —
11
+ // duplicates.tokenize.js — stripping, body-end detection, tokenization, winnowing fingerprints
12
+ // duplicates.compute.js — fragment extraction, inverted-index pairing, computeDuplicates
13
+ // duplicates.run.js — worker offload + mtime cache (runDuplicates entry)
14
+ export { computeDuplicates } from "./duplicates.compute.js";
15
+ export { runDuplicates } from "./duplicates.run.js";