weavatrix 0.3.14 → 1.1.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.
Files changed (306) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +132 -200
  3. package/bin/native/darwin-arm64/weavatrix +0 -0
  4. package/bin/native/darwin-x64/weavatrix +0 -0
  5. package/bin/native/linux-arm64/weavatrix +0 -0
  6. package/bin/native/linux-x64/weavatrix +0 -0
  7. package/bin/native/win32-arm64/weavatrix.exe +0 -0
  8. package/bin/native/win32-x64/weavatrix.exe +0 -0
  9. package/bin/resolve-binary.mjs +73 -0
  10. package/bin/run-native.mjs +26 -0
  11. package/bin/weavatrix-mcp.mjs +7 -6
  12. package/bin/weavatrix.mjs +5 -0
  13. package/package.json +10 -67
  14. package/server.json +38 -0
  15. package/skill/SKILL.md +62 -374
  16. package/skill/agents/openai.yaml +4 -0
  17. package/skill/references/tool-routing.md +45 -0
  18. package/SECURITY.md +0 -101
  19. package/docs/adr/0001-v0.3-offline-online-split.md +0 -60
  20. package/docs/agent-task-benchmark.md +0 -58
  21. package/docs/releases/v0.2.19.md +0 -33
  22. package/docs/releases/v0.3.0.md +0 -43
  23. package/docs/releases/v0.3.1.md +0 -30
  24. package/docs/releases/v0.3.10.md +0 -76
  25. package/docs/releases/v0.3.11.md +0 -55
  26. package/docs/releases/v0.3.12.md +0 -44
  27. package/docs/releases/v0.3.13.md +0 -34
  28. package/docs/releases/v0.3.14.md +0 -37
  29. package/docs/releases/v0.3.2.md +0 -15
  30. package/docs/releases/v0.3.3.md +0 -25
  31. package/docs/releases/v0.3.4.md +0 -40
  32. package/docs/releases/v0.3.5.md +0 -50
  33. package/docs/releases/v0.3.6.md +0 -44
  34. package/docs/releases/v0.3.7.md +0 -37
  35. package/docs/releases/v0.3.8.md +0 -21
  36. package/docs/releases/v0.3.9.md +0 -36
  37. package/scripts/run-agent-task-benchmark.mjs +0 -118
  38. package/src/analysis/allowed-test-runner.js +0 -70
  39. package/src/analysis/architecture/contract-graph.js +0 -119
  40. package/src/analysis/architecture/contract-schema.js +0 -110
  41. package/src/analysis/architecture/contract-storage.js +0 -35
  42. package/src/analysis/architecture/contract-verification.js +0 -168
  43. package/src/analysis/architecture-contract.js +0 -16
  44. package/src/analysis/audit-debt.js +0 -94
  45. package/src/analysis/audit-extensions.js +0 -60
  46. package/src/analysis/cargo-dependency-evidence.js +0 -108
  47. package/src/analysis/cargo-manifests.js +0 -81
  48. package/src/analysis/change-classification/diff-parser.js +0 -103
  49. package/src/analysis/change-classification/options.js +0 -40
  50. package/src/analysis/change-classification/symbol-classifier.js +0 -177
  51. package/src/analysis/change-classification.js +0 -188
  52. package/src/analysis/coverage-reports-tarpaulin.js +0 -112
  53. package/src/analysis/coverage-reports.js +0 -246
  54. package/src/analysis/cycle-route.js +0 -14
  55. package/src/analysis/data-flow-evidence.js +0 -114
  56. package/src/analysis/dead-check.js +0 -300
  57. package/src/analysis/dead-code-review/candidates.js +0 -194
  58. package/src/analysis/dead-code-review/policy.js +0 -23
  59. package/src/analysis/dead-code-review.js +0 -119
  60. package/src/analysis/dep-check-ecosystems.js +0 -205
  61. package/src/analysis/dep-check.js +0 -290
  62. package/src/analysis/dep-rules.js +0 -10
  63. package/src/analysis/dependency/conventions.js +0 -16
  64. package/src/analysis/dependency/scoped-dependencies.js +0 -51
  65. package/src/analysis/dependency/source-references.js +0 -21
  66. package/src/analysis/duplicate-groups.js +0 -104
  67. package/src/analysis/duplicates-worker.js +0 -11
  68. package/src/analysis/duplicates.compute.js +0 -269
  69. package/src/analysis/duplicates.js +0 -15
  70. package/src/analysis/duplicates.run.js +0 -52
  71. package/src/analysis/duplicates.tokenize.js +0 -199
  72. package/src/analysis/endpoints/common.js +0 -79
  73. package/src/analysis/endpoints/extract.js +0 -120
  74. package/src/analysis/endpoints/inventory.js +0 -84
  75. package/src/analysis/endpoints/mounts.js +0 -129
  76. package/src/analysis/endpoints-java.js +0 -260
  77. package/src/analysis/endpoints-rust.js +0 -124
  78. package/src/analysis/endpoints.js +0 -3
  79. package/src/analysis/findings.js +0 -70
  80. package/src/analysis/git-history/analytics.js +0 -177
  81. package/src/analysis/git-history/collector.js +0 -67
  82. package/src/analysis/git-history/options.js +0 -66
  83. package/src/analysis/git-history.js +0 -143
  84. package/src/analysis/git-ref-graph.js +0 -76
  85. package/src/analysis/go-dependency-evidence.js +0 -62
  86. package/src/analysis/graph-analysis.aggregate.js +0 -296
  87. package/src/analysis/graph-analysis.edges.js +0 -24
  88. package/src/analysis/graph-analysis.js +0 -7
  89. package/src/analysis/graph-analysis.refs.js +0 -202
  90. package/src/analysis/graph-analysis.summaries.js +0 -65
  91. package/src/analysis/health-capabilities.js +0 -83
  92. package/src/analysis/hot-path-review.js +0 -266
  93. package/src/analysis/http-contract-wrappers.js +0 -241
  94. package/src/analysis/http-contracts/analysis.js +0 -179
  95. package/src/analysis/http-contracts/client-call-detection.js +0 -82
  96. package/src/analysis/http-contracts/client-call-parser.js +0 -273
  97. package/src/analysis/http-contracts/graph-context.js +0 -143
  98. package/src/analysis/http-contracts/matching.js +0 -61
  99. package/src/analysis/http-contracts/shared.js +0 -85
  100. package/src/analysis/http-contracts.js +0 -6
  101. package/src/analysis/internal-audit/dependency-health.js +0 -113
  102. package/src/analysis/internal-audit/python-manifests.js +0 -78
  103. package/src/analysis/internal-audit/repo-files.js +0 -50
  104. package/src/analysis/internal-audit/supply-chain.js +0 -149
  105. package/src/analysis/internal-audit.collect.js +0 -213
  106. package/src/analysis/internal-audit.js +0 -9
  107. package/src/analysis/internal-audit.reach.js +0 -201
  108. package/src/analysis/internal-audit.run.js +0 -256
  109. package/src/analysis/java-source.js +0 -36
  110. package/src/analysis/jvm-artifact-index.js +0 -87
  111. package/src/analysis/jvm-dependency-evidence.js +0 -138
  112. package/src/analysis/jvm-manifests.js +0 -114
  113. package/src/analysis/manifests.js +0 -123
  114. package/src/analysis/package-reachability.js +0 -39
  115. package/src/analysis/source-complexity.ast.js +0 -97
  116. package/src/analysis/source-complexity.constants.js +0 -55
  117. package/src/analysis/source-complexity.js +0 -14
  118. package/src/analysis/source-complexity.report.js +0 -81
  119. package/src/analysis/source-complexity.walk.js +0 -228
  120. package/src/analysis/source-correctness/retry-patterns.js +0 -93
  121. package/src/analysis/source-correctness.js +0 -222
  122. package/src/analysis/static-test-reachability.js +0 -150
  123. package/src/analysis/structure/dependency-graph.js +0 -151
  124. package/src/analysis/structure/findings.js +0 -162
  125. package/src/analysis/task-retrieval.js +0 -107
  126. package/src/analysis/transport-contracts.js +0 -224
  127. package/src/analysis/transport-runtime-evidence.js +0 -155
  128. package/src/analysis-kit.mjs +0 -17
  129. package/src/bounds.js +0 -4
  130. package/src/build-graph.js +0 -209
  131. package/src/child-env.js +0 -7
  132. package/src/config.js +0 -5
  133. package/src/extension/local-services.mjs +0 -75
  134. package/src/git-exec.js +0 -67
  135. package/src/graph/build-worker.js +0 -49
  136. package/src/graph/builder/go-receiver-resolution.js +0 -112
  137. package/src/graph/builder/js/dynamic-import.js +0 -26
  138. package/src/graph/builder/js/queries.js +0 -48
  139. package/src/graph/builder/lang-csharp.js +0 -40
  140. package/src/graph/builder/lang-css.js +0 -29
  141. package/src/graph/builder/lang-go.js +0 -140
  142. package/src/graph/builder/lang-html.js +0 -29
  143. package/src/graph/builder/lang-java-calls.js +0 -142
  144. package/src/graph/builder/lang-java.js +0 -215
  145. package/src/graph/builder/lang-js.js +0 -291
  146. package/src/graph/builder/lang-python.js +0 -235
  147. package/src/graph/builder/lang-rust-calls.js +0 -63
  148. package/src/graph/builder/lang-rust.js +0 -299
  149. package/src/graph/builder/lang-solidity.js +0 -126
  150. package/src/graph/builder/lang-sql.js +0 -263
  151. package/src/graph/builder/pass2-resolution.js +0 -81
  152. package/src/graph/builder/spec-pkg.js +0 -87
  153. package/src/graph/community.js +0 -27
  154. package/src/graph/edge-provenance.js +0 -31
  155. package/src/graph/file-lock.js +0 -69
  156. package/src/graph/freshness-probe.js +0 -142
  157. package/src/graph/graph-filter.js +0 -63
  158. package/src/graph/incremental-refresh.js +0 -235
  159. package/src/graph/internal-builder.barrels.js +0 -235
  160. package/src/graph/internal-builder.build.js +0 -300
  161. package/src/graph/internal-builder.java.js +0 -33
  162. package/src/graph/internal-builder.js +0 -12
  163. package/src/graph/internal-builder.langs.js +0 -157
  164. package/src/graph/internal-builder.pass2.js +0 -163
  165. package/src/graph/internal-builder.resolvers.js +0 -286
  166. package/src/graph/layout.js +0 -51
  167. package/src/graph/node-id.js +0 -7
  168. package/src/graph/parser-artifact-boundary.js +0 -55
  169. package/src/graph/relations.js +0 -4
  170. package/src/graph/repo-registry.js +0 -124
  171. package/src/graph/resolvers/rust.js +0 -117
  172. package/src/infra/infra-items.js +0 -255
  173. package/src/infra/infra-registry.js +0 -184
  174. package/src/infra/infra.detect.js +0 -119
  175. package/src/infra/infra.js +0 -38
  176. package/src/infra/infra.match.js +0 -102
  177. package/src/infra/infra.scan.js +0 -93
  178. package/src/mcp/actions/graph-lifecycle.mjs +0 -148
  179. package/src/mcp/architecture-bootstrap.mjs +0 -168
  180. package/src/mcp/architecture-starter.mjs +0 -234
  181. package/src/mcp/catalog.mjs +0 -233
  182. package/src/mcp/company-contract-page.mjs +0 -142
  183. package/src/mcp/company-contract-reconcile.mjs +0 -87
  184. package/src/mcp/company-contract-verdict.mjs +0 -42
  185. package/src/mcp/evidence/bun-lock-graph.mjs +0 -209
  186. package/src/mcp/evidence/duplicate-member-order.mjs +0 -8
  187. package/src/mcp/evidence/package-graph-common.mjs +0 -115
  188. package/src/mcp/evidence/package-lock-graph.mjs +0 -92
  189. package/src/mcp/evidence-snapshot.architecture.mjs +0 -80
  190. package/src/mcp/evidence-snapshot.common.mjs +0 -158
  191. package/src/mcp/evidence-snapshot.duplicates.mjs +0 -213
  192. package/src/mcp/evidence-snapshot.health.mjs +0 -102
  193. package/src/mcp/evidence-snapshot.inventory.mjs +0 -148
  194. package/src/mcp/evidence-snapshot.mjs +0 -50
  195. package/src/mcp/evidence-snapshot.package-graph.mjs +0 -34
  196. package/src/mcp/evidence-snapshot.structure.mjs +0 -84
  197. package/src/mcp/extension-api.mjs +0 -77
  198. package/src/mcp/git-output.mjs +0 -7
  199. package/src/mcp/graph/context-core.mjs +0 -111
  200. package/src/mcp/graph/context-seeds.mjs +0 -207
  201. package/src/mcp/graph/context-state.mjs +0 -85
  202. package/src/mcp/graph/reverse-reach.mjs +0 -42
  203. package/src/mcp/graph/tools-core.mjs +0 -143
  204. package/src/mcp/graph/tools-query.mjs +0 -276
  205. package/src/mcp/graph-context.mjs +0 -5
  206. package/src/mcp/graph-diff.mjs +0 -218
  207. package/src/mcp/health/audit-format.mjs +0 -199
  208. package/src/mcp/health/audit.mjs +0 -199
  209. package/src/mcp/health/dead-code.mjs +0 -110
  210. package/src/mcp/health/duplicates.mjs +0 -121
  211. package/src/mcp/health/endpoints.mjs +0 -71
  212. package/src/mcp/health/structure.mjs +0 -220
  213. package/src/mcp/runtime-version.mjs +0 -31
  214. package/src/mcp/server/auto-refresh.mjs +0 -66
  215. package/src/mcp/server/runtime-config.mjs +0 -43
  216. package/src/mcp/server/shutdown.mjs +0 -40
  217. package/src/mcp/staleness-notice.mjs +0 -20
  218. package/src/mcp/sync/evidence-architecture.mjs +0 -54
  219. package/src/mcp/sync/evidence-common.mjs +0 -88
  220. package/src/mcp/sync/evidence-duplicates.mjs +0 -97
  221. package/src/mcp/sync/evidence-health.mjs +0 -56
  222. package/src/mcp/sync/evidence-packages.mjs +0 -95
  223. package/src/mcp/sync/payload-common.mjs +0 -97
  224. package/src/mcp/sync/payload-v2.mjs +0 -54
  225. package/src/mcp/sync/payload-v3.mjs +0 -79
  226. package/src/mcp/sync-evidence.mjs +0 -23
  227. package/src/mcp/sync-payload.mjs +0 -70
  228. package/src/mcp/tool-result.mjs +0 -54
  229. package/src/mcp/tools-actions.mjs +0 -11
  230. package/src/mcp/tools-architecture.mjs +0 -177
  231. package/src/mcp/tools-company.mjs +0 -251
  232. package/src/mcp/tools-context.mjs +0 -222
  233. package/src/mcp/tools-endpoints.mjs +0 -207
  234. package/src/mcp/tools-graph-hubs.mjs +0 -78
  235. package/src/mcp/tools-graph.mjs +0 -17
  236. package/src/mcp/tools-health.mjs +0 -24
  237. package/src/mcp/tools-history.mjs +0 -28
  238. package/src/mcp/tools-impact-change.mjs +0 -220
  239. package/src/mcp/tools-impact-precision.mjs +0 -89
  240. package/src/mcp/tools-impact.mjs +0 -169
  241. package/src/mcp/tools-source.mjs +0 -238
  242. package/src/mcp/tools-verified-change.mjs +0 -200
  243. package/src/mcp-rg.mjs +0 -50
  244. package/src/mcp-runtime.mjs +0 -2
  245. package/src/mcp-server.mjs +0 -298
  246. package/src/mcp-source-tools.mjs +0 -163
  247. package/src/path-classification.js +0 -226
  248. package/src/path-ignore.js +0 -69
  249. package/src/precision/lsp-client/constants.js +0 -12
  250. package/src/precision/lsp-client/environment.js +0 -20
  251. package/src/precision/lsp-client/errors.js +0 -15
  252. package/src/precision/lsp-client/lifecycle.js +0 -114
  253. package/src/precision/lsp-client/message-parser.js +0 -81
  254. package/src/precision/lsp-client/protocol.js +0 -212
  255. package/src/precision/lsp-client/registry.js +0 -59
  256. package/src/precision/lsp-client/repo-uri.js +0 -60
  257. package/src/precision/lsp-client/stdio-client.js +0 -140
  258. package/src/precision/lsp-client.js +0 -10
  259. package/src/precision/lsp-overlay/budget-policy.js +0 -78
  260. package/src/precision/lsp-overlay/build.js +0 -261
  261. package/src/precision/lsp-overlay/contract.js +0 -61
  262. package/src/precision/lsp-overlay/reference-results.js +0 -108
  263. package/src/precision/lsp-overlay/semantic-inputs.js +0 -62
  264. package/src/precision/lsp-overlay/source-session.js +0 -142
  265. package/src/precision/lsp-overlay/store.js +0 -150
  266. package/src/precision/lsp-overlay/target-index.js +0 -152
  267. package/src/precision/lsp-overlay/target-query.js +0 -55
  268. package/src/precision/lsp-overlay.js +0 -11
  269. package/src/precision/symbol-query.js +0 -224
  270. package/src/precision/typescript-lsp-provider.js +0 -12
  271. package/src/precision/typescript-provider/client.js +0 -89
  272. package/src/precision/typescript-provider/discovery.js +0 -124
  273. package/src/precision/typescript-provider/isolated-runtime.js +0 -39
  274. package/src/precision/typescript-provider/project-host.js +0 -254
  275. package/src/precision/typescript-provider/project-safety.js +0 -166
  276. package/src/precision/typescript-provider/reference-usage.js +0 -53
  277. package/src/process.js +0 -95
  278. package/src/repo-path.js +0 -53
  279. package/src/scan/discover.inventory.js +0 -78
  280. package/src/scan/discover.js +0 -5
  281. package/src/scan/discover.list.js +0 -79
  282. package/src/scan/discover.stack.js +0 -227
  283. package/src/scan/search.core.js +0 -24
  284. package/src/scan/search.git.js +0 -102
  285. package/src/scan/search.js +0 -9
  286. package/src/scan/search.node.js +0 -83
  287. package/src/scan/search.preview.js +0 -49
  288. package/src/scan/search.rg.js +0 -145
  289. package/src/security/advisory-store.js +0 -172
  290. package/src/security/installed-jvm-rust.js +0 -46
  291. package/src/security/installed.js +0 -280
  292. package/src/security/malware-file-heuristics.js +0 -121
  293. package/src/security/malware-heuristics.exclusions.js +0 -134
  294. package/src/security/malware-heuristics.js +0 -15
  295. package/src/security/malware-heuristics.roots.js +0 -145
  296. package/src/security/malware-heuristics.scan.js +0 -89
  297. package/src/security/malware-heuristics.sweep.js +0 -122
  298. package/src/security/malware-scoring.js +0 -105
  299. package/src/security/match.js +0 -85
  300. package/src/security/registry-sig.classify.js +0 -137
  301. package/src/security/registry-sig.js +0 -18
  302. package/src/security/registry-sig.rules.js +0 -192
  303. package/src/security/rust-advisory-report.js +0 -60
  304. package/src/security/typosquat.js +0 -81
  305. package/src/util.js +0 -40
  306. package/src/version.js +0 -7
@@ -1,149 +0,0 @@
1
- import { collectInstalled } from "../../security/installed.js";
2
- import { advisoryQueryFingerprint, loadStore, queryStore } from "../../security/advisory-store.js";
3
- import { matchAdvisories } from "../../security/match.js";
4
- import { scanMalware } from "../../security/malware-heuristics.js";
5
- import { classifyTyposquat } from "../../security/typosquat.js";
6
- import { loadRustAdvisoryReport } from "../../security/rust-advisory-report.js";
7
- import { makeFinding } from "../findings.js";
8
- import { packageReachability } from "../package-reachability.js";
9
-
10
- const LOWER_SEVERITY = { critical: "high", high: "medium", medium: "low", low: "info", info: "info" };
11
-
12
- const removalHint = (pkg) => {
13
- if (pkg?.ecosystem === "npm") return `npm uninstall ${pkg.name} and audit what it touched`;
14
- if (pkg?.ecosystem === "PyPI") return `remove ${pkg.name} from the Python environment/manifest and audit what it touched`;
15
- if (pkg?.ecosystem === "Go") return `remove ${pkg.name} from the Go module graph, run go mod tidy, and audit what it touched`;
16
- if (pkg?.ecosystem === "crates.io") return `cargo remove ${pkg.name}, rebuild every feature/target, and audit what it touched`;
17
- if (pkg?.ecosystem === "Maven") return `remove or upgrade ${pkg.name} in Maven/Gradle, refresh the resolved graph, and audit what it touched`;
18
- return `remove ${pkg?.name || "the package"} with its ecosystem's package manager and audit what it touched`;
19
- };
20
-
21
- export async function runSupplyChainChecks(repoPath, {
22
- externalImports = [],
23
- packageScopes = [],
24
- isNonProductPath = () => false,
25
- advisoryStorePath,
26
- skipMalwareScan = false,
27
- malwareExclusions = {},
28
- rgPath = "",
29
- } = {}) {
30
- const findings = [];
31
- let advisoryDbDate = null;
32
- let installedCount = 0;
33
- let inst = { installed: [], drift: [] };
34
- const checks = {
35
- osv: { status: "NOT_CHECKED", detail: "Advisory cache was never refreshed for this repository. The MIT core remains offline; use the separate Weavatrix Online connector only if you choose to query OSV with pinned package names and versions." },
36
- malware: { status: skipMalwareScan ? "NOT_CHECKED" : "PENDING", detail: skipMalwareScan ? "Installed-package malware scan is opt-in and was not requested." : "" },
37
- rustsec: { status: "NOT_CHECKED", detail: "No saved cargo audit --json report was inspected." },
38
- };
39
-
40
- try {
41
- inst = collectInstalled(repoPath);
42
- installedCount = inst.installed.length;
43
- const store = advisoryStorePath ? loadStore(advisoryStorePath) : loadStore();
44
- const repoStamp = store.meta?.repos?.[repoPath] || null;
45
- advisoryDbDate = typeof repoStamp === "string" ? repoStamp : repoStamp?.fetched_at || null;
46
- if (advisoryDbDate) {
47
- let status = typeof repoStamp === "object" && ["OK", "PARTIAL", "ERROR"].includes(repoStamp.status) ? repoStamp.status : "PARTIAL";
48
- const fingerprintMatches = typeof repoStamp === "object" && repoStamp.query_fingerprint === advisoryQueryFingerprint(inst.installed);
49
- if (!fingerprintMatches && status === "OK") status = "PARTIAL";
50
- const coverage = typeof repoStamp === "object" && Number.isFinite(repoStamp.queried)
51
- ? ` (${repoStamp.queried_ok ?? repoStamp.queried}/${repoStamp.queried} package versions queried successfully)`
52
- : "";
53
- const drift = fingerprintMatches ? "" : " Dependency versions changed, or this is a legacy stamp without a package fingerprint; refresh through the separate Weavatrix Online connector for complete advisory coverage.";
54
- checks.osv = {
55
- status,
56
- detail: `${status === "PARTIAL" ? "Partially matched" : "Matched"} installed packages against the cached OSV snapshot from ${advisoryDbDate}${coverage}.${drift}`,
57
- checkedAt: advisoryDbDate,
58
- };
59
- for (const hit of matchAdvisories(inst.installed, (ecosystem, name) => queryStore(store, ecosystem, name))) {
60
- const malicious = hit.adv.kind === "malicious";
61
- const reachability = packageReachability(externalImports, hit.pkg.name, { isNonProductPath });
62
- const observedInProduct = reachability.state === "DIRECT_RUNTIME_IMPORT";
63
- const reachabilityDetail = observedInProduct
64
- ? ` Graph reachability: directly imported by product code in ${reachability.directRuntimeImports} callsite(s) across ${reachability.files.length} file(s).`
65
- : ` Graph reachability: ${reachability.state}; ${reachability.note}`;
66
- findings.push(makeFinding({
67
- category: malicious ? "malware" : "vulnerability",
68
- rule: malicious ? "malicious-package" : "known-vuln",
69
- severity: malicious || observedInProduct ? (malicious ? "critical" : hit.adv.severity) : LOWER_SEVERITY[hit.adv.severity] || hit.adv.severity,
70
- confidence: malicious || observedInProduct ? hit.confidence : "low",
71
- title: `${malicious ? "Known-malicious package" : `Known vulnerability (${hit.adv.id})`}: ${hit.pkg.name}@${hit.pkg.version}`,
72
- detail: `${hit.adv.summary || hit.adv.id}${hit.adv.fixedIn.length ? ` Fixed in: ${hit.adv.fixedIn.join(", ")}.` : malicious ? " Remove this package immediately and rotate any secrets it could reach." : ""} (matched by ${hit.matchedBy}${hit.adv.aliases.length ? `; aliases ${hit.adv.aliases.join(", ")}` : ""}).${reachabilityDetail}`,
73
- package: hit.pkg.name,
74
- version: hit.pkg.version,
75
- reachability,
76
- evidence: [
77
- { file: hit.adv.id, line: 0, snippet: `installed via ${hit.pkg.source}${hit.pkg.dev ? " (dev)" : ""}` },
78
- ...reachability.evidence.slice(0, 5).map((item) => ({ file: item.file, line: item.line, snippet: `${item.typeOnly ? "type-only " : ""}${item.kind}` })),
79
- ],
80
- source: "osv",
81
- fixHint: malicious
82
- ? removalHint(hit.pkg)
83
- : hit.adv.fixedIn.length
84
- ? `upgrade ${hit.pkg.name} to ${hit.adv.fixedIn.at(-1)}+ with its ecosystem's package manager`
85
- : "no fixed version published; consider replacing the package",
86
- }));
87
- }
88
- }
89
- const directDependencyNames = new Set(packageScopes.flatMap((scope) => Object.keys({ ...(scope.pkg?.dependencies || {}), ...(scope.pkg?.devDependencies || {}) })));
90
- for (const name of directDependencyNames) {
91
- const candidate = classifyTyposquat(name);
92
- if (!candidate) continue;
93
- findings.push(makeFinding({
94
- category: "malware",
95
- rule: "typosquat",
96
- severity: "medium",
97
- confidence: "low",
98
- title: `Possible typosquat: ${name} (looks like "${candidate.nearest}")`,
99
- detail: `Direct dependency "${name}" is edit-distance ${candidate.distance} from the popular package "${candidate.nearest}". Confirm you meant "${name}" and not "${candidate.nearest}" — name-confusion is a common supply-chain lure.`,
100
- package: name,
101
- source: "internal",
102
- fixHint: `verify "${name}" is the intended package (not a typo of "${candidate.nearest}")`,
103
- }));
104
- }
105
- for (const item of inst.drift.slice(0, 20)) {
106
- findings.push(makeFinding({
107
- category: "malware",
108
- rule: "lockfile-drift",
109
- severity: "low",
110
- confidence: "medium",
111
- title: `Lockfile drift: ${item.name} (locked ${item.locked}, installed ${item.installed})`,
112
- detail: "The version on disk differs from the lockfile — a stale install, a manual edit, or (worst case) tampering. Reinstall from the lockfile to realign.",
113
- package: item.name,
114
- version: item.installed,
115
- source: "internal",
116
- fixHint: "npm ci (clean install from the lockfile)",
117
- }));
118
- }
119
- const rustsec = loadRustAdvisoryReport(repoPath);
120
- checks.rustsec = { status: rustsec.status, detail: rustsec.detail, checkedAt: rustsec.checkedAt || null };
121
- for (const issue of rustsec.findings) {
122
- findings.push(makeFinding({
123
- category: "vulnerability", rule: issue.kind === "vulnerability" ? "known-vuln" : "rust-advisory-warning",
124
- severity: issue.kind === "vulnerability" ? "high" : "medium", confidence: "high",
125
- title: `${issue.id}: ${issue.package}${issue.version ? `@${issue.version}` : ""}`,
126
- detail: `${issue.title}${issue.patched.length ? ` Patched: ${issue.patched.join(", ")}.` : ""}`,
127
- package: issue.package, version: issue.version, source: "rustsec",
128
- evidence: issue.url ? [{ file: issue.url, line: 0, snippet: `imported from ${rustsec.file}` }] : [{ file: rustsec.file, line: 0, snippet: issue.id }],
129
- fixHint: issue.patched.length ? `upgrade ${issue.package} to a patched RustSec range (${issue.patched.join(", ")})` : `review or replace ${issue.package}; no patched range was reported`,
130
- }));
131
- }
132
- } catch (error) {
133
- checks.osv = { status: "ERROR", detail: `Offline advisory matching failed: ${error instanceof Error ? error.message : String(error)}` };
134
- }
135
-
136
- let malwareScan = null;
137
- if (!skipMalwareScan) {
138
- try {
139
- const importedPkgs = new Set(externalImports.filter((entry) => entry.pkg && !entry.builtin).map((entry) => entry.pkg));
140
- const scan = await scanMalware(repoPath, { installed: inst.installed, importedPkgs, malwareExclusions, rgPath });
141
- findings.push(...scan.findings);
142
- malwareScan = { scanMode: scan.scanMode, packagesScanned: scan.packagesScanned, findings: scan.findings.length, excludedSignals: scan.excludedSignals || 0 };
143
- checks.malware = { status: "OK", detail: `Scanned ${scan.packagesScanned} installed package(s) using ${scan.scanMode}.` };
144
- } catch (error) {
145
- checks.malware = { status: "ERROR", detail: `Installed-package malware scan failed: ${error instanceof Error ? error.message : String(error)}` };
146
- }
147
- }
148
- return { findings, checks, installedCount, advisoryDbDate, malwareScan };
149
- }
@@ -1,213 +0,0 @@
1
- // internal-audit.collect.js — filesystem collection helpers for the internal audit: source/config
2
- // text gathering, workspace package names, and the Python manifest reader. Split from internal-audit.js.
3
- import { readdirSync } from "node:fs";
4
- import { dirname, join } from "node:path";
5
- import { createRepoBoundary } from "../repo-path.js";
6
- import {listRepoFiles, readJson, readRepoJson, readRepoText, readText} from './internal-audit/repo-files.js'
7
-
8
- export {listRepoFiles, readJson, readRepoJson, readRepoText, readText} from './internal-audit/repo-files.js'
9
- export {collectPyManifest} from './internal-audit/python-manifests.js'
10
- const SOURCE_EXT_RE = /\.(?:[cm]?[jt]sx?|py|go|java|rs|cs|vue|svelte)$/i;
11
-
12
- const NON_RUNTIME_DIR_RE = /^(?:templates?|examples?|samples?|fixtures?|snippets?|__fixtures__)$/i;
13
- const NON_RUNTIME_README_RE = /(?:\b(?:reusable|copyable|reference)\b[\s\S]{0,160}\b(?:templates?|snippets?|examples?|samples?)\b|\b(?:these|contents?)\s+are\s+templates?\b)/i;
14
- const normConfiguredRoot = (value) => {
15
- const root = String(value || "").trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+|\/+$/g, "");
16
- if (!root || root === "." || root.split("/").some((part) => part === "..")) return "";
17
- return root;
18
- };
19
-
20
- // Runtime health findings should not treat copy-paste catalogs as deployed applications. Conventional
21
- // template/example directories are safe to infer; a top-level custom catalog is inferred only when its
22
- // own README explicitly describes reusable templates/snippets. Projects can declare additional roots in
23
- // `.weavatrix-deps.json` through `nonRuntimeRoots` / `templateRoots`.
24
- export function collectNonRuntimeRoots(repoRoot, rules = {}) {
25
- const files = listRepoFiles(repoRoot);
26
- const roots = new Set();
27
- const configured = [
28
- rules.nonRuntimeRoots, rules.templateRoots,
29
- rules.dependencies?.nonRuntimeRoots, rules.dependencies?.templateRoots,
30
- ].flatMap((value) => Array.isArray(value) ? value : typeof value === "string" ? [value] : []);
31
- for (const value of configured) {
32
- const root = normConfiguredRoot(value);
33
- if (root) roots.add(root);
34
- }
35
-
36
- for (const file of files) {
37
- const parts = file.replace(/\\/g, "/").split("/");
38
- for (let i = 0; i < parts.length - 1; i++) {
39
- if (NON_RUNTIME_DIR_RE.test(parts[i])) roots.add(parts.slice(0, i + 1).join("/"));
40
- }
41
- }
42
-
43
- const boundary = createRepoBoundary(repoRoot);
44
- for (const file of files) {
45
- if (!/^[^/]+\/README\.md$/i.test(file)) continue; // custom inference is deliberately top-level only
46
- const text = readRepoText(boundary, file);
47
- if (text != null && NON_RUNTIME_README_RE.test(text)) roots.add(normRoot(dirname(file)));
48
- }
49
- return [...roots].filter(Boolean).sort((a, b) => a.localeCompare(b));
50
- }
51
-
52
- export function collectSourceTexts(repoRoot, graph) {
53
- const sources = new Map();
54
- const boundary = createRepoBoundary(repoRoot);
55
- const add = (rel) => {
56
- const file = String(rel || "").replace(/\\/g, "/");
57
- if (!file || sources.has(file)) return;
58
- const resolved = boundary.resolve(file);
59
- if (!resolved.ok) return;
60
- const text = readText(resolved.path);
61
- if (text != null) sources.set(file, text);
62
- };
63
-
64
- for (const n of graph.nodes || []) add(n.source_file);
65
-
66
- for (const file of listRepoFiles(repoRoot)) if (SOURCE_EXT_RE.test(file)) add(file);
67
- return sources;
68
- }
69
-
70
- // Root config files whose TEXT keeps a dependency "mentioned" (dep-check downgrades/skips those).
71
- // package.json is deliberately ABSENT — every declared dep appears there, it would blank all findings;
72
- // its scripts are passed to dep-check separately via pkg.
73
- const CONFIG_FILES = [
74
- "tsconfig.json", "jsconfig.json",
75
- ".eslintrc", ".eslintrc.json", ".eslintrc.js", ".eslintrc.cjs", "eslint.config.js", "eslint.config.mjs",
76
- ".babelrc", "babel.config.js", "babel.config.cjs",
77
- "jest.config.js", "jest.config.ts", "jest.config.cjs", "jest.config.mjs",
78
- "vite.config.js", "vite.config.ts", "vite.config.mjs", "vitest.config.js", "vitest.config.ts",
79
- "webpack.config.js", "rollup.config.js", "esbuild.config.js",
80
- "postcss.config.js", "postcss.config.cjs", "postcss.config.mjs", "postcss.config.ts",
81
- "tailwind.config.js", "tailwind.config.cjs", "tailwind.config.mjs", "tailwind.config.ts",
82
- ".prettierrc", ".prettierrc.json", "prettier.config.js",
83
- "playwright.config.js", "playwright.config.ts", "cypress.config.js", "cypress.config.ts",
84
- "next.config.js", "next.config.mjs", "nuxt.config.ts", "svelte.config.js", "astro.config.mjs",
85
- "angular.json", "nest-cli.json", ".mocharc.json", ".mocharc.yml",
86
- "commitlint.config.js", ".lintstagedrc", ".lintstagedrc.json", "knip.json", ".releaserc",
87
- "electron-builder.yml", "electron-builder.json", "serverless.yml", "Dockerfile", "docker-compose.yml",
88
- // python tool configs (pyproject.toml is deliberately absent — it DECLARES deps, scanning it would blank findings)
89
- "tox.ini", "pytest.ini", "setup.cfg", ".pre-commit-config.yaml", "Makefile", "Procfile",
90
- ];
91
-
92
- export function collectConfigTexts(repoRoot) {
93
- const map = new Map();
94
- const boundary = createRepoBoundary(repoRoot);
95
- const names = new Set(CONFIG_FILES.map((f) => f.toLowerCase()));
96
- for (const f of listRepoFiles(repoRoot)) {
97
- const base = f.slice(f.lastIndexOf("/") + 1).toLowerCase();
98
- if (!names.has(base) && !/^\.github\/workflows\/.*\.ya?ml$/i.test(f)) continue;
99
- const t = readRepoText(boundary, f);
100
- if (t != null) map.set(f, t);
101
- }
102
- return map;
103
- }
104
-
105
- function readJsonc(text) {
106
- if (text == null) return null;
107
- try {
108
- const input = String(text).replace(/^\uFEFF/, "");
109
- let clean = "", inString = false, escaped = false;
110
- for (let i = 0; i < input.length; i++) {
111
- const ch = input[i], next = input[i + 1];
112
- if (inString) {
113
- clean += ch;
114
- if (escaped) escaped = false;
115
- else if (ch === "\\") escaped = true;
116
- else if (ch === '"') inString = false;
117
- continue;
118
- }
119
- if (ch === '"') { inString = true; clean += ch; continue; }
120
- if (ch === "/" && next === "/") {
121
- while (i < input.length && input[i] !== "\n") i++;
122
- clean += "\n";
123
- continue;
124
- }
125
- if (ch === "/" && next === "*") {
126
- i += 2;
127
- while (i < input.length && !(input[i] === "*" && input[i + 1] === "/")) i++;
128
- i++;
129
- continue;
130
- }
131
- clean += ch;
132
- }
133
- clean = clean.replace(/,\s*([}\]])/g, "$1");
134
- return JSON.parse(clean);
135
- } catch { return null; }
136
- }
137
-
138
- const normRoot = (root) => {
139
- const value = String(root || "").replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+|\/+$/g, "");
140
- return value === "." ? "" : value;
141
- };
142
- const inScope = (file, root) => !root || file === root || file.startsWith(`${root}/`);
143
-
144
- function aliasesForScope(repoRoot, root, files, boundary, scopeRoots) {
145
- const ownerOf = (file) => scopeRoots.find((candidate) => inScope(file, candidate)) ?? "";
146
- const configs = files
147
- .filter((f) => ownerOf(f) === root && /(^|\/)(?:tsconfig|jsconfig)(?:\.[^/]+)?\.json$/i.test(f))
148
- .filter((f) => normRoot(dirname(f)) === root)
149
- .sort((a, b) => Number(!/(^|\/)(?:tsconfig|jsconfig)\.json$/i.test(a)) - Number(!/(^|\/)(?:tsconfig|jsconfig)\.json$/i.test(b)) || a.localeCompare(b));
150
- const aliases = new Map();
151
- for (const config of configs) {
152
- const cfg = readJsonc(readRepoText(boundary, config));
153
- const paths = cfg?.compilerOptions?.paths || {};
154
- for (const key of Object.keys(paths)) if (!aliases.has(key)) aliases.set(key, {
155
- key,
156
- prefix: String(key).replace(/\*.*$/, ""),
157
- suffix: String(key).includes("*") ? String(key).slice(String(key).indexOf("*") + 1) : "",
158
- config,
159
- });
160
- }
161
- return [...aliases.values()];
162
- }
163
-
164
- // Every package.json defines a dependency scope. The nearest ancestor manifest owns an import, matching
165
- // npm workspace/package semantics. Aliases are collected from that scope's tsconfig/jsconfig so `@/*`
166
- // remains local rather than becoming a phantom npm package.
167
- export function collectPackageScopes(repoRoot, rootPkg = null) {
168
- const boundary = createRepoBoundary(repoRoot);
169
- const files = listRepoFiles(repoRoot);
170
- const manifests = files.filter((f) => /(^|\/)package\.json$/i.test(f));
171
- if (!manifests.includes("package.json") && rootPkg) manifests.unshift("package.json");
172
- const uniqueManifests = [...new Set(manifests)];
173
- const scopeRoots = uniqueManifests
174
- .map((manifest) => manifest === "package.json" ? "" : normRoot(dirname(manifest)))
175
- .sort((a, b) => b.length - a.length);
176
- const scopes = [];
177
- for (const manifest of uniqueManifests) {
178
- const root = manifest === "package.json" ? "" : normRoot(dirname(manifest));
179
- const pkg = manifest === "package.json" && rootPkg ? rootPkg : readRepoJson(boundary, manifest);
180
- if (!pkg || typeof pkg !== "object") continue;
181
- scopes.push({ root, manifest, pkg, aliases: aliasesForScope(repoRoot, root, files, boundary, scopeRoots) });
182
- }
183
- if (!scopes.some((s) => !s.root)) scopes.push({ root: "", manifest: "package.json", pkg: rootPkg || {}, aliases: aliasesForScope(repoRoot, "", files, boundary, [...scopeRoots, ""]) });
184
- return scopes.sort((a, b) => b.root.length - a.root.length);
185
- }
186
-
187
- // Monorepo-local package names: "packages/*"-style workspace globs → each child's package.json name.
188
- // Those are importable without being declared — never "missing" deps.
189
- export function workspacePkgNames(repoRoot, pkg) {
190
- const names = new Set();
191
- const boundary = createRepoBoundary(repoRoot);
192
- const globs = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces && pkg.workspaces.packages) || [];
193
- for (const g of globs) {
194
- const base = String(g).replace(/\/?\*+.*$/, "");
195
- let dirs = [];
196
- if (/\*/.test(String(g))) {
197
- try {
198
- const resolvedBase = boundary.resolve(base || ".");
199
- if (!resolvedBase.ok) continue;
200
- dirs = readdirSync(resolvedBase.path).map((d) => join(base, d));
201
- } catch { continue; }
202
- }
203
- else dirs = [String(g)];
204
- for (const d of dirs) {
205
- const p = readRepoJson(boundary, join(d, "package.json"));
206
- if (p && p.name) names.add(p.name);
207
- }
208
- }
209
- for (const scope of collectPackageScopes(repoRoot, pkg)) if (scope.pkg?.name) names.add(scope.pkg.name);
210
- return names;
211
- }
212
-
213
- export const TEST_FILE_RE = /(^|[/])(test|tests|__tests__|spec|e2e|__mocks__)([/]|$)|[._-](test|spec)\.[a-z0-9]+$/i;
@@ -1,9 +0,0 @@
1
- // internal-audit.js — façade over the internal analyzers: loads a repo's graph.json + package.json,
2
- // runs dead-check (files) + computeUnusedExports + dep-check, and emits the unified findings envelope
3
- // (DEPS_SECURITY_PLAN.md §2.2-2.3). ALL filesystem access lives here; the analyzers stay pure.
4
- // P2 will add dep-rules (cycles/orphans/boundary); the security/ analyzers join in P4-P5.
5
- // Split: fs collection helpers live in internal-audit.collect.js, reachability in
6
- // internal-audit.reach.js, and the audit runner in internal-audit.run.js — this file
7
- // re-exports the public surface so external import paths keep working unchanged.
8
- export { collectSourceTexts } from "./internal-audit.collect.js";
9
- export { runInternalAudit } from "./internal-audit.run.js";
@@ -1,201 +0,0 @@
1
- // internal-audit.reach.js — entry-point discovery + file-level reachability BFS for the internal
2
- // audit. Split from internal-audit.js.
3
- import { posix } from "node:path";
4
- import { ENTRY_FILE, isFrameworkEntryFile } from "./dead-check.js";
5
- import { TEST_FILE_RE } from "./internal-audit.collect.js";
6
- import { maskJavaNonCode } from "./java-source.js";
7
-
8
- const isFileNode = (n) => !String(n.id).includes("#");
9
-
10
- const springAnnotation = (name) => new RegExp(`@(?:[A-Za-z_$][\\w$]*\\s*\\.\\s*)*${name}\\b`);
11
- const SPRING_CONVENTIONS = [
12
- ["SpringBootApplication", "high", "Spring Boot application entry point is launched externally and starts component scanning"],
13
- ["RestControllerAdvice", "high", "Spring registers @RestControllerAdvice through application-context scanning"],
14
- ["ControllerAdvice", "high", "Spring registers @ControllerAdvice through application-context scanning"],
15
- ["RestController", "high", "Spring registers @RestController through component scanning and routes requests to it"],
16
- ["Controller", "high", "Spring registers @Controller through component scanning"],
17
- ["Configuration", "high", "Spring discovers @Configuration and invokes its bean definitions externally"],
18
- ["Service", "high", "Spring registers @Service through component scanning"],
19
- ["Repository", "high", "Spring registers @Repository through component scanning or repository proxy creation"],
20
- ["Component", "high", "Spring registers @Component through component scanning"],
21
- ["ConfigurationProperties", "high", "Spring binds @ConfigurationProperties outside the static import graph"],
22
- ["KafkaListener", "high", "Spring Kafka invokes @KafkaListener methods from the message container"],
23
- ["Scheduled", "high", "Spring invokes @Scheduled methods from its task scheduler"],
24
- ["EventListener", "high", "Spring invokes @EventListener methods from the application event bus"],
25
- ];
26
-
27
- // Framework-managed Java files are externally entered by the Spring container, not by an ordinary
28
- // source import. Return bounded, explainable evidence so suppressing an orphan is never a silent guess.
29
- export function springConventionEntries(sources, fileSet = null) {
30
- const out = [];
31
- for (const [rawFile, rawText] of sources || []) {
32
- const file = String(rawFile || "").replace(/\\/g, "/");
33
- if (!/\.java$/i.test(file) || (fileSet && !fileSet.has(file))) continue;
34
- const text = maskJavaNonCode(rawText);
35
- let evidence = null;
36
- for (const [marker, confidence, reason] of SPRING_CONVENTIONS) {
37
- if (springAnnotation(marker).test(text)) {
38
- evidence = { file, framework: "spring", marker: `@${marker}`, confidence, reason };
39
- break;
40
- }
41
- }
42
- if (!evidence && /\binterface\s+[A-Za-z_$][\w$]*(?:\s*<[^>{}]+>)?\s+extends\s+[^;{]*(?:JpaRepository|MongoRepository|ReactiveCrudRepository|CrudRepository|PagingAndSortingRepository|Repository)\s*</s.test(text)) {
43
- evidence = {
44
- file,
45
- framework: "spring-data",
46
- marker: "repository interface",
47
- confidence: "high",
48
- reason: "Spring Data creates the repository implementation and proxy from the interface at runtime",
49
- };
50
- }
51
- if (evidence) out.push(evidence);
52
- }
53
- return out.sort((a, b) => a.file.localeCompare(b.file));
54
- }
55
-
56
- // Electron loads preload scripts from BrowserWindow.webPreferences rather than through a normal
57
- // import edge. Require both a conventional preload filename and a bounded `preload:` option that
58
- // names that exact file, so an unrelated helper called preload.js is not silently blessed.
59
- export function electronPreloadEntries(sources, fileSet = null) {
60
- const files = fileSet || new Set((sources || new Map()).keys());
61
- const out = [];
62
- for (const rawFile of files) {
63
- const file = String(rawFile || "").replace(/\\/g, "/");
64
- if (!/(^|\/)preload\.[cm]?[jt]s$/i.test(file)) continue;
65
- const basename = posix.basename(file).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
- const marker = new RegExp(`\\bpreload\\s*:\\s*[\\s\\S]{0,240}?["'\\x60]${basename}["'\\x60]`, "i");
67
- const owner = [...(sources || [])].find(([other, text]) => String(other).replace(/\\/g, "/") !== file && marker.test(String(text || "")));
68
- if (!owner) continue;
69
- out.push({
70
- file,
71
- framework: "electron",
72
- marker: `BrowserWindow preload option in ${String(owner[0]).replace(/\\/g, "/")}`,
73
- confidence: "high",
74
- reason: "Electron loads this exact preload script outside the static import graph",
75
- });
76
- }
77
- return out.sort((a, b) => a.file.localeCompare(b.file));
78
- }
79
-
80
- // Entry set for reachability: conventional entry names + package.json main/module/browser/bin/exports +
81
- // html pages (they root classic-script apps) + test files (the runner enters them) + root config files +
82
- // dynamic-import targets. Anything reachable from here is "used"; the rest corroborates unused-file.
83
- export function entryFiles(graph, pkgOrScopes, dynamicTargets = new Set(), { declaredEntries = [], sources = new Map(), conventionEvidence = [] } = {}) {
84
- const entries = new Set();
85
- const scopes = Array.isArray(pkgOrScopes)
86
- ? pkgOrScopes
87
- : [{ root: "", manifest: "package.json", pkg: pkgOrScopes || {} }];
88
- const fileSet = new Set((graph.nodes || []).filter(isFileNode).map((n) => String(n.source_file || n.id).replace(/\\/g, "/")));
89
- const pe = new Set();
90
- const resolveEntry = (root, raw) => {
91
- let p = String(raw || "").trim().replace(/^['"]|['"]$/g, "").replace(/^file:/, "").replace(/\\/g, "/");
92
- if (!p || p.startsWith("-") || /^https?:/.test(p)) return "";
93
- p = p.replace(/^\.\//, "");
94
- const joined = posix.normalize(root ? posix.join(root, p) : p).replace(/^\.\//, "");
95
- if (fileSet.has(joined)) return joined;
96
- for (const ext of [".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py"]) if (fileSet.has(joined + ext)) return joined + ext;
97
- return joined;
98
- };
99
- for (const scope of scopes) {
100
- const pkg = scope.pkg || {};
101
- const root = String(scope.root || "").replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
102
- const pkgEntries = [];
103
- for (const k of ["main", "module", "browser"]) if (typeof pkg[k] === "string") pkgEntries.push(pkg[k]);
104
- if (pkg.bin) pkgEntries.push(...(typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin)));
105
- (function walkExports(e) {
106
- if (typeof e === "string") pkgEntries.push(e);
107
- else if (e && typeof e === "object") Object.values(e).forEach(walkExports);
108
- })(pkg.exports);
109
- // Script commands are external entry surfaces. Extract only path-shaped source tokens; package names,
110
- // flags and shell operators are intentionally ignored.
111
- for (const script of Object.values(pkg.scripts || {})) {
112
- const re = /(?:^|[\s'"=])((?:\.?\.?\/)?[\w@./-]+\.(?:[cm]?[jt]sx?|py|go))(?=$|[\s'";,)&|])/gi;
113
- let m;
114
- while ((m = re.exec(String(script)))) pkgEntries.push(m[1]);
115
- const runner = /\b(?:node|bun|deno|tsx|ts-node|python\d*|electron)\s+(?!-)([\w@./\\-]+)/gi;
116
- while ((m = runner.exec(String(script)))) if (/[./\\]/.test(m[1])) pkgEntries.push(m[1]);
117
- }
118
- for (const p of pkgEntries) pe.add(resolveEntry(root, p));
119
- }
120
- for (const n of graph.nodes || []) {
121
- if (!isFileNode(n)) continue;
122
- const f = n.source_file;
123
- if (ENTRY_FILE.test(f) || isFrameworkEntryFile(f) || /\.d\.[cm]?ts$/i.test(f) || TEST_FILE_RE.test(f) || /\.html?$/i.test(f) || pe.has(f) || /(^|\/)[^/]*\.config\.[a-z]+$/i.test(f)) entries.add(f);
124
- }
125
- // Classic/static HTML pages load scripts, styles and other assets without a
126
- // JavaScript import edge. Treat an exact local src/href target as an entry
127
- // surface so a deployed asset is not mislabeled orphan/dead.
128
- for (const [rawFile, rawText] of sources || []) {
129
- const htmlFile = String(rawFile || "").replace(/\\/g, "/");
130
- if (!/\.html?$/i.test(htmlFile)) continue;
131
- const htmlDir = posix.dirname(htmlFile);
132
- const attr = /\b(?:src|href)\s*=\s*["']([^"']+)["']/gi;
133
- let match;
134
- while ((match = attr.exec(String(rawText || "")))) {
135
- const rawTarget = String(match[1] || "").trim().split(/[?#]/, 1)[0];
136
- if (!rawTarget || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(rawTarget)) continue;
137
- const relative = rawTarget.replace(/^\/+/, "");
138
- const candidates = rawTarget.startsWith("/")
139
- ? [posix.normalize(posix.join(htmlDir, relative)), posix.normalize(relative)]
140
- : [posix.normalize(posix.join(htmlDir, relative))];
141
- const target = candidates.find((candidate) => fileSet.has(candidate));
142
- if (target) entries.add(target);
143
- }
144
- }
145
- // Drizzle Kit loads schema modules from configuration strings rather than a
146
- // runtime import. Resolve the bounded `schema:` value so the schema and its
147
- // exported tables are not reported as orphan/test-only production code.
148
- for (const [rawFile, rawText] of sources || []) {
149
- const configFile = String(rawFile || "").replace(/\\/g, "/");
150
- if (!/(^|\/)drizzle(?:\.[^/]*)?\.config\.[cm]?[jt]s$/i.test(configFile)) continue;
151
- const value = /\bschema\s*:\s*(\[[\s\S]{0,1000}?\]|["'][^"']+["'])/i.exec(String(rawText || ""))?.[1] || "";
152
- const quoted = /["']([^"']+)["']/g;
153
- let match;
154
- while ((match = quoted.exec(value))) {
155
- const candidate = posix.normalize(posix.join(posix.dirname(configFile), match[1].replace(/^\.\//, "")));
156
- if (fileSet.has(candidate)) entries.add(candidate);
157
- }
158
- }
159
- for (const evidence of springConventionEntries(sources, fileSet)) {
160
- entries.add(evidence.file);
161
- conventionEvidence.push(evidence);
162
- }
163
- for (const evidence of electronPreloadEntries(sources, fileSet)) {
164
- entries.add(evidence.file);
165
- conventionEvidence.push(evidence);
166
- }
167
- for (const raw of Array.isArray(declaredEntries) ? declaredEntries : [declaredEntries]) {
168
- const resolved = resolveEntry("", raw);
169
- if (resolved && fileSet.has(resolved)) entries.add(resolved);
170
- }
171
- // Bundled helper programs are often launched by filename (`resolveResource("worker.py")`) rather than
172
- // imported. A quoted basename reference from another source file is enough to establish that a code file
173
- // under resources/ is a runtime entry, without treating arbitrary prose/config files as roots.
174
- for (const file of fileSet) {
175
- if (!/(^|\/)resources\/.*\.(?:py|[cm]?[jt]s)$/i.test(file)) continue;
176
- const base = posix.basename(file).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
177
- const quoted = new RegExp(`["'\x60]${base}["'\x60]`);
178
- if ([...sources].some(([other, text]) => other !== file && quoted.test(String(text || "")))) entries.add(file);
179
- }
180
- for (const t of dynamicTargets) entries.add(t);
181
- return entries;
182
- }
183
-
184
- // File-level BFS over every non-contains link (symbol endpoints collapse to their file via the id prefix).
185
- export function computeReachability(graph, entries) {
186
- const fileOf = (v) => { const s = String(v && typeof v === "object" ? v.id : v); const h = s.indexOf("#"); return h < 0 ? s : s.slice(0, h); };
187
- const adj = new Map();
188
- for (const l of graph.links || []) {
189
- if (l.relation === "contains") continue;
190
- const a = fileOf(l.source), b = fileOf(l.target);
191
- if (!a || !b || a === b) continue;
192
- (adj.get(a) || adj.set(a, new Set()).get(a)).add(b);
193
- }
194
- const reached = new Set(entries);
195
- const queue = [...entries];
196
- while (queue.length) {
197
- const cur = queue.pop();
198
- for (const nxt of adj.get(cur) || []) if (!reached.has(nxt)) { reached.add(nxt); queue.push(nxt); }
199
- }
200
- return reached;
201
- }