weavatrix 0.1.0 → 0.1.2
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.
- package/README.md +59 -18
- package/SECURITY.md +31 -0
- package/package.json +16 -4
- package/skill/SKILL.md +16 -10
- package/src/analysis/coverage-reports.js +14 -11
- package/src/analysis/dead-check.js +7 -2
- package/src/analysis/duplicates.compute.js +221 -215
- package/src/analysis/duplicates.js +15 -15
- package/src/analysis/duplicates.run.js +52 -51
- package/src/analysis/duplicates.tokenize.js +182 -182
- package/src/analysis/endpoints.js +5 -3
- package/src/analysis/graph-analysis.aggregate.js +5 -1
- package/src/analysis/internal-audit.collect.js +37 -11
- package/src/analysis/internal-audit.run.js +8 -5
- package/src/build-graph.js +2 -1
- package/src/child-env.js +7 -0
- package/src/graph/internal-builder.build.js +6 -3
- package/src/graph/internal-builder.langs.js +17 -6
- package/src/graph/internal-builder.resolvers.js +10 -3
- package/src/mcp/catalog.mjs +9 -7
- package/src/mcp/graph-context.mjs +8 -5
- package/src/mcp/sync-payload.mjs +102 -0
- package/src/mcp/tools-actions.mjs +22 -13
- package/src/mcp/tools-impact.mjs +3 -2
- package/src/mcp-rg.mjs +2 -1
- package/src/mcp-server.mjs +26 -17
- package/src/mcp-source-tools.mjs +16 -5
- package/src/process.js +4 -3
- package/src/repo-path.js +53 -0
- package/src/security/installed.js +44 -31
- package/src/security/malware-heuristics.exclusions.js +134 -134
- package/src/security/malware-heuristics.js +15 -15
- package/src/security/malware-heuristics.roots.js +142 -142
- package/src/security/malware-heuristics.scan.js +85 -85
- package/src/security/malware-heuristics.sweep.js +122 -122
|
@@ -1,51 +1,52 @@
|
|
|
1
|
-
// duplicates.run.js — the repos:duplicates entry point (split from duplicates.js): worker-thread
|
|
2
|
-
// offload with in-process fallback, cached per (repo, graph.json mtime).
|
|
3
|
-
import { existsSync, statSync } from "node:fs";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { Worker } from "node:worker_threads";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
worker.once("
|
|
22
|
-
worker.once("
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
1
|
+
// duplicates.run.js — the repos:duplicates entry point (split from duplicates.js): worker-thread
|
|
2
|
+
// offload with in-process fallback, cached per (repo, graph.json mtime).
|
|
3
|
+
import { existsSync, statSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Worker } from "node:worker_threads";
|
|
6
|
+
import { childProcessEnv } from "../child-env.js";
|
|
7
|
+
import { graphOutDirForRepo } from "../graph/layout.js";
|
|
8
|
+
import { computeDuplicates } from "./duplicates.compute.js";
|
|
9
|
+
|
|
10
|
+
function computeInWorker(repoPath, graphJsonPath) {
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
let worker;
|
|
13
|
+
try {
|
|
14
|
+
worker = new Worker(new URL("./duplicates-worker.js", import.meta.url), { workerData: { repoPath, graphJsonPath }, env: childProcessEnv() });
|
|
15
|
+
} catch (e) {
|
|
16
|
+
reject(Object.assign(e, { workerStartFailed: true }));
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
let settled = false;
|
|
20
|
+
const done = (fn, v) => { if (!settled) { settled = true; fn(v); } };
|
|
21
|
+
worker.once("message", (msg) => done(resolve, msg));
|
|
22
|
+
worker.once("error", (e) => done(reject, Object.assign(e, { workerStartFailed: true })));
|
|
23
|
+
worker.once("exit", (code) => { if (code !== 0) done(reject, Object.assign(new Error(`duplicates worker exited with code ${code}`), { workerStartFailed: true })); });
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// repos:duplicates entry — cached per (repo, graph.json mtime): re-running with an unchanged graph is
|
|
28
|
+
// free. `force` (the UI's ↻ rescan) bypasses the cache: fragment BODIES are read from live source, so a
|
|
29
|
+
// source edit that didn't rebuild the graph (same mtime) must still be re-scanned on demand.
|
|
30
|
+
const _cache = new Map();
|
|
31
|
+
export async function runDuplicates(repoPath, force = false) {
|
|
32
|
+
const repo = String(repoPath || "");
|
|
33
|
+
if (!repo || !existsSync(repo)) return { ok: false, error: "Repo path not found" };
|
|
34
|
+
const graphJsonPath = join(graphOutDirForRepo(repo), "graph.json");
|
|
35
|
+
if (!existsSync(graphJsonPath)) {
|
|
36
|
+
return { ok: false, needsGraph: true, error: "No graph yet — build the Relations graph first (↻ on the Relations tab)" };
|
|
37
|
+
}
|
|
38
|
+
let mtime = 0;
|
|
39
|
+
try { mtime = statSync(graphJsonPath).mtimeMs; } catch { /* treat as uncached */ }
|
|
40
|
+
const cached = _cache.get(repo);
|
|
41
|
+
if (!force && cached && cached.mtime === mtime) return cached.result;
|
|
42
|
+
let result;
|
|
43
|
+
try {
|
|
44
|
+
result = await computeInWorker(repo, graphJsonPath);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (!e || !e.workerStartFailed) return { ok: false, error: e.message || String(e) };
|
|
47
|
+
try { result = computeDuplicates(repo, graphJsonPath); } // in-process fallback (exotic packaging)
|
|
48
|
+
catch (e2) { return { ok: false, error: e2.message || String(e2) }; }
|
|
49
|
+
}
|
|
50
|
+
if (result && result.ok) _cache.set(repo, { mtime, result });
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
@@ -1,182 +1,182 @@
|
|
|
1
|
-
// duplicates.tokenize.js — lexical layer of the clone detector (split from duplicates.js): comment &
|
|
2
|
-
// string stripping, body-end detection, strict/renamed tokenization, and winnowing fingerprints.
|
|
3
|
-
|
|
4
|
-
const K = 8; // k-gram length (tokens)
|
|
5
|
-
const W = 4; // winnowing window → guaranteed detection of matches ≥ K+W-1 tokens
|
|
6
|
-
const STRLIT = String.fromCharCode(0); // opaque-literal sentinel for every string/regex body: a NUL
|
|
7
|
-
// its own class (never an identifier "I" nor a number "N"), so a literal can
|
|
8
|
-
// never masquerade as code in either mode
|
|
9
|
-
|
|
10
|
-
const KEYWORDS = new Set(("if else for while do switch case break continue return function const let var new class extends async await try catch finally throw import from export default typeof instanceof in of delete void yield static get set this super null undefined true false def elif except lambda pass raise with as is not and or None True False func go defer chan map range struct interface type package nil err string int bool byte float64 public private protected final void long double boolean").split(" "));
|
|
11
|
-
|
|
12
|
-
// A leading `/` is a REGEX literal (not division) when the previous significant char is one of these
|
|
13
|
-
// or the fragment start; after a word char / ) / ] it is division. Covers .match(/…/), = /…/, (/…/),
|
|
14
|
-
// and arrow `x => /…/`. NOTE: `+` and `-` are deliberately EXCLUDED — a regex never legitimately
|
|
15
|
-
// follows them, but `i++ / 2` and `a - b / c` do, and including them mis-scanned the division as a
|
|
16
|
-
// regex and ate the rest of the line.
|
|
17
|
-
const REGEX_PREV = new Set("(,=:[!&|?{};~*%^<>".split(""));
|
|
18
|
-
|
|
19
|
-
// Replace comments with nothing and string/regex BODIES with the sentinel, so their contents never
|
|
20
|
-
// count as code. Handles Python triple-quoted docstrings (embedded quotes no longer desync the scan)
|
|
21
|
-
// and JS regex literals (a quote inside /['"]/ no longer opens a phantom string).
|
|
22
|
-
export function stripNonCode(text, py) {
|
|
23
|
-
let out = "", i = 0, prevSig = "";
|
|
24
|
-
const s = String(text || "");
|
|
25
|
-
const push = (c) => { out += c; const t = c.trim(); if (t) prevSig = t[t.length - 1]; };
|
|
26
|
-
while (i < s.length) {
|
|
27
|
-
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
28
|
-
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
29
|
-
if (py && (three === "'''" || three === '"""')) {
|
|
30
|
-
i += 3;
|
|
31
|
-
while (i < s.length && s.slice(i, i + 3) !== three) i++;
|
|
32
|
-
i += 3; push(` ${STRLIT} `); continue;
|
|
33
|
-
}
|
|
34
|
-
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
35
|
-
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") i++; i += 2; continue; }
|
|
36
|
-
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
37
|
-
i++; let inClass = false; // '/' inside a [...] char class is literal, not the terminator
|
|
38
|
-
while (i < s.length && s[i] !== "\n") {
|
|
39
|
-
const c = s[i];
|
|
40
|
-
if (c === "\\") { i += 2; continue; }
|
|
41
|
-
if (c === "[") inClass = true;
|
|
42
|
-
else if (c === "]") inClass = false;
|
|
43
|
-
else if (c === "/" && !inClass) { i++; break; }
|
|
44
|
-
i++;
|
|
45
|
-
}
|
|
46
|
-
while (i < s.length && /[a-z]/i.test(s[i])) i++; // regex flags (gimsuy)
|
|
47
|
-
push(` ${STRLIT} `); continue;
|
|
48
|
-
}
|
|
49
|
-
if (ch === '"' || ch === "'" || ch === "`") {
|
|
50
|
-
const q = ch; i++;
|
|
51
|
-
while (i < s.length && s[i] !== q) { if (s[i] === "\\") i++; i++; }
|
|
52
|
-
i++; push(` ${STRLIT} `); continue;
|
|
53
|
-
}
|
|
54
|
-
push(ch); i++;
|
|
55
|
-
}
|
|
56
|
-
return out;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// Where a symbol's body ends — so the LAST symbol in a file doesn't swallow trailing module-level code
|
|
60
|
-
// (module.exports tables, main() calls, handler registrations) up to EOF and dilute/misattribute
|
|
61
|
-
// clones. Brace/bracket depth for brace langs (body ends when {}()[] balance after first opening);
|
|
62
|
-
// indentation for Python. Returns a 1-based line count within bodyLines (≤ its length; = its length
|
|
63
|
-
// when the construct never closes, so the caller's cap stands).
|
|
64
|
-
export function bodyEndLineCount(bodyLines, py) {
|
|
65
|
-
if (py) {
|
|
66
|
-
const base = bodyLines[0].match(/^[ \t]*/)[0].length;
|
|
67
|
-
let last = 1;
|
|
68
|
-
for (let k = 1; k < bodyLines.length; k++) {
|
|
69
|
-
const ln = bodyLines[k];
|
|
70
|
-
if (!ln.trim()) continue; // blank lines never end a block
|
|
71
|
-
if (ln.match(/^[ \t]*/)[0].length <= base) return last; // dedent to ≤ the def → body ended above
|
|
72
|
-
last = k + 1;
|
|
73
|
-
}
|
|
74
|
-
return bodyLines.length;
|
|
75
|
-
}
|
|
76
|
-
const text = bodyLines.join("\n");
|
|
77
|
-
let depth = 0, opened = false, i = 0, line = 1, prevSig = "";
|
|
78
|
-
while (i < text.length) {
|
|
79
|
-
const ch = text[i], two = text.slice(i, i + 2);
|
|
80
|
-
if (ch === "\n") { line++; i++; continue; }
|
|
81
|
-
if (two === "//") { while (i < text.length && text[i] !== "\n") i++; continue; }
|
|
82
|
-
if (two === "/*") { i += 2; while (i < text.length && text.slice(i, i + 2) !== "*/") { if (text[i] === "\n") line++; i++; } i += 2; continue; }
|
|
83
|
-
if (ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
84
|
-
i++; let inClass = false;
|
|
85
|
-
while (i < text.length && text[i] !== "\n") { const c = text[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
86
|
-
prevSig = "/"; continue;
|
|
87
|
-
}
|
|
88
|
-
if (ch === '"' || ch === "'" || ch === "`") { const q = ch; i++; while (i < text.length && text[i] !== q) { if (text[i] === "\\") i++; else if (text[i] === "\n") line++; i++; } i++; prevSig = q; continue; }
|
|
89
|
-
// depth tracks all brackets, but only a { or [ opens the BODY — a bare (param list) returning to
|
|
90
|
-
// depth 0 must not be read as the construct closing on line 1
|
|
91
|
-
if (ch === "{" || ch === "(" || ch === "[") { depth++; if (ch === "{" || ch === "[") opened = true; }
|
|
92
|
-
else if (ch === "}" || ch === ")" || ch === "]") { depth--; if (opened && depth <= 0) return line; }
|
|
93
|
-
if (ch.trim()) prevSig = ch;
|
|
94
|
-
i++;
|
|
95
|
-
}
|
|
96
|
-
return bodyLines.length;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// Large multi-line string literals — the OPPOSITE selection to stripNonCode: everything the code
|
|
100
|
-
// scan throws away. Embedded DSLs (inline C#/SQL/PowerShell templates) are invisible to the normal
|
|
101
|
-
// clone pass because their bodies are stripped; this extractor feeds them back in as their own
|
|
102
|
-
// fragments when the caller opts in (find_duplicates include_strings). Comment/regex handling
|
|
103
|
-
// mirrors stripNonCode so a quote inside a comment never opens a phantom literal.
|
|
104
|
-
export function extractLargeStrings(text, { py = false, cs = false, minLines = 6 } = {}) {
|
|
105
|
-
const s = String(text || "");
|
|
106
|
-
const out = [];
|
|
107
|
-
let i = 0, line = 1, prevSig = "";
|
|
108
|
-
const capture = (from, to, startLine) => {
|
|
109
|
-
const content = s.slice(from, to);
|
|
110
|
-
const nl = (content.match(/\n/g) || []).length;
|
|
111
|
-
if (nl + 1 >= minLines) out.push({ start: startLine, end: startLine + nl, content });
|
|
112
|
-
};
|
|
113
|
-
while (i < s.length) {
|
|
114
|
-
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
115
|
-
if (ch === "\n") { line++; i++; continue; }
|
|
116
|
-
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
117
|
-
if (py && (three === "'''" || three === '"""')) {
|
|
118
|
-
const startLine = line; i += 3; const from = i;
|
|
119
|
-
while (i < s.length && s.slice(i, i + 3) !== three) { if (s[i] === "\n") line++; i++; }
|
|
120
|
-
capture(from, i, startLine); i += 3; continue;
|
|
121
|
-
}
|
|
122
|
-
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
123
|
-
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") { if (s[i] === "\n") line++; i++; } i += 2; continue; }
|
|
124
|
-
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
125
|
-
i++; let inClass = false;
|
|
126
|
-
while (i < s.length && s[i] !== "\n") { const c = s[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
127
|
-
prevSig = "/"; continue;
|
|
128
|
-
}
|
|
129
|
-
if (cs && two === '@"') { // C# verbatim string; "" is the escaped quote
|
|
130
|
-
const startLine = line; i += 2; const from = i;
|
|
131
|
-
while (i < s.length) { if (s.slice(i, i + 2) === '""') { i += 2; continue; } if (s[i] === '"') break; if (s[i] === "\n") line++; i++; }
|
|
132
|
-
capture(from, i, startLine); i++; continue;
|
|
133
|
-
}
|
|
134
|
-
if (!py && ch === "`") { // JS/TS template literal — the main multi-line carrier
|
|
135
|
-
const startLine = line; i++; const from = i;
|
|
136
|
-
while (i < s.length && s[i] !== "`") { if (s[i] === "\\") { i++; if (s[i] === "\n") line++; i++; continue; } if (s[i] === "\n") line++; i++; }
|
|
137
|
-
capture(from, i, startLine); i++; continue;
|
|
138
|
-
}
|
|
139
|
-
if (ch === '"' || ch === "'") { // single-line strings can't span minLines — just skip past
|
|
140
|
-
const q = ch; i++;
|
|
141
|
-
while (i < s.length && s[i] !== q && s[i] !== "\n") { if (s[i] === "\\") i++; i++; }
|
|
142
|
-
if (s[i] === q) i++; continue;
|
|
143
|
-
}
|
|
144
|
-
if (ch.trim()) prevSig = ch;
|
|
145
|
-
i++;
|
|
146
|
-
}
|
|
147
|
-
return out;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// one raw token stream; the two modes differ only in identifier canonicalization
|
|
151
|
-
export function tokenize(text) {
|
|
152
|
-
const raw = text.match(/[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|[^\s\w]/g) || [];
|
|
153
|
-
const strict = [];
|
|
154
|
-
const renamed = [];
|
|
155
|
-
for (const t of raw) {
|
|
156
|
-
if (/^\d/.test(t)) { strict.push("N"); renamed.push("N"); continue; }
|
|
157
|
-
if (/^[A-Za-z_$]/.test(t) && !KEYWORDS.has(t)) { strict.push(t); renamed.push("I"); continue; }
|
|
158
|
-
strict.push(t); renamed.push(t);
|
|
159
|
-
}
|
|
160
|
-
return { strict, renamed };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
export function fingerprints(toks) {
|
|
164
|
-
if (toks.length < K + W - 1) return new Set();
|
|
165
|
-
const hashes = [];
|
|
166
|
-
for (let i = 0; i + K <= toks.length; i++) {
|
|
167
|
-
let h = 0;
|
|
168
|
-
for (let j = i; j < i + K; j++) {
|
|
169
|
-
const s = toks[j];
|
|
170
|
-
for (let c = 0; c < s.length; c++) h = (h * 31 + s.charCodeAt(c)) | 0;
|
|
171
|
-
h = (h * 131) | 0;
|
|
172
|
-
}
|
|
173
|
-
hashes.push(h >>> 0);
|
|
174
|
-
}
|
|
175
|
-
const fp = new Set();
|
|
176
|
-
for (let i = 0; i + W <= hashes.length + 1; i++) {
|
|
177
|
-
let min = Infinity;
|
|
178
|
-
for (let j = i; j < Math.min(i + W, hashes.length); j++) if (hashes[j] < min) min = hashes[j];
|
|
179
|
-
fp.add(min);
|
|
180
|
-
}
|
|
181
|
-
return fp;
|
|
182
|
-
}
|
|
1
|
+
// duplicates.tokenize.js — lexical layer of the clone detector (split from duplicates.js): comment &
|
|
2
|
+
// string stripping, body-end detection, strict/renamed tokenization, and winnowing fingerprints.
|
|
3
|
+
|
|
4
|
+
const K = 8; // k-gram length (tokens)
|
|
5
|
+
const W = 4; // winnowing window → guaranteed detection of matches ≥ K+W-1 tokens
|
|
6
|
+
const STRLIT = String.fromCharCode(0); // opaque-literal sentinel for every string/regex body: a NUL
|
|
7
|
+
// its own class (never an identifier "I" nor a number "N"), so a literal can
|
|
8
|
+
// never masquerade as code in either mode
|
|
9
|
+
|
|
10
|
+
const KEYWORDS = new Set(("if else for while do switch case break continue return function const let var new class extends async await try catch finally throw import from export default typeof instanceof in of delete void yield static get set this super null undefined true false def elif except lambda pass raise with as is not and or None True False func go defer chan map range struct interface type package nil err string int bool byte float64 public private protected final void long double boolean").split(" "));
|
|
11
|
+
|
|
12
|
+
// A leading `/` is a REGEX literal (not division) when the previous significant char is one of these
|
|
13
|
+
// or the fragment start; after a word char / ) / ] it is division. Covers .match(/…/), = /…/, (/…/),
|
|
14
|
+
// and arrow `x => /…/`. NOTE: `+` and `-` are deliberately EXCLUDED — a regex never legitimately
|
|
15
|
+
// follows them, but `i++ / 2` and `a - b / c` do, and including them mis-scanned the division as a
|
|
16
|
+
// regex and ate the rest of the line.
|
|
17
|
+
const REGEX_PREV = new Set("(,=:[!&|?{};~*%^<>".split(""));
|
|
18
|
+
|
|
19
|
+
// Replace comments with nothing and string/regex BODIES with the sentinel, so their contents never
|
|
20
|
+
// count as code. Handles Python triple-quoted docstrings (embedded quotes no longer desync the scan)
|
|
21
|
+
// and JS regex literals (a quote inside /['"]/ no longer opens a phantom string).
|
|
22
|
+
export function stripNonCode(text, py) {
|
|
23
|
+
let out = "", i = 0, prevSig = "";
|
|
24
|
+
const s = String(text || "");
|
|
25
|
+
const push = (c) => { out += c; const t = c.trim(); if (t) prevSig = t[t.length - 1]; };
|
|
26
|
+
while (i < s.length) {
|
|
27
|
+
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
28
|
+
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
29
|
+
if (py && (three === "'''" || three === '"""')) {
|
|
30
|
+
i += 3;
|
|
31
|
+
while (i < s.length && s.slice(i, i + 3) !== three) i++;
|
|
32
|
+
i += 3; push(` ${STRLIT} `); continue;
|
|
33
|
+
}
|
|
34
|
+
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
35
|
+
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") i++; i += 2; continue; }
|
|
36
|
+
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
37
|
+
i++; let inClass = false; // '/' inside a [...] char class is literal, not the terminator
|
|
38
|
+
while (i < s.length && s[i] !== "\n") {
|
|
39
|
+
const c = s[i];
|
|
40
|
+
if (c === "\\") { i += 2; continue; }
|
|
41
|
+
if (c === "[") inClass = true;
|
|
42
|
+
else if (c === "]") inClass = false;
|
|
43
|
+
else if (c === "/" && !inClass) { i++; break; }
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
while (i < s.length && /[a-z]/i.test(s[i])) i++; // regex flags (gimsuy)
|
|
47
|
+
push(` ${STRLIT} `); continue;
|
|
48
|
+
}
|
|
49
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
50
|
+
const q = ch; i++;
|
|
51
|
+
while (i < s.length && s[i] !== q) { if (s[i] === "\\") i++; i++; }
|
|
52
|
+
i++; push(` ${STRLIT} `); continue;
|
|
53
|
+
}
|
|
54
|
+
push(ch); i++;
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Where a symbol's body ends — so the LAST symbol in a file doesn't swallow trailing module-level code
|
|
60
|
+
// (module.exports tables, main() calls, handler registrations) up to EOF and dilute/misattribute
|
|
61
|
+
// clones. Brace/bracket depth for brace langs (body ends when {}()[] balance after first opening);
|
|
62
|
+
// indentation for Python. Returns a 1-based line count within bodyLines (≤ its length; = its length
|
|
63
|
+
// when the construct never closes, so the caller's cap stands).
|
|
64
|
+
export function bodyEndLineCount(bodyLines, py) {
|
|
65
|
+
if (py) {
|
|
66
|
+
const base = bodyLines[0].match(/^[ \t]*/)[0].length;
|
|
67
|
+
let last = 1;
|
|
68
|
+
for (let k = 1; k < bodyLines.length; k++) {
|
|
69
|
+
const ln = bodyLines[k];
|
|
70
|
+
if (!ln.trim()) continue; // blank lines never end a block
|
|
71
|
+
if (ln.match(/^[ \t]*/)[0].length <= base) return last; // dedent to ≤ the def → body ended above
|
|
72
|
+
last = k + 1;
|
|
73
|
+
}
|
|
74
|
+
return bodyLines.length;
|
|
75
|
+
}
|
|
76
|
+
const text = bodyLines.join("\n");
|
|
77
|
+
let depth = 0, opened = false, i = 0, line = 1, prevSig = "";
|
|
78
|
+
while (i < text.length) {
|
|
79
|
+
const ch = text[i], two = text.slice(i, i + 2);
|
|
80
|
+
if (ch === "\n") { line++; i++; continue; }
|
|
81
|
+
if (two === "//") { while (i < text.length && text[i] !== "\n") i++; continue; }
|
|
82
|
+
if (two === "/*") { i += 2; while (i < text.length && text.slice(i, i + 2) !== "*/") { if (text[i] === "\n") line++; i++; } i += 2; continue; }
|
|
83
|
+
if (ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
84
|
+
i++; let inClass = false;
|
|
85
|
+
while (i < text.length && text[i] !== "\n") { const c = text[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
86
|
+
prevSig = "/"; continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === '"' || ch === "'" || ch === "`") { const q = ch; i++; while (i < text.length && text[i] !== q) { if (text[i] === "\\") i++; else if (text[i] === "\n") line++; i++; } i++; prevSig = q; continue; }
|
|
89
|
+
// depth tracks all brackets, but only a { or [ opens the BODY — a bare (param list) returning to
|
|
90
|
+
// depth 0 must not be read as the construct closing on line 1
|
|
91
|
+
if (ch === "{" || ch === "(" || ch === "[") { depth++; if (ch === "{" || ch === "[") opened = true; }
|
|
92
|
+
else if (ch === "}" || ch === ")" || ch === "]") { depth--; if (opened && depth <= 0) return line; }
|
|
93
|
+
if (ch.trim()) prevSig = ch;
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
return bodyLines.length;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Large multi-line string literals — the OPPOSITE selection to stripNonCode: everything the code
|
|
100
|
+
// scan throws away. Embedded DSLs (inline C#/SQL/PowerShell templates) are invisible to the normal
|
|
101
|
+
// clone pass because their bodies are stripped; this extractor feeds them back in as their own
|
|
102
|
+
// fragments when the caller opts in (find_duplicates include_strings). Comment/regex handling
|
|
103
|
+
// mirrors stripNonCode so a quote inside a comment never opens a phantom literal.
|
|
104
|
+
export function extractLargeStrings(text, { py = false, cs = false, minLines = 6 } = {}) {
|
|
105
|
+
const s = String(text || "");
|
|
106
|
+
const out = [];
|
|
107
|
+
let i = 0, line = 1, prevSig = "";
|
|
108
|
+
const capture = (from, to, startLine) => {
|
|
109
|
+
const content = s.slice(from, to);
|
|
110
|
+
const nl = (content.match(/\n/g) || []).length;
|
|
111
|
+
if (nl + 1 >= minLines) out.push({ start: startLine, end: startLine + nl, content });
|
|
112
|
+
};
|
|
113
|
+
while (i < s.length) {
|
|
114
|
+
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
115
|
+
if (ch === "\n") { line++; i++; continue; }
|
|
116
|
+
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
117
|
+
if (py && (three === "'''" || three === '"""')) {
|
|
118
|
+
const startLine = line; i += 3; const from = i;
|
|
119
|
+
while (i < s.length && s.slice(i, i + 3) !== three) { if (s[i] === "\n") line++; i++; }
|
|
120
|
+
capture(from, i, startLine); i += 3; continue;
|
|
121
|
+
}
|
|
122
|
+
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
123
|
+
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") { if (s[i] === "\n") line++; i++; } i += 2; continue; }
|
|
124
|
+
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
125
|
+
i++; let inClass = false;
|
|
126
|
+
while (i < s.length && s[i] !== "\n") { const c = s[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
127
|
+
prevSig = "/"; continue;
|
|
128
|
+
}
|
|
129
|
+
if (cs && two === '@"') { // C# verbatim string; "" is the escaped quote
|
|
130
|
+
const startLine = line; i += 2; const from = i;
|
|
131
|
+
while (i < s.length) { if (s.slice(i, i + 2) === '""') { i += 2; continue; } if (s[i] === '"') break; if (s[i] === "\n") line++; i++; }
|
|
132
|
+
capture(from, i, startLine); i++; continue;
|
|
133
|
+
}
|
|
134
|
+
if (!py && ch === "`") { // JS/TS template literal — the main multi-line carrier
|
|
135
|
+
const startLine = line; i++; const from = i;
|
|
136
|
+
while (i < s.length && s[i] !== "`") { if (s[i] === "\\") { i++; if (s[i] === "\n") line++; i++; continue; } if (s[i] === "\n") line++; i++; }
|
|
137
|
+
capture(from, i, startLine); i++; continue;
|
|
138
|
+
}
|
|
139
|
+
if (ch === '"' || ch === "'") { // single-line strings can't span minLines — just skip past
|
|
140
|
+
const q = ch; i++;
|
|
141
|
+
while (i < s.length && s[i] !== q && s[i] !== "\n") { if (s[i] === "\\") i++; i++; }
|
|
142
|
+
if (s[i] === q) i++; continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch.trim()) prevSig = ch;
|
|
145
|
+
i++;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// one raw token stream; the two modes differ only in identifier canonicalization
|
|
151
|
+
export function tokenize(text) {
|
|
152
|
+
const raw = text.match(/[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|[^\s\w]/g) || [];
|
|
153
|
+
const strict = [];
|
|
154
|
+
const renamed = [];
|
|
155
|
+
for (const t of raw) {
|
|
156
|
+
if (/^\d/.test(t)) { strict.push("N"); renamed.push("N"); continue; }
|
|
157
|
+
if (/^[A-Za-z_$]/.test(t) && !KEYWORDS.has(t)) { strict.push(t); renamed.push("I"); continue; }
|
|
158
|
+
strict.push(t); renamed.push(t);
|
|
159
|
+
}
|
|
160
|
+
return { strict, renamed };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function fingerprints(toks) {
|
|
164
|
+
if (toks.length < K + W - 1) return new Set();
|
|
165
|
+
const hashes = [];
|
|
166
|
+
for (let i = 0; i + K <= toks.length; i++) {
|
|
167
|
+
let h = 0;
|
|
168
|
+
for (let j = i; j < i + K; j++) {
|
|
169
|
+
const s = toks[j];
|
|
170
|
+
for (let c = 0; c < s.length; c++) h = (h * 31 + s.charCodeAt(c)) | 0;
|
|
171
|
+
h = (h * 131) | 0;
|
|
172
|
+
}
|
|
173
|
+
hashes.push(h >>> 0);
|
|
174
|
+
}
|
|
175
|
+
const fp = new Set();
|
|
176
|
+
for (let i = 0; i + W <= hashes.length + 1; i++) {
|
|
177
|
+
let min = Infinity;
|
|
178
|
+
for (let j = i; j < Math.min(i + W, hashes.length); j++) if (hashes[j] < min) min = hashes[j];
|
|
179
|
+
fp.add(min);
|
|
180
|
+
}
|
|
181
|
+
return fp;
|
|
182
|
+
}
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
// • method-call routes (Express/Fastify/Koa/Hono/gin/echo): app.get("/path", handler)
|
|
7
7
|
// • decorators (FastAPI/Flask/NestJS): @app.get("/path") / @Get("/path")
|
|
8
8
|
// • Go net/http: mux.HandleFunc("/path", handler)
|
|
9
|
-
import { join } from "node:path";
|
|
10
9
|
import { safeRead } from "../util.js";
|
|
10
|
+
import { createRepoBoundary } from "../repo-path.js";
|
|
11
11
|
|
|
12
12
|
const MAX_FILES = 3000;
|
|
13
13
|
const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "ALL", "ANY"]);
|
|
@@ -125,11 +125,13 @@ const normParamKey = (p) => String(p).replace(/\{([^/}]+)\}/g, ":$1");
|
|
|
125
125
|
export function detectEndpoints(repoPath, codeFiles) {
|
|
126
126
|
const files = (codeFiles || []).slice(0, MAX_FILES);
|
|
127
127
|
const byKey = new Map();
|
|
128
|
+
const boundary = createRepoBoundary(repoPath);
|
|
128
129
|
for (const f of files) {
|
|
129
130
|
const rel = f.path || f;
|
|
130
|
-
const full = f.full || join(repoPath, rel);
|
|
131
131
|
if (!/\.(js|ts|tsx|jsx|cjs|mjs|py|go)$/i.test(rel)) continue;
|
|
132
|
-
const
|
|
132
|
+
const resolved = boundary.resolve(rel);
|
|
133
|
+
if (!resolved.ok) continue;
|
|
134
|
+
const text = safeRead(resolved.path);
|
|
133
135
|
if (!text || !/["'`]\/|\.(get|post|put|patch|delete)\s*\(|HandleFunc|@\w*\.?(get|post|put|patch|delete)/i.test(text)) continue;
|
|
134
136
|
for (const e of extractEndpointsFromText(text, rel.replace(/\\/g, "/"))) {
|
|
135
137
|
const key = `${e.method} ${normParamKey(e.path)}`;
|
|
@@ -5,6 +5,7 @@ import { readFileSync } from "node:fs";
|
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { normalizeRepoParts, readCoverageForRepo, pctFromCounts } from "./coverage-reports.js";
|
|
7
7
|
import { bareSymbolName, countLocalRefsOutsideOwnRange, computeSymbolExternalRefs } from "./graph-analysis.refs.js";
|
|
8
|
+
import { createRepoBoundary } from "../repo-path.js";
|
|
8
9
|
|
|
9
10
|
// Aggregate a built graph.json into the file- and module-level view the UI needs:
|
|
10
11
|
// - graph-builder nodes are FILES *and* their symbols (functions/methods), linked file→symbol by the
|
|
@@ -175,11 +176,14 @@ export function aggregateGraph(graph, repoRoot) {
|
|
|
175
176
|
const fileLoc = new Map();
|
|
176
177
|
const fileText = new Map();
|
|
177
178
|
if (repoRoot) {
|
|
179
|
+
const boundary = createRepoBoundary(repoRoot);
|
|
178
180
|
folderLoc = {};
|
|
179
181
|
for (const [sourceFile, mod] of fileModule) {
|
|
180
182
|
let loc = 0;
|
|
181
183
|
try {
|
|
182
|
-
const
|
|
184
|
+
const resolved = boundary.resolve(sourceFile);
|
|
185
|
+
if (!resolved.ok) throw new Error("source path is outside the repository");
|
|
186
|
+
const txt = readFileSync(resolved.path, "utf8");
|
|
183
187
|
loc = txt ? txt.split("\n").length : 0;
|
|
184
188
|
fileText.set(sourceFile, txt || "");
|
|
185
189
|
} catch {
|
|
@@ -3,9 +3,18 @@
|
|
|
3
3
|
import { readFileSync, readdirSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { parseRequirementsNames, parsePyprojectDeps, parsePipfileDeps } from "./manifests.js";
|
|
6
|
+
import { createRepoBoundary } from "../repo-path.js";
|
|
6
7
|
|
|
7
8
|
export const readText = (p) => { try { return readFileSync(p, "utf8"); } catch { return null; } };
|
|
8
9
|
export const readJson = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; } };
|
|
10
|
+
export const readRepoText = (boundary, relativePath) => {
|
|
11
|
+
const resolved = boundary.resolve(relativePath);
|
|
12
|
+
return resolved.ok ? readText(resolved.path) : null;
|
|
13
|
+
};
|
|
14
|
+
export const readRepoJson = (boundary, relativePath) => {
|
|
15
|
+
const resolved = boundary.resolve(relativePath);
|
|
16
|
+
return resolved.ok ? readJson(resolved.path) : null;
|
|
17
|
+
};
|
|
9
18
|
const SOURCE_EXT_RE = /\.(?:[cm]?[jt]sx?|py|go|vue|svelte)$/i;
|
|
10
19
|
const SOURCE_SKIP_DIRS = new Set([
|
|
11
20
|
".git", ".hg", ".svn", "node_modules", "vendor", "dist", "build", "coverage", ".next", "out",
|
|
@@ -15,10 +24,13 @@ const SOURCE_SKIP_DIRS = new Set([
|
|
|
15
24
|
|
|
16
25
|
export function collectSourceTexts(repoRoot, graph) {
|
|
17
26
|
const sources = new Map();
|
|
27
|
+
const boundary = createRepoBoundary(repoRoot);
|
|
18
28
|
const add = (rel) => {
|
|
19
29
|
const file = String(rel || "").replace(/\\/g, "/");
|
|
20
30
|
if (!file || sources.has(file)) return;
|
|
21
|
-
const
|
|
31
|
+
const resolved = boundary.resolve(file);
|
|
32
|
+
if (!resolved.ok) return;
|
|
33
|
+
const text = readText(resolved.path);
|
|
22
34
|
if (text != null) sources.set(file, text);
|
|
23
35
|
};
|
|
24
36
|
|
|
@@ -63,11 +75,14 @@ const CONFIG_FILES = [
|
|
|
63
75
|
|
|
64
76
|
export function collectConfigTexts(repoRoot) {
|
|
65
77
|
const map = new Map();
|
|
66
|
-
|
|
78
|
+
const boundary = createRepoBoundary(repoRoot);
|
|
79
|
+
for (const f of CONFIG_FILES) { const t = readRepoText(boundary, f); if (t != null) map.set(f, t); }
|
|
67
80
|
try {
|
|
68
|
-
|
|
81
|
+
const workflows = boundary.resolve(".github/workflows");
|
|
82
|
+
if (!workflows.ok) throw new Error("workflows directory is outside the repository");
|
|
83
|
+
for (const wf of readdirSync(workflows.path)) {
|
|
69
84
|
if (!/\.ya?ml$/i.test(wf)) continue;
|
|
70
|
-
const t =
|
|
85
|
+
const t = readRepoText(boundary, `.github/workflows/${wf}`);
|
|
71
86
|
if (t != null) map.set(`.github/workflows/${wf}`, t);
|
|
72
87
|
}
|
|
73
88
|
} catch { /* no workflows */ }
|
|
@@ -78,14 +93,21 @@ export function collectConfigTexts(repoRoot) {
|
|
|
78
93
|
// Those are importable without being declared — never "missing" deps.
|
|
79
94
|
export function workspacePkgNames(repoRoot, pkg) {
|
|
80
95
|
const names = new Set();
|
|
96
|
+
const boundary = createRepoBoundary(repoRoot);
|
|
81
97
|
const globs = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces && pkg.workspaces.packages) || [];
|
|
82
98
|
for (const g of globs) {
|
|
83
99
|
const base = String(g).replace(/\/?\*+.*$/, "");
|
|
84
100
|
let dirs = [];
|
|
85
|
-
if (/\*/.test(String(g))) {
|
|
101
|
+
if (/\*/.test(String(g))) {
|
|
102
|
+
try {
|
|
103
|
+
const resolvedBase = boundary.resolve(base || ".");
|
|
104
|
+
if (!resolvedBase.ok) continue;
|
|
105
|
+
dirs = readdirSync(resolvedBase.path).map((d) => join(base, d));
|
|
106
|
+
} catch { continue; }
|
|
107
|
+
}
|
|
86
108
|
else dirs = [String(g)];
|
|
87
109
|
for (const d of dirs) {
|
|
88
|
-
const p =
|
|
110
|
+
const p = readRepoJson(boundary, join(d, "package.json"));
|
|
89
111
|
if (p && p.name) names.add(p.name);
|
|
90
112
|
}
|
|
91
113
|
}
|
|
@@ -100,18 +122,22 @@ export function collectPyManifest(repoRoot) {
|
|
|
100
122
|
const deps = [];
|
|
101
123
|
let present = false;
|
|
102
124
|
let names = [];
|
|
103
|
-
|
|
104
|
-
try { names
|
|
125
|
+
const boundary = createRepoBoundary(repoRoot);
|
|
126
|
+
try { names = readdirSync(boundary.root).filter((n) => /^requirements[\w.-]*\.(txt|in)$/i.test(n)); } catch { /* unreadable root */ }
|
|
127
|
+
try {
|
|
128
|
+
const requirements = boundary.resolve("requirements");
|
|
129
|
+
if (requirements.ok) names.push(...readdirSync(requirements.path).filter((n) => /\.(txt|in)$/i.test(n)).map((n) => `requirements/${n}`));
|
|
130
|
+
} catch { /* no requirements dir */ }
|
|
105
131
|
for (const n of names) {
|
|
106
|
-
const t =
|
|
132
|
+
const t = readRepoText(boundary, n);
|
|
107
133
|
if (t == null) continue;
|
|
108
134
|
present = true;
|
|
109
135
|
const dev = /dev|test|lint|doc|ci/i.test(n.replace(/^requirements[/\\]?/i, ""));
|
|
110
136
|
for (const d of parseRequirementsNames(t)) deps.push({ ...d, dev });
|
|
111
137
|
}
|
|
112
|
-
const pp =
|
|
138
|
+
const pp = readRepoText(boundary, "pyproject.toml");
|
|
113
139
|
if (pp != null) { const r = parsePyprojectDeps(pp); if (r.present) { present = true; deps.push(...r.deps); } }
|
|
114
|
-
const pf =
|
|
140
|
+
const pf = readRepoText(boundary, "Pipfile");
|
|
115
141
|
if (pf != null) { const r = parsePipfileDeps(pf); if (r.present) { present = true; deps.push(...r.deps); } }
|
|
116
142
|
return { present, deps };
|
|
117
143
|
}
|