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,77 +0,0 @@
1
- const EXTENSION_NAME = /^[a-z0-9][a-z0-9._-]{0,127}$/
2
- const TOOL_NAME = /^[a-z][a-z0-9_]{0,127}$/
3
-
4
- const asArray = (value, field) => {
5
- if (value == null) return []
6
- if (!Array.isArray(value)) throw new TypeError(`${field} must be an array`)
7
- return value
8
- }
9
-
10
- const validateProfiles = (profiles = {}) => {
11
- if (!profiles || typeof profiles !== 'object' || Array.isArray(profiles)) throw new TypeError('extension profiles must be an object')
12
- const normalized = {}
13
- for (const [name, capabilities] of Object.entries(profiles)) {
14
- if (!EXTENSION_NAME.test(name)) throw new TypeError(`invalid extension profile name: ${name}`)
15
- normalized[name] = asArray(capabilities, `profile ${name}`).map(String)
16
- }
17
- return Object.freeze(normalized)
18
- }
19
-
20
- const validateTools = (tools = []) => Object.freeze(asArray(tools, 'extension tools').map((tool) => {
21
- if (!tool || typeof tool !== 'object') throw new TypeError('each extension tool must be an object')
22
- if (!TOOL_NAME.test(String(tool.name || ''))) throw new TypeError(`invalid extension tool name: ${tool.name || '(missing)'}`)
23
- if (!EXTENSION_NAME.test(String(tool.cap || ''))) throw new TypeError(`invalid extension tool capability: ${tool.cap || '(missing)'}`)
24
- if (typeof tool.run !== 'function') throw new TypeError(`extension tool ${tool.name} must provide run()`)
25
- return Object.freeze({...tool})
26
- }))
27
-
28
- const validateAuditProviders = (providers = []) => Object.freeze(asArray(providers, 'auditProviders').map((provider) => {
29
- if (!provider || typeof provider !== 'object') throw new TypeError('each audit provider must be an object')
30
- if (!EXTENSION_NAME.test(String(provider.id || ''))) throw new TypeError(`invalid audit provider id: ${provider.id || '(missing)'}`)
31
- if (typeof provider.run !== 'function') throw new TypeError(`audit provider ${provider.id} must provide run()`)
32
- if (provider.network !== undefined && provider.network !== 'none') throw new TypeError(`audit provider ${provider.id} must be local (network: "none")`)
33
- return Object.freeze({...provider, network: 'none'})
34
- }))
35
-
36
- const validateSkills = (skills = []) => Object.freeze(asArray(skills, 'skills').map((skill) => {
37
- if (!skill || typeof skill !== 'object') throw new TypeError('each extension skill must be an object')
38
- if (!EXTENSION_NAME.test(String(skill.name || ''))) throw new TypeError(`invalid extension skill name: ${skill.name || '(missing)'}`)
39
- if (!String(skill.path || '').trim()) throw new TypeError(`extension skill ${skill.name} must provide a package-relative path`)
40
- return Object.freeze({...skill, name: String(skill.name), path: String(skill.path)})
41
- }))
42
-
43
- // Public composition contract for packages layered on top of the MIT core. Extensions may add
44
- // tools, local audit providers and packaged skills, but cannot replace core tools or profiles.
45
- export function defineWeavatrixExtension(spec) {
46
- if (!spec || typeof spec !== 'object') throw new TypeError('extension definition must be an object')
47
- const name = String(spec.name || '')
48
- const version = String(spec.version || '')
49
- if (!EXTENSION_NAME.test(name)) throw new TypeError(`invalid extension name: ${name || '(missing)'}`)
50
- if (!version.trim()) throw new TypeError(`extension ${name} must provide a version`)
51
- return Object.freeze({
52
- name,
53
- version,
54
- tools: validateTools(spec.tools),
55
- profiles: validateProfiles(spec.profiles),
56
- auditProviders: validateAuditProviders(spec.auditProviders),
57
- skills: validateSkills(spec.skills),
58
- })
59
- }
60
-
61
- export function normalizeWeavatrixExtensions(extensions = []) {
62
- const normalized = asArray(extensions, 'extensions').map((extension) => defineWeavatrixExtension(extension))
63
- const names = new Set()
64
- for (const extension of normalized) {
65
- if (names.has(extension.name)) throw new TypeError(`duplicate extension name: ${extension.name}`)
66
- names.add(extension.name)
67
- }
68
- return Object.freeze(normalized)
69
- }
70
-
71
- export const extensionRuntimeSummary = (extensions = []) => extensions.map((extension) => ({
72
- name: extension.name,
73
- version: extension.version,
74
- tools: extension.tools.length,
75
- auditProviders: extension.auditProviders.length,
76
- skills: extension.skills.map((skill) => skill.name),
77
- }))
@@ -1,7 +0,0 @@
1
- import {runGit} from '../git-exec.js'
2
-
3
- export function gitLines(repoRoot, args) {
4
- const result = runGit(repoRoot, args)
5
- if (result.status !== 0) return null
6
- return String(result.stdout || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
7
- }
@@ -1,111 +0,0 @@
1
- import {readFileSync} from 'node:fs'
2
- import {isStructuralRelation} from '../../graph/relations.js'
3
- import {edgeProvenance} from '../../graph/edge-provenance.js'
4
- import {mergePrecisionOverlay, precisionSemanticInputsMatch, readPrecisionOverlay} from '../../precision/lsp-overlay.js'
5
-
6
- export function loadGraph(path, {repoRoot = null} = {}) {
7
- const saved = JSON.parse(readFileSync(path, 'utf8'))
8
- const overlay = readPrecisionOverlay(path, saved)
9
- const safeOverlay = repoRoot && typeof overlay?.semanticInputFingerprint === 'string'
10
- && !precisionSemanticInputsMatch(overlay, repoRoot, saved) ? null : overlay
11
- const raw = mergePrecisionOverlay(saved, safeOverlay)
12
- const nodes = Array.isArray(raw.nodes) ? raw.nodes : []
13
- const links = Array.isArray(raw.links) ? raw.links : []
14
- const byId = new Map()
15
- const byLabel = new Map()
16
- for (const n of nodes) {
17
- if (!n || n.id == null) continue
18
- byId.set(String(n.id), n)
19
- const key = String(n.label ?? n.id).toLowerCase()
20
- if (!byLabel.has(key)) byLabel.set(key, [])
21
- byLabel.get(key).push(n)
22
- }
23
- const out = new Map()
24
- const inn = new Map()
25
- const push = (map, k, v) => {
26
- if (!map.has(k)) map.set(k, [])
27
- map.get(k).push(v)
28
- }
29
- for (const e of links) {
30
- if (!e || e.source == null || e.target == null) continue
31
- const s = String(e.source), t = String(e.target)
32
- const metadata = {
33
- relation: e.relation,
34
- confidence: e.confidence,
35
- provenance: edgeProvenance(e),
36
- ...(e.typeOnly === true ? {typeOnly: true} : {}),
37
- ...(e.compileOnly === true ? {compileOnly: true} : {}),
38
- ...(Number.isInteger(e.line) ? {line: e.line} : {}),
39
- ...(typeof e.specifier === 'string' ? {specifier: e.specifier} : {}),
40
- ...(e.barrelProxy === true ? {barrelProxy: true} : {}),
41
- ...(e.semanticOrigin === true ? {semanticOrigin: true} : {}),
42
- ...(typeof e.viaBarrel === 'string' ? {viaBarrel: e.viaBarrel} : {}),
43
- }
44
- push(out, s, {id: t, ...metadata})
45
- push(inn, t, {id: s, ...metadata})
46
- }
47
- return {
48
- nodes, links, byId, byLabel, out, inn,
49
- repoBoundaryV: Number(raw.repoBoundaryV) || 0,
50
- edgeTypesV: Number(raw.edgeTypesV) || 0,
51
- edgeProvenanceV: Number(raw.edgeProvenanceV) || 0,
52
- barrelResolutionV: Number(raw.barrelResolutionV) || 0,
53
- reExportOccurrencesV: Number(raw.reExportOccurrencesV) || 0,
54
- symbolSpacesV: Number(raw.symbolSpacesV) || 0,
55
- reExportOccurrences: Array.isArray(raw.reExportOccurrences) ? raw.reExportOccurrences : [],
56
- jsExportRecords: raw.jsExportRecords && typeof raw.jsExportRecords === 'object' ? raw.jsExportRecords : {},
57
- extractorSchemaV: Number(raw.extractorSchemaV) || 0,
58
- extImportsV: Number(raw.extImportsV) || 0,
59
- complexityV: Number(raw.complexityV) || 0,
60
- physicalFileLocV: Number(raw.physicalFileLocV) || 0,
61
- graphBuildMode: ['full', 'no-tests', 'tests-only'].includes(raw.graphBuildMode) ? raw.graphBuildMode : 'full',
62
- graphBuildScope: typeof raw.graphBuildScope === 'string' ? raw.graphBuildScope : null,
63
- graphRevision: typeof raw.graphRevision === 'string' ? raw.graphRevision : null,
64
- repositoryFreshnessProbeV: Number(raw.repositoryFreshnessProbeV) || 0,
65
- repositoryFreshnessBuilderSchemaV: Number(raw.repositoryFreshnessBuilderSchemaV) || 0,
66
- repositoryFreshnessBuilderVersion: typeof raw.repositoryFreshnessBuilderVersion === 'string' ? raw.repositoryFreshnessBuilderVersion : null,
67
- repositoryFreshnessProbe: typeof raw.repositoryFreshnessProbe === 'string' ? raw.repositoryFreshnessProbe : null,
68
- repositoryFreshnessMode: typeof raw.repositoryFreshnessMode === 'string' ? raw.repositoryFreshnessMode : null,
69
- graphPrecisionMode: raw.graphPrecisionMode === 'off' ? 'off' : 'lsp',
70
- precisionOverlayV: Number(raw.precisionOverlayV) || 0,
71
- precision: raw.precision || null,
72
- }
73
- }
74
-
75
- export const isSymbol = (id) => String(id).includes('#')
76
- export const labelOf = (g, id) => {
77
- const n = g.byId.get(String(id))
78
- return n ? String(n.label ?? n.id) : String(id)
79
- }
80
- export const connList = (list) => (list || []).filter((e) => !isStructuralRelation(e.relation) && e.barrelProxy !== true)
81
- export const degreeOf = (g, id) => connList(g.out.get(id)).length + connList(g.inn.get(id)).length
82
- export const uniqueConnCount = (list) => new Set(connList(list).map((e) => String(e.id))).size
83
-
84
- export function resolveNodeInfo(g, query) {
85
- const q = String(query ?? '').trim()
86
- if (!q) return {node: null, matches: 0, alternates: []}
87
- if (g.byId.has(q)) return {node: g.byId.get(q), matches: 1, alternates: []}
88
- const exactLabel = g.byLabel.get(q.toLowerCase())
89
- if (exactLabel?.length) return pickBest(g, exactLabel)
90
- const hits = []
91
- for (const n of g.nodes) {
92
- if (String(n.id).toLowerCase().includes(q.toLowerCase()) || String(n.label ?? '').toLowerCase().includes(q.toLowerCase())) hits.push(n)
93
- if (hits.length > 500) break
94
- }
95
- return hits.length ? pickBest(g, hits) : {node: null, matches: 0, alternates: []}
96
- }
97
-
98
- export const resolveNode = (g, query) => resolveNodeInfo(g, query).node
99
- const bestByDegree = (g, list) => list.reduce((best, n) => (degreeOf(g, n.id) > degreeOf(g, best.id) ? n : best), list[0])
100
- function pickBest(g, list) {
101
- const node = bestByDegree(g, list)
102
- const alternates = list.filter((n) => n !== node).sort((a, b) => degreeOf(g, b.id) - degreeOf(g, a.id))
103
- .slice(0, 4).map((n) => `${n.label ?? n.id} [${n.id}]`)
104
- return {node, matches: list.length, alternates}
105
- }
106
-
107
- export function ambiguityNote(query, info) {
108
- if (!info.node || info.matches <= 1) return null
109
- const more = info.matches - 1 - info.alternates.length
110
- return `Note: "${query}" matched ${info.matches} nodes; using the best-connected. Others: ${info.alternates.join(', ')}${more > 0 ? ` (+${more} more)` : ''}`
111
- }
@@ -1,207 +0,0 @@
1
- import {PATH_CLASS_NAMES, PATH_CLASS_QUERY_TERMS, createPathClassifier, hasPathClass} from '../../path-classification.js'
2
- import {degreeOf, isSymbol, uniqueConnCount} from './context-core.mjs'
3
-
4
- const QUERY_STOP = new Set('a an and are around architecture best code do does exact explain find focus focused for from how identify in inspect inspection is logic me of or path production project repository request requests rest show symbol symbols the through to trace what where which with'.split(' '))
5
- const QUERY_INTENTS = [
6
- ['bootstrap', ['bootstrap', 'startup', 'entrypoint', 'entry', 'main', 'root', 'app', 'application', 'applications', 'index', 'server', 'cli']],
7
- ['tool-execution', ['tool', 'tools', 'tooling', 'mcp', 'execution', 'execute', 'invocation', 'invoke', 'dispatch', 'dispatcher', 'handler', 'catalog', 'registry']],
8
- ['auth', ['auth', 'authentication', 'authorization', 'login', 'session', 'authgate']],
9
- ['routing', ['routing', 'router', 'routes', 'route', 'navigation']],
10
- ['layout', ['layout', 'layouts', 'shell']],
11
- ['api', ['api', 'apis', 'endpoint', 'endpoints', 'client']],
12
- ['state', ['state', 'store', 'stores', 'reducer', 'context']],
13
- ]
14
- const INTENT_BY_TERM = new Map(QUERY_INTENTS.filter(([id]) => id !== 'tool-execution')
15
- .flatMap(([id, terms]) => terms.map((term) => [term, {id, terms}])))
16
- const TOOL_EXECUTION_TERMS = QUERY_INTENTS.find(([id]) => id === 'tool-execution')[1]
17
- const TOOL_EXECUTION_TRIGGERS = new Set(['tool', 'tools', 'tooling', 'mcp'])
18
- const wordsOf = (value) => String(value ?? '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean)
19
- const normPath = (value) => String(value ?? '').replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase()
20
- const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|py|go|java|rs|kt|kts|cs|rb|php|sol|sql)$/i
21
- const DATA_OR_PROSE_RE = /\.(?:json|ya?ml|toml|ini|md|mdx|rst|adoc|html?|css|scss|less|svg)$/i
22
- const LANGUAGE_EXTENSIONS = Object.freeze({
23
- rust: ['rs'], python: ['py', 'pyi'], typescript: ['ts', 'tsx', 'mts', 'cts'],
24
- javascript: ['js', 'jsx', 'mjs', 'cjs'], go: ['go'], java: ['java'], csharp: ['cs'],
25
- solidity: ['sol'], sql: ['sql'],
26
- })
27
-
28
- function requestedLanguages(query) {
29
- const raw = String(query || ''), words = new Set(wordsOf(query)), requested = new Set()
30
- if (words.has('rust')) requested.add('rust')
31
- if (words.has('python') || words.has('py')) requested.add('python')
32
- if (words.has('typescript') || words.has('ts') || /typescript/i.test(raw)) requested.add('typescript')
33
- if (words.has('javascript') || words.has('js') || words.has('nodejs') || /javascript|node\.?js/i.test(raw)) requested.add('javascript')
34
- if (words.has('golang') || /(?:^|[^A-Za-z])Go(?:[^A-Za-z]|$)/.test(raw)) requested.add('go')
35
- if (words.has('java')) requested.add('java')
36
- if (words.has('csharp') || words.has('dotnet') || /csharp|(?:^|[^A-Za-z])C#(?:[^A-Za-z]|$)/i.test(raw)) requested.add('csharp')
37
- if (words.has('solidity') || words.has('contract') || words.has('contracts')) requested.add('solidity')
38
- if (words.has('sql') || words.has('schema') || words.has('migration') || words.has('migrations')) requested.add('sql')
39
- return new Set([...requested].flatMap((language) => LANGUAGE_EXTENSIONS[language]))
40
- }
41
-
42
- const sourceFileOf = (node) => normPath(node?.source_file || String(node?.id ?? '').split('#', 1)[0])
43
- const matchesLanguage = (node, extensions) => {
44
- if (!extensions.size) return true
45
- const match = /\.([^.\/]+)$/.exec(sourceFileOf(node))
46
- return !!match && extensions.has(match[1].toLowerCase())
47
- }
48
-
49
- export function requestedPathClasses(query) {
50
- const words = new Set(wordsOf(query)), requested = new Set()
51
- for (const [category, terms] of Object.entries(PATH_CLASS_QUERY_TERMS)) if (terms.some((term) => words.has(term))) requested.add(category)
52
- if (requested.has('test')) requested.add('e2e')
53
- if (requested.has('e2e')) requested.add('test')
54
- return requested
55
- }
56
-
57
- function isQueryEligible(node, requestedClasses, classificationCache, classifier) {
58
- if (node?.test_surface === true && !requestedClasses.has('test')) return false
59
- const source = sourceFileOf(node)
60
- if (!source) return true
61
- if (!classificationCache.has(source)) classificationCache.set(source, classifier.explain(source, {content: ''}))
62
- const info = classificationCache.get(source)
63
- const classified = PATH_CLASS_NAMES.filter((category) => hasPathClass(info, category))
64
- return classified.length === 0 || classified.some((category) => requestedClasses.has(category))
65
- }
66
-
67
- function entrypointSignal(g, node, source, stem) {
68
- if (isSymbol(node.id) || !CODE_FILE_RE.test(source)) return 0
69
- const depth = source.split('/').length
70
- let score = 0
71
- if (node.entrypoint === true || node.is_entrypoint === true || node.declared_entry === true) score = 72
72
- if (/^bin\//.test(source) || /\/(?:bin|cmd)\//.test(source)) score = Math.max(score, 62)
73
- if (depth <= 2 && /^(?:index|main|app|server|cli|bootstrap|entry|run)$/.test(stem)) score = Math.max(score, 60)
74
- if (depth <= 2 && /(?:^|[-_.])(?:main|server|cli|bootstrap|entry)(?:$|[-_.])/.test(stem)) score = Math.max(score, 57)
75
- if (depth <= 3 && /^(?:main|app|server|cli|bootstrap|entry|run)$/.test(stem)) score = Math.max(score, 52)
76
- const incoming = uniqueConnCount(g.inn.get(String(node.id))), outgoing = uniqueConnCount(g.out.get(String(node.id)))
77
- if (score && incoming === 0 && outgoing > 0) score += Math.min(7, 2 + outgoing)
78
- return score
79
- }
80
-
81
- function toolExecutionSignal(node, source, words, stem) {
82
- if (!CODE_FILE_RE.test(source)) return 0
83
- let score = 0
84
- if (/(^|\/)(?:mcp(?:[-_.][^/]*)?|tools?)(?:\/|[-_.])/.test(source)) score = Math.max(score, 51)
85
- if (/^(?:catalog|dispatch(?:er)?|registry)$/.test(stem)) score = Math.max(score, 68)
86
- if (/^(?:tool[-_.]?(?:handler|runner|executor)|tools?[-_.])/.test(stem)) score = Math.max(score, 55)
87
- if ([...words].some((word) => /^(?:dispatch|dispatcher|toolcall|toolhandler|executetool|invoketool|calltool)$/.test(word))) score = Math.max(score, 64)
88
- if (source.includes('/mcp/') || stem.includes('mcp-server')) score = Math.max(score, 48)
89
- return score
90
- }
91
-
92
- // relaxStop is the last-resort fallback: when EVERY token is a stop word (e.g. a bare
93
- // "architecture" query), keep them as concepts so the query still seeds instead of
94
- // misreporting "No nodes matched" for a concept the repository clearly contains.
95
- function queryConcepts(query, {relaxStop = false} = {}) {
96
- const tokens = wordsOf(query)
97
- const toolExecution = tokens.some((token) => TOOL_EXECUTION_TRIGGERS.has(token))
98
- const explanatoryWork = tokens.some((token) => token === 'how' || token === 'explain')
99
- const seen = new Set(), concepts = []
100
- for (const raw of tokens) {
101
- if (raw.length < 2 || (!relaxStop && QUERY_STOP.has(raw))) continue
102
- if (explanatoryWork && (raw === 'work' || raw === 'works' || raw === 'working')) continue
103
- if (toolExecution && TOOL_EXECUTION_TERMS.includes(raw)) {
104
- if (seen.has('tool-execution')) continue
105
- const trigger = tokens.find((token) => TOOL_EXECUTION_TRIGGERS.has(token)) || raw
106
- seen.add('tool-execution')
107
- concepts.push({id: 'tool-execution', raw: trigger, terms: [trigger, ...TOOL_EXECUTION_TERMS.filter((term) => term !== trigger)]})
108
- continue
109
- }
110
- const intent = INTENT_BY_TERM.get(raw), id = intent?.id || raw
111
- if (seen.has(id)) continue
112
- seen.add(id)
113
- concepts.push({id, raw, terms: intent ? [raw, ...intent.terms.filter((term) => term !== raw)] : [raw]})
114
- }
115
- return concepts
116
- }
117
-
118
- function exactIdentifierSeeds(g, query, limit, {repoRoot = null} = {}) {
119
- const identifiers = [...new Set((String(query || '').match(/[A-Za-z_$][A-Za-z0-9_$]*/g) || [])
120
- .filter((item) => /(?:[a-z0-9][A-Z]|_)/.test(item)).map((item) => item.toLowerCase()))]
121
- if (!identifiers.length) return []
122
- const requestedClasses = requestedPathClasses(query), languageExtensions = effectiveLanguages(g, query)
123
- const classifier = createPathClassifier(repoRoot), classificationCache = new Map(), matches = []
124
- for (const identifier of identifiers) {
125
- const candidates = g.nodes.filter((node) => String(node.label || '').replace(/\(\)$/, '').toLowerCase() === identifier
126
- && matchesLanguage(node, languageExtensions) && isQueryEligible(node, requestedClasses, classificationCache, classifier))
127
- .sort((left, right) => degreeOf(g, right.id) - degreeOf(g, left.id) || String(left.id).localeCompare(String(right.id)))
128
- for (const node of candidates) {
129
- if (!matches.some((existing) => String(existing.id) === String(node.id))) matches.push(node)
130
- if (matches.length >= limit) return matches
131
- }
132
- }
133
- return matches
134
- }
135
-
136
- function conceptScore(g, node, concept, queryContext) {
137
- const id = normPath(node.id), label = String(node.label ?? '').toLowerCase(), source = sourceFileOf(node)
138
- const stem = (label.split('/').pop() || '').replace(/\.[^.]+$/, '')
139
- const words = new Set(wordsOf(`${node.id} ${node.label ?? ''} ${node.source_file ?? ''}`))
140
- const segments = new Set(source.split('/').flatMap((part) => wordsOf(part.replace(/\.[^.]+$/, ''))))
141
- let match = 0
142
- concept.terms.forEach((term, index) => {
143
- const primary = index === 0
144
- if (label === term || stem === term) match = Math.max(match, primary ? 60 : 42)
145
- else if (segments.has(term)) match = Math.max(match, primary ? 48 : 36)
146
- else if (words.has(term)) match = Math.max(match, primary ? 36 : 25)
147
- else if (term.length >= 4 && term !== 'tool' && term !== 'tools' && (id.includes(term) || label.includes(term))) match = Math.max(match, primary ? 12 : 7)
148
- })
149
- const extension = (/\.([^.\/]+)$/.exec(source) || [])[1] || ''
150
- const languageConcept = {rust: ['rs'], python: ['py', 'pyi'], py: ['py', 'pyi'], typescript: ['ts', 'tsx', 'mts', 'cts'], ts: ['ts', 'tsx', 'mts', 'cts'], javascript: ['js', 'jsx', 'mjs', 'cjs'], js: ['js', 'jsx', 'mjs', 'cjs'], nodejs: ['js', 'jsx', 'mjs', 'cjs'], golang: ['go'], go: ['go'], java: ['java'], csharp: ['cs'], dotnet: ['cs'], solidity: ['sol'], sql: ['sql'], schema: ['sql']}[concept.raw]
151
- if (languageConcept?.includes(extension) && queryContext.languageExtensions.has(extension)) match = Math.max(match, 58)
152
- const fileNode = !isSymbol(node.id), depth = source ? source.split('/').length : 9
153
- if (concept.id === 'bootstrap') match = Math.max(match, entrypointSignal(g, node, source, stem))
154
- if (concept.id === 'tool-execution') match = Math.max(match, toolExecutionSignal(node, source, words, stem))
155
- if (!match) return 0
156
- let score = match + (fileNode ? 7 : 0) + Math.max(0, 4 - depth) + Math.min(2, degreeOf(g, node.id) / 40)
157
- if ((concept.id === 'bootstrap' || concept.id === 'tool-execution') && DATA_OR_PROSE_RE.test(source)) score -= 34
158
- if ((concept.id === 'bootstrap' || concept.id === 'tool-execution') && !fileNode) score -= 18
159
- if (queryContext.runtimeIntent && !queryContext.maintenanceIntent && /^(?:scripts?|tools?\/scripts?)\//.test(source)) score -= 32
160
- if (queryContext.runtimeIntent && /^(?:site|website|public|static|assets)\//.test(source)) score -= 28
161
- return Math.max(0, score)
162
- }
163
-
164
- // A requested language that matches ZERO nodes in this graph is over-eager inference (e.g.
165
- // "contract" inferring Solidity in a repo with no .sol files); drop the filter rather than
166
- // eliminate every candidate and return nothing.
167
- function effectiveLanguages(g, query) {
168
- const languageExtensions = requestedLanguages(query)
169
- if (languageExtensions.size && !g.nodes.some((node) => matchesLanguage(node, languageExtensions))) return new Set()
170
- return languageExtensions
171
- }
172
-
173
- export function findSeeds(g, query, limit = 8, {repoRoot = null} = {}) {
174
- const exact = exactIdentifierSeeds(g, query, limit, {repoRoot})
175
- if (exact.length) return exact
176
- let concepts = queryConcepts(query)
177
- if (!concepts.length) concepts = queryConcepts(query, {relaxStop: true})
178
- if (!concepts.length || limit <= 0) return []
179
- const requestedClasses = requestedPathClasses(query), languageExtensions = effectiveLanguages(g, query)
180
- const queryContext = {runtimeIntent: concepts.some((concept) => concept.id === 'bootstrap' || concept.id === 'tool-execution'), maintenanceIntent: wordsOf(query).some((word) => ['script', 'scripts', 'build', 'release', 'publish', 'packaging'].includes(word)), languageExtensions}
181
- const classifier = createPathClassifier(repoRoot), classificationCache = new Map()
182
- const rows = g.nodes.filter((node) => matchesLanguage(node, languageExtensions) && isQueryEligible(node, requestedClasses, classificationCache, classifier)).map((node) => {
183
- const scores = concepts.map((concept) => conceptScore(g, node, concept, queryContext))
184
- return {node, scores, total: Math.max(...scores) + scores.reduce((sum, score) => sum + score, 0) / 10}
185
- })
186
- const chosen = [], used = new Set()
187
- for (let index = 0; index < concepts.length && chosen.length < limit; index++) {
188
- const best = rows.filter((row) => !used.has(String(row.node.id)) && row.scores[index] > 0)
189
- .sort((a, b) => b.scores[index] - a.scores[index] || String(a.node.id).localeCompare(String(b.node.id)))[0]
190
- if (best) { chosen.push(best.node); used.add(String(best.node.id)) }
191
- }
192
- rows.filter((row) => row.total > 0 && !used.has(String(row.node.id)))
193
- .sort((a, b) => b.total - a.total || String(a.node.id).localeCompare(String(b.node.id)))
194
- .slice(0, Math.max(0, limit - chosen.length)).forEach((row) => chosen.push(row.node))
195
- return chosen
196
- }
197
-
198
- export function resolveSeedFiles(g, requested, limit = 12) {
199
- const files = Array.isArray(requested) ? requested.slice(0, limit) : [], seeds = [], missing = []
200
- for (const raw of files) {
201
- const wanted = normPath(raw)
202
- const node = g.nodes.find((candidate) => !isSymbol(candidate.id) && (normPath(candidate.id) === wanted || normPath(candidate.source_file) === wanted))
203
- if (!node) missing.push(String(raw))
204
- else if (!seeds.some((seed) => String(seed.id) === String(node.id))) seeds.push(node)
205
- }
206
- return {seeds, missing}
207
- }
@@ -1,85 +0,0 @@
1
- import {readFileSync, statSync} from 'node:fs'
2
- import {join} from 'node:path'
3
- import {runGit} from '../../git-exec.js'
4
- import {resolveRepoPath} from '../../repo-path.js'
5
- import {mergePrecisionOverlay, precisionSemanticInputsMatch, readPrecisionOverlay} from '../../precision/lsp-overlay.js'
6
-
7
- let stalenessCache = {key: '', checkedAt: 0, info: null}
8
-
9
- export function graphStaleness(ctx) {
10
- const now = Date.now()
11
- if (stalenessCache.info && stalenessCache.key === ctx.graphPath && now - stalenessCache.checkedAt < 60_000) return stalenessCache.info
12
- const info = {builtAt: null, headAt: null, stale: false, behind: null}
13
- try { info.builtAt = statSync(ctx.graphPath).mtime } catch { /* no graph file */ }
14
- if (ctx.repoRoot && info.builtAt) {
15
- try {
16
- const head = runGit(ctx.repoRoot, ['log', '-1', '--format=%cI'], {timeout: 4000})
17
- const iso = (head.stdout || '').trim()
18
- if (head.status === 0 && iso) {
19
- info.headAt = new Date(iso)
20
- if (info.headAt > info.builtAt) {
21
- info.stale = true
22
- const count = runGit(ctx.repoRoot, ['rev-list', '--count', `--since=${info.builtAt.toISOString()}`, 'HEAD'], {timeout: 4000})
23
- if (count.status === 0) info.behind = Number(count.stdout.trim()) || null
24
- }
25
- }
26
- } catch { /* git unavailable */ }
27
- try {
28
- const status = runGit(ctx.repoRoot, ['status', '--porcelain'], {timeout: 4000})
29
- if (status.status === 0) {
30
- let newer = 0
31
- for (const line of String(status.stdout || '').split(/\r?\n/).filter(Boolean).slice(0, 200)) {
32
- const path = line.slice(3).trim().replace(/^"|"$/g, '')
33
- try { if (statSync(join(ctx.repoRoot, path)).mtime > info.builtAt) newer++ } catch { newer++ }
34
- }
35
- info.dirtyNewer = newer
36
- if (newer > 0) info.stale = true
37
- }
38
- } catch { /* git unavailable */ }
39
- }
40
- stalenessCache = {key: ctx.graphPath, checkedAt: now, info}
41
- return info
42
- }
43
-
44
- export const resetStalenessCache = () => { stalenessCache = {key: '', checkedAt: 0, info: null} }
45
-
46
- export function stalenessLine(ctx) {
47
- const state = graphStaleness(ctx)
48
- if (!state.stale) return null
49
- const bits = []
50
- if (state.headAt && state.headAt > state.builtAt) bits.push(`${state.behind != null ? `${state.behind} commit${state.behind === 1 ? '' : 's'}` : 'commits'} newer than the graph`)
51
- if (state.dirtyNewer) bits.push(`${state.dirtyNewer} uncommitted file(s) edited after the build`)
52
- return `Warning: graph may be stale — the repo has ${bits.join(' and ')} (built ${state.builtAt.toISOString()}). Line numbers may have drifted; call rebuild_graph.`
53
- }
54
-
55
- export function fileStalenessNote(ctx, sourceFile) {
56
- if (!ctx?.repoRoot || !sourceFile) return null
57
- const state = graphStaleness(ctx)
58
- if (!state.builtAt) return null
59
- try {
60
- const resolved = resolveRepoPath(ctx.repoRoot, String(sourceFile))
61
- if (resolved.ok && statSync(resolved.path).mtime > state.builtAt) {
62
- return `Note: ${sourceFile} changed after the graph was built — line numbers above may have drifted (rebuild_graph refreshes them).`
63
- }
64
- } catch { /* missing file */ }
65
- return null
66
- }
67
-
68
- let rawGraphCache = {path: '', mtimeMs: 0, data: null}
69
-
70
- export function rawGraph(ctx) {
71
- const mtimeMs = statSync(ctx.graphPath).mtimeMs
72
- if (!rawGraphCache.data || rawGraphCache.path !== ctx.graphPath || rawGraphCache.mtimeMs !== mtimeMs) {
73
- rawGraphCache = {path: ctx.graphPath, mtimeMs, data: JSON.parse(readFileSync(ctx.graphPath, 'utf8'))}
74
- }
75
- return rawGraphCache.data
76
- }
77
-
78
- export function effectiveRawGraph(ctx) {
79
- const raw = rawGraph(ctx)
80
- const overlay = readPrecisionOverlay(ctx.graphPath, raw)
81
- const safeOverlay = ctx?.repoRoot && typeof overlay?.semanticInputFingerprint === 'string'
82
- && !precisionSemanticInputsMatch(overlay, ctx.repoRoot, raw)
83
- ? null : overlay
84
- return mergePrecisionOverlay(raw, safeOverlay)
85
- }
@@ -1,42 +0,0 @@
1
- import {isStructuralRelation} from '../../graph/relations.js'
2
-
3
- // Shared reverse dependency walk for get_dependents and change_impact. Keep one
4
- // representation so runtime/compile-time depth and edge provenance cannot drift
5
- // between the two public tools.
6
- export function reverseReach(g, seeds, maxDepth) {
7
- const states = new Map([...seeds].map((id) => [String(id), {
8
- runtimeDepth: 0, runtimeRelation: null, runtimeProvenance: null,
9
- compileDepth: null, compileRelation: null, compileProvenance: null,
10
- }]))
11
- const frontier = [...seeds].map((id) => ({id: String(id), depth: 0, compileOnly: false}))
12
- for (let cursor = 0; cursor < frontier.length; cursor++) {
13
- const current = frontier[cursor]
14
- if (current.depth >= maxDepth) continue
15
- for (const edge of g.inn.get(current.id) || []) {
16
- if (isStructuralRelation(edge.relation) || edge.barrelProxy === true) continue
17
- const id = String(edge.id)
18
- const compileOnly = current.compileOnly || edge.typeOnly === true || edge.compileOnly === true
19
- const depth = current.depth + 1
20
- const entry = states.get(id) || {
21
- runtimeDepth: null, runtimeRelation: null, runtimeProvenance: null,
22
- compileDepth: null, compileRelation: null, compileProvenance: null,
23
- }
24
- const depthKey = compileOnly ? 'compileDepth' : 'runtimeDepth'
25
- const relationKey = compileOnly ? 'compileRelation' : 'runtimeRelation'
26
- const provenanceKey = compileOnly ? 'compileProvenance' : 'runtimeProvenance'
27
- if (entry[depthKey] != null && entry[depthKey] <= depth) continue
28
- entry[depthKey] = depth
29
- entry[relationKey] = edge.relation || 'rel'
30
- entry[provenanceKey] = edge.provenance || 'UNKNOWN'
31
- states.set(id, entry)
32
- frontier.push({id, depth, compileOnly})
33
- }
34
- }
35
- return new Map([...states].map(([id, entry]) => [id, {
36
- ...entry,
37
- depth: entry.runtimeDepth ?? entry.compileDepth ?? 0,
38
- compileOnly: entry.runtimeDepth == null,
39
- relation: entry.runtimeDepth != null ? entry.runtimeRelation : entry.compileRelation,
40
- provenance: entry.runtimeDepth != null ? entry.runtimeProvenance : entry.compileProvenance,
41
- }]))
42
- }