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,71 +0,0 @@
1
- import {rawGraph} from '../graph-context.mjs'
2
- import {analyzeEndpointInventory} from '../../analysis/endpoints.js'
3
- import {PATH_CLASS_NAMES, createPathClassifier, hasPathClass} from '../../path-classification.js'
4
- import {toolResult} from '../tool-result.mjs'
5
-
6
- export function tListEndpoints(g, args, ctx) {
7
- if (!ctx.repoRoot) return 'Endpoint detection needs the repo root (not provided to this server).'
8
- const graph = rawGraph(ctx)
9
- const codeFiles = [...new Set(
10
- (graph.nodes || [])
11
- .filter((n) => !String(n.id).includes('#') && n.source_file && n.file_type === 'code')
12
- .map((n) => n.source_file)
13
- )]
14
- const inventory = analyzeEndpointInventory(ctx.repoRoot, codeFiles)
15
- let eps = inventory.endpoints
16
- const method = args.method ? String(args.method).toUpperCase() : null
17
- const path = args.path ? String(args.path) : null
18
- if (method) eps = eps.filter((endpoint) => endpoint.method === method)
19
- if (path) eps = eps.filter((endpoint) => endpoint.path === path || endpoint.path.endsWith(path))
20
- // Production-first: classified endpoints are suppressed by default; a tests-only graph would
21
- // suppress everything, so that build mode auto-includes them (same precedent as module_map).
22
- const includeClassified = args.include_classified === true || graph.graphBuildMode === 'tests-only'
23
- const classifier = createPathClassifier(ctx.repoRoot)
24
- const byFile = new Map()
25
- const classesOf = (file) => {
26
- const key = String(file || '')
27
- if (!byFile.has(key)) {
28
- const info = classifier.explain(key, {content: ''})
29
- byFile.set(key, {classified: info.excluded || hasPathClass(info, ...PATH_CLASS_NAMES), pathClasses: info.classes})
30
- }
31
- return byFile.get(key)
32
- }
33
- const production = eps.filter((endpoint) => !classesOf(endpoint.file).classified)
34
- const classified = eps.filter((endpoint) => classesOf(endpoint.file).classified)
35
- const suppressed = includeClassified ? 0 : classified.length
36
- eps = includeClassified ? [...production, ...classified] : production
37
- const suppressionNote = suppressed
38
- ? `${suppressed} endpoint(s) in classified test/e2e/generated/vendored/mock/story/docs/benchmark/temp or explicitly excluded paths were suppressed; pass include_classified:true to inspect them.`
39
- : ''
40
- if (!eps.length) return suppressed
41
- ? `No production HTTP endpoints detected; ${suppressionNote}`
42
- : 'No HTTP endpoints detected in the indexed code files.'
43
- const max = Math.max(1, Math.min(300, Number(args.max_results) || 100))
44
- const shown = eps.slice(0, max)
45
- const stats = inventory.stats
46
- const text = [
47
- `${eps.length} endpoint(s) matched${eps.length > shown.length ? `, showing ${shown.length}` : ''}. Inventory: ${stats.declaredRoutes} declaration(s); ${stats.reachableStaticRoutes} statically reachable composed route(s); ${stats.localDeclarations} local/root declaration candidate(s); ${stats.staticMounts} static router mount(s)${stats.truncated ? `; TRUNCATED at ${stats.maxEndpoints}` : ''}.${suppressed ? ` ${suppressionNote}` : ''}`,
48
- ...shown.map((e) => {
49
- const via = e.mountChain?.length
50
- ? `\n declared ${e.declaredPath} in ${e.file}${e.line ? `:${e.line}` : ''}; mount chain ${e.mountChain.map((mount) => `${mount.file}:${mount.line} ${mount.path}`).join(' → ')}`
51
- : ''
52
- const activation = e.conditional
53
- ? `; conditional default ${e.defaultActive === false ? 'inactive' : e.defaultActive === true ? 'active' : 'unknown'}`
54
- : ''
55
- const info = classesOf(e.file)
56
- const tag = info.classified ? ` [classified${info.pathClasses.length ? `:${info.pathClasses.join('+')}` : ''}]` : ''
57
- return ` ${e.method.toUpperCase().padEnd(6)} ${e.path}${e.handler ? ` → ${e.handler}` : ''} (${e.file}${e.line ? `:${e.line}` : ''}; ${e.mountState}/${e.confidence}${activation})${tag}${via}`
58
- }),
59
- ].join('\n')
60
- return toolResult(text, {
61
- filters: {method, path},
62
- stats,
63
- pathPolicy: includeClassified ? 'all' : 'production-first',
64
- suppressed,
65
- endpoints: shown.map((e) => {
66
- const info = classesOf(e.file)
67
- return info.classified ? {...e, classified: true, pathClasses: info.pathClasses} : e
68
- }),
69
- page: {shown: shown.length, total: eps.length, truncated: eps.length > shown.length || stats.truncated},
70
- }, {completeness: {status: stats.truncated ? 'PARTIAL' : 'COMPLETE', reason: stats.truncated ? `endpoint cap ${stats.maxEndpoints} reached` : 'all indexed code files scanned'}})
71
- }
@@ -1,220 +0,0 @@
1
- import {degreeOf, rawGraph} from '../graph-context.mjs'
2
- import {summarizeCommunities, aggregateGraph} from '../../analysis/graph-analysis.js'
3
- import {computeStaticTestReachability} from '../../analysis/static-test-reachability.js'
4
- import {computeHotPathReview} from '../../analysis/hot-path-review.js'
5
- import {createPathClassifier, hasPathClass} from '../../path-classification.js'
6
- import {toolResult} from '../tool-result.mjs'
7
-
8
- export function tListCommunities(g, args, ctx) {
9
- const max = Math.max(1, Math.min(100, Number(args.top_n) || 20))
10
- const list = summarizeCommunities(ctx.graphPath, max)
11
- if (!list.length) return 'No communities found in the graph.'
12
- return [
13
- `Communities, largest first (list position = community_id for get_community):`,
14
- ...list.map((c, i) => `${String(i).padStart(3)}. ${c.name} — ${c.size} nodes (raw id ${c.id}; e.g. ${[...new Set(c.files)].join(', ')})`),
15
- ].join('\n')
16
- }
17
-
18
- // Folder-level architecture map: modules (top-two path segments) with file/symbol counts and the
19
- // strongest module→module dependencies. Pure graph aggregation — no filesystem reads.
20
- export function tModuleMap(g, args, ctx) {
21
- const graph = rawGraph(ctx)
22
- const testsOnly = graph.graphBuildMode === 'tests-only'
23
- const includeNonProduct = args.include_non_product === true || testsOnly
24
- const classifier = createPathClassifier(ctx?.repoRoot || null)
25
- const nonProductFiles = new Set()
26
- const classifiedFiles = new Set()
27
- if (!includeNonProduct) {
28
- for (const node of graph.nodes || []) {
29
- if (!node?.source_file) continue
30
- const sourceFile = String(node.source_file)
31
- if (classifiedFiles.has(sourceFile)) continue
32
- classifiedFiles.add(sourceFile)
33
- const explanation = classifier.explain(sourceFile)
34
- if (explanation.excluded || hasPathClass(explanation, 'test', 'e2e', 'generated', 'vendored', 'mock', 'story', 'docs', 'benchmark', 'temp')) {
35
- nonProductFiles.add(sourceFile)
36
- }
37
- }
38
- }
39
- const visibleGraph = includeNonProduct || nonProductFiles.size === 0 ? graph : (() => {
40
- const keep = new Set((graph.nodes || [])
41
- .filter((node) => !node?.source_file || !nonProductFiles.has(String(node.source_file)))
42
- .map((node) => String(node.id)))
43
- const endpoint = (value) => String(value && typeof value === 'object' ? value.id : value)
44
- return {
45
- ...graph,
46
- nodes: (graph.nodes || []).filter((node) => keep.has(String(node.id))),
47
- links: (graph.links || []).filter((link) => keep.has(endpoint(link.source)) && keep.has(endpoint(link.target))),
48
- }
49
- })()
50
- const agg = aggregateGraph(visibleGraph, null)
51
- const topN = Math.max(1, Math.min(60, Number(args.top_n) || 25))
52
- const mods = agg.modules.slice(0, topN)
53
- const edges = agg.moduleEdges.slice(0, Math.min(50, topN * 2))
54
- const compileEdges = new Map()
55
- const collectCompileEdges = (list, kind) => {
56
- for (const edge of list || []) {
57
- const key = `${edge.from}\0${edge.to}`
58
- const current = compileEdges.get(key) || {from: edge.from, to: edge.to, count: 0, typeOnly: 0, compileOnly: 0}
59
- current.count += edge.count
60
- current[kind] += edge.count
61
- compileEdges.set(key, current)
62
- }
63
- }
64
- collectCompileEdges(agg.typeOnlyModuleEdges, 'typeOnly')
65
- collectCompileEdges(agg.compileOnlyModuleEdges, 'compileOnly')
66
- const compiled = [...compileEdges.values()].sort((a, b) => b.count - a.count).slice(0, Math.min(50, topN * 2))
67
- return [
68
- testsOnly
69
- ? 'Scope: tests-only graph; classified test/e2e/fixture surfaces are retained automatically.'
70
- : includeNonProduct
71
- ? 'Scope: all indexed files, including classified non-product surfaces.'
72
- : `Scope: production-only (default); excluded ${nonProductFiles.size} classified test/fixture/benchmark/generated/docs file(s). Pass include_non_product:true for the complete graph.`,
73
- `Module map: ${agg.totals.files} files in ${agg.modules.length} folder-modules, ${agg.totals.moduleEdges} runtime module dependencies and ${agg.totals.compileTimeModuleEdges || 0} compile-time dependencies (${agg.totals.typeOnlyModuleEdges || 0} type-only, ${agg.totals.compileOnlyModuleEdges || 0} compile-only). Top ${mods.length}:`,
74
- ...mods.map((m) => ` ${m.name} — ${m.fileCount} files, ${m.symbolCount} symbols`),
75
- ``,
76
- `Strongest runtime module dependencies:`,
77
- ...edges.map((e) => ` ${e.from} → ${e.to} (${e.count})`),
78
- compiled.length ? `` : null,
79
- compiled.length ? `Compile-time module dependencies (not runtime coupling):` : null,
80
- ...compiled.map((e) => ` ${e.from} → ${e.to} (${e.count}; ${e.typeOnly} type-only, ${e.compileOnly} compile-only)`),
81
- ].filter((line) => line != null).join('\n')
82
- }
83
-
84
- // Parser-backed local cost review. This keeps syntax, graph coupling and measured/static test
85
- // evidence as separate fields so callers cannot mistake a ranking heuristic for profiler output.
86
- export function tHotPathReview(g, args, ctx) {
87
- const review = computeHotPathReview(rawGraph(ctx), {
88
- repoRoot: ctx?.repoRoot || null,
89
- path: args.path,
90
- includeTests: args.include_tests === true,
91
- includeClassified: args.include_classified === true,
92
- topN: args.top_n,
93
- cyclomaticThreshold: args.cyclomatic_threshold,
94
- callThreshold: args.call_threshold,
95
- loopDepthThreshold: args.loop_depth_threshold,
96
- timeRankThreshold: args.time_rank_threshold,
97
- minScore: args.min_score,
98
- })
99
- if (!review.ok) return toolResult(`Hot-path review refused: ${review.error}.`, review)
100
- const pct = (value) => typeof value === 'number' ? `${Math.round(value * 100)}%` : String(value || 'NOT_AVAILABLE')
101
- const coverageLine = review.coverage.actualCoverage === 'AVAILABLE'
102
- ? `Measured coverage: ${review.coverage.measuredFiles} file(s) from ${review.coverage.sources.join(', ') || 'coverage report'}.`
103
- : review.coverage.staticReachability
104
- ? `actualCoverage: NOT_AVAILABLE; static test reachability ${review.coverage.staticReachability.reachableFiles}/${review.coverage.staticReachability.productFiles} product file(s).`
105
- : 'actualCoverage: NOT_AVAILABLE; no measured or static test evidence was available.'
106
- const text = [
107
- `Local hot-path review: ${review.candidateSymbols} candidate(s) from ${review.analyzedSymbols} analyzed symbol(s); showing ${review.hotspots.length}.`,
108
- `Thresholds: time rank >=${review.thresholds.timeRank}, cyclomatic >=${review.thresholds.cyclomatic}, calls >=${review.thresholds.calls}, loop depth >=${review.thresholds.loopDepth}, score >=${review.thresholds.minScore}.`,
109
- `Selection: ${review.selectionPolicy.mode}${review.selectionPolicy.strongLocalFallback ? '; strong local sort/recursion/deep-loop evidence can pass below the blended score gate' : '; strict explicit score gate'}.`,
110
- coverageLine,
111
- 'Local syntax cost and graph coupling are separate. Scores are review priority, not measured runtime.',
112
- '',
113
- ...(review.hotspots.length ? review.hotspots.flatMap((item, index) => {
114
- const tests = item.testEvidence.actualCoverage === 'NOT_AVAILABLE'
115
- ? item.testEvidence.staticReachable ? `static-test d${item.testEvidence.distance}` : 'no-static-test-path'
116
- : `coverage ${pct(item.testEvidence.actualCoverage)}`
117
- const pointer = `${item.file}${item.startLine ? `:${item.startLine}${item.endLine > item.startLine ? `-${item.endLine}` : ''}` : ''}`
118
- const evidence = item.sourceEvidence.length
119
- ? `\n evidence: ${item.sourceEvidence.map((entry) => `${entry.kind}@L${entry.line || '?'}${entry.detail ? ` (${entry.detail})` : ''}`).join('; ')}`
120
- : ''
121
- return [
122
- ` ${String(index + 1).padStart(2)}. score ${String(item.score).padStart(5)} syntax ${String(item.localSyntax.score).padStart(5)} graph ${String(item.graphRisk.score).padStart(5)} ${item.confidence}`,
123
- ` ${item.label} (${pointer}; fan-in ${item.graphRisk.fanIn}, fan-out ${item.graphRisk.fanOut}; ${tests})`,
124
- ` ${item.reasons.slice(0, 5).join('; ')}${evidence}`,
125
- ]
126
- }) : [' (none at the selected thresholds)']),
127
- review.bounds.truncated ? `... +${review.bounds.totalCandidates - review.bounds.returned} more (raise top_n to display more, raise min_score or narrow path to tighten; lower min_score to broaden).` : null,
128
- '',
129
- 'Caveat: no interprocedural Big-O, recursion-bound, CFG, dead-store or taint-flow claim is made.',
130
- ].filter((line) => line != null).join('\n')
131
- return toolResult(text, review, {
132
- completeness: {
133
- symbols: 'COMPLETE_FOR_INDEXED_GRAPH',
134
- output: review.bounds.truncated ? 'BOUNDED' : 'COMPLETE',
135
- coverage: review.coverage.actualCoverage,
136
- },
137
- })
138
- }
139
-
140
- // Coverage × graph: map an EXISTING coverage report (istanbul/lcov/coverage.py/Go — read offline,
141
- // tests are never executed here) onto files and symbols, then rank refactor risk as
142
- // connectivity × uncovered share. Pairs with get_dependents: many dependents + low coverage ⇒ write
143
- // tests before changing. Coverage pcts in this layer are fractions (0..1).
144
- export function tCoverageMap(g, args, ctx) {
145
- if (!ctx.repoRoot) return 'Coverage mapping needs the repo root (not provided to this server).'
146
- const agg = aggregateGraph(rawGraph(ctx), ctx.repoRoot)
147
- const pathFilter = args.path ? String(args.path).replace(/\\/g, '/').replace(/\/+$/, '') : null
148
- const inScope = (p) => !pathFilter || p === pathFilter || String(p).startsWith(`${pathFilter}/`)
149
- const allFiles = agg.modules.flatMap((m) => m.files.filter((f) => inScope(f.path)))
150
- const measured = allFiles.filter((f) => f.coverage != null)
151
- if (!measured.length) {
152
- const fallback = computeStaticTestReachability(rawGraph(ctx), {repoRoot: ctx.repoRoot, path: pathFilter || ''})
153
- const topN = Math.max(1, Math.min(50, Number(args.top_n) || 15))
154
- const reachable = fallback.reachable.slice(0, topN)
155
- const unreachable = fallback.unreachable.slice(0, topN)
156
- return [
157
- `Static test reachability${pathFilter ? ` for ${pathFilter}` : ''}: ${fallback.reachableFiles}/${fallback.productFiles} product file(s) have a runtime graph path from ${fallback.testFiles} indexed test file(s).`,
158
- `actualCoverage: ${fallback.actualCoverage}. This is NOT coverage: imports/calls only show that a test can statically reach a file, never that a line, branch or symbol executed.`,
159
- fallback.bounds.truncated ? `Traversal was bounded/truncated (${fallback.bounds.traversedStates}/${fallback.bounds.maxStates} states, depth ≤${fallback.bounds.maxDepth}, ${fallback.testFiles}/${fallback.totalTestFiles} test files).` : `Traversal: ${fallback.bounds.traversedStates} bounded state(s), depth ≤${fallback.bounds.maxDepth}.`,
160
- '',
161
- 'Nearest runtime paths from tests:',
162
- ...(reachable.length ? reachable.map((entry) => {
163
- const nearest = entry.nearestTests[0]
164
- return ` ${nearest.confidence.padStart(6)} d${nearest.distance} ${entry.file} ← ${nearest.test}\n path: ${nearest.path.join(' → ')}`
165
- }) : [' (none)']),
166
- '',
167
- `No runtime path from an indexed test (${fallback.unreachableFiles}; not proof of no tests):`,
168
- ...(unreachable.length ? unreachable.map((file) => ` ${file}`) : [' (none)']),
169
- fallback.unreachableFiles > unreachable.length ? ` … +${fallback.unreachableFiles - unreachable.length} more (raise top_n or narrow path)` : null,
170
- '',
171
- 'No coverage report found — generate one for measured coverage:',
172
- 'Generate one with the repo\'s own test runner, then call coverage_map again:',
173
- ' JS/TS: npx vitest run --coverage (or jest --coverage)',
174
- ' Python: pytest --cov --cov-report=json',
175
- ' Go: go test ./... -coverprofile=coverage.out',
176
- ' Rust: cargo tarpaulin --out Json --output-dir .',
177
- ' or cargo llvm-cov --lcov --output-path lcov.info',
178
- 'Read locations: coverage/coverage-summary.json, coverage/coverage-final.json, (coverage/)lcov.info, coverage.json, tarpaulin-report.json, coverage.out.',
179
- ].filter((line) => line != null).join('\n')
180
- }
181
- const pctStr = (v) => (v == null ? 'n/a' : `${Math.round(v * 100)}%`)
182
- const sources = [...new Set(measured.map((f) => f.coverageSource).filter(Boolean))]
183
- const avg = measured.reduce((s, f) => s + f.coverage, 0) / measured.length
184
- const rollup = agg.modules
185
- .map((m) => {
186
- const withCov = m.files.filter((f) => f.coverage != null && inScope(f.path))
187
- if (!withCov.length) return null
188
- return {
189
- name: m.name,
190
- measured: withCov.length,
191
- total: m.files.filter((f) => inScope(f.path)).length,
192
- avg: withCov.reduce((s, f) => s + f.coverage, 0) / withCov.length,
193
- }
194
- })
195
- .filter(Boolean)
196
- .sort((a, b) => a.avg - b.avg)
197
- const topN = Math.max(1, Math.min(50, Number(args.top_n) || 15))
198
- // risk = graph degree × uncovered share; only symbols below 80% matter
199
- const risky = agg.symbols
200
- .filter((s) => s.coverage != null && s.coverage < 0.8 && inScope(s.file))
201
- .map((s) => ({...s, degree: degreeOf(g, s.id)}))
202
- .filter((s) => s.degree > 0)
203
- .sort((a, b) => b.degree * (1 - b.coverage) - a.degree * (1 - a.coverage))
204
- .slice(0, topN)
205
- return [
206
- `Coverage map (${measured.length}/${allFiles.length} files measured, avg ${pctStr(avg)}; report: ${sources.join(', ') || 'unknown'}${pathFilter ? `; filter ${pathFilter}` : ''}).`,
207
- ``,
208
- `Modules by average coverage (worst first):`,
209
- ...rollup.slice(0, 20).map((m) => ` ${pctStr(m.avg).padStart(5)} ${m.name} (${m.measured}/${m.total} files measured)`),
210
- ``,
211
- `Refactor-risk hotspots — connected symbols with low coverage (ranked by degree × uncovered):`,
212
- ...(risky.length
213
- ? risky.map((s) => ` ${pctStr(s.coverage).padStart(5)} deg ${String(s.degree).padStart(3)} ${s.label} (${s.file}${s.line ? `:${s.line}` : ''})`)
214
- : [' (none — every connected symbol is ≥80% covered or unmeasured)']),
215
- ``,
216
- `Tip: before refactoring a hotspot, run get_dependents on it — low coverage × many dependents means write tests first.`,
217
- ].join('\n')
218
- }
219
-
220
- // HTTP endpoint inventory: Express/Fastify/Nest/Flask/FastAPI/Go/Rust/Spring route definitions.
@@ -1,31 +0,0 @@
1
- import {readFileSync} from 'node:fs'
2
- import process from 'node:process'
3
-
4
- const STALE_RUNTIME_OVERRIDE_ENV = 'WEAVATRIX_ALLOW_STALE_RUNTIME'
5
-
6
- export function runtimeVersionStatus({runningVersion, packageJsonPath, allowStale} = {}) {
7
- let diskVersion = null, packageVersionError = null
8
- try {
9
- const parsed = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
10
- diskVersion = typeof parsed?.version === 'string' && parsed.version.trim() ? parsed.version.trim() : null
11
- if (!diskVersion) packageVersionError = 'package.json has no valid version'
12
- } catch (error) {
13
- packageVersionError = `package.json is unreadable: ${error.message}`
14
- }
15
- const staleRuntime = diskVersion !== String(runningVersion || '')
16
- const staleRuntimeAllowed = allowStale == null
17
- ? process.env[STALE_RUNTIME_OVERRIDE_ENV] === '1'
18
- : allowStale === true
19
- return {
20
- version: String(runningVersion || ''),
21
- diskVersion,
22
- staleRuntime,
23
- staleRuntimeAllowed,
24
- ...(packageVersionError ? {packageVersionError} : {}),
25
- }
26
- }
27
-
28
- export function staleRuntimeMessage(status) {
29
- const disk = status.diskVersion || 'unavailable'
30
- return `STALE_RUNTIME: running Weavatrix ${status.version || 'unknown'} but package.json on disk is ${disk}. Restart/reconnect the MCP server before using tools. For deliberate source-development only, set ${STALE_RUNTIME_OVERRIDE_ENV}=1.`
31
- }
@@ -1,66 +0,0 @@
1
- import {dirname} from 'node:path'
2
- import {buildGraphForRepo, defaultPrecisionMode} from '../../build-graph.js'
3
- import {persistedFreshnessMatches, repositoryFreshnessProbe} from '../../graph/freshness-probe.js'
4
- import {PRECISION_OVERLAY_V, precisionSemanticInputsMatch, readPrecisionOverlay} from '../../precision/lsp-overlay.js'
5
- import {loadGraph} from '../graph-context.mjs'
6
-
7
- export function createAutoRefresh(getApi) {
8
- const probeCache = new Map()
9
- const configured = process.env.WEAVATRIX_AUTO_REFRESH_DEBOUNCE_MS == null
10
- ? 2_000 : Number(process.env.WEAVATRIX_AUTO_REFRESH_DEBOUNCE_MS)
11
- const debounceMs = Math.max(0, Math.min(5_000, Number.isFinite(configured) ? configured : 2_000))
12
- return async function autoRefresh(callCtx, currentGraph) {
13
- if (!callCtx?.repoRoot || !callCtx?.graphPath) return {graph: null, refresh: null}
14
- const activePrecision = currentGraph?.graphPrecisionMode || defaultPrecisionMode()
15
- const probeKey = `${callCtx.graphPath}\0${currentGraph?.graphBuildMode || 'full'}\0${activePrecision}`
16
- let semanticInputsChanged = false
17
- if (activePrecision === 'lsp' && currentGraph) {
18
- try {
19
- const overlay = readPrecisionOverlay(callCtx.graphPath, currentGraph)
20
- semanticInputsChanged = typeof overlay?.semanticInputFingerprint === 'string'
21
- && !precisionSemanticInputsMatch(overlay, callCtx.repoRoot, currentGraph)
22
- } catch {
23
- semanticInputsChanged = true
24
- }
25
- }
26
- const cached = probeCache.get(probeKey)
27
- if (!semanticInputsChanged && currentGraph && cached && Date.now() - cached.checkedAt < debounceMs) {
28
- return {graph: currentGraph, refresh: {kind: 'none', revision: currentGraph.graphRevision || null, changedFiles: 0}}
29
- }
30
- const beforeProbe = repositoryFreshnessProbe(callCtx.repoRoot)
31
- const precisionMissing = activePrecision === 'lsp' && (
32
- Number(currentGraph?.precisionOverlayV) !== PRECISION_OVERLAY_V || semanticInputsChanged
33
- )
34
- if (!precisionMissing && beforeProbe && currentGraph && (
35
- cached?.probe === beforeProbe
36
- || persistedFreshnessMatches(currentGraph, beforeProbe, currentGraph.graphBuildMode || 'full')
37
- )) {
38
- probeCache.set(probeKey, {probe: beforeProbe, checkedAt: Date.now()})
39
- return {graph: currentGraph, refresh: {kind: 'none', revision: currentGraph.graphRevision || null, changedFiles: 0}}
40
- }
41
- const result = await buildGraphForRepo(callCtx.repoRoot, {
42
- mode: currentGraph?.graphBuildMode || 'full',
43
- precision: activePrecision,
44
- scope: '',
45
- outDir: dirname(callCtx.graphPath),
46
- })
47
- if (!result.ok) throw new Error(result.error || 'automatic graph refresh failed')
48
- getApi().resetStalenessCache()
49
- const fresh = loadGraph(callCtx.graphPath, {repoRoot: callCtx.repoRoot})
50
- const afterProbe = repositoryFreshnessProbe(callCtx.repoRoot)
51
- if (afterProbe && afterProbe === beforeProbe) probeCache.set(probeKey, {probe: afterProbe, checkedAt: Date.now()})
52
- else probeCache.delete(probeKey)
53
- const update = result.refresh || {kind: 'full', changedFiles: [], reason: 'automatic-refresh'}
54
- return {
55
- graph: fresh,
56
- refresh: {
57
- kind: update.kind,
58
- revision: update.revision || fresh.graphRevision || null,
59
- changedFiles: Array.isArray(update.changedFiles) ? update.changedFiles.length : 0,
60
- notice: update.kind === 'none'
61
- ? undefined
62
- : `Graph ${update.kind === 'incremental' ? 'incrementally refreshed' : 'rebuilt'} before this answer (${update.reason || 'repository changed'}).`,
63
- },
64
- }
65
- }
66
- }
@@ -1,43 +0,0 @@
1
- import {createRequire} from 'node:module'
2
- import {existsSync, realpathSync, statSync} from 'node:fs'
3
- import {dirname, join} from 'node:path'
4
- import {fileURLToPath} from 'node:url'
5
- import {graphOutDirForRepo} from '../../graph/layout.js'
6
-
7
- const SOURCE_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
8
- const MCP_DIR = join(SOURCE_DIR, 'mcp')
9
- const CATALOG_URL = new URL('../catalog.mjs', import.meta.url)
10
-
11
- export const PACKAGE_JSON_PATH = join(SOURCE_DIR, '..', 'package.json')
12
- export const PACKAGE_VERSION = (() => {
13
- try { return createRequire(import.meta.url)('../../../package.json').version } catch { return '0.0.0' }
14
- })()
15
- export const SERVER_INFO = {name: 'weavatrix', version: PACKAGE_VERSION}
16
-
17
- export const loadServerCatalog = (version = 0) => import(version ? `${CATALOG_URL.href}?v=${version}` : CATALOG_URL.href)
18
-
19
- export function hotCatalogVersion(hotFiles) {
20
- let version = 0
21
- for (const file of hotFiles) {
22
- try {
23
- const modified = statSync(join(MCP_DIR, file)).mtimeMs
24
- if (modified > version) version = modified
25
- } catch { /* a missing file does not bump the version */ }
26
- }
27
- return version
28
- }
29
-
30
- export function resolveServerTarget(argv, log = () => {}) {
31
- let graphPath = argv[2], repoArg = argv[3], capabilities = argv[4]
32
- try {
33
- if (graphPath && statSync(graphPath).isDirectory()) {
34
- repoArg = realpathSync.native(graphPath)
35
- capabilities = argv[3]
36
- graphPath = join(graphOutDirForRepo(repoArg), 'graph.json')
37
- if (!existsSync(graphPath)) log(`no graph built yet for ${repoArg} — ask the agent to call rebuild_graph; it builds into the standard weavatrix-graphs layout`)
38
- }
39
- } catch { /* argv[2] is a graph path or unavailable */ }
40
- let repoRoot = null
41
- try { if (repoArg && statSync(repoArg).isDirectory()) repoRoot = realpathSync.native(repoArg) } catch { /* invalid repo root */ }
42
- return {graphPath, repoRoot, capabilities}
43
- }
@@ -1,40 +0,0 @@
1
- import process from 'node:process'
2
- import {
3
- activeLspClientCount,
4
- beginLspClientShutdown,
5
- shutdownActiveLspClients,
6
- } from '../../precision/lsp-client.js'
7
-
8
- async function settleWithin(promise, timeoutMs) {
9
- let timer
10
- const settled = await Promise.race([
11
- Promise.resolve(promise).then(() => true, () => true),
12
- new Promise((resolve) => { timer = setTimeout(() => resolve(false), timeoutMs) }),
13
- ])
14
- if (timer) clearTimeout(timer)
15
- return settled
16
- }
17
-
18
- export function createShutdownController({log, targetMutation}) {
19
- let shuttingDown = false, shutdownPromise = null
20
- const request = (reason, exitCode = 0) => {
21
- if (shutdownPromise) return shutdownPromise
22
- shuttingDown = true
23
- beginLspClientShutdown()
24
- process.stdin.pause()
25
- const activeAtStart = activeLspClientCount()
26
- log(`shutdown requested (${reason}); draining graph work and ${activeAtStart} semantic provider(s)`)
27
- shutdownPromise = (async () => {
28
- const initiallyDrained = await settleWithin(targetMutation(), 2_500)
29
- const semantic = await shutdownActiveLspClients({timeoutMs: 3_000})
30
- const fullyDrained = initiallyDrained || await settleWithin(targetMutation(), 1_500)
31
- log(`shutdown cleanup: graph=${fullyDrained ? 'drained' : 'bounded-timeout'}, semantic=${semantic.requested} requested/${semantic.remaining} remaining${semantic.timedOut ? ' (forced)' : ''}`)
32
- })().catch((error) => {
33
- log(`shutdown cleanup failed: ${error.stack || error.message}`)
34
- }).finally(() => {
35
- process.exit(exitCode)
36
- })
37
- return shutdownPromise
38
- }
39
- return {isShuttingDown: () => shuttingDown, request}
40
- }
@@ -1,20 +0,0 @@
1
- // Staleness is important, but repeating an identical paragraph after every graph call drowns the
2
- // actual answer. Surface a changed condition immediately, then remind periodically. graph_stats can
3
- // force the notice because freshness is the purpose of that tool.
4
- export function createStalenessNoticeGate(cooldownMs = 5 * 60_000) {
5
- let lastKey = ''
6
- let lastShownAt = 0
7
- return {
8
- shouldShow({line, graphPath = '', force = false, now = Date.now()} = {}) {
9
- if (!line) return false
10
- const key = `${graphPath}\u0000${line}`
11
- if (force || key !== lastKey || now - lastShownAt >= cooldownMs) {
12
- lastKey = key
13
- lastShownAt = now
14
- return true
15
- }
16
- return false
17
- },
18
- reset() { lastKey = ''; lastShownAt = 0 },
19
- }
20
- }
@@ -1,54 +0,0 @@
1
- import {
2
- CAPS, SEVERITIES, bool, compare, count, int, list, moduleId, path,
3
- reasons, state, text, token, verdict,
4
- } from './evidence-common.mjs'
5
-
6
- function moduleFact(value) {
7
- const id = moduleId(value?.id || value?.name)
8
- return id ? {id, fileCount: int(value.fileCount), nodeCount: int(value.nodeCount), symbolCount: int(value.symbolCount)} : null
9
- }
10
-
11
- function dependency(value) {
12
- const from = moduleId(value?.from), to = moduleId(value?.to)
13
- return from && to && from !== to ? {from, to, count: int(value.count)} : null
14
- }
15
-
16
- function cycleFact(value) {
17
- const id = text(value?.id, 64), kind = value?.kind
18
- if (!id || !/^[a-f0-9]{16,64}$/i.test(id) || !['runtime', 'compile-time'].includes(kind)) return null
19
- const members = [...new Set((value.members || []).map((item) => path(item)).filter(Boolean))].sort(compare).slice(0, 200)
20
- const representativePath = (value.representativePath || []).map((item) => path(item)).filter(Boolean).slice(0, 201)
21
- if (members.length < 2 || representativePath.length < 2) return null
22
- return {id, kind, size: Math.max(int(value.size), members.length), members, membersTruncated: bool(value.membersTruncated) || int(value.size) > members.length, representativePath}
23
- }
24
-
25
- function boundaryFact(value) {
26
- const ruleId = token(value?.ruleId, 96), from = path(value?.from), to = path(value?.to)
27
- if (!ruleId || !from || !to || !['forbidden', 'allowedOnly'].includes(value?.kind) || !SEVERITIES.has(value?.severity)) return null
28
- return {kind: value.kind, ruleId, severity: value.severity, from, to}
29
- }
30
-
31
- export function sanitizeArchitecture(value) {
32
- const modules = list(value?.modules, CAPS.modules, moduleFact, (a, b) => compare(a.id, b.id))
33
- const dependencies = {}
34
- let truncated = modules.truncated
35
- const dependencyMeta = {}
36
- for (const kind of ['runtime', 'typeOnly', 'compileOnly']) {
37
- const result = list(value?.dependencies?.[kind], CAPS.dependencies, dependency, (a, b) => compare(a.from, b.from) || compare(a.to, b.to))
38
- dependencies[kind] = result.items
39
- const completenessKey = `${kind}Dependencies`
40
- dependencyMeta[completenessKey] = count(value?.completeness?.[completenessKey], result.total, result.items.length)
41
- truncated ||= result.truncated
42
- }
43
- const cycles = list(value?.cycles, CAPS.findings, cycleFact, (a, b) => compare(a.kind, b.kind) || b.size - a.size || compare(a.id, b.id))
44
- const boundaries = list(value?.boundaryViolations, CAPS.findings, boundaryFact, (a, b) => compare(a.ruleId, b.ruleId) || compare(a.from, b.from) || compare(a.to, b.to))
45
- truncated ||= cycles.truncated || boundaries.truncated
46
- const outState = state(value?.state)
47
- return {
48
- state: truncated && outState === 'COMPLETE' ? 'PARTIAL' : outState,
49
- verdict: verdict(value?.verdict),
50
- completeness: {modules: count(value?.completeness?.modules, modules.total, modules.items.length), ...dependencyMeta, cycles: count(value?.completeness?.cycles, cycles.total, cycles.items.length), boundaryViolations: count(value?.completeness?.boundaryViolations, boundaries.total, boundaries.items.length), reasons: reasons(value?.completeness?.reasons)},
51
- modules: modules.items, dependencies, cycles: cycles.items, boundaryViolations: boundaries.items,
52
- boundaryRulesState: state(value?.boundaryRulesState),
53
- }
54
- }
@@ -1,88 +0,0 @@
1
- export const SEVERITIES = new Set(['critical', 'high', 'medium', 'low', 'info'])
2
- export const CONFIDENCE = new Set(['high', 'medium', 'low'])
3
- export const CATEGORIES = new Set(['unused', 'structure', 'vulnerability', 'malware'])
4
- const CHECK_KEYS = ['osv', 'malware']
5
- export const PACKAGE_DEPENDENCY_KINDS = new Set(['runtime', 'dev', 'optional', 'peer', 'optional-peer'])
6
- export const CAPS = Object.freeze({
7
- modules: 500, dependencies: 2000, findings: 500, hotspots: 250, badges: 100,
8
- packages: 5000, usage: 1000, files: 20, packageGraphNodes: 5000, packageGraphEdges: 20000,
9
- duplicateGroups: 100, duplicateMembers: 12, divergenceCandidates: 100,
10
- })
11
- export const DUPLICATE_THRESHOLDS = Object.freeze({
12
- clones: Object.freeze({mode: 'renamed', minSimilarityPercent: 80, minTokens: 50}),
13
- divergence: Object.freeze({sameName: true, maxSimilarityPercent: 45, minTokens: 50, maxImplementationsPerName: 12}),
14
- })
15
-
16
- const STATES = new Set(['COMPLETE', 'PARTIAL', 'NOT_CHECKED', 'NOT_APPLICABLE', 'ERROR'])
17
- const VERDICTS = new Set(['PASS', 'FAIL', 'UNKNOWN'])
18
- const CONTROL = /[\u0000-\u001f\u007f]/
19
- const ABSOLUTE_PATH_FRAGMENT = /(?:^|[\/\s"'`(=])[a-z]:[\\/]|(?:^|[\s"'`(=])(?:\\\\[^\\/\s]+(?:[\\/]|$)|file:(?:\/\/)?[\\/]|\/(?!\/)[^\s])/i
20
- const TOKEN = /^[\p{L}\p{N}_.:@+\-#$<>()\[\],]+$/u
21
- const PACKAGE = /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/i
22
-
23
- export const int = (value) => Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0
24
- export const bool = (value) => value === true
25
- export const text = (value, max = 256) => typeof value === 'string' && value.length > 0 && value.length <= max && !CONTROL.test(value) ? value : undefined
26
- export const token = (value, max = 256) => { const valueText = text(value, max); return valueText && TOKEN.test(valueText) ? valueText : undefined }
27
- export const privacySafeText = (value, max = 256) => { const valueText = text(value, max); return valueText && !ABSOLUTE_PATH_FRAGMENT.test(valueText) ? valueText : undefined }
28
- export const packageName = (value) => { const valueText = text(value, 256); return valueText && PACKAGE.test(valueText) ? valueText : undefined }
29
- export const packageVersion = (value) => { const valueText = text(value, 128); return valueText && /^[A-Za-z0-9][A-Za-z0-9._+~-]*$/.test(valueText) ? valueText : undefined }
30
- export const state = (value) => STATES.has(value) ? value : 'ERROR'
31
- export const verdict = (value) => VERDICTS.has(value) ? value : 'UNKNOWN'
32
- export const compare = (a, b) => String(a).localeCompare(String(b), 'en')
33
-
34
- export function path(value, max = 4096) {
35
- const raw = text(value, max)
36
- if (!raw) return undefined
37
- const normalized = raw.replace(/\\/g, '/')
38
- if (/^(?:[a-z][a-z0-9+.-]*:|\/)/i.test(normalized)) return undefined
39
- const parts = normalized.split('/')
40
- return parts.length && parts.every((part) => part && part !== '.' && part !== '..') ? normalized : undefined
41
- }
42
-
43
- export function graphId(value) {
44
- const id = text(value, 4096)
45
- if (!id) return undefined
46
- const hash = id.indexOf('#')
47
- const file = hash < 0 ? id : id.slice(0, hash)
48
- const safeFile = path(file)
49
- if (!safeFile) return undefined
50
- if (hash < 0) return safeFile
51
- const suffix = id.slice(hash)
52
- return suffix.length <= 512 && /^#[^\\/\s\u0000-\u001f\u007f]{1,511}$/u.test(suffix) ? `${safeFile}${suffix}` : undefined
53
- }
54
-
55
- export function moduleId(value) { return value === '(root)' ? value : path(value) }
56
- export function set(out, key, value) { if (value !== undefined) out[key] = value }
57
-
58
- export function stableStringify(value) {
59
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
60
- if (value && typeof value === 'object') return `{${Object.keys(value).sort(compare).map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
61
- return JSON.stringify(value)
62
- }
63
-
64
- export function list(values, cap, mapper, sorter) {
65
- const all = (Array.isArray(values) ? values : []).map(mapper).filter(Boolean).sort(sorter)
66
- return {items: all.slice(0, cap), total: all.length, truncated: all.length > cap}
67
- }
68
-
69
- export function count(value, fallbackTotal, returned) {
70
- const total = Math.max(int(value?.total), fallbackTotal)
71
- return {total, returned, truncated: bool(value?.truncated) || total > returned}
72
- }
73
-
74
- export function reasons(values) {
75
- return [...new Set((Array.isArray(values) ? values : []).map((value) => token(value, 96)).filter(Boolean))].sort(compare).slice(0, 32)
76
- }
77
-
78
- export function numericRecord(value, keys) {
79
- const out = {}
80
- for (const key of keys) out[key] = int(value?.[key])
81
- return out
82
- }
83
-
84
- export function checks(value) {
85
- const out = {}
86
- for (const key of CHECK_KEYS) out[key] = state(value?.[key])
87
- return out
88
- }