weavatrix 0.3.13 → 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 -65
- 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.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.js +0 -235
- 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 -62
- package/src/analysis/endpoints/extract.js +0 -107
- 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 -295
- 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 -154
- 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 -173
- 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 -174
- package/src/mcp/health/dead-code.mjs +0 -110
- package/src/mcp/health/duplicates.mjs +0 -85
- package/src/mcp/health/endpoints.mjs +0 -71
- package/src/mcp/health/structure.mjs +0 -219
- 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 -220
- 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,51 +0,0 @@
|
|
|
1
|
-
import {posix} from 'node:path'
|
|
2
|
-
|
|
3
|
-
export const normalizeDependencyScope = (root) => String(root || '').replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+|\/+$/g, '')
|
|
4
|
-
export const dependencyScopeRoot = (manifest) => {
|
|
5
|
-
const root = posix.dirname(normalizeDependencyScope(manifest))
|
|
6
|
-
return root === '.' ? '' : root
|
|
7
|
-
}
|
|
8
|
-
export const dependencyScopeOwnsFile = (scope, file) => !scope || file === scope || String(file || '').startsWith(`${scope}/`)
|
|
9
|
-
|
|
10
|
-
// Bind the ecosystem-specific core without introducing a facade/helper import cycle.
|
|
11
|
-
export function createScopedDepFindings(computeDepFindings) {
|
|
12
|
-
return function computeScopedDepFindings({
|
|
13
|
-
externalImports = [], packageScopes = [], workspacePkgNames = new Set(), configTexts = new Map(),
|
|
14
|
-
sourceTexts = new Map(), nonRuntimeRoots = [], sourceFiles = [],
|
|
15
|
-
} = {}) {
|
|
16
|
-
const scopes = packageScopes.length
|
|
17
|
-
? packageScopes.map((scope) => ({...scope, root: normalizeDependencyScope(scope.root)})).sort((a, b) => b.root.length - a.root.length)
|
|
18
|
-
: [{root: '', manifest: 'package.json', pkg: {}, aliases: []}]
|
|
19
|
-
const importsByScope = new Map(scopes.map((scope) => [scope, []]))
|
|
20
|
-
const sourceFilesByScope = new Map(scopes.map((scope) => [scope, []]))
|
|
21
|
-
const sourceTextsByScope = new Map(scopes.map((scope) => [scope, new Map()]))
|
|
22
|
-
for (const item of externalImports) {
|
|
23
|
-
const owner = scopes.find((scope) => dependencyScopeOwnsFile(scope.root, item.file)) || scopes[scopes.length - 1]
|
|
24
|
-
importsByScope.get(owner).push(item)
|
|
25
|
-
}
|
|
26
|
-
for (const file of sourceFiles) {
|
|
27
|
-
const owner = scopes.find((scope) => dependencyScopeOwnsFile(scope.root, file)) || scopes[scopes.length - 1]
|
|
28
|
-
sourceFilesByScope.get(owner).push(file)
|
|
29
|
-
}
|
|
30
|
-
for (const [file, text] of sourceTexts) {
|
|
31
|
-
const owner = scopes.find((scope) => dependencyScopeOwnsFile(scope.root, file)) || scopes[scopes.length - 1]
|
|
32
|
-
sourceTextsByScope.get(owner).set(file, text)
|
|
33
|
-
}
|
|
34
|
-
const configOwner = new Map()
|
|
35
|
-
for (const [file] of configTexts) configOwner.set(file, scopes.find((scope) => dependencyScopeOwnsFile(scope.root, file)) || scopes[scopes.length - 1])
|
|
36
|
-
const findings = [], usedPackages = new Map(), declared = new Set()
|
|
37
|
-
for (const scope of scopes) {
|
|
38
|
-
const scopeConfig = new Map([...configTexts].filter(([file]) => configOwner.get(file) === scope))
|
|
39
|
-
const result = computeDepFindings({
|
|
40
|
-
externalImports: importsByScope.get(scope), pkg: scope.pkg || {}, workspacePkgNames,
|
|
41
|
-
configTexts: scopeConfig, sourceTexts: sourceTextsByScope.get(scope), aliases: scope.aliases || [], scope: scope.root,
|
|
42
|
-
manifest: scope.manifest || (scope.root ? `${scope.root}/package.json` : 'package.json'),
|
|
43
|
-
nonRuntimeRoots, sourceFiles: sourceFilesByScope.get(scope),
|
|
44
|
-
})
|
|
45
|
-
findings.push(...result.findings)
|
|
46
|
-
for (const [name, use] of result.usedPackages) usedPackages.set(`${scope.root || '.'}:${name}`, use)
|
|
47
|
-
for (const name of result.declared) declared.add(`${scope.root || '.'}:${name}`)
|
|
48
|
-
}
|
|
49
|
-
return {findings, usedPackages, declared}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
// Dynamic package loaders often construct a node_modules path instead of using
|
|
2
|
-
// import/require, so they never become graph externalImports. Restrict this
|
|
3
|
-
// fallback to executable npm source: manifests merely declare every dependency
|
|
4
|
-
// and must never count as usage evidence.
|
|
5
|
-
const NPM_SOURCE_RE = /\.(?:[cm]?[jt]sx?|vue|svelte)$/i
|
|
6
|
-
const escRe = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
7
|
-
const mentioned = (blob, name) => new RegExp(`(^|[^\\w@.-])${escRe(name)}($|[^\\w.-])`).test(blob)
|
|
8
|
-
|
|
9
|
-
export function createPackageSourceMatcher(sourceTexts = new Map()) {
|
|
10
|
-
const blob = [...sourceTexts]
|
|
11
|
-
.filter(([file]) => NPM_SOURCE_RE.test(String(file || '')))
|
|
12
|
-
.map(([, text]) => String(text || ''))
|
|
13
|
-
.join('\n')
|
|
14
|
-
return (name) => {
|
|
15
|
-
if (mentioned(blob, name)) return true
|
|
16
|
-
if (!name.startsWith('@') || !name.includes('/')) return false
|
|
17
|
-
const [namespace, base] = name.split('/', 2)
|
|
18
|
-
// join(root, "node_modules", "@scope", "package", ...)
|
|
19
|
-
return new RegExp(`["'\x60]${escRe(namespace)}["'\x60][\\s\\S]{0,96}?["'\x60]${escRe(base)}["'\x60]`).test(blob)
|
|
20
|
-
}
|
|
21
|
-
}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import {createHash} from 'node:crypto'
|
|
2
|
-
import {writeFileSync} from 'node:fs'
|
|
3
|
-
import {join} from 'node:path'
|
|
4
|
-
import {computeDuplicates} from './duplicates.js'
|
|
5
|
-
import {withGitRefCheckout} from './git-ref-graph.js'
|
|
6
|
-
import {buildInternalGraph} from '../graph/internal-builder.js'
|
|
7
|
-
import {filterGraphForMode} from '../graph/graph-filter.js'
|
|
8
|
-
|
|
9
|
-
const NON_PRODUCT = new Set(['generated', 'mock', 'story', 'docs', 'benchmark', 'temp'])
|
|
10
|
-
const eligible = (fragment, settings) => {
|
|
11
|
-
const classes = new Set(fragment.classes || [])
|
|
12
|
-
if (fragment.n < settings.tokMin) return false
|
|
13
|
-
if (settings.skipTests && (fragment.test || classes.has('test') || classes.has('e2e'))) return false
|
|
14
|
-
return settings.includeClassified || !(fragment.excluded || [...classes].some((name) => NON_PRODUCT.has(name)))
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function groupPairs(data, settings) {
|
|
18
|
-
const fragments = data.frags || []
|
|
19
|
-
const pairs = (data.modes?.[settings.mode] || []).filter(([a, b, similarity]) => similarity >= settings.simMin && eligible(fragments[a], settings) && eligible(fragments[b], settings))
|
|
20
|
-
const parent = new Map()
|
|
21
|
-
const find = (value) => { let root = value; while (parent.get(root) !== root) root = parent.get(root); return root }
|
|
22
|
-
for (const [a, b] of pairs) {
|
|
23
|
-
if (!parent.has(a)) parent.set(a, a)
|
|
24
|
-
if (!parent.has(b)) parent.set(b, b)
|
|
25
|
-
parent.set(find(a), find(b))
|
|
26
|
-
}
|
|
27
|
-
const groups = new Map()
|
|
28
|
-
for (const [a, b, similarity] of pairs) {
|
|
29
|
-
const root = find(a)
|
|
30
|
-
if (!groups.has(root)) groups.set(root, {members: new Set(), maxSim: 0})
|
|
31
|
-
const group = groups.get(root)
|
|
32
|
-
group.members.add(a); group.members.add(b); group.maxSim = Math.max(group.maxSim, similarity)
|
|
33
|
-
}
|
|
34
|
-
return [...groups.values()].map((group) => {
|
|
35
|
-
const members = [...group.members].map((index) => fragments[index]).sort((a, b) => b.n - a.n)
|
|
36
|
-
return {members, maxSim: group.maxSim, tokens: members.reduce((sum, item) => sum + item.n, 0)}
|
|
37
|
-
}).sort((a, b) => b.tokens - a.tokens)
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function isFrameworkBoilerplateCloneGroup(group) {
|
|
41
|
-
const members = Array.isArray(group?.members) ? group.members : []
|
|
42
|
-
if (members.length < 2) return false
|
|
43
|
-
return members.every((member) => /(?:^|\/)\w[^/]*\.router\.[cm]?[jt]s$/i.test(String(member.file || '').replace(/\\/g, '/'))
|
|
44
|
-
&& /^(?:router|routes)\(?\)?$/i.test(String(member.label || '').trim()))
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function isDeclarativeCatalogCloneGroup(group) {
|
|
48
|
-
const members = Array.isArray(group?.members) ? group.members : []
|
|
49
|
-
return members.length >= 2 && members.every((member) => member.declarative === true)
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function analyzeDuplicateGroups(repoRoot, graphPath, args = {}) {
|
|
53
|
-
const settings = {
|
|
54
|
-
simMin: Math.min(100, Math.max(50, Number(args.min_similarity) || 80)),
|
|
55
|
-
tokMin: Math.min(400, Math.max(12, Number(args.min_tokens) || 50)),
|
|
56
|
-
mode: args.mode === 'strict' ? 'strict' : 'renamed',
|
|
57
|
-
skipTests: args.include_tests !== true,
|
|
58
|
-
includeClassified: args.include_classified === true || args.include_non_product === true,
|
|
59
|
-
includeBoilerplate: args.include_boilerplate === true,
|
|
60
|
-
includeDeclarative: args.include_declarative === true,
|
|
61
|
-
}
|
|
62
|
-
const data = computeDuplicates(repoRoot, graphPath, {includeStrings: args.include_strings === true, minTokens: settings.tokMin})
|
|
63
|
-
const allGroups = groupPairs(data, settings)
|
|
64
|
-
const afterBoilerplate = settings.includeBoilerplate ? allGroups : allGroups.filter((group) => !isFrameworkBoilerplateCloneGroup(group))
|
|
65
|
-
const groups = settings.includeDeclarative ? afterBoilerplate : afterBoilerplate.filter((group) => !isDeclarativeCatalogCloneGroup(group))
|
|
66
|
-
const suppressed = (data.frags || []).filter((fragment) => !eligible(fragment, settings)).length
|
|
67
|
-
return {
|
|
68
|
-
settings, groups, suppressed,
|
|
69
|
-
boilerplateSuppressed: allGroups.length - afterBoilerplate.length,
|
|
70
|
-
declarativeSuppressed: afterBoilerplate.length - groups.length,
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const digest = (value) => createHash('sha256').update(value).digest('hex').slice(0, 20)
|
|
75
|
-
function groupKey(group, mode) {
|
|
76
|
-
const members = group.members.map((fragment) => {
|
|
77
|
-
const fingerprints = Array.isArray(fragment.fp?.[mode]) ? [...fragment.fp[mode]].sort() : []
|
|
78
|
-
return `${String(fragment.file).replace(/\\/g, '/')}\0${fragment.label || ''}\0${digest(JSON.stringify(fingerprints))}`
|
|
79
|
-
}).sort()
|
|
80
|
-
return digest(members.join('\n'))
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export async function compareDuplicateGroups({repoRoot, graphPath, currentGraph, baseRef, changedFiles = [], args = {}}) {
|
|
84
|
-
const current = analyzeDuplicateGroups(repoRoot, graphPath, args)
|
|
85
|
-
const mode = ['full', 'no-tests', 'tests-only'].includes(currentGraph?.graphBuildMode) ? currentGraph.graphBuildMode : 'full'
|
|
86
|
-
const baseline = await withGitRefCheckout(repoRoot, baseRef, async (checkout) => {
|
|
87
|
-
let graph = await buildInternalGraph(checkout)
|
|
88
|
-
if (mode !== 'full') graph = filterGraphForMode(graph, mode, {repoRoot: checkout})
|
|
89
|
-
graph.graphBuildMode = mode
|
|
90
|
-
const baselineGraphPath = join(checkout, '.weavatrix-verified-graph.json')
|
|
91
|
-
writeFileSync(baselineGraphPath, JSON.stringify(graph))
|
|
92
|
-
return analyzeDuplicateGroups(checkout, baselineGraphPath, args)
|
|
93
|
-
})
|
|
94
|
-
if (!baseline.ok) return {state: 'UNKNOWN', reason: baseline.error, currentGroups: current.groups.length}
|
|
95
|
-
const baselineKeys = new Set(baseline.value.groups.map((group) => groupKey(group, current.settings.mode)))
|
|
96
|
-
const changed = new Set(changedFiles.map((file) => String(file).replace(/\\/g, '/')))
|
|
97
|
-
const added = current.groups.filter((group) => !baselineKeys.has(groupKey(group, current.settings.mode)))
|
|
98
|
-
const scoped = added.filter((group) => group.members.some((member) => changed.has(String(member.file).replace(/\\/g, '/'))))
|
|
99
|
-
return {
|
|
100
|
-
state: scoped.length ? 'BLOCKED' : 'PASS', baseline: {ref: baseline.ref, commit: baseline.commit},
|
|
101
|
-
currentGroups: current.groups.length, baselineGroups: baseline.value.groups.length, newGroups: added.length,
|
|
102
|
-
scopedNewGroups: scoped.slice(0, 20).map((group) => ({similarity: group.maxSim, tokens: group.tokens, members: group.members.slice(0, 8).map((item) => ({file: item.file, start: item.start, end: item.end, label: item.label}))})),
|
|
103
|
-
}
|
|
104
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// duplicates-worker.js — runs clone detection OFF Electron's main thread (same rationale as
|
|
2
|
-
// graph/build-worker.js: a blocked main event loop freezes every window on Windows). The fingerprint
|
|
3
|
-
// sets never leave the worker; only slim fragment metadata + similarity pairs cross back.
|
|
4
|
-
import { parentPort, workerData } from "node:worker_threads";
|
|
5
|
-
import { computeDuplicates } from "./duplicates.js";
|
|
6
|
-
|
|
7
|
-
try {
|
|
8
|
-
parentPort.postMessage(computeDuplicates(workerData.repoPath, workerData.graphJsonPath));
|
|
9
|
-
} catch (e) {
|
|
10
|
-
parentPort.postMessage({ ok: false, error: (e && e.message) || String(e) });
|
|
11
|
-
}
|
|
@@ -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
|
-
}
|