weavatrix 0.3.14 → 1.0.0
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/LICENSE +1 -0
- package/README.md +231 -199
- package/bin/native/darwin-arm64/weavatrix +0 -0
- package/bin/native/darwin-x64/weavatrix +0 -0
- package/bin/native/linux-arm64/weavatrix +0 -0
- package/bin/native/linux-x64/weavatrix +0 -0
- package/bin/native/win32-arm64/weavatrix.exe +0 -0
- package/bin/native/win32-x64/weavatrix.exe +0 -0
- package/bin/resolve-binary.mjs +73 -0
- package/bin/run-native.mjs +26 -0
- package/bin/weavatrix-mcp.mjs +7 -6
- package/bin/weavatrix.mjs +5 -0
- package/package.json +8 -66
- package/skill/SKILL.md +62 -374
- package/skill/agents/openai.yaml +4 -0
- package/skill/references/tool-routing.md +45 -0
- package/SECURITY.md +0 -101
- package/docs/adr/0001-v0.3-offline-online-split.md +0 -60
- package/docs/agent-task-benchmark.md +0 -58
- package/docs/releases/v0.2.19.md +0 -33
- package/docs/releases/v0.3.0.md +0 -43
- package/docs/releases/v0.3.1.md +0 -30
- package/docs/releases/v0.3.10.md +0 -76
- package/docs/releases/v0.3.11.md +0 -55
- package/docs/releases/v0.3.12.md +0 -44
- package/docs/releases/v0.3.13.md +0 -34
- package/docs/releases/v0.3.14.md +0 -37
- package/docs/releases/v0.3.2.md +0 -15
- package/docs/releases/v0.3.3.md +0 -25
- package/docs/releases/v0.3.4.md +0 -40
- package/docs/releases/v0.3.5.md +0 -50
- package/docs/releases/v0.3.6.md +0 -44
- package/docs/releases/v0.3.7.md +0 -37
- package/docs/releases/v0.3.8.md +0 -21
- package/docs/releases/v0.3.9.md +0 -36
- package/scripts/run-agent-task-benchmark.mjs +0 -118
- package/src/analysis/allowed-test-runner.js +0 -70
- package/src/analysis/architecture/contract-graph.js +0 -119
- package/src/analysis/architecture/contract-schema.js +0 -110
- package/src/analysis/architecture/contract-storage.js +0 -35
- package/src/analysis/architecture/contract-verification.js +0 -168
- package/src/analysis/architecture-contract.js +0 -16
- package/src/analysis/audit-debt.js +0 -94
- package/src/analysis/audit-extensions.js +0 -60
- package/src/analysis/cargo-dependency-evidence.js +0 -108
- package/src/analysis/cargo-manifests.js +0 -81
- package/src/analysis/change-classification/diff-parser.js +0 -103
- package/src/analysis/change-classification/options.js +0 -40
- package/src/analysis/change-classification/symbol-classifier.js +0 -177
- package/src/analysis/change-classification.js +0 -188
- package/src/analysis/coverage-reports-tarpaulin.js +0 -112
- package/src/analysis/coverage-reports.js +0 -246
- package/src/analysis/cycle-route.js +0 -14
- package/src/analysis/data-flow-evidence.js +0 -114
- package/src/analysis/dead-check.js +0 -300
- package/src/analysis/dead-code-review/candidates.js +0 -194
- package/src/analysis/dead-code-review/policy.js +0 -23
- package/src/analysis/dead-code-review.js +0 -119
- package/src/analysis/dep-check-ecosystems.js +0 -205
- package/src/analysis/dep-check.js +0 -290
- package/src/analysis/dep-rules.js +0 -10
- package/src/analysis/dependency/conventions.js +0 -16
- package/src/analysis/dependency/scoped-dependencies.js +0 -51
- package/src/analysis/dependency/source-references.js +0 -21
- package/src/analysis/duplicate-groups.js +0 -104
- package/src/analysis/duplicates-worker.js +0 -11
- package/src/analysis/duplicates.compute.js +0 -269
- package/src/analysis/duplicates.js +0 -15
- package/src/analysis/duplicates.run.js +0 -52
- package/src/analysis/duplicates.tokenize.js +0 -199
- package/src/analysis/endpoints/common.js +0 -79
- package/src/analysis/endpoints/extract.js +0 -120
- package/src/analysis/endpoints/inventory.js +0 -84
- package/src/analysis/endpoints/mounts.js +0 -129
- package/src/analysis/endpoints-java.js +0 -260
- package/src/analysis/endpoints-rust.js +0 -124
- package/src/analysis/endpoints.js +0 -3
- package/src/analysis/findings.js +0 -70
- package/src/analysis/git-history/analytics.js +0 -177
- package/src/analysis/git-history/collector.js +0 -67
- package/src/analysis/git-history/options.js +0 -66
- package/src/analysis/git-history.js +0 -143
- package/src/analysis/git-ref-graph.js +0 -76
- package/src/analysis/go-dependency-evidence.js +0 -62
- package/src/analysis/graph-analysis.aggregate.js +0 -296
- package/src/analysis/graph-analysis.edges.js +0 -24
- package/src/analysis/graph-analysis.js +0 -7
- package/src/analysis/graph-analysis.refs.js +0 -202
- package/src/analysis/graph-analysis.summaries.js +0 -65
- package/src/analysis/health-capabilities.js +0 -83
- package/src/analysis/hot-path-review.js +0 -266
- package/src/analysis/http-contract-wrappers.js +0 -241
- package/src/analysis/http-contracts/analysis.js +0 -179
- package/src/analysis/http-contracts/client-call-detection.js +0 -82
- package/src/analysis/http-contracts/client-call-parser.js +0 -273
- package/src/analysis/http-contracts/graph-context.js +0 -143
- package/src/analysis/http-contracts/matching.js +0 -61
- package/src/analysis/http-contracts/shared.js +0 -85
- package/src/analysis/http-contracts.js +0 -6
- package/src/analysis/internal-audit/dependency-health.js +0 -113
- package/src/analysis/internal-audit/python-manifests.js +0 -78
- package/src/analysis/internal-audit/repo-files.js +0 -50
- package/src/analysis/internal-audit/supply-chain.js +0 -149
- package/src/analysis/internal-audit.collect.js +0 -213
- package/src/analysis/internal-audit.js +0 -9
- package/src/analysis/internal-audit.reach.js +0 -201
- package/src/analysis/internal-audit.run.js +0 -256
- package/src/analysis/java-source.js +0 -36
- package/src/analysis/jvm-artifact-index.js +0 -87
- package/src/analysis/jvm-dependency-evidence.js +0 -138
- package/src/analysis/jvm-manifests.js +0 -114
- package/src/analysis/manifests.js +0 -123
- package/src/analysis/package-reachability.js +0 -39
- package/src/analysis/source-complexity.ast.js +0 -97
- package/src/analysis/source-complexity.constants.js +0 -55
- package/src/analysis/source-complexity.js +0 -14
- package/src/analysis/source-complexity.report.js +0 -81
- package/src/analysis/source-complexity.walk.js +0 -228
- package/src/analysis/source-correctness/retry-patterns.js +0 -93
- package/src/analysis/source-correctness.js +0 -222
- package/src/analysis/static-test-reachability.js +0 -150
- package/src/analysis/structure/dependency-graph.js +0 -151
- package/src/analysis/structure/findings.js +0 -162
- package/src/analysis/task-retrieval.js +0 -107
- package/src/analysis/transport-contracts.js +0 -224
- package/src/analysis/transport-runtime-evidence.js +0 -155
- package/src/analysis-kit.mjs +0 -17
- package/src/bounds.js +0 -4
- package/src/build-graph.js +0 -209
- package/src/child-env.js +0 -7
- package/src/config.js +0 -5
- package/src/extension/local-services.mjs +0 -75
- package/src/git-exec.js +0 -67
- package/src/graph/build-worker.js +0 -49
- package/src/graph/builder/go-receiver-resolution.js +0 -112
- package/src/graph/builder/js/dynamic-import.js +0 -26
- package/src/graph/builder/js/queries.js +0 -48
- package/src/graph/builder/lang-csharp.js +0 -40
- package/src/graph/builder/lang-css.js +0 -29
- package/src/graph/builder/lang-go.js +0 -140
- package/src/graph/builder/lang-html.js +0 -29
- package/src/graph/builder/lang-java-calls.js +0 -142
- package/src/graph/builder/lang-java.js +0 -215
- package/src/graph/builder/lang-js.js +0 -291
- package/src/graph/builder/lang-python.js +0 -235
- package/src/graph/builder/lang-rust-calls.js +0 -63
- package/src/graph/builder/lang-rust.js +0 -299
- package/src/graph/builder/lang-solidity.js +0 -126
- package/src/graph/builder/lang-sql.js +0 -263
- package/src/graph/builder/pass2-resolution.js +0 -81
- package/src/graph/builder/spec-pkg.js +0 -87
- package/src/graph/community.js +0 -27
- package/src/graph/edge-provenance.js +0 -31
- package/src/graph/file-lock.js +0 -69
- package/src/graph/freshness-probe.js +0 -142
- package/src/graph/graph-filter.js +0 -63
- package/src/graph/incremental-refresh.js +0 -235
- package/src/graph/internal-builder.barrels.js +0 -235
- package/src/graph/internal-builder.build.js +0 -300
- package/src/graph/internal-builder.java.js +0 -33
- package/src/graph/internal-builder.js +0 -12
- package/src/graph/internal-builder.langs.js +0 -157
- package/src/graph/internal-builder.pass2.js +0 -163
- package/src/graph/internal-builder.resolvers.js +0 -286
- package/src/graph/layout.js +0 -51
- package/src/graph/node-id.js +0 -7
- package/src/graph/parser-artifact-boundary.js +0 -55
- package/src/graph/relations.js +0 -4
- package/src/graph/repo-registry.js +0 -124
- package/src/graph/resolvers/rust.js +0 -117
- package/src/infra/infra-items.js +0 -255
- package/src/infra/infra-registry.js +0 -184
- package/src/infra/infra.detect.js +0 -119
- package/src/infra/infra.js +0 -38
- package/src/infra/infra.match.js +0 -102
- package/src/infra/infra.scan.js +0 -93
- package/src/mcp/actions/graph-lifecycle.mjs +0 -148
- package/src/mcp/architecture-bootstrap.mjs +0 -168
- package/src/mcp/architecture-starter.mjs +0 -234
- package/src/mcp/catalog.mjs +0 -233
- package/src/mcp/company-contract-page.mjs +0 -142
- package/src/mcp/company-contract-reconcile.mjs +0 -87
- package/src/mcp/company-contract-verdict.mjs +0 -42
- package/src/mcp/evidence/bun-lock-graph.mjs +0 -209
- package/src/mcp/evidence/duplicate-member-order.mjs +0 -8
- package/src/mcp/evidence/package-graph-common.mjs +0 -115
- package/src/mcp/evidence/package-lock-graph.mjs +0 -92
- package/src/mcp/evidence-snapshot.architecture.mjs +0 -80
- package/src/mcp/evidence-snapshot.common.mjs +0 -158
- package/src/mcp/evidence-snapshot.duplicates.mjs +0 -213
- package/src/mcp/evidence-snapshot.health.mjs +0 -102
- package/src/mcp/evidence-snapshot.inventory.mjs +0 -148
- package/src/mcp/evidence-snapshot.mjs +0 -50
- package/src/mcp/evidence-snapshot.package-graph.mjs +0 -34
- package/src/mcp/evidence-snapshot.structure.mjs +0 -84
- package/src/mcp/extension-api.mjs +0 -77
- package/src/mcp/git-output.mjs +0 -7
- package/src/mcp/graph/context-core.mjs +0 -111
- package/src/mcp/graph/context-seeds.mjs +0 -207
- package/src/mcp/graph/context-state.mjs +0 -85
- package/src/mcp/graph/reverse-reach.mjs +0 -42
- package/src/mcp/graph/tools-core.mjs +0 -143
- package/src/mcp/graph/tools-query.mjs +0 -276
- package/src/mcp/graph-context.mjs +0 -5
- package/src/mcp/graph-diff.mjs +0 -218
- package/src/mcp/health/audit-format.mjs +0 -199
- package/src/mcp/health/audit.mjs +0 -199
- package/src/mcp/health/dead-code.mjs +0 -110
- package/src/mcp/health/duplicates.mjs +0 -121
- package/src/mcp/health/endpoints.mjs +0 -71
- package/src/mcp/health/structure.mjs +0 -220
- package/src/mcp/runtime-version.mjs +0 -31
- package/src/mcp/server/auto-refresh.mjs +0 -66
- package/src/mcp/server/runtime-config.mjs +0 -43
- package/src/mcp/server/shutdown.mjs +0 -40
- package/src/mcp/staleness-notice.mjs +0 -20
- package/src/mcp/sync/evidence-architecture.mjs +0 -54
- package/src/mcp/sync/evidence-common.mjs +0 -88
- package/src/mcp/sync/evidence-duplicates.mjs +0 -97
- package/src/mcp/sync/evidence-health.mjs +0 -56
- package/src/mcp/sync/evidence-packages.mjs +0 -95
- package/src/mcp/sync/payload-common.mjs +0 -97
- package/src/mcp/sync/payload-v2.mjs +0 -54
- package/src/mcp/sync/payload-v3.mjs +0 -79
- package/src/mcp/sync-evidence.mjs +0 -23
- package/src/mcp/sync-payload.mjs +0 -70
- package/src/mcp/tool-result.mjs +0 -54
- package/src/mcp/tools-actions.mjs +0 -11
- package/src/mcp/tools-architecture.mjs +0 -177
- package/src/mcp/tools-company.mjs +0 -251
- package/src/mcp/tools-context.mjs +0 -222
- package/src/mcp/tools-endpoints.mjs +0 -207
- package/src/mcp/tools-graph-hubs.mjs +0 -78
- package/src/mcp/tools-graph.mjs +0 -17
- package/src/mcp/tools-health.mjs +0 -24
- package/src/mcp/tools-history.mjs +0 -28
- package/src/mcp/tools-impact-change.mjs +0 -220
- package/src/mcp/tools-impact-precision.mjs +0 -89
- package/src/mcp/tools-impact.mjs +0 -169
- package/src/mcp/tools-source.mjs +0 -238
- package/src/mcp/tools-verified-change.mjs +0 -200
- package/src/mcp-rg.mjs +0 -50
- package/src/mcp-runtime.mjs +0 -2
- package/src/mcp-server.mjs +0 -298
- package/src/mcp-source-tools.mjs +0 -163
- package/src/path-classification.js +0 -226
- package/src/path-ignore.js +0 -69
- package/src/precision/lsp-client/constants.js +0 -12
- package/src/precision/lsp-client/environment.js +0 -20
- package/src/precision/lsp-client/errors.js +0 -15
- package/src/precision/lsp-client/lifecycle.js +0 -114
- package/src/precision/lsp-client/message-parser.js +0 -81
- package/src/precision/lsp-client/protocol.js +0 -212
- package/src/precision/lsp-client/registry.js +0 -59
- package/src/precision/lsp-client/repo-uri.js +0 -60
- package/src/precision/lsp-client/stdio-client.js +0 -140
- package/src/precision/lsp-client.js +0 -10
- package/src/precision/lsp-overlay/budget-policy.js +0 -78
- package/src/precision/lsp-overlay/build.js +0 -261
- package/src/precision/lsp-overlay/contract.js +0 -61
- package/src/precision/lsp-overlay/reference-results.js +0 -108
- package/src/precision/lsp-overlay/semantic-inputs.js +0 -62
- package/src/precision/lsp-overlay/source-session.js +0 -142
- package/src/precision/lsp-overlay/store.js +0 -150
- package/src/precision/lsp-overlay/target-index.js +0 -152
- package/src/precision/lsp-overlay/target-query.js +0 -55
- package/src/precision/lsp-overlay.js +0 -11
- package/src/precision/symbol-query.js +0 -224
- package/src/precision/typescript-lsp-provider.js +0 -12
- package/src/precision/typescript-provider/client.js +0 -89
- package/src/precision/typescript-provider/discovery.js +0 -124
- package/src/precision/typescript-provider/isolated-runtime.js +0 -39
- package/src/precision/typescript-provider/project-host.js +0 -254
- package/src/precision/typescript-provider/project-safety.js +0 -166
- package/src/precision/typescript-provider/reference-usage.js +0 -53
- package/src/process.js +0 -95
- package/src/repo-path.js +0 -53
- package/src/scan/discover.inventory.js +0 -78
- package/src/scan/discover.js +0 -5
- package/src/scan/discover.list.js +0 -79
- package/src/scan/discover.stack.js +0 -227
- package/src/scan/search.core.js +0 -24
- package/src/scan/search.git.js +0 -102
- package/src/scan/search.js +0 -9
- package/src/scan/search.node.js +0 -83
- package/src/scan/search.preview.js +0 -49
- package/src/scan/search.rg.js +0 -145
- package/src/security/advisory-store.js +0 -172
- package/src/security/installed-jvm-rust.js +0 -46
- package/src/security/installed.js +0 -280
- package/src/security/malware-file-heuristics.js +0 -121
- package/src/security/malware-heuristics.exclusions.js +0 -134
- package/src/security/malware-heuristics.js +0 -15
- package/src/security/malware-heuristics.roots.js +0 -145
- package/src/security/malware-heuristics.scan.js +0 -89
- package/src/security/malware-heuristics.sweep.js +0 -122
- package/src/security/malware-scoring.js +0 -105
- package/src/security/match.js +0 -85
- package/src/security/registry-sig.classify.js +0 -137
- package/src/security/registry-sig.js +0 -18
- package/src/security/registry-sig.rules.js +0 -192
- package/src/security/rust-advisory-report.js +0 -60
- package/src/security/typosquat.js +0 -81
- package/src/util.js +0 -40
- package/src/version.js +0 -7
|
@@ -1,269 +0,0 @@
|
|
|
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 { createRepoBoundary } from "../repo-path.js";
|
|
5
|
-
import { createPathClassifier, hasPathClass } from "../path-classification.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 = 12; // absolute safety floor; normal scans still default to 30+ tokens
|
|
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
|
-
const smallFragment = Math.min(frags[i].n, frags[j].n) < 30;
|
|
97
|
-
const enoughEvidence = smallFragment
|
|
98
|
-
? sim >= 0.95 && count >= 2
|
|
99
|
-
: count >= MIN_SHARED_FP;
|
|
100
|
-
if (sim >= FLOOR_SIM && enoughEvidence) pairs.push([i, j, Math.round(sim * 100)]);
|
|
101
|
-
}
|
|
102
|
-
return pairs;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// Parse "L<line>" graph symbol locations into per-file ordered symbol lists.
|
|
106
|
-
function symbolRanges(graph) {
|
|
107
|
-
const byFile = new Map();
|
|
108
|
-
for (const n of graph.nodes || []) {
|
|
109
|
-
if (!n.source_file || !String(n.id || "").includes("#")) continue;
|
|
110
|
-
const line = Number((String(n.source_location || "").match(/L(\d+)/) || [])[1] || 0);
|
|
111
|
-
if (!line) continue;
|
|
112
|
-
let arr = byFile.get(n.source_file);
|
|
113
|
-
if (!arr) byFile.set(n.source_file, (arr = []));
|
|
114
|
-
arr.push({ id: n.id, label: n.label || n.id, line, symbolKind: n.symbol_kind || "", testSurface: n.test_surface === true });
|
|
115
|
-
}
|
|
116
|
-
for (const arr of byFile.values()) arr.sort((a, b) => a.line - b.line);
|
|
117
|
-
return byFile;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function loadGraph(graphInput) {
|
|
121
|
-
if (graphInput && typeof graphInput === "object" && !Array.isArray(graphInput)) {
|
|
122
|
-
return { nodes: Array.isArray(graphInput.nodes) ? graphInput.nodes : [] };
|
|
123
|
-
}
|
|
124
|
-
if (typeof graphInput !== "string" || !graphInput) throw new TypeError("graph path or graph object is required");
|
|
125
|
-
const parsed = JSON.parse(readFileSync(graphInput, "utf8"));
|
|
126
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("graph must be an object");
|
|
127
|
-
return { nodes: Array.isArray(parsed.nodes) ? parsed.nodes : [] };
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export function computeDuplicates(repoPath, graphJsonPath, opts = {}) {
|
|
131
|
-
const includeStrings = !!opts.includeStrings;
|
|
132
|
-
const scanTokenFloor = Math.max(FLOOR_TOKENS, Math.min(400, Number(opts.minTokens) || 30));
|
|
133
|
-
const graph = loadGraph(graphJsonPath);
|
|
134
|
-
const byFile = symbolRanges(graph);
|
|
135
|
-
// total symbol nodes in the graph — 0 means a file-only graph (built by an older builder before
|
|
136
|
-
// symbol extraction, or a stale graph): clone detection has nothing to work with, and the UI must
|
|
137
|
-
// say "rebuild the graph" instead of the misleading "no clones at these thresholds".
|
|
138
|
-
const repoFiles = listRepoFiles(repoPath);
|
|
139
|
-
const allowedFiles = new Set(repoFiles);
|
|
140
|
-
let graphSymbols = 0;
|
|
141
|
-
for (const [file, arr] of byFile) if (allowedFiles.has(file)) graphSymbols += arr.length;
|
|
142
|
-
const frags = [];
|
|
143
|
-
const boundary = createRepoBoundary(repoPath);
|
|
144
|
-
const classifier = createPathClassifier(repoPath);
|
|
145
|
-
const classificationByFile = new Map();
|
|
146
|
-
const classify = (file, content) => {
|
|
147
|
-
if (!classificationByFile.has(file)) classificationByFile.set(file, classifier.explain(file, { content }));
|
|
148
|
-
return classificationByFile.get(file);
|
|
149
|
-
};
|
|
150
|
-
const classificationFields = (info) => ({
|
|
151
|
-
test: hasPathClass(info, "test", "e2e"),
|
|
152
|
-
classes: info.classes,
|
|
153
|
-
excluded: info.excluded,
|
|
154
|
-
matchedRule: info.matchedRule,
|
|
155
|
-
});
|
|
156
|
-
for (const [file, syms] of byFile) {
|
|
157
|
-
if (!allowedFiles.has(file)) continue;
|
|
158
|
-
const resolved = boundary.resolve(file);
|
|
159
|
-
if (!resolved.ok) continue;
|
|
160
|
-
const full = resolved.path;
|
|
161
|
-
let lines;
|
|
162
|
-
try { lines = readFileSync(full, "utf8").split(/\r?\n/); } catch { continue; }
|
|
163
|
-
const py = /\.py$/i.test(file);
|
|
164
|
-
const pathInfo = classify(file, lines.join("\n"));
|
|
165
|
-
for (let i = 0; i < syms.length; i++) {
|
|
166
|
-
const start = syms[i].line;
|
|
167
|
-
// hard cap first (next symbol, or EOF, whichever comes first, ≤ MAX_BODY_LINES) …
|
|
168
|
-
const hardEnd = Math.min(i + 1 < syms.length ? syms[i + 1].line - 1 : lines.length, start + MAX_BODY_LINES);
|
|
169
|
-
if (hardEnd - start < 2) continue; // one-liners can't be meaningful clones
|
|
170
|
-
// … then shrink to where the construct actually closes, so the last symbol doesn't absorb
|
|
171
|
-
// trailing module-level code (module.exports tables, main() calls) up to EOF.
|
|
172
|
-
const bodyLines = lines.slice(start - 1, hardEnd);
|
|
173
|
-
const body = bodyLines.slice(0, bodyEndLineCount(bodyLines, py));
|
|
174
|
-
const end = start + body.length - 1;
|
|
175
|
-
if (end - start < 2) continue;
|
|
176
|
-
const toks = tokenize(stripNonCode(body.join("\n"), py));
|
|
177
|
-
if (toks.strict.length < scanTokenFloor) continue;
|
|
178
|
-
const strippedBody = stripNonCode(body.join("\n"), py);
|
|
179
|
-
const declarativeValue = /^(?:export\s+)?(?:const|let|var)\s+[\w$]+(?:\s*:[^=]+)?\s*=\s*(?:Object\.(?:freeze|seal)\s*\(\s*)?[\[{]/s.test(strippedBody.trim())
|
|
180
|
-
&& !/=>|\b(?:function|if|for|while|switch|try|await|yield|return|throw|new)\b/.test(strippedBody);
|
|
181
|
-
const declarativeFactory = /^(?:export\s+)?const\s+[\w$]+(?:\s*:[^=]+)?\s*=\s*(?:sqliteTable|pgTable|mysqlTable)\s*\(/s.test(strippedBody.trim());
|
|
182
|
-
const declarative = declarativeValue || declarativeFactory || /^(?:interface|type|enum)$/i.test(syms[i].symbolKind);
|
|
183
|
-
frags.push({
|
|
184
|
-
id: syms[i].id, label: syms[i].label, file, start, end,
|
|
185
|
-
n: toks.strict.length, declarative,
|
|
186
|
-
...classificationFields(pathInfo),
|
|
187
|
-
// Inline test surfaces (Rust `#[cfg(test)] mod tests`, `#[test]` fns) live in production files, so a
|
|
188
|
-
// path check alone misses them; the graph already flags the symbol. OR it in so skip-tests suppresses
|
|
189
|
-
// them by default and two #[test] fns are never reported as a production clone.
|
|
190
|
-
test: hasPathClass(pathInfo, "test", "e2e") || syms[i].testSurface === true,
|
|
191
|
-
fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
// ---- opt-in: large multi-line string literals as their own fragments. The code pass above strips
|
|
195
|
-
// string bodies (correctly — content isn't code), which makes embedded DSL templates (inline
|
|
196
|
-
// C#/SQL/PowerShell) invisible to clone detection. Tokenized RAW: the content IS the payload.
|
|
197
|
-
if (includeStrings) {
|
|
198
|
-
const base = file.split("/").pop();
|
|
199
|
-
const pushStr = (startLine, endLine, content) => {
|
|
200
|
-
const toks = tokenize(content);
|
|
201
|
-
if (toks.strict.length < scanTokenFloor) return;
|
|
202
|
-
frags.push({
|
|
203
|
-
id: `${file}#str@${startLine}`, label: `${base}:${startLine} ~${endLine - startLine + 1}-line string`,
|
|
204
|
-
file, start: startLine, end: endLine, n: toks.strict.length, ...classificationFields(pathInfo), kind: "string",
|
|
205
|
-
fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
|
|
206
|
-
});
|
|
207
|
-
};
|
|
208
|
-
for (const str of extractLargeStrings(lines.join("\n"), { py, cs: /\.cs$/i.test(file) })) {
|
|
209
|
-
const strLines = str.content.split(/\r?\n/).slice(0, MAX_BODY_LINES);
|
|
210
|
-
// A SECTION shared between two big templates dilutes below the similarity floor when the whole
|
|
211
|
-
// literals are compared (70 shared lines inside 220- and 107-line strings ≈ 27% jaccard). Big
|
|
212
|
-
// literals therefore get the same WINDOW treatment as CSS/HTML files; small ones stay whole.
|
|
213
|
-
if (strLines.length <= WINDOW_LINES * 2) {
|
|
214
|
-
pushStr(str.start, str.start + strLines.length - 1, strLines.join("\n"));
|
|
215
|
-
} else {
|
|
216
|
-
for (let off = 0; off < strLines.length; off += WINDOW_LINES) {
|
|
217
|
-
const chunk = strLines.slice(off, off + WINDOW_LINES);
|
|
218
|
-
if (chunk.length < 3) break;
|
|
219
|
-
pushStr(str.start + off, str.start + off + chunk.length - 1, chunk.join("\n"));
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
// ---- windowed fragments for symbol-less file types (CSS/HTML/MD/…), found by walking the repo (NOT the
|
|
226
|
-
// graph — assets are dedup-only). Each file is sliced into WINDOW_LINES blocks and fingerprinted.
|
|
227
|
-
const symFiles = new Set(byFile.keys());
|
|
228
|
-
const allAssetFiles = repoFiles.filter((file) => WINDOW_EXTS.test(file));
|
|
229
|
-
const assetFiles = allAssetFiles.slice(0, MAX_ASSET_FILES);
|
|
230
|
-
for (const file of assetFiles) {
|
|
231
|
-
if (symFiles.has(file)) continue;
|
|
232
|
-
const resolved = boundary.resolve(file);
|
|
233
|
-
if (!resolved.ok) continue;
|
|
234
|
-
let lines;
|
|
235
|
-
try { lines = readFileSync(resolved.path, "utf8").split(/\r?\n/); } catch { continue; }
|
|
236
|
-
const pathInfo = classify(file, lines.join("\n"));
|
|
237
|
-
for (let start = 1; start <= lines.length; start += WINDOW_LINES) {
|
|
238
|
-
const end = Math.min(start + WINDOW_LINES - 1, lines.length);
|
|
239
|
-
if (end - start < 2) continue;
|
|
240
|
-
const toks = tokenize(stripNonCode(lines.slice(start - 1, end).join("\n"), false));
|
|
241
|
-
if (toks.strict.length < scanTokenFloor) continue;
|
|
242
|
-
frags.push({
|
|
243
|
-
id: `${file}#win@${start}`, label: `${file.split("/").pop()}:${start}-${end}`, file, start, end,
|
|
244
|
-
n: toks.strict.length, ...classificationFields(pathInfo),
|
|
245
|
-
fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
const modes = { strict: pairsForMode(frags, "strict"), renamed: pairsForMode(frags, "renamed") };
|
|
250
|
-
const nameTwins = opts.nameTwins ? computeNameTwins(frags) : null;
|
|
251
|
-
// fp sets are worker-internal — strip them from the payload that crosses the thread boundary
|
|
252
|
-
const slim = frags.map(({ fp, ...rest }) => rest);
|
|
253
|
-
return {
|
|
254
|
-
ok: true,
|
|
255
|
-
frags: slim,
|
|
256
|
-
modes,
|
|
257
|
-
...(nameTwins ? { nameTwins } : {}),
|
|
258
|
-
graphSymbols,
|
|
259
|
-
completeness: {
|
|
260
|
-
assetFiles: {
|
|
261
|
-
total: allAssetFiles.length,
|
|
262
|
-
scanned: assetFiles.length,
|
|
263
|
-
truncated: allAssetFiles.length > assetFiles.length,
|
|
264
|
-
},
|
|
265
|
-
nameTwinsTruncated: !!nameTwins && nameTwins.length >= 200,
|
|
266
|
-
},
|
|
267
|
-
floors: { tokens: scanTokenFloor, absoluteTokens: FLOOR_TOKENS, sim: FLOOR_SIM * 100 },
|
|
268
|
-
};
|
|
269
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
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,52 +0,0 @@
|
|
|
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,199 +0,0 @@
|
|
|
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 string bodies: 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
|
-
const REGEXLIT = String.fromCharCode(1); // regex bodies are executable behavior, so retain an equality anchor
|
|
10
|
-
const literalHash = (value) => {
|
|
11
|
-
let hash = 2166136261;
|
|
12
|
-
for (const char of String(value || "")) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
|
|
13
|
-
return (hash >>> 0).toString(16);
|
|
14
|
-
};
|
|
15
|
-
const regexMarker = (value) => ` ${REGEXLIT} 0x${literalHash(value)} `;
|
|
16
|
-
|
|
17
|
-
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(" "));
|
|
18
|
-
|
|
19
|
-
// A leading `/` is a REGEX literal (not division) when the previous significant char is one of these
|
|
20
|
-
// or the fragment start; after a word char / ) / ] it is division. Covers .match(/…/), = /…/, (/…/),
|
|
21
|
-
// and arrow `x => /…/`. NOTE: `+` and `-` are deliberately EXCLUDED — a regex never legitimately
|
|
22
|
-
// follows them, but `i++ / 2` and `a - b / c` do, and including them mis-scanned the division as a
|
|
23
|
-
// regex and ate the rest of the line.
|
|
24
|
-
const REGEX_PREV = new Set("(,=:[!&|?{};~*%^<>".split(""));
|
|
25
|
-
|
|
26
|
-
// Replace comments with nothing and string bodies with an opaque sentinel. Regex bodies retain only
|
|
27
|
-
// a one-way equality anchor: their source is executable behavior, and collapsing every pattern to the
|
|
28
|
-
// same token creates false clone groups for unrelated replace/validate pipelines.
|
|
29
|
-
export function stripNonCode(text, py) {
|
|
30
|
-
let out = "", i = 0, prevSig = "";
|
|
31
|
-
const s = String(text || "");
|
|
32
|
-
const push = (c) => { out += c; const t = c.trim(); if (t) prevSig = t[t.length - 1]; };
|
|
33
|
-
while (i < s.length) {
|
|
34
|
-
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
35
|
-
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
36
|
-
if (py && (three === "'''" || three === '"""')) {
|
|
37
|
-
i += 3;
|
|
38
|
-
while (i < s.length && s.slice(i, i + 3) !== three) i++;
|
|
39
|
-
i += 3; push(` ${STRLIT} `); continue;
|
|
40
|
-
}
|
|
41
|
-
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
42
|
-
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") i++; i += 2; continue; }
|
|
43
|
-
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
44
|
-
i++; const regexStart = i; let inClass = false; // '/' inside a [...] char class is literal, not the terminator
|
|
45
|
-
while (i < s.length && s[i] !== "\n") {
|
|
46
|
-
const c = s[i];
|
|
47
|
-
if (c === "\\") { i += 2; continue; }
|
|
48
|
-
if (c === "[") inClass = true;
|
|
49
|
-
else if (c === "]") inClass = false;
|
|
50
|
-
else if (c === "/" && !inClass) { i++; break; }
|
|
51
|
-
i++;
|
|
52
|
-
}
|
|
53
|
-
while (i < s.length && /[a-z]/i.test(s[i])) i++; // regex flags (gimsuy)
|
|
54
|
-
push(regexMarker(s.slice(regexStart, i))); continue;
|
|
55
|
-
}
|
|
56
|
-
if (ch === '"' || ch === "'" || ch === "`") {
|
|
57
|
-
const q = ch; i++;
|
|
58
|
-
while (i < s.length && s[i] !== q) { if (s[i] === "\\") i++; i++; }
|
|
59
|
-
i++; push(` ${STRLIT} `); continue;
|
|
60
|
-
}
|
|
61
|
-
push(ch); i++;
|
|
62
|
-
}
|
|
63
|
-
return out;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Where a symbol's body ends — so the LAST symbol in a file doesn't swallow trailing module-level code
|
|
67
|
-
// (module.exports tables, main() calls, handler registrations) up to EOF and dilute/misattribute
|
|
68
|
-
// clones. Brace/bracket depth for brace langs (body ends when {}()[] balance after first opening);
|
|
69
|
-
// indentation for Python. Returns a 1-based line count within bodyLines (≤ its length; = its length
|
|
70
|
-
// when the construct never closes, so the caller's cap stands).
|
|
71
|
-
export function bodyEndLineCount(bodyLines, py) {
|
|
72
|
-
if (py) {
|
|
73
|
-
const base = bodyLines[0].match(/^[ \t]*/)[0].length;
|
|
74
|
-
let last = 1;
|
|
75
|
-
for (let k = 1; k < bodyLines.length; k++) {
|
|
76
|
-
const ln = bodyLines[k];
|
|
77
|
-
if (!ln.trim()) continue; // blank lines never end a block
|
|
78
|
-
if (ln.match(/^[ \t]*/)[0].length <= base) return last; // dedent to ≤ the def → body ended above
|
|
79
|
-
last = k + 1;
|
|
80
|
-
}
|
|
81
|
-
return bodyLines.length;
|
|
82
|
-
}
|
|
83
|
-
const text = bodyLines.join("\n");
|
|
84
|
-
let depth = 0, opened = false, i = 0, line = 1, prevSig = "";
|
|
85
|
-
while (i < text.length) {
|
|
86
|
-
const ch = text[i], two = text.slice(i, i + 2);
|
|
87
|
-
if (ch === "\n") { line++; i++; continue; }
|
|
88
|
-
if (two === "//") { while (i < text.length && text[i] !== "\n") i++; continue; }
|
|
89
|
-
if (two === "/*") { i += 2; while (i < text.length && text.slice(i, i + 2) !== "*/") { if (text[i] === "\n") line++; i++; } i += 2; continue; }
|
|
90
|
-
if (ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
91
|
-
i++; let inClass = false;
|
|
92
|
-
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++; }
|
|
93
|
-
prevSig = "/"; continue;
|
|
94
|
-
}
|
|
95
|
-
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; }
|
|
96
|
-
// depth tracks all brackets, but only a { or [ opens the BODY — a bare (param list) returning to
|
|
97
|
-
// depth 0 must not be read as the construct closing on line 1
|
|
98
|
-
if (ch === "{" || ch === "(" || ch === "[") { depth++; if (ch === "{" || ch === "[") opened = true; }
|
|
99
|
-
else if (ch === "}" || ch === ")" || ch === "]") { depth--; if (opened && depth <= 0) return line; }
|
|
100
|
-
if (ch.trim()) prevSig = ch;
|
|
101
|
-
i++;
|
|
102
|
-
}
|
|
103
|
-
return bodyLines.length;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Large multi-line string literals — the OPPOSITE selection to stripNonCode: everything the code
|
|
107
|
-
// scan throws away. Embedded DSLs (inline C#/SQL/PowerShell templates) are invisible to the normal
|
|
108
|
-
// clone pass because their bodies are stripped; this extractor feeds them back in as their own
|
|
109
|
-
// fragments when the caller opts in (find_duplicates include_strings). Comment/regex handling
|
|
110
|
-
// mirrors stripNonCode so a quote inside a comment never opens a phantom literal.
|
|
111
|
-
export function extractLargeStrings(text, { py = false, cs = false, minLines = 6 } = {}) {
|
|
112
|
-
const s = String(text || "");
|
|
113
|
-
const out = [];
|
|
114
|
-
let i = 0, line = 1, prevSig = "";
|
|
115
|
-
const capture = (from, to, startLine) => {
|
|
116
|
-
const content = s.slice(from, to);
|
|
117
|
-
const nl = (content.match(/\n/g) || []).length;
|
|
118
|
-
if (nl + 1 >= minLines) out.push({ start: startLine, end: startLine + nl, content });
|
|
119
|
-
};
|
|
120
|
-
while (i < s.length) {
|
|
121
|
-
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
122
|
-
if (ch === "\n") { line++; i++; continue; }
|
|
123
|
-
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
124
|
-
if (py && (three === "'''" || three === '"""')) {
|
|
125
|
-
const startLine = line; i += 3; const from = i;
|
|
126
|
-
while (i < s.length && s.slice(i, i + 3) !== three) { if (s[i] === "\n") line++; i++; }
|
|
127
|
-
capture(from, i, startLine); i += 3; continue;
|
|
128
|
-
}
|
|
129
|
-
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
130
|
-
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") { if (s[i] === "\n") line++; i++; } i += 2; continue; }
|
|
131
|
-
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
132
|
-
i++; let inClass = false;
|
|
133
|
-
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++; }
|
|
134
|
-
prevSig = "/"; continue;
|
|
135
|
-
}
|
|
136
|
-
if (cs && two === '@"') { // C# verbatim string; "" is the escaped quote
|
|
137
|
-
const startLine = line; i += 2; const from = i;
|
|
138
|
-
while (i < s.length) { if (s.slice(i, i + 2) === '""') { i += 2; continue; } if (s[i] === '"') break; if (s[i] === "\n") line++; i++; }
|
|
139
|
-
capture(from, i, startLine); i++; continue;
|
|
140
|
-
}
|
|
141
|
-
if (!py && ch === "`") { // JS/TS template literal — the main multi-line carrier
|
|
142
|
-
const startLine = line; i++; const from = i;
|
|
143
|
-
while (i < s.length && s[i] !== "`") { if (s[i] === "\\") { i++; if (s[i] === "\n") line++; i++; continue; } if (s[i] === "\n") line++; i++; }
|
|
144
|
-
capture(from, i, startLine); i++; continue;
|
|
145
|
-
}
|
|
146
|
-
if (ch === '"' || ch === "'") { // single-line strings can't span minLines — just skip past
|
|
147
|
-
const q = ch; i++;
|
|
148
|
-
while (i < s.length && s[i] !== q && s[i] !== "\n") { if (s[i] === "\\") i++; i++; }
|
|
149
|
-
if (s[i] === q) i++; continue;
|
|
150
|
-
}
|
|
151
|
-
if (ch.trim()) prevSig = ch;
|
|
152
|
-
i++;
|
|
153
|
-
}
|
|
154
|
-
return out;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// one raw token stream; the two modes differ only in identifier canonicalization
|
|
158
|
-
export function tokenize(text) {
|
|
159
|
-
const raw = text.match(/[A-Za-z_$][\w$]*|(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d[\d_]*)?)n?|[^\s\w]/g) || [];
|
|
160
|
-
const strict = [];
|
|
161
|
-
const renamed = [];
|
|
162
|
-
for (const t of raw) {
|
|
163
|
-
if (/^\d/.test(t)) {
|
|
164
|
-
// Numeric constants are behavior, not renameable identifiers. Preserve
|
|
165
|
-
// their value so same-shape limit/config tables with different numbers do
|
|
166
|
-
// not become perfect clones; a small constant edit still leaves the rest
|
|
167
|
-
// of a genuine copied body highly similar.
|
|
168
|
-
strict.push(`N:${t}`); renamed.push(`N:${t}`); continue;
|
|
169
|
-
}
|
|
170
|
-
if (/^[A-Za-z_$]/.test(t) && !KEYWORDS.has(t)) { strict.push(t); renamed.push("I"); continue; }
|
|
171
|
-
strict.push(t); renamed.push(t);
|
|
172
|
-
}
|
|
173
|
-
return { strict, renamed };
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function fingerprints(toks) {
|
|
177
|
-
if (toks.length < K + W - 1) return new Set();
|
|
178
|
-
const hashes = [];
|
|
179
|
-
for (let i = 0; i + K <= toks.length; i++) {
|
|
180
|
-
let h = 0;
|
|
181
|
-
for (let j = i; j < i + K; j++) {
|
|
182
|
-
const s = toks[j];
|
|
183
|
-
for (let c = 0; c < s.length; c++) h = (h * 31 + s.charCodeAt(c)) | 0;
|
|
184
|
-
h = (h * 131) | 0;
|
|
185
|
-
}
|
|
186
|
-
hashes.push(h >>> 0);
|
|
187
|
-
}
|
|
188
|
-
const fp = new Set();
|
|
189
|
-
for (let i = 0; i + W <= hashes.length + 1; i++) {
|
|
190
|
-
let min = Infinity;
|
|
191
|
-
for (let j = i; j < Math.min(i + W, hashes.length); j++) if (hashes[j] < min) min = hashes[j];
|
|
192
|
-
fp.add(min);
|
|
193
|
-
}
|
|
194
|
-
// Winnowing can skip every changed literal in a repetitive policy table.
|
|
195
|
-
// Exact numeric anchors keep behavior-defining limits in the similarity
|
|
196
|
-
// denominator while leaving ordinary copied bodies tolerant of a small edit.
|
|
197
|
-
for (const token of toks) if (token.startsWith("N:")) fp.add(`numeric:${token}`);
|
|
198
|
-
return fp;
|
|
199
|
-
}
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
export const MAX_ENDPOINT_FILES = 3_000;
|
|
2
|
-
export const MAX_ENDPOINTS = 2_000;
|
|
3
|
-
export const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE", "CONNECT", "ALL", "ANY"]);
|
|
4
|
-
|
|
5
|
-
export function lineAt(text, index) {
|
|
6
|
-
let line = 1;
|
|
7
|
-
for (let i = 0; i < index && i < text.length; i++) if (text[i] === "\n") line++;
|
|
8
|
-
return line;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
// Preserve offsets and literals while hiding comments from regex extractors.
|
|
12
|
-
export function maskComments(text, { hashComments = false } = {}) {
|
|
13
|
-
const chars = String(text || "").split("");
|
|
14
|
-
let quote = "", escaped = false, lineComment = false, blockComment = false, regex = false, regexClass = false;
|
|
15
|
-
const startsRegex = (index) => {
|
|
16
|
-
let cursor = index - 1;
|
|
17
|
-
while (cursor >= 0 && /\s/.test(chars[cursor])) cursor--;
|
|
18
|
-
if (cursor < 0) return true;
|
|
19
|
-
if (/[=(:,!&|?{}[\];]/.test(chars[cursor])) return true;
|
|
20
|
-
const prefix = chars.slice(Math.max(0, cursor - 12), cursor + 1).join("");
|
|
21
|
-
return /(?:^|\b)(?:return|throw|case|yield|await)\s*$/i.test(prefix) || /=>\s*$/.test(prefix);
|
|
22
|
-
};
|
|
23
|
-
for (let i = 0; i < chars.length; i++) {
|
|
24
|
-
const ch = chars[i], next = chars[i + 1];
|
|
25
|
-
if (lineComment) {
|
|
26
|
-
if (ch === "\n" || ch === "\r") lineComment = false;
|
|
27
|
-
else chars[i] = " ";
|
|
28
|
-
continue;
|
|
29
|
-
}
|
|
30
|
-
if (blockComment) {
|
|
31
|
-
if (ch === "*" && next === "/") { chars[i] = chars[i + 1] = " "; i++; blockComment = false; }
|
|
32
|
-
else if (ch !== "\n" && ch !== "\r") chars[i] = " ";
|
|
33
|
-
continue;
|
|
34
|
-
}
|
|
35
|
-
if (regex) {
|
|
36
|
-
if (escaped) escaped = false;
|
|
37
|
-
else if (ch === "\\") escaped = true;
|
|
38
|
-
else if (ch === "[") regexClass = true;
|
|
39
|
-
else if (ch === "]") regexClass = false;
|
|
40
|
-
else if (ch === "/" && !regexClass) regex = false;
|
|
41
|
-
continue;
|
|
42
|
-
}
|
|
43
|
-
if (quote) {
|
|
44
|
-
if (escaped) escaped = false;
|
|
45
|
-
else if (ch === "\\") escaped = true;
|
|
46
|
-
else if (ch === quote) quote = "";
|
|
47
|
-
continue;
|
|
48
|
-
}
|
|
49
|
-
if (ch === '"' || ch === "'" || ch === "`") { quote = ch; continue; }
|
|
50
|
-
if (ch === "/" && next === "/") { chars[i] = chars[i + 1] = " "; i++; lineComment = true; continue; }
|
|
51
|
-
if (ch === "/" && next === "*") { chars[i] = chars[i + 1] = " "; i++; blockComment = true; continue; }
|
|
52
|
-
if (!hashComments && ch === "/" && startsRegex(i)) { regex = true; regexClass = false; escaped = false; continue; }
|
|
53
|
-
if (hashComments && ch === "#") { chars[i] = " "; lineComment = true; }
|
|
54
|
-
}
|
|
55
|
-
return chars.join("");
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function handlerName(expr) {
|
|
59
|
-
const source = String(expr || "").trim();
|
|
60
|
-
if (!source || /=>/.test(source) || /^\s*(async\s+)?function\b/.test(source) || /^\s*(?:async\s+)?(?:move\s+)?\|[^|]*\|/.test(source)) return "";
|
|
61
|
-
const turbofish = /(?:^|::)([A-Za-z_][\w]*)\s*::<[\s\S]*>\s*$/.exec(source);
|
|
62
|
-
if (turbofish) return turbofish[1];
|
|
63
|
-
const identifiers = source.match(/[A-Za-z_$][\w$]*/g);
|
|
64
|
-
if (!identifiers) return "";
|
|
65
|
-
const skipped = new Set(["async", "function", "await", "req", "res", "ctx", "request", "response", "next", "return"]);
|
|
66
|
-
for (let i = identifiers.length - 1; i >= 0; i--) if (!skipped.has(identifiers[i])) return identifiers[i];
|
|
67
|
-
return "";
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function handlerReference(expr) {
|
|
71
|
-
const source = String(expr || "").trim();
|
|
72
|
-
if (!source || /=>/.test(source) || /^\s*(async\s+)?function\b/.test(source)) return "";
|
|
73
|
-
const refs = [...source.matchAll(/([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)+)/g)];
|
|
74
|
-
return refs.length ? refs.at(-1)[1].replace(/\s+/g, "") : "";
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export const looksLikePath = (path) => typeof path === "string" && /^\/[\w\-./:{}*$?]*$/.test(path) && !path.includes("://");
|
|
78
|
-
export const cleanPath = (path) => String(path || "").replace(/\/+$/, "") || "/";
|
|
79
|
-
export const normalizedFile = (file) => String(file || "").replace(/\\/g, "/").replace(/^\.\//, "");
|