weavatrix 0.3.13 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +231 -199
  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 +8 -65
  14. package/skill/SKILL.md +62 -374
  15. package/skill/agents/openai.yaml +4 -0
  16. package/skill/references/tool-routing.md +45 -0
  17. package/SECURITY.md +0 -101
  18. package/docs/adr/0001-v0.3-offline-online-split.md +0 -60
  19. package/docs/agent-task-benchmark.md +0 -58
  20. package/docs/releases/v0.2.19.md +0 -33
  21. package/docs/releases/v0.3.0.md +0 -43
  22. package/docs/releases/v0.3.1.md +0 -30
  23. package/docs/releases/v0.3.10.md +0 -76
  24. package/docs/releases/v0.3.11.md +0 -55
  25. package/docs/releases/v0.3.12.md +0 -44
  26. package/docs/releases/v0.3.13.md +0 -34
  27. package/docs/releases/v0.3.2.md +0 -15
  28. package/docs/releases/v0.3.3.md +0 -25
  29. package/docs/releases/v0.3.4.md +0 -40
  30. package/docs/releases/v0.3.5.md +0 -50
  31. package/docs/releases/v0.3.6.md +0 -44
  32. package/docs/releases/v0.3.7.md +0 -37
  33. package/docs/releases/v0.3.8.md +0 -21
  34. package/docs/releases/v0.3.9.md +0 -36
  35. package/scripts/run-agent-task-benchmark.mjs +0 -118
  36. package/src/analysis/allowed-test-runner.js +0 -70
  37. package/src/analysis/architecture/contract-graph.js +0 -119
  38. package/src/analysis/architecture/contract-schema.js +0 -110
  39. package/src/analysis/architecture/contract-storage.js +0 -35
  40. package/src/analysis/architecture/contract-verification.js +0 -168
  41. package/src/analysis/architecture-contract.js +0 -16
  42. package/src/analysis/audit-debt.js +0 -94
  43. package/src/analysis/audit-extensions.js +0 -60
  44. package/src/analysis/cargo-dependency-evidence.js +0 -108
  45. package/src/analysis/cargo-manifests.js +0 -81
  46. package/src/analysis/change-classification/diff-parser.js +0 -103
  47. package/src/analysis/change-classification/options.js +0 -40
  48. package/src/analysis/change-classification/symbol-classifier.js +0 -177
  49. package/src/analysis/change-classification.js +0 -188
  50. package/src/analysis/coverage-reports.js +0 -235
  51. package/src/analysis/cycle-route.js +0 -14
  52. package/src/analysis/data-flow-evidence.js +0 -114
  53. package/src/analysis/dead-check.js +0 -300
  54. package/src/analysis/dead-code-review/candidates.js +0 -194
  55. package/src/analysis/dead-code-review/policy.js +0 -23
  56. package/src/analysis/dead-code-review.js +0 -119
  57. package/src/analysis/dep-check-ecosystems.js +0 -205
  58. package/src/analysis/dep-check.js +0 -290
  59. package/src/analysis/dep-rules.js +0 -10
  60. package/src/analysis/dependency/conventions.js +0 -16
  61. package/src/analysis/dependency/scoped-dependencies.js +0 -51
  62. package/src/analysis/dependency/source-references.js +0 -21
  63. package/src/analysis/duplicate-groups.js +0 -104
  64. package/src/analysis/duplicates-worker.js +0 -11
  65. package/src/analysis/duplicates.compute.js +0 -269
  66. package/src/analysis/duplicates.js +0 -15
  67. package/src/analysis/duplicates.run.js +0 -52
  68. package/src/analysis/duplicates.tokenize.js +0 -199
  69. package/src/analysis/endpoints/common.js +0 -62
  70. package/src/analysis/endpoints/extract.js +0 -107
  71. package/src/analysis/endpoints/inventory.js +0 -84
  72. package/src/analysis/endpoints/mounts.js +0 -129
  73. package/src/analysis/endpoints-java.js +0 -260
  74. package/src/analysis/endpoints-rust.js +0 -124
  75. package/src/analysis/endpoints.js +0 -3
  76. package/src/analysis/findings.js +0 -70
  77. package/src/analysis/git-history/analytics.js +0 -177
  78. package/src/analysis/git-history/collector.js +0 -67
  79. package/src/analysis/git-history/options.js +0 -66
  80. package/src/analysis/git-history.js +0 -143
  81. package/src/analysis/git-ref-graph.js +0 -76
  82. package/src/analysis/go-dependency-evidence.js +0 -62
  83. package/src/analysis/graph-analysis.aggregate.js +0 -295
  84. package/src/analysis/graph-analysis.edges.js +0 -24
  85. package/src/analysis/graph-analysis.js +0 -7
  86. package/src/analysis/graph-analysis.refs.js +0 -154
  87. package/src/analysis/graph-analysis.summaries.js +0 -65
  88. package/src/analysis/health-capabilities.js +0 -83
  89. package/src/analysis/hot-path-review.js +0 -266
  90. package/src/analysis/http-contract-wrappers.js +0 -241
  91. package/src/analysis/http-contracts/analysis.js +0 -179
  92. package/src/analysis/http-contracts/client-call-detection.js +0 -82
  93. package/src/analysis/http-contracts/client-call-parser.js +0 -273
  94. package/src/analysis/http-contracts/graph-context.js +0 -143
  95. package/src/analysis/http-contracts/matching.js +0 -61
  96. package/src/analysis/http-contracts/shared.js +0 -85
  97. package/src/analysis/http-contracts.js +0 -6
  98. package/src/analysis/internal-audit/dependency-health.js +0 -113
  99. package/src/analysis/internal-audit/python-manifests.js +0 -78
  100. package/src/analysis/internal-audit/repo-files.js +0 -50
  101. package/src/analysis/internal-audit/supply-chain.js +0 -149
  102. package/src/analysis/internal-audit.collect.js +0 -213
  103. package/src/analysis/internal-audit.js +0 -9
  104. package/src/analysis/internal-audit.reach.js +0 -173
  105. package/src/analysis/internal-audit.run.js +0 -256
  106. package/src/analysis/java-source.js +0 -36
  107. package/src/analysis/jvm-artifact-index.js +0 -87
  108. package/src/analysis/jvm-dependency-evidence.js +0 -138
  109. package/src/analysis/jvm-manifests.js +0 -114
  110. package/src/analysis/manifests.js +0 -123
  111. package/src/analysis/package-reachability.js +0 -39
  112. package/src/analysis/source-complexity.ast.js +0 -97
  113. package/src/analysis/source-complexity.constants.js +0 -55
  114. package/src/analysis/source-complexity.js +0 -14
  115. package/src/analysis/source-complexity.report.js +0 -81
  116. package/src/analysis/source-complexity.walk.js +0 -228
  117. package/src/analysis/source-correctness/retry-patterns.js +0 -93
  118. package/src/analysis/source-correctness.js +0 -222
  119. package/src/analysis/static-test-reachability.js +0 -150
  120. package/src/analysis/structure/dependency-graph.js +0 -151
  121. package/src/analysis/structure/findings.js +0 -162
  122. package/src/analysis/task-retrieval.js +0 -107
  123. package/src/analysis/transport-contracts.js +0 -224
  124. package/src/analysis/transport-runtime-evidence.js +0 -155
  125. package/src/analysis-kit.mjs +0 -17
  126. package/src/bounds.js +0 -4
  127. package/src/build-graph.js +0 -209
  128. package/src/child-env.js +0 -7
  129. package/src/config.js +0 -5
  130. package/src/extension/local-services.mjs +0 -75
  131. package/src/git-exec.js +0 -67
  132. package/src/graph/build-worker.js +0 -49
  133. package/src/graph/builder/go-receiver-resolution.js +0 -112
  134. package/src/graph/builder/js/dynamic-import.js +0 -26
  135. package/src/graph/builder/js/queries.js +0 -48
  136. package/src/graph/builder/lang-csharp.js +0 -40
  137. package/src/graph/builder/lang-css.js +0 -29
  138. package/src/graph/builder/lang-go.js +0 -140
  139. package/src/graph/builder/lang-html.js +0 -29
  140. package/src/graph/builder/lang-java-calls.js +0 -142
  141. package/src/graph/builder/lang-java.js +0 -215
  142. package/src/graph/builder/lang-js.js +0 -291
  143. package/src/graph/builder/lang-python.js +0 -235
  144. package/src/graph/builder/lang-rust-calls.js +0 -63
  145. package/src/graph/builder/lang-rust.js +0 -299
  146. package/src/graph/builder/lang-solidity.js +0 -126
  147. package/src/graph/builder/lang-sql.js +0 -263
  148. package/src/graph/builder/pass2-resolution.js +0 -81
  149. package/src/graph/builder/spec-pkg.js +0 -87
  150. package/src/graph/community.js +0 -27
  151. package/src/graph/edge-provenance.js +0 -31
  152. package/src/graph/file-lock.js +0 -69
  153. package/src/graph/freshness-probe.js +0 -142
  154. package/src/graph/graph-filter.js +0 -63
  155. package/src/graph/incremental-refresh.js +0 -235
  156. package/src/graph/internal-builder.barrels.js +0 -235
  157. package/src/graph/internal-builder.build.js +0 -300
  158. package/src/graph/internal-builder.java.js +0 -33
  159. package/src/graph/internal-builder.js +0 -12
  160. package/src/graph/internal-builder.langs.js +0 -157
  161. package/src/graph/internal-builder.pass2.js +0 -163
  162. package/src/graph/internal-builder.resolvers.js +0 -286
  163. package/src/graph/layout.js +0 -51
  164. package/src/graph/node-id.js +0 -7
  165. package/src/graph/parser-artifact-boundary.js +0 -55
  166. package/src/graph/relations.js +0 -4
  167. package/src/graph/repo-registry.js +0 -124
  168. package/src/graph/resolvers/rust.js +0 -117
  169. package/src/infra/infra-items.js +0 -255
  170. package/src/infra/infra-registry.js +0 -184
  171. package/src/infra/infra.detect.js +0 -119
  172. package/src/infra/infra.js +0 -38
  173. package/src/infra/infra.match.js +0 -102
  174. package/src/infra/infra.scan.js +0 -93
  175. package/src/mcp/actions/graph-lifecycle.mjs +0 -148
  176. package/src/mcp/architecture-bootstrap.mjs +0 -168
  177. package/src/mcp/architecture-starter.mjs +0 -234
  178. package/src/mcp/catalog.mjs +0 -233
  179. package/src/mcp/company-contract-page.mjs +0 -142
  180. package/src/mcp/company-contract-reconcile.mjs +0 -87
  181. package/src/mcp/company-contract-verdict.mjs +0 -42
  182. package/src/mcp/evidence/bun-lock-graph.mjs +0 -209
  183. package/src/mcp/evidence/duplicate-member-order.mjs +0 -8
  184. package/src/mcp/evidence/package-graph-common.mjs +0 -115
  185. package/src/mcp/evidence/package-lock-graph.mjs +0 -92
  186. package/src/mcp/evidence-snapshot.architecture.mjs +0 -80
  187. package/src/mcp/evidence-snapshot.common.mjs +0 -158
  188. package/src/mcp/evidence-snapshot.duplicates.mjs +0 -213
  189. package/src/mcp/evidence-snapshot.health.mjs +0 -102
  190. package/src/mcp/evidence-snapshot.inventory.mjs +0 -148
  191. package/src/mcp/evidence-snapshot.mjs +0 -50
  192. package/src/mcp/evidence-snapshot.package-graph.mjs +0 -34
  193. package/src/mcp/evidence-snapshot.structure.mjs +0 -84
  194. package/src/mcp/extension-api.mjs +0 -77
  195. package/src/mcp/git-output.mjs +0 -7
  196. package/src/mcp/graph/context-core.mjs +0 -111
  197. package/src/mcp/graph/context-seeds.mjs +0 -207
  198. package/src/mcp/graph/context-state.mjs +0 -85
  199. package/src/mcp/graph/reverse-reach.mjs +0 -42
  200. package/src/mcp/graph/tools-core.mjs +0 -143
  201. package/src/mcp/graph/tools-query.mjs +0 -276
  202. package/src/mcp/graph-context.mjs +0 -5
  203. package/src/mcp/graph-diff.mjs +0 -218
  204. package/src/mcp/health/audit-format.mjs +0 -199
  205. package/src/mcp/health/audit.mjs +0 -174
  206. package/src/mcp/health/dead-code.mjs +0 -110
  207. package/src/mcp/health/duplicates.mjs +0 -85
  208. package/src/mcp/health/endpoints.mjs +0 -71
  209. package/src/mcp/health/structure.mjs +0 -219
  210. package/src/mcp/runtime-version.mjs +0 -31
  211. package/src/mcp/server/auto-refresh.mjs +0 -66
  212. package/src/mcp/server/runtime-config.mjs +0 -43
  213. package/src/mcp/server/shutdown.mjs +0 -40
  214. package/src/mcp/staleness-notice.mjs +0 -20
  215. package/src/mcp/sync/evidence-architecture.mjs +0 -54
  216. package/src/mcp/sync/evidence-common.mjs +0 -88
  217. package/src/mcp/sync/evidence-duplicates.mjs +0 -97
  218. package/src/mcp/sync/evidence-health.mjs +0 -56
  219. package/src/mcp/sync/evidence-packages.mjs +0 -95
  220. package/src/mcp/sync/payload-common.mjs +0 -97
  221. package/src/mcp/sync/payload-v2.mjs +0 -54
  222. package/src/mcp/sync/payload-v3.mjs +0 -79
  223. package/src/mcp/sync-evidence.mjs +0 -23
  224. package/src/mcp/sync-payload.mjs +0 -70
  225. package/src/mcp/tool-result.mjs +0 -54
  226. package/src/mcp/tools-actions.mjs +0 -11
  227. package/src/mcp/tools-architecture.mjs +0 -177
  228. package/src/mcp/tools-company.mjs +0 -251
  229. package/src/mcp/tools-context.mjs +0 -222
  230. package/src/mcp/tools-endpoints.mjs +0 -207
  231. package/src/mcp/tools-graph-hubs.mjs +0 -78
  232. package/src/mcp/tools-graph.mjs +0 -17
  233. package/src/mcp/tools-health.mjs +0 -24
  234. package/src/mcp/tools-history.mjs +0 -28
  235. package/src/mcp/tools-impact-change.mjs +0 -220
  236. package/src/mcp/tools-impact-precision.mjs +0 -89
  237. package/src/mcp/tools-impact.mjs +0 -169
  238. package/src/mcp/tools-source.mjs +0 -238
  239. package/src/mcp/tools-verified-change.mjs +0 -200
  240. package/src/mcp-rg.mjs +0 -50
  241. package/src/mcp-runtime.mjs +0 -2
  242. package/src/mcp-server.mjs +0 -298
  243. package/src/mcp-source-tools.mjs +0 -163
  244. package/src/path-classification.js +0 -220
  245. package/src/path-ignore.js +0 -69
  246. package/src/precision/lsp-client/constants.js +0 -12
  247. package/src/precision/lsp-client/environment.js +0 -20
  248. package/src/precision/lsp-client/errors.js +0 -15
  249. package/src/precision/lsp-client/lifecycle.js +0 -114
  250. package/src/precision/lsp-client/message-parser.js +0 -81
  251. package/src/precision/lsp-client/protocol.js +0 -212
  252. package/src/precision/lsp-client/registry.js +0 -59
  253. package/src/precision/lsp-client/repo-uri.js +0 -60
  254. package/src/precision/lsp-client/stdio-client.js +0 -140
  255. package/src/precision/lsp-client.js +0 -10
  256. package/src/precision/lsp-overlay/budget-policy.js +0 -78
  257. package/src/precision/lsp-overlay/build.js +0 -261
  258. package/src/precision/lsp-overlay/contract.js +0 -61
  259. package/src/precision/lsp-overlay/reference-results.js +0 -108
  260. package/src/precision/lsp-overlay/semantic-inputs.js +0 -62
  261. package/src/precision/lsp-overlay/source-session.js +0 -142
  262. package/src/precision/lsp-overlay/store.js +0 -150
  263. package/src/precision/lsp-overlay/target-index.js +0 -152
  264. package/src/precision/lsp-overlay/target-query.js +0 -55
  265. package/src/precision/lsp-overlay.js +0 -11
  266. package/src/precision/symbol-query.js +0 -224
  267. package/src/precision/typescript-lsp-provider.js +0 -12
  268. package/src/precision/typescript-provider/client.js +0 -89
  269. package/src/precision/typescript-provider/discovery.js +0 -124
  270. package/src/precision/typescript-provider/isolated-runtime.js +0 -39
  271. package/src/precision/typescript-provider/project-host.js +0 -254
  272. package/src/precision/typescript-provider/project-safety.js +0 -166
  273. package/src/precision/typescript-provider/reference-usage.js +0 -53
  274. package/src/process.js +0 -95
  275. package/src/repo-path.js +0 -53
  276. package/src/scan/discover.inventory.js +0 -78
  277. package/src/scan/discover.js +0 -5
  278. package/src/scan/discover.list.js +0 -79
  279. package/src/scan/discover.stack.js +0 -227
  280. package/src/scan/search.core.js +0 -24
  281. package/src/scan/search.git.js +0 -102
  282. package/src/scan/search.js +0 -9
  283. package/src/scan/search.node.js +0 -83
  284. package/src/scan/search.preview.js +0 -49
  285. package/src/scan/search.rg.js +0 -145
  286. package/src/security/advisory-store.js +0 -172
  287. package/src/security/installed-jvm-rust.js +0 -46
  288. package/src/security/installed.js +0 -280
  289. package/src/security/malware-file-heuristics.js +0 -121
  290. package/src/security/malware-heuristics.exclusions.js +0 -134
  291. package/src/security/malware-heuristics.js +0 -15
  292. package/src/security/malware-heuristics.roots.js +0 -145
  293. package/src/security/malware-heuristics.scan.js +0 -89
  294. package/src/security/malware-heuristics.sweep.js +0 -122
  295. package/src/security/malware-scoring.js +0 -105
  296. package/src/security/match.js +0 -85
  297. package/src/security/registry-sig.classify.js +0 -137
  298. package/src/security/registry-sig.js +0 -18
  299. package/src/security/registry-sig.rules.js +0 -192
  300. package/src/security/rust-advisory-report.js +0 -60
  301. package/src/security/typosquat.js +0 -81
  302. package/src/util.js +0 -40
  303. package/src/version.js +0 -7
@@ -1,162 +0,0 @@
1
- import {makeFinding} from '../findings.js'
2
- import {formatRepresentativeCycle} from '../cycle-route.js'
3
- import {
4
- buildFileImportGraph,
5
- checkBoundaries,
6
- findOrphans,
7
- findSccs,
8
- representativeCycle,
9
- } from './dependency-graph.js'
10
-
11
- const MAX_CYCLE_FINDINGS = 50
12
- const MAX_BOUNDARY_FINDINGS = 100
13
-
14
- const edgeCountIn = (component, edges) => {
15
- const inside = new Set(component)
16
- return edges.reduce((count, [source, target]) => count + (inside.has(source) && inside.has(target) ? 1 : 0), 0)
17
- }
18
-
19
- function runtimeCycleFinding(adjacency, component) {
20
- const cycle = representativeCycle(adjacency, component)
21
- const cycleRoute = formatRepresentativeCycle(cycle)
22
- return makeFinding({
23
- category: 'structure',
24
- rule: 'circular-dep',
25
- severity: component.length > 4 ? 'high' : 'medium',
26
- confidence: 'high',
27
- title: `Circular dependency: ${component.length} files`,
28
- detail: `${cycleRoute}${component.length + 1 > cycle.length ? ` (representative loop; the tangle spans ${component.length} files)` : ''}. Break the cycle by extracting the shared piece or inverting one import.`,
29
- cycleRoute,
30
- cycleMembers: [...component].sort(),
31
- file: cycle[0],
32
- graphNodeId: cycle[0],
33
- evidence: cycle.map((file) => ({file, line: 0, snippet: ''})),
34
- source: 'internal',
35
- fixHint: 'extract the shared code into a module both sides import, or invert the weaker dependency',
36
- })
37
- }
38
-
39
- function compileTimeFinding(adjacency, component, runtimeComponents, edges) {
40
- const cycle = representativeCycle(adjacency, component)
41
- const cycleRoute = formatRepresentativeCycle(cycle)
42
- const runtimeInside = edgeCountIn(component, edges.runtime)
43
- const typeInside = edgeCountIn(component, edges.typeOnly)
44
- const compileInside = edgeCountIn(component, edges.compileOnly)
45
- const containsRuntimeCycle = runtimeComponents.some((runtime) => runtime.every((file) => component.includes(file)))
46
- const typeSpecific = compileInside === 0
47
- return makeFinding({
48
- category: 'structure',
49
- rule: typeSpecific ? 'type-coupling' : 'compile-time-coupling',
50
- severity: 'info',
51
- confidence: 'high',
52
- title: `${containsRuntimeCycle
53
- ? (typeSpecific ? 'Type imports expand dependency coupling' : 'Compile-time edges expand dependency coupling')
54
- : (typeSpecific ? 'Type-induced dependency cycle (no runtime cycle)' : 'Compile-time dependency cycle (no runtime cycle)')}: ${component.length} files`,
55
- detail: `${cycleRoute}. This strongly-connected group needs compile-time-only edges to close; it contains ${runtimeInside} runtime edge(s), ${typeInside} type-only edge(s), and ${compileInside} compile-only edge(s)${containsRuntimeCycle ? ', with a smaller runtime cycle reported separately' : ', while its runtime import graph is acyclic'}. Treat this as design coupling, not an initialization-order failure.`,
56
- cycleRoute,
57
- cycleMembers: [...component].sort(),
58
- file: cycle[0],
59
- graphNodeId: cycle[0],
60
- evidence: cycle.map((file) => ({file, line: 0, snippet: ''})),
61
- source: 'internal',
62
- fixHint: 'review the compile-time ownership only if the coupling impedes changes; no runtime-cycle fix is required',
63
- })
64
- }
65
-
66
- // Idiomatic Rust module trees close compile-time SCCs by construction: the parent (mod.rs, lib.rs,
67
- // main.rs, or a 2018-edition foo.rs) declares `mod child` while children reach back via super::/crate::.
68
- // Suppress only when every member is a .rs file sitting under one anchor's directory; genuine
69
- // cross-directory .rs cycles keep their findings.
70
- export function isRustModuleTreeComponent(component) {
71
- if (!component.every((file) => String(file).endsWith('.rs'))) return false
72
- return component.some((anchor) => {
73
- const path = String(anchor)
74
- const slash = path.lastIndexOf('/')
75
- const base = path.slice(slash + 1)
76
- const anchorDir = ['mod.rs', 'lib.rs', 'main.rs'].includes(base)
77
- ? (slash >= 0 ? path.slice(0, slash) : '')
78
- : path.slice(0, -'.rs'.length)
79
- return anchorDir !== '' && component.every((member) => member === anchor || String(member).startsWith(`${anchorDir}/`))
80
- })
81
- }
82
-
83
- export function computeStructureFindings(graph, {rules = {}, entrySet = new Set(), externalImportFiles = new Set()} = {}) {
84
- const imports = buildFileImportGraph(graph)
85
- const findings = []
86
- const runtimeComponents = findSccs(imports.adj).sort((a, b) => b.length - a.length)
87
- for (const component of runtimeComponents.slice(0, MAX_CYCLE_FINDINGS)) {
88
- findings.push(runtimeCycleFinding(imports.adj, component))
89
- }
90
-
91
- const runtimeKeys = new Set(runtimeComponents.map((component) => [...component].sort().join('\0')))
92
- const allComponents = findSccs(imports.allAdj).sort((a, b) => b.length - a.length)
93
- const compileTimeCandidates = allComponents.filter((component) => !runtimeKeys.has([...component].sort().join('\0')))
94
- const rustModuleTreeComponents = compileTimeCandidates.filter((component) => isRustModuleTreeComponent(component))
95
- const compileTimeCouplings = compileTimeCandidates.filter((component) => !isRustModuleTreeComponent(component))
96
- for (const component of compileTimeCouplings.slice(0, MAX_CYCLE_FINDINGS)) {
97
- findings.push(compileTimeFinding(imports.allAdj, component, runtimeComponents, {
98
- runtime: imports.edges,
99
- typeOnly: imports.typeOnlyEdges,
100
- compileOnly: imports.compileOnlyEdges,
101
- }))
102
- }
103
- if (runtimeComponents.length > MAX_CYCLE_FINDINGS) findings.push(makeFinding({
104
- category: 'structure', rule: 'circular-dep', severity: 'info', confidence: 'high',
105
- title: `…and ${runtimeComponents.length - MAX_CYCLE_FINDINGS} more dependency cycles`,
106
- detail: `Cycle findings are capped at ${MAX_CYCLE_FINDINGS}; ${runtimeComponents.length} strongly-connected groups exist in total.`,
107
- source: 'internal',
108
- }))
109
-
110
- for (const orphan of findOrphans(graph, {entrySet, externalImportFiles})) findings.push(makeFinding({
111
- category: 'structure',
112
- rule: 'orphan-file',
113
- severity: 'info',
114
- confidence: orphan.importsExternals ? 'low' : 'medium',
115
- title: `Orphan file: ${orphan.file}`,
116
- detail: `No repo file imports it and it imports/calls nothing in the repo${orphan.importsExternals ? ' (it does use npm packages — possibly a standalone script or tool)' : ''}. Possibly dead, possibly an undeclared entry point.`,
117
- file: orphan.file,
118
- graphNodeId: orphan.file,
119
- source: 'internal',
120
- }))
121
-
122
- const violations = checkBoundaries(imports.edges, rules)
123
- for (const item of violations.slice(0, MAX_BOUNDARY_FINDINGS)) findings.push(makeFinding({
124
- category: 'structure',
125
- rule: 'boundary-violation',
126
- severity: ['critical', 'high', 'medium', 'low', 'info'].includes(item.severity) ? item.severity : 'medium',
127
- confidence: 'high',
128
- title: `Boundary violation (${item.name}): ${item.from} → ${item.to}`,
129
- detail: `${item.kind === 'allowedOnly' ? 'Import leaves the allowed set' : 'Forbidden import'}${item.comment ? `: ${item.comment}` : ''}.`,
130
- file: item.from,
131
- graphNodeId: item.from,
132
- evidence: [{file: item.from, line: 0, snippet: `imports ${item.to}`}],
133
- source: 'internal',
134
- }))
135
- if (violations.length > MAX_BOUNDARY_FINDINGS) findings.push(makeFinding({
136
- category: 'structure', rule: 'boundary-violation', severity: 'info', confidence: 'high',
137
- title: `…and ${violations.length - MAX_BOUNDARY_FINDINGS} more boundary violations`,
138
- detail: `Boundary findings are capped at ${MAX_BOUNDARY_FINDINGS}; ${violations.length} edges violate the rules in total.`,
139
- source: 'internal',
140
- }))
141
-
142
- return {
143
- findings,
144
- stats: {
145
- importEdges: imports.allEdges.length,
146
- runtimeImportEdges: imports.edges.length,
147
- typeOnlyImportEdges: imports.typeOnlyEdges.length,
148
- compileOnlyImportEdges: imports.compileOnlyEdges.length,
149
- compileTimeImportEdges: imports.compileTimeEdges.length,
150
- cycles: runtimeComponents.length,
151
- runtimeCycles: runtimeComponents.length,
152
- largestCycle: runtimeComponents[0]?.length || 0,
153
- typeCouplings: compileTimeCouplings.length,
154
- largestTypeCoupling: compileTimeCouplings[0]?.length || 0,
155
- compileTimeCouplings: compileTimeCouplings.length,
156
- largestCompileTimeCoupling: compileTimeCouplings[0]?.length || 0,
157
- rustModuleTreeCouplings: rustModuleTreeComponents.length,
158
- orphans: findings.filter((finding) => finding.rule === 'orphan-file').length,
159
- boundaryViolations: violations.length,
160
- },
161
- }
162
- }
@@ -1,107 +0,0 @@
1
- import {PATH_CLASS_NAMES, PATH_CLASS_TASK_QUERY_TERMS, createPathClassifier, hasPathClass} from '../path-classification.js'
2
-
3
- const words = (value) => new Set(String(value || '').toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$-]{2,}/gu) || [])
4
- const fileOf = (node) => String(node?.source_file || (String(node?.id || '').includes('#') ? String(node.id).split('#')[0] : node?.id || '')).replace(/\\/g, '/')
5
- const isSymbol = (id) => String(id || '').includes('#')
6
-
7
- const INTENT_TRANSLATIONS = [
8
- [/авториз|аутентиф|логин|сесси|токен/iu, 'auth authentication login session token'],
9
- [/маршрут|роут|эндпоинт|апи|http/iu, 'route router endpoint api http'],
10
- [/тест|покрыти/iu, 'test spec coverage verify'],
11
- [/к[эе]ш|хранилищ/iu, 'cache store storage'],
12
- [/баз[аы]|запрос|sql/iu, 'database query sql'],
13
- [/конфиг|настройк/iu, 'config settings configuration'],
14
- [/безопас|вредонос|секрет/iu, 'security malware secret'],
15
- [/зависим|импорт/iu, 'dependency import module'],
16
- [/дублик|клон/iu, 'duplicate clone'],
17
- ]
18
-
19
- export function expandTaskQuery(task) {
20
- const text = String(task || '')
21
- const expansions = INTENT_TRANSLATIONS.filter(([pattern]) => pattern.test(text)).map(([, value]) => value)
22
- return [...new Set([text, ...expansions])].join(' ')
23
- }
24
-
25
- function overlapScore(taskWords, node) {
26
- const haystack = words(`${node?.label || ''} ${node?.id || ''} ${node?.symbol_kind || ''}`)
27
- let score = 0
28
- for (const word of taskWords) if (haystack.has(word)) score += 8
29
- return score
30
- }
31
-
32
- function addCandidate(map, node, score, reason) {
33
- if (!node?.id) return
34
- const id = String(node.id)
35
- const current = map.get(id) || {node, score: 0, reasons: new Set()}
36
- current.score += score
37
- current.reasons.add(reason)
38
- map.set(id, current)
39
- }
40
-
41
- function containedSymbols(g, node) {
42
- if (isSymbol(node?.id)) return [node]
43
- return (g.out.get(String(node?.id)) || [])
44
- .filter((edge) => edge.relation === 'contains')
45
- .map((edge) => g.byId.get(String(edge.id)))
46
- .filter(Boolean)
47
- }
48
-
49
- // Combines intent-expanded search seeds with exact changed symbols. The result deliberately stays
50
- // deterministic and source-free; exact LSP/source evidence is collected by context_bundle later.
51
- export function retrieveTaskContext(g, {
52
- task, semanticSeeds = [], changedSeedIds = [], maxSymbols = 3, repoRoot = null, includeClassified = false,
53
- } = {}) {
54
- const expandedTask = expandTaskQuery(task)
55
- const taskWords = words(expandedTask)
56
- const requestedClasses = new Set(Object.entries(PATH_CLASS_TASK_QUERY_TERMS)
57
- .filter(([, terms]) => terms.some((term) => taskWords.has(term)))
58
- .map(([name]) => name))
59
- if (requestedClasses.has('test')) requestedClasses.add('e2e')
60
- if (requestedClasses.has('e2e')) requestedClasses.add('test')
61
- const classifier = createPathClassifier(repoRoot)
62
- const classificationCache = new Map()
63
- const changedFiles = new Set((changedSeedIds || []).map((id) => fileOf(g.byId.get(String(id)) || {id})))
64
- const pathAllowed = (node) => {
65
- const file = fileOf(node)
66
- if (!file || changedFiles.has(file) || includeClassified === true) return true
67
- // Node-level test surfaces (Rust #[cfg(test)]) follow the same production-first policy.
68
- if (node?.test_surface === true && !requestedClasses.has('test')) return false
69
- if (!classificationCache.has(file)) classificationCache.set(file, classifier.explain(file, {content: ''}))
70
- const info = classificationCache.get(file)
71
- const classes = PATH_CLASS_NAMES.filter((name) => hasPathClass(info, name))
72
- if (!info?.excluded && !classes.length) return true
73
- return classes.some((name) => requestedClasses.has(name))
74
- }
75
- const candidates = new Map()
76
- for (const id of changedSeedIds || []) {
77
- const node = g.byId.get(String(id))
78
- if (node) addCandidate(candidates, node, 100 + overlapScore(taskWords, node), 'changed-symbol')
79
- }
80
- for (const seed of semanticSeeds || []) addCandidate(candidates, seed, 45 + overlapScore(taskWords, seed), 'task-intent')
81
-
82
- for (const candidate of [...candidates.values()]) {
83
- for (const symbol of containedSymbols(g, candidate.node)) {
84
- const degree = (g.out.get(String(symbol.id)) || []).length + (g.inn.get(String(symbol.id)) || []).length
85
- addCandidate(candidates, symbol, 22 + overlapScore(taskWords, symbol) + Math.min(12, degree), `symbol-in:${fileOf(candidate.node)}`)
86
- }
87
- }
88
-
89
- const symbolCandidates = [...candidates.values()].filter((item) => isSymbol(item.node.id))
90
- const ranked = symbolCandidates
91
- .filter((item) => pathAllowed(item.node))
92
- .sort((left, right) => right.score - left.score || String(left.node.id).localeCompare(String(right.node.id)))
93
- const limit = Math.max(1, Math.min(5, Number(maxSymbols) || 3))
94
- return {
95
- method: 'intent-expanded graph retrieval + exact changed-symbol seeds',
96
- status: ranked.length ? 'COMPLETE' : 'NO_SYMBOLS',
97
- selected: ranked.slice(0, limit).map((item) => ({
98
- id: String(item.node.id), label: item.node.label || String(item.node.id), file: fileOf(item.node),
99
- kind: item.node.symbol_kind || null, score: item.score, reasons: [...item.reasons].sort(),
100
- })),
101
- candidateCount: ranked.length,
102
- suppressedClassified: symbolCandidates.length - ranked.length,
103
- pathPolicy: includeClassified === true
104
- ? {mode: 'ALL_CLASSIFIED'}
105
- : {mode: 'PRODUCTION_FIRST', requestedClasses: [...requestedClasses].sort(), changedFilesPinned: changedFiles.size},
106
- }
107
- }
@@ -1,224 +0,0 @@
1
- import { createRepoBoundary } from "../repo-path.js";
2
- import { lineNumberAt, uniqueBy } from "../util.js";
3
- import { listRepoFiles, readRepoText } from "./internal-audit/repo-files.js";
4
- import { affectedForEndpoint, reverseRuntimeImports } from "./http-contracts/graph-context.js";
5
- import { loadTransportRuntimeEvidence } from "./transport-runtime-evidence.js";
6
-
7
- const TEST_RE = /(^|\/)(?:test|tests|__tests__|spec|e2e|fixtures?)(\/|$)|[._-](?:test|spec)\.[a-z0-9]+$/i;
8
- const SOURCE_RE = /\.(?:[cm]?[jt]sx?|py|go|java|rs|cs|proto|graphql|gql)$/i;
9
- const lineAt = lineNumberAt;
10
- const norm = (value) => String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "");
11
-
12
- function sourcesFor(descriptor, { includeTests, maxFiles }) {
13
- const boundary = createRepoBoundary(descriptor.repoRoot);
14
- if (!boundary.root) return { sources: [], reasons: [`${descriptor.id}: repository boundary is unreadable`] };
15
- const candidates = listRepoFiles(boundary.root).filter((file) => SOURCE_RE.test(file) && (includeTests || !TEST_RE.test(file))).sort();
16
- const sources = [];
17
- for (const file of candidates.slice(0, maxFiles)) {
18
- const text = readRepoText(boundary, file);
19
- if (text != null) sources.push({ file, text });
20
- }
21
- return { sources, reasons: candidates.length > maxFiles ? [`${descriptor.id}: transport file cap reached`] : [] };
22
- }
23
-
24
- function graphQlEvidence(source, role) {
25
- const contracts = [], uncertain = [];
26
- for (const schema of source.text.matchAll(/\btype\s+(Query|Mutation|Subscription)\s*(?:extends\s+\w+\s*)?\{([\s\S]*?)\}/gi)) {
27
- for (const field of schema[2].matchAll(/^\s*([A-Za-z_]\w*)\s*(?:\([^)]*\))?\s*:/gm)) contracts.push({
28
- transport: "graphql", side: "server", operation: schema[1].toUpperCase(), name: field[1], file: source.file,
29
- line: lineAt(source.text, schema.index + schema[0].indexOf(field[0])), detector: "graphql-schema",
30
- });
31
- }
32
- for (const operation of source.text.matchAll(/\b(query|mutation|subscription)\s*(?:[A-Za-z_]\w*\s*)?(?:\([^)]*\)\s*)?\{\s*([A-Za-z_]\w*)/gi)) contracts.push({
33
- transport: "graphql", side: role === "backend" ? "server-call" : "client", operation: operation[1].toUpperCase(), name: operation[2],
34
- file: source.file, line: lineAt(source.text, operation.index), detector: "graphql-operation",
35
- });
36
- for (const dynamic of source.text.matchAll(/\b(?:gql|graphql)\s*(?:\(|`)\s*\$\{|\b(?:query|mutate)\s*\(\s*(?!["'`])/gi)) uncertain.push({
37
- transport: "graphql", file: source.file, line: lineAt(source.text, dynamic.index), reason: "GraphQL document or operation is runtime-computed",
38
- });
39
- return { contracts, uncertain };
40
- }
41
-
42
- function grpcEvidence(source, role) {
43
- const contracts = [], uncertain = [], aliases = new Map();
44
- for (const service of source.text.matchAll(/\bservice\s+([A-Za-z_]\w*)\s*\{([\s\S]*?)\}/g)) {
45
- for (const rpc of service[2].matchAll(/\brpc\s+([A-Za-z_]\w*)\s*\(/g)) contracts.push({
46
- transport: "grpc", side: "server", service: service[1], name: rpc[1], file: source.file,
47
- line: lineAt(source.text, service.index + service[0].indexOf(rpc[0])), detector: "proto-service",
48
- });
49
- }
50
- const aliasPatterns = [
51
- /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*new\s+([A-Za-z_]\w*(?:Service)?Client)\b/g,
52
- /\b([A-Za-z_]\w*)\s*=\s*([A-Za-z_]\w*Stub)\s*\(/g,
53
- /\b([A-Za-z_]\w*)\s*:?=\s*\w*\.New([A-Za-z_]\w*)Client\s*\(/g,
54
- /\b(?:[A-Za-z_]\w*\.)*([A-Za-z_]\w*(?:Blocking|Future|Async)?Stub)\s+([A-Za-z_]\w*)\s*[=;]/g,
55
- ];
56
- for (const [index, pattern] of aliasPatterns.entries()) for (const match of source.text.matchAll(pattern)) {
57
- const alias = index === 3 ? match[2] : match[1];
58
- const type = index === 3 ? match[1] : match[2];
59
- aliases.set(alias, type.replace(/(?:Service)?Client$|(?:Blocking|Future|Async)?Stub$/i, ""));
60
- }
61
- for (const call of source.text.matchAll(/\b([A-Za-z_$][\w$]*)\s*(?:\.|->)\s*([A-Za-z_]\w*)\s*\(/g)) {
62
- if (!aliases.has(call[1])) continue;
63
- contracts.push({ transport: "grpc", side: role === "backend" ? "server-call" : "client", service: aliases.get(call[1]), name: call[2], file: source.file, line: lineAt(source.text, call.index), detector: "grpc-stub-call" });
64
- }
65
- for (const dynamic of source.text.matchAll(/\b(?:ServerReflection|ProtoReflection|grpc\.reflection|Class\.forName|Method\.invoke|reflect\.Value|dynamicStub)\b/g)) uncertain.push({
66
- transport: "grpc", file: source.file, line: lineAt(source.text, dynamic.index), reason: "gRPC/reflection target is runtime-resolved",
67
- });
68
- return { contracts, uncertain };
69
- }
70
-
71
- function eventEvidence(source, role) {
72
- const contracts = [], uncertain = [];
73
- const add = (side, kind, match, topicIndex = 2) => contracts.push({
74
- transport: "event", side, kind, name: match[topicIndex], file: source.file, line: lineAt(source.text, match.index), detector: "static-topic",
75
- });
76
- const subscriptions = [
77
- /\b(?:consumer|kafka|bus|events?|eventBus)\s*(?:\.|->)\s*(subscribe|on|consume)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
78
- /@KafkaListener\s*\([^)]*\btopics?\s*=\s*["']([^"']+)["']/gi,
79
- /\bsubscribe\s*\(\s*\{\s*topic\s*:\s*["'`]([^"'`]+)["'`]/gi,
80
- ];
81
- for (const [index, pattern] of subscriptions.entries()) for (const match of source.text.matchAll(pattern)) add("subscriber", index === 0 ? match[1] : "subscribe", match, index === 0 ? 2 : 1);
82
- const publications = [
83
- /\b(?:producer|kafka|bus|events?|eventBus|kafkaTemplate)\s*(?:\.|->)\s*(publish|emit|send|produce)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
84
- /\b(?:producer|kafka)\s*(?:\.|->)\s*send\s*\(\s*\{\s*topic\s*:\s*["'`]([^"'`]+)["'`]/gi,
85
- ];
86
- for (const [index, pattern] of publications.entries()) for (const match of source.text.matchAll(pattern)) add("publisher", index === 0 ? match[1] : "send", match, index === 0 ? 2 : 1);
87
- for (const dynamic of source.text.matchAll(/\b(?:subscribe|publish|emit|consume|produce)\s*\(\s*(?!["'`{])([A-Za-z_$][\w$]*)/gi)) uncertain.push({
88
- transport: "event", file: source.file, line: lineAt(source.text, dynamic.index), reason: `Event topic is runtime-computed (${dynamic[1]})`, role,
89
- });
90
- return { contracts, uncertain };
91
- }
92
-
93
- const contractIdentity = (item) => `${item.transport}|${item.side}|${norm(item.service)}|${item.operation || ""}|${item.name}`;
94
-
95
- function mergeRuntimeContracts(staticContracts, observations) {
96
- const contracts = staticContracts.map((item) => ({ ...item, evidence: ["STATIC"] }));
97
- const byIdentity = new Map(contracts.map((item) => [contractIdentity(item), item]));
98
- for (const observation of observations) {
99
- const key = contractIdentity(observation);
100
- const existing = byIdentity.get(key);
101
- if (existing) {
102
- existing.runtimeObserved = true;
103
- existing.observedCount = (existing.observedCount || 0) + observation.observedCount;
104
- existing.evidence = ["STATIC", "RUNTIME"];
105
- continue;
106
- }
107
- const added = { ...observation, evidence: ["RUNTIME"] };
108
- contracts.push(added); byIdentity.set(key, added);
109
- }
110
- return contracts;
111
- }
112
-
113
- function sameRuntimeLocation(uncertain, observation) {
114
- return observation.file && observation.line && observation.transport === uncertain.transport &&
115
- observation.file === uncertain.file && observation.line === uncertain.line;
116
- }
117
-
118
- function detect(descriptor, role, options) {
119
- const loaded = sourcesFor(descriptor, options), contracts = [], uncertain = [];
120
- for (const source of loaded.sources) {
121
- for (const detector of [graphQlEvidence, grpcEvidence, eventEvidence]) {
122
- const result = detector(source, role);
123
- contracts.push(...result.contracts); uncertain.push(...result.uncertain);
124
- }
125
- }
126
- const runtime = loadTransportRuntimeEvidence(descriptor, {
127
- file: options.runtimeEvidenceFiles?.[descriptor.id],
128
- maxAgeHours: options.runtimeEvidenceMaxAgeHours,
129
- transport: options.transport,
130
- now: options.now,
131
- });
132
- const runtimeContracts = runtime.observations.filter((item) => options.transport === "all" || item.transport === options.transport);
133
- const resolvedRuntime = uncertain.filter((item) => runtimeContracts.some((observation) => sameRuntimeLocation(item, observation)));
134
- const unresolved = uncertain.filter((item) => !runtimeContracts.some((observation) => sameRuntimeLocation(item, observation)));
135
- return {
136
- contracts: mergeRuntimeContracts(
137
- uniqueBy(contracts, (item) => `${item.transport}|${item.side}|${item.service || ""}|${item.operation || ""}|${item.name}|${item.file}|${item.line}`),
138
- runtimeContracts,
139
- ),
140
- uncertain: uniqueBy(unresolved, (item) => `${item.transport}|${item.file}|${item.line}|${item.reason}`),
141
- resolvedRuntime: uniqueBy(resolvedRuntime, (item) => `${item.transport}|${item.file}|${item.line}|${item.reason}`),
142
- reasons: [...loaded.reasons, ...runtime.reasons],
143
- runtime,
144
- filesScanned: loaded.sources.length,
145
- };
146
- }
147
-
148
- function contractMatch(server, caller, backendServers) {
149
- if (server.transport !== caller.transport) return null;
150
- const runtime = server.runtimeObserved || caller.runtimeObserved;
151
- const match = (kind) => ({ confidence: "high", kind, evidence: runtime ? "RUNTIME_OBSERVED" : "STATIC" });
152
- if (server.transport === "graphql" && caller.side === "client" && server.operation === caller.operation && server.name === caller.name) return match("operation-field");
153
- if (server.transport === "grpc" && caller.side === "client" && norm(server.name) === norm(caller.name)) {
154
- if (caller.service && norm(server.service) === norm(caller.service)) return match("service-method");
155
- const sameMethod = backendServers.filter((item) => item.transport === "grpc" && norm(item.name) === norm(caller.name));
156
- if (!caller.service && sameMethod.length === 1) return { confidence: "medium", kind: "unique-method", evidence: runtime ? "RUNTIME_OBSERVED" : "STATIC" };
157
- }
158
- if (server.transport === "event" && server.name === caller.name && server.side !== caller.side) return match("topic-direction");
159
- return null;
160
- }
161
-
162
- export function analyzeTransportContracts(input = {}) {
163
- const transport = ["all", "graphql", "grpc", "event"].includes(input.transport) ? input.transport : "all";
164
- const options = {
165
- includeTests: input.includeTests === true,
166
- maxFiles: Math.max(1, Math.min(10_000, Number(input.maxFiles) || 3_000)),
167
- transport,
168
- runtimeEvidenceFiles: input.runtimeEvidenceFiles || {},
169
- runtimeEvidenceMaxAgeHours: input.runtimeEvidenceMaxAgeHours,
170
- now: input.now,
171
- };
172
- const backend = detect(input.backend, "backend", options);
173
- const clients = (input.clients || []).map((descriptor) => ({ descriptor, evidence: detect(descriptor, "client", options), reverse: reverseRuntimeImports(descriptor.graph) }));
174
- const selected = (item) => transport === "all" || item.transport === transport;
175
- const backendContracts = backend.contracts.filter(selected);
176
- const servers = backendContracts.filter((item) => item.side === "server" || item.transport === "event");
177
- const results = [];
178
- for (const server of servers) {
179
- const callsites = [];
180
- for (const client of clients) for (const caller of client.evidence.contracts.filter(selected)) {
181
- const match = contractMatch(server, caller, servers);
182
- if (!match) continue;
183
- callsites.push({ clientRepo: client.descriptor.id, file: caller.file, line: caller.line, detector: caller.detector, match, runtimeObserved: caller.runtimeObserved === true, observedCount: caller.observedCount });
184
- }
185
- const affected = affectedForEndpoint(callsites, clients.map((item) => ({ id: item.descriptor.id, reverse: item.reverse })), {
186
- maxImpactDepth: Math.max(0, Math.min(5, Number(input.maxImpactDepth) || 2)),
187
- maxAffectedFiles: Math.max(1, Math.min(500, Number(input.maxAffectedFiles) || 100)), maxScreens: 50, maxModules: 50,
188
- });
189
- results.push({ ...server, callsites, affected, liveness: callsites.length ? "NOT_DEAD_EXTERNAL_USE" : "UNKNOWN" });
190
- }
191
- const uncertain = [
192
- ...backend.uncertain.map((item) => ({ repository: input.backend.id, ...item })),
193
- ...clients.flatMap((item) => item.evidence.uncertain.map((entry) => ({ repository: item.descriptor.id, ...entry }))),
194
- ].filter(selected);
195
- const reasons = [...backend.reasons, ...clients.flatMap((item) => item.evidence.reasons)];
196
- if (uncertain.length) reasons.push(`${uncertain.length} dynamic/reflection contract expression(s) remain UNKNOWN`);
197
- const runtimeReports = [
198
- { repository: input.backend.id, ...backend.runtime },
199
- ...clients.map((item) => ({ repository: item.descriptor.id, ...item.evidence.runtime })),
200
- ];
201
- const resolvedRuntime = backend.resolvedRuntime.length + clients.reduce((sum, item) => sum + item.evidence.resolvedRuntime.length, 0);
202
- return {
203
- transportContractsV: 2,
204
- transport,
205
- status: reasons.length ? "PARTIAL" : "COMPLETE",
206
- completeness: { complete: reasons.length === 0, reasons: [...new Set(reasons)] },
207
- totals: {
208
- contracts: results.length,
209
- matches: results.reduce((sum, item) => sum + item.callsites.length, 0),
210
- uncertain: uncertain.length,
211
- filesScanned: backend.filesScanned + clients.reduce((sum, item) => sum + item.evidence.filesScanned, 0),
212
- runtimeObservations: runtimeReports.reduce((sum, item) => sum + item.observations.length, 0),
213
- runtimeResolved: resolvedRuntime,
214
- runtimeReportsComplete: runtimeReports.filter((item) => item.status === "COMPLETE").length,
215
- },
216
- contracts: results,
217
- uncertain: uncertain.slice(0, 200),
218
- runtimeEvidence: {
219
- status: runtimeReports.every((item) => item.status === "COMPLETE") ? "COMPLETE" : "PARTIAL",
220
- reports: runtimeReports.map(({ observations, reasons: reportReasons, ...report }) => ({ ...report, observationCount: observations.length, reasons: reportReasons })),
221
- resolvedUnknowns: resolvedRuntime,
222
- },
223
- };
224
- }
@@ -1,155 +0,0 @@
1
- import { readFileSync, statSync } from "node:fs";
2
- import { isAbsolute, relative, resolve } from "node:path";
3
- import { createRepoBoundary, isPathInside } from "../repo-path.js";
4
-
5
- const TRANSPORT_RUNTIME_SCHEMA = "weavatrix.transport-runtime.v1";
6
- const TRANSPORTS = ["graphql", "grpc", "event"];
7
- const DEFAULT_REPORTS = [
8
- ".weavatrix/transport-runtime.json",
9
- ".weavatrix/reports/transport-runtime.json",
10
- ];
11
- const MAX_REPORT_BYTES = 2 * 1024 * 1024;
12
- const MAX_OBSERVATIONS = 10_000;
13
-
14
- const text = (value, max = 256) => typeof value === "string" ? value.trim().slice(0, max) : "";
15
- const number = (value) => Number.isFinite(Number(value)) ? Number(value) : undefined;
16
-
17
- function requestedTransports(transport) {
18
- return TRANSPORTS.includes(transport) ? [transport] : TRANSPORTS;
19
- }
20
-
21
- function reportPath(descriptor, candidate) {
22
- const boundary = createRepoBoundary(descriptor.repoRoot);
23
- const resolved = boundary.resolve(candidate);
24
- return resolved.ok ? { boundary, path: resolved.path } : { boundary, reason: resolved.reason };
25
- }
26
-
27
- function safeSourceFile(descriptor, value) {
28
- const raw = text(value, 1024).replace(/\\/g, "/");
29
- if (!raw || raw.includes("\0")) return undefined;
30
- if (!isAbsolute(raw) && !raw.startsWith("../") && !raw.includes("/../")) return raw.replace(/^\.\//, "");
31
- const root = resolve(descriptor.repoRoot);
32
- const target = resolve(raw);
33
- return isPathInside(root, target) ? relative(root, target).replace(/\\/g, "/") : undefined;
34
- }
35
-
36
- function attributeValue(attribute) {
37
- const value = attribute?.value ?? attribute;
38
- for (const key of ["stringValue", "intValue", "doubleValue", "boolValue"]) {
39
- if (value?.[key] !== undefined) return value[key];
40
- }
41
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? value : undefined;
42
- }
43
-
44
- function attributes(input) {
45
- const out = new Map();
46
- for (const item of Array.isArray(input) ? input : []) if (typeof item?.key === "string") out.set(item.key, attributeValue(item));
47
- return out;
48
- }
49
-
50
- function spanSide(span, transport) {
51
- const kind = String(span?.kind ?? "").toUpperCase();
52
- const numeric = Number(span?.kind);
53
- if (transport === "event") {
54
- if (kind.includes("PRODUCER") || numeric === 4) return "publisher";
55
- if (kind.includes("CONSUMER") || numeric === 5) return "subscriber";
56
- }
57
- if (kind.includes("SERVER") || numeric === 2) return "server";
58
- if (kind.includes("CLIENT") || numeric === 3) return "client";
59
- return "";
60
- }
61
-
62
- function observationFromSpan(descriptor, span) {
63
- const attrs = attributes(span?.attributes);
64
- const common = {
65
- file: safeSourceFile(descriptor, attrs.get("code.file.path") ?? attrs.get("code.filepath")),
66
- line: number(attrs.get("code.line.number") ?? attrs.get("code.lineno")),
67
- observedCount: 1,
68
- detector: "otlp-span",
69
- };
70
- const rpcSystem = text(attrs.get("rpc.system")).toLowerCase();
71
- if (rpcSystem === "grpc") {
72
- const fallback = text(span?.name).split("/").filter(Boolean);
73
- return { ...common, transport: "grpc", side: spanSide(span, "grpc"), service: text(attrs.get("rpc.service")) || fallback.at(-2), name: text(attrs.get("rpc.method")) || fallback.at(-1) };
74
- }
75
- const graphOperation = text(attrs.get("graphql.operation.type")).toUpperCase();
76
- const graphField = text(attrs.get("graphql.field.name") ?? attrs.get("graphql.field"));
77
- if (graphOperation || graphField) return { ...common, transport: "graphql", side: spanSide(span, "graphql"), operation: graphOperation, name: graphField };
78
- const messagingSystem = text(attrs.get("messaging.system")).toLowerCase();
79
- const destination = text(attrs.get("messaging.destination.name") ?? attrs.get("messaging.destination"));
80
- if (messagingSystem || destination) return { ...common, transport: "event", side: spanSide(span, "event"), kind: text(attrs.get("messaging.operation.type") ?? attrs.get("messaging.operation")), name: destination };
81
- return null;
82
- }
83
-
84
- function otlpObservations(descriptor, report) {
85
- const root = report.otlp && typeof report.otlp === "object" ? report.otlp : report;
86
- const out = [];
87
- for (const resource of Array.isArray(root.resourceSpans) ? root.resourceSpans : []) {
88
- const scopes = resource.scopeSpans ?? resource.instrumentationLibrarySpans ?? [];
89
- for (const scope of scopes) for (const span of Array.isArray(scope.spans) ? scope.spans : []) {
90
- const observation = observationFromSpan(descriptor, span);
91
- if (observation) out.push(observation);
92
- }
93
- }
94
- return out;
95
- }
96
-
97
- function normalizeObservation(descriptor, raw) {
98
- const transport = text(raw?.transport).toLowerCase();
99
- const side = text(raw?.side).toLowerCase();
100
- const name = text(raw?.name);
101
- if (!TRANSPORTS.includes(transport) || !name) return null;
102
- const allowedSides = transport === "event" ? ["publisher", "subscriber"] : ["server", "client", "server-call"];
103
- if (!allowedSides.includes(side)) return null;
104
- const operation = text(raw?.operation).toUpperCase();
105
- if (transport === "graphql" && !["QUERY", "MUTATION", "SUBSCRIPTION"].includes(operation)) return null;
106
- const line = number(raw?.line);
107
- return {
108
- transport, side, name,
109
- ...(operation ? { operation } : {}),
110
- ...(text(raw?.service) ? { service: text(raw.service) } : {}),
111
- ...(text(raw?.kind) ? { kind: text(raw.kind) } : {}),
112
- ...(safeSourceFile(descriptor, raw?.file) ? { file: safeSourceFile(descriptor, raw.file) } : {}),
113
- ...(line > 0 && line <= 10_000_000 ? { line: Math.floor(line) } : {}),
114
- observedCount: Math.max(1, Math.min(1_000_000_000, Math.floor(number(raw?.observedCount) || 1))),
115
- detector: text(raw?.detector) || "runtime-report",
116
- runtimeObserved: true,
117
- };
118
- }
119
-
120
- function validateReport(descriptor, report, options, file) {
121
- const reasons = [];
122
- let usable = true;
123
- if (report?.schema !== TRANSPORT_RUNTIME_SCHEMA) { reasons.push(`${descriptor.id}: unsupported runtime evidence schema`); usable = false; }
124
- if (!descriptor.graph?.graphRevision || report?.repositoryRevision !== descriptor.graph.graphRevision) { reasons.push(`${descriptor.id}: runtime evidence revision does not match the active graph`); usable = false; }
125
- const generatedAt = Date.parse(report?.generatedAt);
126
- const now = Number(options.now ?? Date.now());
127
- const maxAgeMs = Math.max(1, Math.min(8760, Number(options.maxAgeHours) || 168)) * 3_600_000;
128
- if (!Number.isFinite(generatedAt)) { reasons.push(`${descriptor.id}: runtime evidence generatedAt is invalid`); usable = false; }
129
- else if (generatedAt > now + 300_000 || now - generatedAt > maxAgeMs) { reasons.push(`${descriptor.id}: runtime evidence is stale or from the future`); usable = false; }
130
- const selected = requestedTransports(options.transport);
131
- const coverage = Object.fromEntries(selected.map((item) => [item, String(report?.coverage?.[item] || "NOT_CHECKED").toUpperCase()]));
132
- for (const [item, status] of Object.entries(coverage)) if (status !== "COMPLETE") reasons.push(`${descriptor.id}: ${item} runtime capture is ${status}`);
133
- const raw = [...(Array.isArray(report?.observations) ? report.observations : []), ...otlpObservations(descriptor, report)].slice(0, MAX_OBSERVATIONS);
134
- const observations = usable ? raw.map((item) => normalizeObservation(descriptor, item)).filter(Boolean) : [];
135
- if (raw.length !== observations.length) reasons.push(`${descriptor.id}: ${raw.length - observations.length} invalid runtime observation(s) were ignored`);
136
- return { status: reasons.length ? "PARTIAL" : "COMPLETE", file, generatedAt: report?.generatedAt, repositoryRevision: report?.repositoryRevision, coverage, observations, reasons };
137
- }
138
-
139
- export function loadTransportRuntimeEvidence(descriptor, options = {}) {
140
- const candidates = options.file ? [String(options.file)] : DEFAULT_REPORTS;
141
- for (const candidate of candidates) {
142
- const resolved = reportPath(descriptor, candidate);
143
- if (!resolved.path) {
144
- if (options.file) return { status: "ERROR", file: candidate, coverage: {}, observations: [], reasons: [`${descriptor.id}: runtime evidence path is ${resolved.reason}`] };
145
- continue;
146
- }
147
- try {
148
- if (statSync(resolved.path).size > MAX_REPORT_BYTES) return { status: "ERROR", file: candidate, coverage: {}, observations: [], reasons: [`${descriptor.id}: runtime evidence exceeds ${MAX_REPORT_BYTES} bytes`] };
149
- return validateReport(descriptor, JSON.parse(readFileSync(resolved.path, "utf8")), options, candidate);
150
- } catch {
151
- return { status: "ERROR", file: candidate, coverage: {}, observations: [], reasons: [`${descriptor.id}: runtime evidence is unreadable or invalid JSON`] };
152
- }
153
- }
154
- return { status: "NOT_CHECKED", file: null, coverage: {}, observations: [], reasons: [`${descriptor.id}: no revision-bound runtime transport evidence was found`] };
155
- }