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,200 +0,0 @@
1
- import {findSeeds, rawGraph} from './graph-context.mjs'
2
- import {toolResult} from './tool-result.mjs'
3
- import {expandTaskQuery, retrieveTaskContext} from '../analysis/task-retrieval.js'
4
- import {extractCallArgumentEvidence} from '../analysis/data-flow-evidence.js'
5
- import {runAllowedTests, validateTestRequests} from '../analysis/allowed-test-runner.js'
6
- import {compareDuplicateGroups} from '../analysis/duplicate-groups.js'
7
- import {buildGraphAtGitRef} from '../analysis/git-ref-graph.js'
8
- import {diffGraphs, formatGraphDiff} from './graph-diff.mjs'
9
-
10
- const richResult = (value) => value?.__weavatrixToolResult === true ? value.result : null
11
- const normalizeFile = (value) => String(value || '').replace(/\\/g, '/')
12
- const changedFilesOf = (impact) => [...new Set((impact?.changes || []).flatMap((change) => [change.path, change.oldPath, change.newPath]).map(normalizeFile).filter((file) => file && file !== '(diff unavailable)'))]
13
- const targetTests = (impact) => [...new Set([
14
- ...(impact?.testEvidence?.changedFiles || []).map((item) => item.staticTestReachability?.test),
15
- ...(impact?.blastRadius?.nodes || []).map((node) => node.testEvidence?.staticTestReachability?.test),
16
- ].filter(Boolean))].slice(0, 30)
17
-
18
- function testCoverage(proof, requests, suggested) {
19
- if (!suggested.length) return {state: 'NOT_APPLICABLE', covered: [], missing: []}
20
- if (proof.state !== 'PASS') return {state: 'PENDING', covered: [], missing: suggested}
21
- if ((requests || []).some((request) => request?.script === 'test' && (!request.args || !request.args.length))) {
22
- return {state: 'COMPLETE', kind: 'full-test-script', covered: suggested, missing: []}
23
- }
24
- const args = (requests || []).flatMap((request) => request?.args || []).map(normalizeFile)
25
- const covered = suggested.filter((file) => args.some((arg) => arg === file || arg.endsWith(`/${file}`)))
26
- return {state: covered.length === suggested.length ? 'COMPLETE' : 'PARTIAL', kind: 'explicit-test-paths', covered, missing: suggested.filter((file) => !covered.includes(file))}
27
- }
28
-
29
- function graphProof(diff) {
30
- const runtimeCycles = diff?.cycles?.runtime?.introduced || []
31
- return {
32
- state: runtimeCycles.length ? 'BLOCKED' : diff.schemaMigration ? 'UNKNOWN' : 'PASS',
33
- ...(diff.schemaMigration ? {reason: 'graph extractor/schema versions differ, so structural ratchets are not comparable'} : {}),
34
- summary: formatGraphDiff(diff),
35
- counts: {
36
- nodesAdded: diff.nodes.added.length, nodesRemoved: diff.nodes.removed.length,
37
- edgesAdded: diff.edges.added, edgesRemoved: diff.edges.removed,
38
- moduleDependenciesAdded: diff.moduleEdges.added.length, orphaned: diff.orphaned.length,
39
- runtimeCyclesIntroduced: runtimeCycles.length,
40
- },
41
- runtimeCycles: runtimeCycles.slice(0, 20), moduleDependenciesAdded: diff.moduleEdges.added.slice(0, 20),
42
- orphaned: diff.orphaned.slice(0, 20), schemaMigration: diff.schemaMigration,
43
- }
44
- }
45
-
46
- async function baselineProof(ctx, baseRef, currentGraph) {
47
- const mode = ['full', 'no-tests', 'tests-only'].includes(currentGraph?.graphBuildMode) ? currentGraph.graphBuildMode : 'full'
48
- const built = await buildGraphAtGitRef(ctx.repoRoot, baseRef, {mode})
49
- if (!built.ok) return {state: 'UNKNOWN', reason: built.error}
50
- return {...graphProof(diffGraphs(built.graph, currentGraph)), baseline: {ref: built.ref, commit: built.commit}}
51
- }
52
-
53
- function apiState(result) {
54
- if (!result || result.status !== 'COMPLETE' || result.completeness?.complete !== true) return 'UNKNOWN'
55
- if (['HTTP_METHOD_MISMATCH', 'CLIENTS_AT_RISK_WITH_METHOD_MISMATCHES'].includes(result.verdict?.code)) return 'BLOCKED'
56
- return 'UNKNOWN'
57
- }
58
-
59
- function architectureState(result) {
60
- if (!result || result.state === 'NOT_CONFIGURED' || result.state === 'ERROR') return 'UNKNOWN'
61
- if (!result.verification) return result.state === 'READY' ? 'PASS' : 'UNKNOWN'
62
- return result.verification.new?.length || String(result.verification.status).toUpperCase() === 'FAIL' ? 'BLOCKED' : 'PASS'
63
- }
64
-
65
- function exactUsageLines(contexts, g) {
66
- if (!contexts.length) return []
67
- return contexts.map((context) => {
68
- const node = g.byId.get(String(context.symbol || context.definition?.id || ''))
69
- const label = String(context.definition?.label || node?.label || context.symbol || 'symbol')
70
- if (context.status !== 'OK') return `Exact usage: ${label} — unavailable (${context.status || 'UNKNOWN'}).`
71
- const exact = context.evidence?.state === 'EXACT'
72
- const occurrences = Number(context.references?.occurrences) || 0
73
- const files = Number(context.references?.files) || 0
74
- const inbound = Array.isArray(context.inbound?.shown) ? context.inbound.shown.slice(0, 3) : []
75
- const callers = inbound.map((item) => `${item.label || item.id}${item.file ? ` [${item.file}]` : ''}`).join(', ')
76
- return `${exact ? 'Exact usage' : 'Bounded usage'}: ${label} — ${occurrences} reference occurrence(s)${files ? ` in ${files} file(s)` : ''}; ${Number(context.inbound?.total) || 0} inbound container(s)${callers ? `: ${callers}` : ''}.`
77
- })
78
- }
79
-
80
- function decide({phase, impact, graph, architecture, duplicates, api, tests, suggestedTests, testCoverageState}) {
81
- if (phase === 'plan') return tests.state === 'BLOCKED'
82
- ? {verdict: 'BLOCKED', blockers: [`targeted test plan was rejected: ${tests.reason || 'invalid request'}`], unknowns: []}
83
- : {verdict: 'UNKNOWN', blockers: [], unknowns: ['verification has not run; apply the edit and call verified_change with phase=verify']}
84
- if (impact.status === 'COMPLETE' && !impact.changes?.length) return {verdict: 'PASS', blockers: [], unknowns: []}
85
- const blockers = [], unknowns = []
86
- if (impact.status !== 'COMPLETE') unknowns.push('change impact is partial or has unmapped evidence')
87
- if (graph.state === 'BLOCKED') blockers.push('the change introduces a runtime dependency cycle')
88
- if (graph.state === 'UNKNOWN') unknowns.push(`Git graph baseline is unavailable: ${graph.reason || 'unknown reason'}`)
89
- if (architecture.state === 'BLOCKED') blockers.push('new architecture-contract violations were found')
90
- if (architecture.state === 'UNKNOWN') unknowns.push('architecture contract is not configured or verification is incomplete')
91
- if (duplicates.state === 'BLOCKED') blockers.push('new duplicate groups intersect the changed files')
92
- if (duplicates.state === 'UNKNOWN') unknowns.push(`duplicate ratchet is incomplete: ${duplicates.reason || 'health capability unavailable'}`)
93
- if (api.state === 'BLOCKED') blockers.push('cross-repository API evidence contains HTTP method mismatches')
94
- if (api.state === 'UNKNOWN') unknowns.push(`API contract evidence is incomplete: ${api.reason || 'no bounded proof'}`)
95
- if (tests.state === 'FAIL' || tests.state === 'BLOCKED') {
96
- const failed = (tests.results || []).filter((result) => result.status !== 'PASS').map((result) => `${result.script} (${result.status}${result.exitCode == null ? '' : `, exit ${result.exitCode}`})`)
97
- blockers.push(`targeted tests failed or were rejected: ${tests.reason || failed.join(', ') || 'unknown failure'}`)
98
- }
99
- if (tests.state === 'DISABLED') unknowns.push('targeted test execution was requested but runtime permission is disabled')
100
- if (tests.state === 'NOT_REQUESTED' && suggestedTests.length) unknowns.push('affected tests were identified but no allowlisted package test was requested')
101
- if (tests.state === 'PASS' && testCoverageState.state === 'PARTIAL') unknowns.push(`targeted test run did not cover ${testCoverageState.missing.length} suggested test path(s)`)
102
- return {verdict: blockers.length ? 'BLOCKED' : unknowns.length ? 'UNKNOWN' : 'PASS', blockers, unknowns}
103
- }
104
-
105
- export async function tVerifiedChange(g, args = {}, ctx = {}, tools = {}, permissions = {}) {
106
- const phase = args.phase === 'verify' ? 'verify' : 'plan'
107
- const currentGraph = rawGraph(ctx)
108
- const impactValue = await tools.impact(g, {base: args.base_ref, diff: args.diff, files: args.files, depth: args.impact_depth, max_nodes: args.max_impact_nodes}, ctx)
109
- const impact = richResult(impactValue) || {status: 'PARTIAL', changes: [], seeds: {ids: []}, blastRadius: {nodes: []}}
110
- const changedFiles = changedFilesOf(impact)
111
- const retrieval = retrieveTaskContext(g, {
112
- task: args.task, semanticSeeds: findSeeds(g, expandTaskQuery(args.task), 12, {repoRoot: ctx.repoRoot}),
113
- changedSeedIds: impact.seeds?.ids, maxSymbols: args.max_symbols, repoRoot: ctx.repoRoot,
114
- })
115
-
116
- let contexts = []
117
- if (permissions.source) contexts = await Promise.all(retrieval.selected.map(async (symbol) => {
118
- const value = await tools.context(g, {label: symbol.id, precision: args.precision, max_related: 8, max_source_files: 3, context_lines: 4}, ctx, tools.inspect)
119
- const result = richResult(value)
120
- return result ? {symbol: symbol.id, status: result.status, definition: result.definition, evidence: result.evidence, references: result.references, inbound: result.inbound, outbound: result.outbound, reExports: result.reExports, source: result.source} : {symbol: symbol.id, status: 'UNKNOWN'}
121
- }))
122
- const dataFlow = permissions.source ? extractCallArgumentEvidence({
123
- graph: g, repoRoot: ctx.repoRoot, seedIds: retrieval.selected.map((item) => item.id),
124
- depth: Math.max(1, Math.min(3, Number(args.data_flow_depth) || 2)),
125
- maxEdges: Math.max(1, Math.min(60, Number(args.max_data_flow_edges) || 30)),
126
- })
127
- : {model: 'bounded call-argument-to-parameter evidence (not CFG or taint analysis)', status: 'UNAVAILABLE', reason: 'source capability is not enabled', edges: [], unsupportedEdges: 0, capped: false}
128
- const suggestedTests = targetTests(impact)
129
- const requestedTests = Array.isArray(args.tests) ? args.tests : []
130
- let testProof
131
- if (!requestedTests.length) {
132
- testProof = {state: 'NOT_REQUESTED', reason: 'no package scripts were requested', plan: [], results: []}
133
- } else if (args.run_tests !== true) {
134
- testProof = await runAllowedTests(ctx.repoRoot, requestedTests, {enabled: false, timeoutMs: args.test_timeout_ms})
135
- } else if (phase === 'verify') {
136
- testProof = await runAllowedTests(ctx.repoRoot, requestedTests, {enabled: true, timeoutMs: args.test_timeout_ms})
137
- } else {
138
- const checkedTests = validateTestRequests(ctx.repoRoot, requestedTests)
139
- testProof = {state: checkedTests.ok ? 'PLANNED' : 'BLOCKED', reason: checkedTests.reason, plan: checkedTests.tests || [], results: []}
140
- }
141
- const testCoverageState = testCoverage(testProof, args.tests || [], suggestedTests)
142
-
143
- const architectureValue = phase === 'verify'
144
- ? (permissions.health ? tools.verifyArchitecture(g, {}, ctx) : null)
145
- : tools.prepareChange(g, {intent: args.task, files: changedFiles}, ctx)
146
- const architectureResult = richResult(architectureValue)
147
- const architecture = {state: architectureState(architectureResult), evidence: architectureResult}
148
- const baseRef = String(args.base_ref || 'HEAD').trim()
149
- const graph = phase === 'verify' ? await baselineProof(ctx, baseRef, currentGraph) : {state: 'PLANNED', baseline: baseRef}
150
-
151
- const duplicateRatchetEnabled = args.duplicate_ratchet !== false
152
- let duplicates
153
- if (!duplicateRatchetEnabled) {
154
- duplicates = {state: 'SKIPPED', enabled: false, reason: 'duplicate ratchet disabled'}
155
- } else if (phase !== 'verify') {
156
- duplicates = {state: 'PLANNED', enabled: true, reason: 'duplicate ratchet runs during verify phase'}
157
- } else {
158
- duplicates = permissions.health
159
- ? {enabled: true, ...await compareDuplicateGroups({repoRoot: ctx.repoRoot, graphPath: ctx.graphPath, currentGraph, baseRef, changedFiles, args: {mode: 'renamed', min_similarity: 80, min_tokens: 50}})}
160
- : {state: 'UNKNOWN', enabled: true, reason: 'health capability is not enabled'}
161
- }
162
-
163
- let api = {state: 'SKIPPED', reason: 'no api_contract scope was requested'}
164
- if (args.api_contract) {
165
- if (!permissions.crossrepo) api = {state: 'UNKNOWN', reason: 'crossrepo capability is not enabled'}
166
- else {
167
- const result = richResult(await tools.traceApi(g, {
168
- ...args.api_contract, changed_files: args.api_contract.changed_files || changedFiles,
169
- max_endpoints: Math.min(100, Number(args.api_contract.max_endpoints) || 100),
170
- max_matches: Math.min(500, Number(args.api_contract.max_matches) || 500),
171
- max_affected_files: Math.min(100, Number(args.api_contract.max_affected_files) || 100),
172
- top_n: Math.min(10, Number(args.api_contract.top_n) || 10),
173
- }, ctx))
174
- api = {state: apiState(result), evidence: result}
175
- }
176
- }
177
-
178
- const decision = decide({phase, impact, graph, architecture, duplicates, api, tests: testProof, suggestedTests, testCoverageState})
179
- if (!permissions.source && retrieval.selected.length) decision.unknowns.push('source capability is disabled; exact LSP/source edit contexts were not collected')
180
- if (phase === 'verify' && contexts.some((item) => item.status !== 'OK' || item.evidence?.state !== 'EXACT' || item.references?.capped)) {
181
- decision.unknowns.push('one or more exact edit contexts are incomplete')
182
- }
183
- if (phase === 'verify' && args.diff) decision.unknowns.push('a supplied diff was classified, but equivalence between that patch and the active graph is not proven; verify on a checked-out change without diff')
184
- if (decision.verdict === 'PASS' && decision.unknowns.length) decision.verdict = 'UNKNOWN'
185
- const result = {
186
- schemaVersion: 'weavatrix.verified-change.v1', verdict: decision.verdict, phase, task: String(args.task),
187
- blockers: decision.blockers, unknowns: decision.unknowns,
188
- retrieval, editContexts: contexts, dataFlow, changeImpact: impact, graphBaseline: graph,
189
- architecture, duplicates, apiContract: api, tests: {...testProof, suggestedFiles: suggestedTests, coverage: testCoverageState},
190
- }
191
- const text = [
192
- `${decision.verdict} — verified_change ${phase}`, `Task: ${String(args.task).slice(0, 500)}`,
193
- `Change: ${changedFiles.length} file(s), ${impact.seeds?.ids?.length || 0} exact seed(s), blast radius ${impact.blastRadius?.impacted || 0}.`,
194
- `Edit context: ${retrieval.selected.length} symbol(s); ${contexts.length} exact bundle(s); data-flow ${dataFlow.status} (${dataFlow.edges.length} call edge(s)).`,
195
- ...exactUsageLines(contexts, g),
196
- `Ratchets: graph ${graph.state}; architecture ${architecture.state}; duplicates ${duplicates.state}; API ${api.state}; tests ${testProof.state}.`,
197
- ...decision.blockers.map((item) => `BLOCKER: ${item}`), ...decision.unknowns.map((item) => `UNKNOWN: ${item}`),
198
- ].join('\n')
199
- return toolResult(text, result, {completeness: {status: decision.verdict === 'UNKNOWN' ? 'PARTIAL' : 'COMPLETE'}})
200
- }
package/src/mcp-rg.mjs DELETED
@@ -1,50 +0,0 @@
1
- import { readdirSync, existsSync } from 'node:fs'
2
- import { join } from 'node:path'
3
- import { createRequire } from 'node:module'
4
- import { runCommandSync } from './process.js'
5
-
6
- const rgInInstall = (base) => [
7
- join(base, 'resources', 'app', 'node_modules', '@vscode', 'ripgrep', 'bin', 'rg.exe'),
8
- join(base, 'resources', 'app', 'node_modules', '@vscode', 'ripgrep-universal', 'bin', 'win32-x64', 'rg.exe'),
9
- ]
10
-
11
- function editorRgCandidates() {
12
- if (process.platform !== 'win32') return []
13
- const local = process.env.LOCALAPPDATA || ''
14
- const pf = process.env.PROGRAMFILES || ''
15
- const roots = [local && join(local, 'Programs', 'Microsoft VS Code'), local && join(local, 'Programs', 'cursor'), pf && join(pf, 'Microsoft VS Code')].filter(Boolean)
16
- const out = []
17
- for (const root of roots) {
18
- if (!existsSync(root)) continue
19
- out.push(...rgInInstall(root))
20
- try {
21
- for (const d of readdirSync(root, {withFileTypes: true})) if (d.isDirectory()) out.push(...rgInInstall(join(root, d.name)))
22
- } catch { /* optional editor install probe */ }
23
- }
24
- return out
25
- }
26
-
27
- export function createRgResolver(selfDir) {
28
- let rgPath
29
- return function resolveRg() {
30
- if (rgPath !== undefined) return rgPath
31
- rgPath = null
32
- const env = (process.env.WEAVATRIX_RG_CMD || '').replace(/^"|"$/g, '')
33
- if (env && existsSync(env)) return (rgPath = env)
34
- try {
35
- const {rgPath: bundledRg} = createRequire(import.meta.url)('@vscode/ripgrep')
36
- if (bundledRg && existsSync(bundledRg)) return (rgPath = bundledRg)
37
- } catch { /* optional bundled ripgrep module */ }
38
- try {
39
- const unpackedRg = join(selfDir, '..', '..', 'node_modules', '@vscode', 'ripgrep', 'bin', process.platform === 'win32' ? 'rg.exe' : 'rg')
40
- if (existsSync(unpackedRg)) return (rgPath = unpackedRg)
41
- } catch { /* optional packaged ripgrep path */ }
42
- for (const c of editorRgCandidates()) if (existsSync(c)) return (rgPath = c)
43
- try {
44
- const probe = runCommandSync(process.platform === 'win32' ? 'where' : 'which', ['rg'], {timeout: 3000})
45
- const p = probe.status === 0 ? probe.stdout.split(/\r?\n/)[0].trim() : ''
46
- if (p && existsSync(p)) return (rgPath = p)
47
- } catch { /* optional PATH probe */ }
48
- return rgPath
49
- }
50
- }
@@ -1,2 +0,0 @@
1
- export {startMcpServer} from './mcp-server.mjs'
2
- export {DEFAULT_CAPS} from './mcp/catalog.mjs'
@@ -1,298 +0,0 @@
1
- // Weavatrix MCP stdio entry point; implementations and extension composition live in src/mcp/*.
2
- // Spawned by Claude Code / Codex as a plain Node child (node mcp-server.mjs <graph.json> <repoRoot>).
3
- // Speaks newline-delimited JSON-RPC 2.0 over stdio (the MCP stdio transport).
4
- //
5
- // .mjs on purpose: guarantees ESM parsing regardless of the nearest package.json. Runtime analyzers
6
- // resolve only dependencies bundled with Weavatrix: web-tree-sitter grammars for graph builds and the
7
- // pinned TypeScript language server for bounded JS/TS semantic evidence. Repository packages/scripts
8
- // are never executed to provide either analyzer.
9
- //
10
- // STDOUT is the protocol channel — nothing but JSON-RPC frames may be written there. All diagnostics
11
- // go to stderr. Two argv forms:
12
- // weavatrix-mcp <repoRoot> [caps] — graph path derived from the standard layout
13
- // weavatrix-mcp <graph.json> <repoRoot> [caps] — explicit graph file (classic form)
14
- import process from 'node:process'
15
- import {resolve} from 'node:path'
16
- import {pathToFileURL} from 'node:url'
17
- import {loadGraph} from './mcp/graph-context.mjs'
18
- import {createStalenessNoticeGate} from './mcp/staleness-notice.mjs'
19
- import {normalizeToolResult} from './mcp/tool-result.mjs'
20
- import {runtimeVersionStatus, staleRuntimeMessage} from './mcp/runtime-version.mjs'
21
- import {createAutoRefresh} from './mcp/server/auto-refresh.mjs'
22
- import {createShutdownController} from './mcp/server/shutdown.mjs'
23
- import {
24
- hotCatalogVersion as hotVersion, loadServerCatalog as loadCatalog, PACKAGE_JSON_PATH,
25
- PACKAGE_VERSION as PKG_VERSION, resolveServerTarget, SERVER_INFO,
26
- } from './mcp/server/runtime-config.mjs'
27
-
28
- // version comes from package.json so serverInfo can never drift from the published package again
29
- const DEFAULT_PROTOCOL = '2024-11-05'
30
- const log = (...a) => process.stderr.write(`[weavatrix] ${a.join(' ')}\n`)
31
-
32
- // ---- hot reload of tool implementations -----------------------------------------------------------
33
- // Node caches modules at spawn, so edits to the tool code would otherwise be invisible until the MCP
34
- // client reconnects. Before each tools/list|call we stat the hot-reloadable files (HOT_FILES); when
35
- // any changed on disk we re-import them through catalog.loadHotApi with a cache-busting version and
36
- // swap the tool table, then notify the client. The stdio shell, graph-context (its caches), and the
37
- // analysis engines are NOT swapped — changing those still needs a reconnect.
38
- export async function startMcpServer({
39
- argv = process.argv,
40
- defaultCapabilities,
41
- loadExtensions = async () => [],
42
- packageJsonPath = PACKAGE_JSON_PATH,
43
- packageVersion = PKG_VERSION,
44
- serverInfo = SERVER_INFO,
45
- } = {}) {
46
- const target = resolveServerTarget(argv, log)
47
- const GRAPH_PATH = target.graphPath
48
- const REPO_ROOT = target.repoRoot
49
- const CAPS_ARG = target.capabilities ?? defaultCapabilities
50
- let catalog = await loadCatalog()
51
- let extensions = await loadExtensions({version: 0})
52
- let api = await catalog.loadHotApi(0, CAPS_ARG, {extensions})
53
- const runtimeInfo = () => ({
54
- ...runtimeVersionStatus({runningVersion: packageVersion, packageJsonPath}),
55
- profile: api.profile || 'custom',
56
- capabilities: [...api.caps],
57
- toolCount: api.tools.length,
58
- ...(api.extensions.items.length ? {extensions: api.extensions.items} : {}),
59
- })
60
- const runtimeInstructions = () => {
61
- const runtime = runtimeInfo()
62
- const stale = runtime.staleRuntime
63
- ? ` ${staleRuntimeMessage(runtime)}${runtime.staleRuntimeAllowed ? ' Development override is active.' : ''}`
64
- : ''
65
- return `Weavatrix ${runtime.version}; diskVersion=${runtime.diskVersion || 'unavailable'}; profile=${runtime.profile}; tools=${runtime.toolCount}; capabilities=${runtime.capabilities.join(',') || '(none)'}.${stale} If this differs from the client-visible tool list, reconnect the MCP client to discard its cached schema.`
66
- }
67
- let graph = null
68
- let graphError = null
69
- // ctx owns the CURRENT target: rebuild_graph reloads it, open_repo retargets graphPath/repoRoot
70
- // at runtime. loadInto always reads ctx.graphPath so both paths share one loader.
71
- const ctx = {graphPath: GRAPH_PATH, repoRoot: REPO_ROOT, reload: null, runtime: runtimeInfo(), extensions: api.extensions}
72
- const loadInto = () => { graph = loadGraph(ctx.graphPath, {repoRoot: ctx.repoRoot}); graphError = null; return graph }
73
- ctx.reload = () => { api.resetStalenessCache(); try { return loadInto() } catch (e) { graphError = e.message; return null } }
74
- try {
75
- if (!ctx.graphPath) throw new Error('no graph.json path given (argv[2])')
76
- loadInto()
77
- log(`loaded ${graph.nodes.length} nodes / ${graph.links.length} edges from ${ctx.graphPath}`)
78
- } catch (e) {
79
- graphError = e.message
80
- log(`failed to load graph: ${e.message}`)
81
- }
82
- log(`repo root: ${REPO_ROOT || '(none — source/action tools disabled)'}`)
83
- log(`capabilities: ${[...api.caps].join(',') || '(none)'} (${api.tools.length} tools)`)
84
-
85
- let protocolVersion = DEFAULT_PROTOCOL
86
- const staleNotices = createStalenessNoticeGate()
87
- // Only build/retarget tools mutate the process-wide graph target. Serialize those mutations while
88
- // ordinary tools use a per-call graph/context snapshot, so an explicitly retargetable registration
89
- // cannot mix one repo's in-memory graph with another repo's source root under concurrent MCP calls.
90
- let targetMutation = Promise.resolve()
91
- const shutdown = createShutdownController({log, targetMutation: () => targetMutation})
92
- const autoRefresh = createAutoRefresh(() => api)
93
- const send = (msg) => {
94
- // A request that was already running when the client disconnected may complete during the
95
- // bounded drain. Do not write a late reply into a closed protocol pipe.
96
- if (shutdown.isShuttingDown() || process.stdout.destroyed || !process.stdout.writable) return false
97
- try {
98
- return process.stdout.write(JSON.stringify(msg) + '\n')
99
- } catch (error) {
100
- if (error?.code === 'EPIPE' || error?.code === 'ERR_STREAM_DESTROYED') return false
101
- throw error
102
- }
103
- }
104
- const reply = (id, result) => send({jsonrpc: '2.0', id, result})
105
- const fail = (id, code, message, data) => send({jsonrpc: '2.0', id, error: {code, message, ...(data ? {data} : {})}})
106
-
107
- const requestShutdown = shutdown.request
108
- process.stdout.on('error', (error) => {
109
- if (error?.code === 'EPIPE' || error?.code === 'ERR_STREAM_DESTROYED') {
110
- void requestShutdown('stdout disconnected')
111
- return
112
- }
113
- log(`stdout error: ${error.stack || error.message}`)
114
- void requestShutdown('stdout error', 1)
115
- })
116
-
117
- let loadedVersion = hotVersion(catalog.HOT_FILES)
118
- let lastFailedVersion = 0
119
- const maybeHotReload = async () => {
120
- const v = hotVersion(catalog.HOT_FILES)
121
- if (v <= loadedVersion || v === lastFailedVersion) return
122
- try {
123
- const nextCatalog = await loadCatalog(v)
124
- const nextExtensions = await loadExtensions({version: v})
125
- const nextApi = await nextCatalog.loadHotApi(v, CAPS_ARG, {extensions: nextExtensions})
126
- catalog = nextCatalog
127
- api = nextApi
128
- extensions = nextExtensions
129
- ctx.runtime = runtimeInfo()
130
- ctx.extensions = api.extensions
131
- loadedVersion = v
132
- log(`hot-reloaded tool implementations from changed source (${api.tools.length} tools)`)
133
- send({jsonrpc: '2.0', method: 'notifications/tools/list_changed'})
134
- } catch (e) {
135
- lastFailedVersion = v // remember the broken version so we don't retry it every call
136
- log(`hot-reload failed, keeping current tools: ${e.message}`)
137
- }
138
- }
139
-
140
- const handle = async (msg) => {
141
- const {id, method, params} = msg
142
- const isNotification = id === undefined || id === null
143
- if (shutdown.isShuttingDown()) {
144
- if (!isNotification) fail(id, -32000, 'MCP server is shutting down')
145
- return
146
- }
147
- if (method === 'initialize' || method === 'tools/list' || method === 'tools/call') {
148
- const runtime = runtimeInfo()
149
- ctx.runtime = runtime
150
- if (runtime.staleRuntime && !runtime.staleRuntimeAllowed) {
151
- if (!isNotification) fail(id, -32001, staleRuntimeMessage(runtime), {'weavatrix/runtime': runtime})
152
- return
153
- }
154
- }
155
- if (method === 'initialize') {
156
- if (params?.protocolVersion) protocolVersion = String(params.protocolVersion)
157
- return reply(id, {
158
- protocolVersion, capabilities: {tools: {listChanged: true}}, serverInfo,
159
- instructions: runtimeInstructions(), _meta: {'weavatrix/runtime': runtimeInfo()},
160
- })
161
- }
162
- if (method === 'notifications/initialized' || method === 'initialized') return
163
- if (method === 'ping') return reply(id, {})
164
- if (method === 'tools/list') {
165
- await maybeHotReload()
166
- if (shutdown.isShuttingDown()) return
167
- return reply(id, {
168
- tools: api.tools.map(({name, description, inputSchema, outputSchema}) => ({name, description, inputSchema, outputSchema})),
169
- _meta: {'weavatrix/runtime': runtimeInfo()},
170
- })
171
- }
172
- if (method === 'tools/call') {
173
- await maybeHotReload()
174
- // EOF can arrive while the hot-reload import is pending. Do not enqueue a graph mutation
175
- // after requestShutdown captured the mutation chain it is responsible for draining.
176
- if (shutdown.isShuttingDown()) return
177
- const tool = api.byName.get(params?.name)
178
- if (!tool) return reply(id, {content: [{type: 'text', text: `Unknown tool: ${params?.name}`}], isError: true})
179
- const refreshesGraph = tool.cap === 'graph' || tool.cap === 'health' || tool.refreshGraph === true
180
- // Graph/health reads can establish a missing graph automatically when a repo root is known.
181
- if (!graph && !refreshesGraph && tool.cap !== 'build' && tool.cap !== 'retarget') return reply(id, {content: [{type: 'text', text: `Graph unavailable: ${graphError}`}], isError: true})
182
- const mutatesTarget = tool.cap === 'build' || tool.cap === 'retarget'
183
- const graphSnapshot = graph
184
- const callCtx = mutatesTarget ? ctx : {...ctx}
185
- const execute = async () => {
186
- const startedAt = performance.now()
187
- try {
188
- // A queued rebuild must see a preceding retarget's graph, while non-mutating calls stay
189
- // pinned to the graph that was active when their request arrived.
190
- let refresh = null
191
- let callGraph = mutatesTarget ? graph : graphSnapshot
192
- if (!mutatesTarget && refreshesGraph) {
193
- const refreshed = await autoRefresh(callCtx, callGraph)
194
- if (refreshed.graph) {
195
- callGraph = refreshed.graph
196
- refresh = refreshed.refresh
197
- if (ctx.graphPath === callCtx.graphPath && ctx.repoRoot === callCtx.repoRoot) graph = callGraph
198
- }
199
- }
200
- const toolArgs = params?.arguments || {}
201
- const value = await tool.run(callGraph, toolArgs, callCtx)
202
- const warnings = []
203
- if (callGraph && callGraph.edgeTypesV < 2 && (tool.cap === 'graph' || tool.cap === 'health')) {
204
- warnings.push({code: 'EDGE_SCHEMA_OUTDATED', message: 'This saved graph predates compile-only edge metadata (edge schema v2); rebuild before acting on cycle, boundary, dependency, or blast-radius findings.'})
205
- }
206
- // Graph answers silently reflect a point-in-time build — surface staleness on every graph tool.
207
- const staleLine = tool.cap === 'graph' ? api.stalenessLine(callCtx) : null
208
- if (staleLine) warnings.push({code: 'GRAPH_STALE', message: staleLine})
209
- const normalized = normalizeToolResult({
210
- toolName: tool.name, value, args: toolArgs, ctx: callCtx, warnings, refresh,
211
- freshness: staleLine ? 'stale' : 'fresh',
212
- })
213
- let text = normalized.text
214
- if (toolArgs.output_format !== 'json') {
215
- const schemaWarning = warnings.find((warning) => warning.code === 'EDGE_SCHEMA_OUTDATED')
216
- if (schemaWarning) text += `\n\nWarning: ${schemaWarning.message}`
217
- if (staleLine && staleNotices.shouldShow({line: staleLine, graphPath: callCtx.graphPath, force: tool.name === 'graph_stats'})) text += `\n\n${staleLine}`
218
- }
219
- const structuredBytes = normalized.structured ? Buffer.byteLength(JSON.stringify(normalized.structured)) : 0
220
- const textBytes = Buffer.byteLength(text)
221
- const durationMs = Math.max(0, performance.now() - startedAt)
222
- const response = {
223
- content: [{type: 'text', text}],
224
- _meta: {
225
- 'weavatrix/metrics': {
226
- schemaVersion: 'weavatrix.metrics.v1',
227
- durationMs: Math.round(durationMs * 10) / 10,
228
- textBytes,
229
- structuredBytes,
230
- estimatedOutputTokens: Math.ceil((textBytes + structuredBytes) / 4),
231
- graphFreshness: staleLine ? 'stale' : (refresh?.error ? 'stale' : 'fresh'),
232
- graphUpdate: refresh?.kind || 'none',
233
- graphRevision: refresh?.revision || callGraph?.graphRevision || null,
234
- cache: refreshesGraph ? (refresh?.kind === 'none' ? 'graph-hit' : 'graph-refreshed') : 'not-applicable',
235
- },
236
- },
237
- }
238
- if (normalized.structured) response.structuredContent = normalized.structured
239
- return reply(id, response)
240
- } catch (e) {
241
- log(`tool ${params?.name} threw: ${e.stack || e.message}`)
242
- const text = `Tool error: ${e.message}`
243
- return reply(id, {
244
- content: [{type: 'text', text}], isError: true,
245
- _meta: {'weavatrix/metrics': {
246
- schemaVersion: 'weavatrix.metrics.v1', durationMs: Math.round(Math.max(0, performance.now() - startedAt) * 10) / 10,
247
- textBytes: Buffer.byteLength(text), structuredBytes: 0,
248
- estimatedOutputTokens: Math.ceil(Buffer.byteLength(text) / 4), graphFreshness: 'unknown',
249
- graphUpdate: 'none', graphRevision: graphSnapshot?.graphRevision || null, cache: 'not-applicable',
250
- }},
251
- })
252
- }
253
- }
254
- if (!mutatesTarget && !refreshesGraph) return execute()
255
- const pending = targetMutation.then(execute, execute)
256
- targetMutation = pending.catch(() => {})
257
- return pending
258
- }
259
- if (!isNotification) return fail(id, -32601, `Method not found: ${method}`)
260
- }
261
-
262
- let buf = ''
263
- process.stdin.setEncoding('utf8')
264
- process.stdin.on('data', (chunk) => {
265
- if (shutdown.isShuttingDown()) return
266
- buf += chunk
267
- let nl
268
- while ((nl = buf.indexOf('\n')) >= 0) {
269
- const line = buf.slice(0, nl).trim()
270
- buf = buf.slice(nl + 1)
271
- if (!line) continue
272
- let msg
273
- try {
274
- msg = JSON.parse(line)
275
- } catch {
276
- log(`bad JSON line: ${line.slice(0, 120)}`)
277
- continue
278
- }
279
- // handle is async (rebuild_graph awaits a build) → catch rejections, not just sync throws
280
- Promise.resolve().then(() => handle(msg)).catch((e) => {
281
- log(`handler error: ${e.stack || e.message}`)
282
- if (msg?.id != null) fail(msg.id, -32603, `Internal error: ${e.message}`)
283
- })
284
- }
285
- })
286
- process.stdin.on('end', () => { void requestShutdown('stdin EOF') })
287
- process.on('SIGTERM', () => { void requestShutdown('SIGTERM') })
288
- process.on('SIGINT', () => { void requestShutdown('SIGINT') })
289
- log('ready')
290
- }
291
-
292
- // Guard: hot-reload re-imports of tool modules never touch this entry, but keep the start guard so a
293
- // stray re-import of the entry itself can never spawn a second stdio loop.
294
- const directEntry = process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href
295
- if (directEntry && !globalThis.__weavatrixMcpStarted) {
296
- globalThis.__weavatrixMcpStarted = true
297
- startMcpServer()
298
- }