weavatrix 0.3.14 → 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 (305) 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 -66
  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.14.md +0 -37
  28. package/docs/releases/v0.3.2.md +0 -15
  29. package/docs/releases/v0.3.3.md +0 -25
  30. package/docs/releases/v0.3.4.md +0 -40
  31. package/docs/releases/v0.3.5.md +0 -50
  32. package/docs/releases/v0.3.6.md +0 -44
  33. package/docs/releases/v0.3.7.md +0 -37
  34. package/docs/releases/v0.3.8.md +0 -21
  35. package/docs/releases/v0.3.9.md +0 -36
  36. package/scripts/run-agent-task-benchmark.mjs +0 -118
  37. package/src/analysis/allowed-test-runner.js +0 -70
  38. package/src/analysis/architecture/contract-graph.js +0 -119
  39. package/src/analysis/architecture/contract-schema.js +0 -110
  40. package/src/analysis/architecture/contract-storage.js +0 -35
  41. package/src/analysis/architecture/contract-verification.js +0 -168
  42. package/src/analysis/architecture-contract.js +0 -16
  43. package/src/analysis/audit-debt.js +0 -94
  44. package/src/analysis/audit-extensions.js +0 -60
  45. package/src/analysis/cargo-dependency-evidence.js +0 -108
  46. package/src/analysis/cargo-manifests.js +0 -81
  47. package/src/analysis/change-classification/diff-parser.js +0 -103
  48. package/src/analysis/change-classification/options.js +0 -40
  49. package/src/analysis/change-classification/symbol-classifier.js +0 -177
  50. package/src/analysis/change-classification.js +0 -188
  51. package/src/analysis/coverage-reports-tarpaulin.js +0 -112
  52. package/src/analysis/coverage-reports.js +0 -246
  53. package/src/analysis/cycle-route.js +0 -14
  54. package/src/analysis/data-flow-evidence.js +0 -114
  55. package/src/analysis/dead-check.js +0 -300
  56. package/src/analysis/dead-code-review/candidates.js +0 -194
  57. package/src/analysis/dead-code-review/policy.js +0 -23
  58. package/src/analysis/dead-code-review.js +0 -119
  59. package/src/analysis/dep-check-ecosystems.js +0 -205
  60. package/src/analysis/dep-check.js +0 -290
  61. package/src/analysis/dep-rules.js +0 -10
  62. package/src/analysis/dependency/conventions.js +0 -16
  63. package/src/analysis/dependency/scoped-dependencies.js +0 -51
  64. package/src/analysis/dependency/source-references.js +0 -21
  65. package/src/analysis/duplicate-groups.js +0 -104
  66. package/src/analysis/duplicates-worker.js +0 -11
  67. package/src/analysis/duplicates.compute.js +0 -269
  68. package/src/analysis/duplicates.js +0 -15
  69. package/src/analysis/duplicates.run.js +0 -52
  70. package/src/analysis/duplicates.tokenize.js +0 -199
  71. package/src/analysis/endpoints/common.js +0 -79
  72. package/src/analysis/endpoints/extract.js +0 -120
  73. package/src/analysis/endpoints/inventory.js +0 -84
  74. package/src/analysis/endpoints/mounts.js +0 -129
  75. package/src/analysis/endpoints-java.js +0 -260
  76. package/src/analysis/endpoints-rust.js +0 -124
  77. package/src/analysis/endpoints.js +0 -3
  78. package/src/analysis/findings.js +0 -70
  79. package/src/analysis/git-history/analytics.js +0 -177
  80. package/src/analysis/git-history/collector.js +0 -67
  81. package/src/analysis/git-history/options.js +0 -66
  82. package/src/analysis/git-history.js +0 -143
  83. package/src/analysis/git-ref-graph.js +0 -76
  84. package/src/analysis/go-dependency-evidence.js +0 -62
  85. package/src/analysis/graph-analysis.aggregate.js +0 -296
  86. package/src/analysis/graph-analysis.edges.js +0 -24
  87. package/src/analysis/graph-analysis.js +0 -7
  88. package/src/analysis/graph-analysis.refs.js +0 -202
  89. package/src/analysis/graph-analysis.summaries.js +0 -65
  90. package/src/analysis/health-capabilities.js +0 -83
  91. package/src/analysis/hot-path-review.js +0 -266
  92. package/src/analysis/http-contract-wrappers.js +0 -241
  93. package/src/analysis/http-contracts/analysis.js +0 -179
  94. package/src/analysis/http-contracts/client-call-detection.js +0 -82
  95. package/src/analysis/http-contracts/client-call-parser.js +0 -273
  96. package/src/analysis/http-contracts/graph-context.js +0 -143
  97. package/src/analysis/http-contracts/matching.js +0 -61
  98. package/src/analysis/http-contracts/shared.js +0 -85
  99. package/src/analysis/http-contracts.js +0 -6
  100. package/src/analysis/internal-audit/dependency-health.js +0 -113
  101. package/src/analysis/internal-audit/python-manifests.js +0 -78
  102. package/src/analysis/internal-audit/repo-files.js +0 -50
  103. package/src/analysis/internal-audit/supply-chain.js +0 -149
  104. package/src/analysis/internal-audit.collect.js +0 -213
  105. package/src/analysis/internal-audit.js +0 -9
  106. package/src/analysis/internal-audit.reach.js +0 -201
  107. package/src/analysis/internal-audit.run.js +0 -256
  108. package/src/analysis/java-source.js +0 -36
  109. package/src/analysis/jvm-artifact-index.js +0 -87
  110. package/src/analysis/jvm-dependency-evidence.js +0 -138
  111. package/src/analysis/jvm-manifests.js +0 -114
  112. package/src/analysis/manifests.js +0 -123
  113. package/src/analysis/package-reachability.js +0 -39
  114. package/src/analysis/source-complexity.ast.js +0 -97
  115. package/src/analysis/source-complexity.constants.js +0 -55
  116. package/src/analysis/source-complexity.js +0 -14
  117. package/src/analysis/source-complexity.report.js +0 -81
  118. package/src/analysis/source-complexity.walk.js +0 -228
  119. package/src/analysis/source-correctness/retry-patterns.js +0 -93
  120. package/src/analysis/source-correctness.js +0 -222
  121. package/src/analysis/static-test-reachability.js +0 -150
  122. package/src/analysis/structure/dependency-graph.js +0 -151
  123. package/src/analysis/structure/findings.js +0 -162
  124. package/src/analysis/task-retrieval.js +0 -107
  125. package/src/analysis/transport-contracts.js +0 -224
  126. package/src/analysis/transport-runtime-evidence.js +0 -155
  127. package/src/analysis-kit.mjs +0 -17
  128. package/src/bounds.js +0 -4
  129. package/src/build-graph.js +0 -209
  130. package/src/child-env.js +0 -7
  131. package/src/config.js +0 -5
  132. package/src/extension/local-services.mjs +0 -75
  133. package/src/git-exec.js +0 -67
  134. package/src/graph/build-worker.js +0 -49
  135. package/src/graph/builder/go-receiver-resolution.js +0 -112
  136. package/src/graph/builder/js/dynamic-import.js +0 -26
  137. package/src/graph/builder/js/queries.js +0 -48
  138. package/src/graph/builder/lang-csharp.js +0 -40
  139. package/src/graph/builder/lang-css.js +0 -29
  140. package/src/graph/builder/lang-go.js +0 -140
  141. package/src/graph/builder/lang-html.js +0 -29
  142. package/src/graph/builder/lang-java-calls.js +0 -142
  143. package/src/graph/builder/lang-java.js +0 -215
  144. package/src/graph/builder/lang-js.js +0 -291
  145. package/src/graph/builder/lang-python.js +0 -235
  146. package/src/graph/builder/lang-rust-calls.js +0 -63
  147. package/src/graph/builder/lang-rust.js +0 -299
  148. package/src/graph/builder/lang-solidity.js +0 -126
  149. package/src/graph/builder/lang-sql.js +0 -263
  150. package/src/graph/builder/pass2-resolution.js +0 -81
  151. package/src/graph/builder/spec-pkg.js +0 -87
  152. package/src/graph/community.js +0 -27
  153. package/src/graph/edge-provenance.js +0 -31
  154. package/src/graph/file-lock.js +0 -69
  155. package/src/graph/freshness-probe.js +0 -142
  156. package/src/graph/graph-filter.js +0 -63
  157. package/src/graph/incremental-refresh.js +0 -235
  158. package/src/graph/internal-builder.barrels.js +0 -235
  159. package/src/graph/internal-builder.build.js +0 -300
  160. package/src/graph/internal-builder.java.js +0 -33
  161. package/src/graph/internal-builder.js +0 -12
  162. package/src/graph/internal-builder.langs.js +0 -157
  163. package/src/graph/internal-builder.pass2.js +0 -163
  164. package/src/graph/internal-builder.resolvers.js +0 -286
  165. package/src/graph/layout.js +0 -51
  166. package/src/graph/node-id.js +0 -7
  167. package/src/graph/parser-artifact-boundary.js +0 -55
  168. package/src/graph/relations.js +0 -4
  169. package/src/graph/repo-registry.js +0 -124
  170. package/src/graph/resolvers/rust.js +0 -117
  171. package/src/infra/infra-items.js +0 -255
  172. package/src/infra/infra-registry.js +0 -184
  173. package/src/infra/infra.detect.js +0 -119
  174. package/src/infra/infra.js +0 -38
  175. package/src/infra/infra.match.js +0 -102
  176. package/src/infra/infra.scan.js +0 -93
  177. package/src/mcp/actions/graph-lifecycle.mjs +0 -148
  178. package/src/mcp/architecture-bootstrap.mjs +0 -168
  179. package/src/mcp/architecture-starter.mjs +0 -234
  180. package/src/mcp/catalog.mjs +0 -233
  181. package/src/mcp/company-contract-page.mjs +0 -142
  182. package/src/mcp/company-contract-reconcile.mjs +0 -87
  183. package/src/mcp/company-contract-verdict.mjs +0 -42
  184. package/src/mcp/evidence/bun-lock-graph.mjs +0 -209
  185. package/src/mcp/evidence/duplicate-member-order.mjs +0 -8
  186. package/src/mcp/evidence/package-graph-common.mjs +0 -115
  187. package/src/mcp/evidence/package-lock-graph.mjs +0 -92
  188. package/src/mcp/evidence-snapshot.architecture.mjs +0 -80
  189. package/src/mcp/evidence-snapshot.common.mjs +0 -158
  190. package/src/mcp/evidence-snapshot.duplicates.mjs +0 -213
  191. package/src/mcp/evidence-snapshot.health.mjs +0 -102
  192. package/src/mcp/evidence-snapshot.inventory.mjs +0 -148
  193. package/src/mcp/evidence-snapshot.mjs +0 -50
  194. package/src/mcp/evidence-snapshot.package-graph.mjs +0 -34
  195. package/src/mcp/evidence-snapshot.structure.mjs +0 -84
  196. package/src/mcp/extension-api.mjs +0 -77
  197. package/src/mcp/git-output.mjs +0 -7
  198. package/src/mcp/graph/context-core.mjs +0 -111
  199. package/src/mcp/graph/context-seeds.mjs +0 -207
  200. package/src/mcp/graph/context-state.mjs +0 -85
  201. package/src/mcp/graph/reverse-reach.mjs +0 -42
  202. package/src/mcp/graph/tools-core.mjs +0 -143
  203. package/src/mcp/graph/tools-query.mjs +0 -276
  204. package/src/mcp/graph-context.mjs +0 -5
  205. package/src/mcp/graph-diff.mjs +0 -218
  206. package/src/mcp/health/audit-format.mjs +0 -199
  207. package/src/mcp/health/audit.mjs +0 -199
  208. package/src/mcp/health/dead-code.mjs +0 -110
  209. package/src/mcp/health/duplicates.mjs +0 -121
  210. package/src/mcp/health/endpoints.mjs +0 -71
  211. package/src/mcp/health/structure.mjs +0 -220
  212. package/src/mcp/runtime-version.mjs +0 -31
  213. package/src/mcp/server/auto-refresh.mjs +0 -66
  214. package/src/mcp/server/runtime-config.mjs +0 -43
  215. package/src/mcp/server/shutdown.mjs +0 -40
  216. package/src/mcp/staleness-notice.mjs +0 -20
  217. package/src/mcp/sync/evidence-architecture.mjs +0 -54
  218. package/src/mcp/sync/evidence-common.mjs +0 -88
  219. package/src/mcp/sync/evidence-duplicates.mjs +0 -97
  220. package/src/mcp/sync/evidence-health.mjs +0 -56
  221. package/src/mcp/sync/evidence-packages.mjs +0 -95
  222. package/src/mcp/sync/payload-common.mjs +0 -97
  223. package/src/mcp/sync/payload-v2.mjs +0 -54
  224. package/src/mcp/sync/payload-v3.mjs +0 -79
  225. package/src/mcp/sync-evidence.mjs +0 -23
  226. package/src/mcp/sync-payload.mjs +0 -70
  227. package/src/mcp/tool-result.mjs +0 -54
  228. package/src/mcp/tools-actions.mjs +0 -11
  229. package/src/mcp/tools-architecture.mjs +0 -177
  230. package/src/mcp/tools-company.mjs +0 -251
  231. package/src/mcp/tools-context.mjs +0 -222
  232. package/src/mcp/tools-endpoints.mjs +0 -207
  233. package/src/mcp/tools-graph-hubs.mjs +0 -78
  234. package/src/mcp/tools-graph.mjs +0 -17
  235. package/src/mcp/tools-health.mjs +0 -24
  236. package/src/mcp/tools-history.mjs +0 -28
  237. package/src/mcp/tools-impact-change.mjs +0 -220
  238. package/src/mcp/tools-impact-precision.mjs +0 -89
  239. package/src/mcp/tools-impact.mjs +0 -169
  240. package/src/mcp/tools-source.mjs +0 -238
  241. package/src/mcp/tools-verified-change.mjs +0 -200
  242. package/src/mcp-rg.mjs +0 -50
  243. package/src/mcp-runtime.mjs +0 -2
  244. package/src/mcp-server.mjs +0 -298
  245. package/src/mcp-source-tools.mjs +0 -163
  246. package/src/path-classification.js +0 -226
  247. package/src/path-ignore.js +0 -69
  248. package/src/precision/lsp-client/constants.js +0 -12
  249. package/src/precision/lsp-client/environment.js +0 -20
  250. package/src/precision/lsp-client/errors.js +0 -15
  251. package/src/precision/lsp-client/lifecycle.js +0 -114
  252. package/src/precision/lsp-client/message-parser.js +0 -81
  253. package/src/precision/lsp-client/protocol.js +0 -212
  254. package/src/precision/lsp-client/registry.js +0 -59
  255. package/src/precision/lsp-client/repo-uri.js +0 -60
  256. package/src/precision/lsp-client/stdio-client.js +0 -140
  257. package/src/precision/lsp-client.js +0 -10
  258. package/src/precision/lsp-overlay/budget-policy.js +0 -78
  259. package/src/precision/lsp-overlay/build.js +0 -261
  260. package/src/precision/lsp-overlay/contract.js +0 -61
  261. package/src/precision/lsp-overlay/reference-results.js +0 -108
  262. package/src/precision/lsp-overlay/semantic-inputs.js +0 -62
  263. package/src/precision/lsp-overlay/source-session.js +0 -142
  264. package/src/precision/lsp-overlay/store.js +0 -150
  265. package/src/precision/lsp-overlay/target-index.js +0 -152
  266. package/src/precision/lsp-overlay/target-query.js +0 -55
  267. package/src/precision/lsp-overlay.js +0 -11
  268. package/src/precision/symbol-query.js +0 -224
  269. package/src/precision/typescript-lsp-provider.js +0 -12
  270. package/src/precision/typescript-provider/client.js +0 -89
  271. package/src/precision/typescript-provider/discovery.js +0 -124
  272. package/src/precision/typescript-provider/isolated-runtime.js +0 -39
  273. package/src/precision/typescript-provider/project-host.js +0 -254
  274. package/src/precision/typescript-provider/project-safety.js +0 -166
  275. package/src/precision/typescript-provider/reference-usage.js +0 -53
  276. package/src/process.js +0 -95
  277. package/src/repo-path.js +0 -53
  278. package/src/scan/discover.inventory.js +0 -78
  279. package/src/scan/discover.js +0 -5
  280. package/src/scan/discover.list.js +0 -79
  281. package/src/scan/discover.stack.js +0 -227
  282. package/src/scan/search.core.js +0 -24
  283. package/src/scan/search.git.js +0 -102
  284. package/src/scan/search.js +0 -9
  285. package/src/scan/search.node.js +0 -83
  286. package/src/scan/search.preview.js +0 -49
  287. package/src/scan/search.rg.js +0 -145
  288. package/src/security/advisory-store.js +0 -172
  289. package/src/security/installed-jvm-rust.js +0 -46
  290. package/src/security/installed.js +0 -280
  291. package/src/security/malware-file-heuristics.js +0 -121
  292. package/src/security/malware-heuristics.exclusions.js +0 -134
  293. package/src/security/malware-heuristics.js +0 -15
  294. package/src/security/malware-heuristics.roots.js +0 -145
  295. package/src/security/malware-heuristics.scan.js +0 -89
  296. package/src/security/malware-heuristics.sweep.js +0 -122
  297. package/src/security/malware-scoring.js +0 -105
  298. package/src/security/match.js +0 -85
  299. package/src/security/registry-sig.classify.js +0 -137
  300. package/src/security/registry-sig.js +0 -18
  301. package/src/security/registry-sig.rules.js +0 -192
  302. package/src/security/rust-advisory-report.js +0 -60
  303. package/src/security/typosquat.js +0 -81
  304. package/src/util.js +0 -40
  305. package/src/version.js +0 -7
@@ -1,177 +0,0 @@
1
- // Executable target architecture for agents: read the active contract before a change, then run the
2
- // same deterministic verifier after it. No tool silently edits policy or accepts debt.
3
- import {contractForChange, normalizeArchitectureContract, verifyArchitecture} from '../analysis/architecture-contract.js'
4
- import {createPathClassifier, hasPathClass} from '../path-classification.js'
5
- import {detectRepoStack} from '../scan/discover.js'
6
- import {toolResult} from './tool-result.mjs'
7
-
8
- const version = new URL(import.meta.url).search
9
- const load = (path) => import(new URL(`${path}${version}`, import.meta.url).href)
10
- const [starter, bootstrap] = await Promise.all([
11
- load('./architecture-starter.mjs'),
12
- load('./architecture-bootstrap.mjs'),
13
- ])
14
- const {createArchitectureStarter, PROVISIONAL_BUDGETS} = starter
15
- export const tBootstrapArchitecture = bootstrap.tBootstrapArchitecture
16
- const activeContract = bootstrap.activeArchitectureContract
17
-
18
- const remediation = () => ({
19
- offlinePath: '.weavatrix/architecture.json',
20
- extensionAction: 'A composing extension may provide owner-approved remote contract storage',
21
- nextTool: 'verify_architecture',
22
- })
23
-
24
- const stackIds = (repoRoot) => {
25
- try {
26
- const stack = detectRepoStack(repoRoot)
27
- return ['languages', 'runtimes', 'tests', 'infra', 'deploy']
28
- .flatMap((category) => (Array.isArray(stack?.[category]) ? stack[category] : []))
29
- .map((item) => String(item?.id || '')).filter(Boolean)
30
- } catch { return [] }
31
- }
32
-
33
- function notConfiguredResult(g, action, {includeStarter = false, repoRoot = null} = {}) {
34
- const proposal = includeStarter ? createArchitectureStarter(g, repoRoot) : null
35
- const starter = proposal?.contract || null
36
- const starterText = starter
37
- ? ` A source-free starter with ${starter.components.length} product-code territories is available in JSON output from this lookup.`
38
- : ''
39
- return toolResult([
40
- `Architecture ${action} is NOT_CONFIGURED — no target contract is active.${starterText}`,
41
- 'Next: save .weavatrix/architecture.json, then call verify_architecture.',
42
- ].join('\n'), {
43
- state: 'NOT_CONFIGURED',
44
- remediation: remediation(),
45
- ...(starter ? {
46
- starterSummary: {
47
- components: starter.components.length, budgets: starter.budgets,
48
- observedDependencyDirections: proposal.observedDependencyProposals.length,
49
- candidateBudgetsNotEnforced: proposal.budgetProposals.length,
50
- },
51
- starterContract: starter,
52
- observedDependencyProposals: proposal.observedDependencyProposals,
53
- budgetProposals: proposal.budgetProposals,
54
- starterMethodology: proposal.methodology,
55
- } : {}),
56
- })
57
- }
58
-
59
- function classifyChangeFiles(files, repoRoot) {
60
- const classifier = createPathClassifier(repoRoot)
61
- const normalized = [...new Set((Array.isArray(files) ? files : [])
62
- .slice(0, 200)
63
- .map((file) => String(file || '').replace(/\\/g, '/').replace(/^\.\//, ''))
64
- .filter((file) => file && !file.startsWith('../') && !file.includes('/../')))]
65
- .sort((a, b) => a.localeCompare(b))
66
- const testOnlyFiles = normalized.filter((file) => hasPathClass(classifier.explain(file), 'test', 'e2e'))
67
- const testOnly = new Set(testOnlyFiles)
68
- return {files: normalized, productFiles: normalized.filter((file) => !testOnly.has(file)), testOnlyFiles}
69
- }
70
-
71
- function provisionalPreflight(g, args, ctx) {
72
- const surfaces = classifyChangeFiles(args?.files, ctx?.repoRoot)
73
- const intent = String(args?.intent || '').slice(0, 500)
74
- const budgetText = [
75
- `no new runtime cycles (baseline ${PROVISIONAL_BUDGETS.runtimeCycles})`,
76
- `file <= ${PROVISIONAL_BUDGETS.maxFileLoc} LOC`,
77
- `function <= ${PROVISIONAL_BUDGETS.maxFunctionLoc} LOC`,
78
- `cyclomatic <= ${PROVISIONAL_BUDGETS.maxCyclomatic}`,
79
- ].join('; ')
80
- return toolResult([
81
- `Architecture preflight is NOT_CONFIGURED for ${surfaces.files.length} file(s)${intent ? ` — ${intent}` : ''}.`,
82
- `Provisional no-regression guidance (not enforced policy): ${budgetText}.`,
83
- `${surfaces.productFiles.length} product file(s); ${surfaces.testOnlyFiles.length} test-only file(s). Save a target contract to make these budgets enforceable.`,
84
- ].join('\n'), {
85
- state: 'NOT_CONFIGURED',
86
- guidance: 'PROVISIONAL_BUDGETS',
87
- enforceable: false,
88
- intent,
89
- ...surfaces,
90
- provisionalBudgets: PROVISIONAL_BUDGETS,
91
- remediation: remediation(),
92
- })
93
- }
94
-
95
- export function tGetArchitectureContract(g, args, ctx) {
96
- if (args?.action === 'preview' || args?.action === 'approve') return tBootstrapArchitecture(g, args, ctx)
97
- const loaded = activeContract(ctx)
98
- if (!loaded.contract) {
99
- const text = loaded.error
100
- ? `Architecture contract is invalid (${loaded.source || 'unknown'}): ${loaded.error}`
101
- : 'No target architecture contract is active.'
102
- if (!loaded.error) return notConfiguredResult(g, 'lookup', {includeStarter: true, repoRoot: ctx?.repoRoot})
103
- return toolResult(text, {state: 'ERROR', source: loaded.source, error: loaded.error})
104
- }
105
- const contract = loaded.contract
106
- return toolResult([
107
- `Target architecture: ${contract.name} (${contract.style}, ${contract.enforcement}).`,
108
- `Contract ${contract.contractHash.slice(0, 12)} from ${loaded.source}; ${contract.components.length} components, ${contract.dependencyRules.length} dependency rules.`,
109
- `Quality budgets: ${Object.entries(contract.budgets).map(([key, value]) => `${key}=${value}`).join(', ') || '(none)'}.`,
110
- ].join('\n'), {state: 'ACTIVE', source: loaded.source, contract})
111
- }
112
-
113
- export function tPrepareChange(g, args = {}, ctx) {
114
- const loaded = activeContract(ctx)
115
- if (!loaded.contract) return provisionalPreflight(g, args, ctx)
116
- const prepared = contractForChange(loaded.contract, args.files)
117
- const surfaces = classifyChangeFiles(prepared.files, ctx?.repoRoot)
118
- const intent = String(args.intent || '').slice(0, 500)
119
- return toolResult([
120
- `Architecture preflight for ${prepared.files.length} file(s)${intent ? ` — ${intent}` : ''}.`,
121
- `Affected target components: ${prepared.components.join(', ') || '(unmapped)'}.`,
122
- ...(surfaces.testOnlyFiles.length ? [`Test-only surface: ${surfaces.testOnlyFiles.join(', ')}.`] : []),
123
- `Applicable rules: ${prepared.rules.map((rule) => rule.id).join(', ') || '(none)'}.`,
124
- 'Run verify_architecture after the edit; do not silently add an exception or rewrite the target contract.',
125
- ].join('\n'), {state: 'READY', intent, contractHash: loaded.contract.contractHash, ...prepared, productFiles: surfaces.productFiles, testOnlyFiles: surfaces.testOnlyFiles})
126
- }
127
-
128
- export function tVerifyArchitecture(g, args, ctx) {
129
- const loaded = activeContract(ctx)
130
- if (!loaded.contract) return notConfiguredResult(g, 'verification')
131
- const verification = verifyArchitecture({graph: g, contract: loaded.contract, technologies: stackIds(ctx.repoRoot)})
132
- const groups = [['new', verification.new], ['existing', verification.existing], ['fixed', verification.fixed], ['excepted', verification.excepted]]
133
- const lines = [
134
- `Architecture verify: ${verification.status} (${verification.enforcement}; contract ${verification.contractHash.slice(0, 12)}).`,
135
- `New ${verification.new.length} · existing debt ${verification.existing.length} · fixed ${verification.fixed.length} · excepted ${verification.excepted.length}.`,
136
- ...groups.filter(([, values]) => values.length).flatMap(([label, values]) => [
137
- `${label}:`,
138
- ...values.slice(0, 20).map((item) => typeof item === 'string' ? ` ${item}` : ` ${item.ruleId}: ${item.evidence}${item.current != null ? ` (${item.current} > ${item.target})` : ''}`),
139
- ]),
140
- ]
141
- return toolResult(lines.join('\n'), {state: verification.status, source: loaded.source, verification}, {
142
- completeness: {violationsReturned: Math.min(20, verification.new.length + verification.existing.length), violationsTotal: verification.new.length + verification.existing.length},
143
- })
144
- }
145
-
146
- export function tExplainArchitectureViolation(g, args, ctx) {
147
- const loaded = activeContract(ctx)
148
- if (!loaded.contract) return toolResult('No active architecture contract.', {state: 'NOT_CONFIGURED'})
149
- const verification = verifyArchitecture({graph: g, contract: loaded.contract, technologies: stackIds(ctx.repoRoot)})
150
- const fingerprint = String(args.fingerprint || '')
151
- const item = [...verification.new, ...verification.existing, ...verification.excepted]
152
- .find((entry) => entry.fingerprint === fingerprint)
153
- if (!item) return toolResult(`Violation ${fingerprint || '(missing)'} is not active in the current verification.`, {state: 'NOT_FOUND', fingerprint})
154
- const rule = loaded.contract.dependencyRules.find((candidate) => candidate.id === item.ruleId)
155
- return toolResult([
156
- `${item.ruleId}: ${item.evidence}.`,
157
- rule?.reason ? `Reason: ${rule.reason}` : 'The finding violates an explicit dependency or quality rule in the active target contract.',
158
- 'Preferred action: change the dependency/metric. If that is intentionally impossible, propose a time-bounded exception for human review.',
159
- ].join('\n'), {state: 'ACTIVE', violation: item, rule: rule || null})
160
- }
161
-
162
- export function tProposeArchitectureException(g, args, ctx) {
163
- const loaded = activeContract(ctx)
164
- if (!loaded.contract) return toolResult('No active architecture contract.', {state: 'NOT_CONFIGURED'})
165
- const verification = verifyArchitecture({graph: g, contract: loaded.contract, technologies: stackIds(ctx.repoRoot)})
166
- const item = [...verification.new, ...verification.existing].find((entry) => entry.fingerprint === String(args.fingerprint || ''))
167
- if (!item) return toolResult('Only an active violation can be proposed as an exception.', {state: 'NOT_FOUND'})
168
- const proposal = {
169
- fingerprint: item.fingerprint,
170
- reason: String(args.reason || '').trim().slice(0, 300),
171
- ...(args.expires ? {expires: String(args.expires)} : {}),
172
- }
173
- const checked = normalizeArchitectureContract({...loaded.contract, exceptions: [...loaded.contract.exceptions, proposal]})
174
- const normalized = checked.exceptions.find((entry) => entry.fingerprint === item.fingerprint)
175
- if (!normalized || !normalized.reason) return toolResult('A non-empty reason and optional YYYY-MM-DD expiry are required.', {state: 'INVALID'})
176
- return toolResult('Exception proposal prepared for human review; the contract was not changed.', {state: 'PROPOSED', proposal: normalized, contractHash: loaded.contract.contractHash})
177
- }
@@ -1,251 +0,0 @@
1
- // Cross-repository HTTP contract intelligence. Repository paths are resolved only through the
2
- // local global registry; callers can select an opaque repository UUID or an unambiguous label but
3
- // can never pass an arbitrary filesystem path through this tool.
4
- import {analyzeHttpContracts} from '../analysis/http-contracts.js'
5
- import {analyzeTransportContracts} from '../analysis/transport-contracts.js'
6
- import {graphHomeDir} from '../graph/layout.js'
7
- import {liveRepositoryRecords} from '../graph/repo-registry.js'
8
- import {ContractCursorError, paginateContractEvidence} from './company-contract-page.mjs'
9
- import {publicRecord, reconcileGraph} from './company-contract-reconcile.mjs'
10
- import {toolResult} from './tool-result.mjs'
11
- import {contractVerdict, contractVerdictLine} from './company-contract-verdict.mjs'
12
-
13
- const CROSS_REPO_HTTP_CONTRACT_V = 4
14
- const selectorText = (value) => String(value ?? '').trim()
15
-
16
- function selectRecord(records, selector) {
17
- const query = selectorText(selector)
18
- if (!query) return {error: 'repository selector is required'}
19
- const byId = records.find((record) => record.repositoryId === query)
20
- if (byId) return {record: byId}
21
- const byLabel = records.filter((record) => String(record.label || '').toLowerCase() === query.toLowerCase())
22
- if (byLabel.length === 1) return {record: byLabel[0]}
23
- if (byLabel.length > 1) return {
24
- error: `repository label "${query}" is ambiguous; use one of these repository IDs`,
25
- candidates: byLabel.map((record) => ({repositoryId: record.repositoryId, label: record.label})),
26
- }
27
- return {error: `repository "${query}" is not present in the live global graph registry`}
28
- }
29
-
30
- function safeAlias(record, records) {
31
- const base = String(record.label || 'repo').normalize('NFKC')
32
- .replace(/[^a-z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '').slice(0, 56) || 'repo'
33
- const duplicates = records.filter((item) => String(item.label || '').toLowerCase() === String(record.label || '').toLowerCase())
34
- return duplicates.length > 1 ? `${base}-${String(record.repositoryId).slice(0, 8)}` : base
35
- }
36
-
37
- export async function tTraceApiContract(_g, args = {}, ctx = {}) {
38
- const graphHome = ctx.graphHome || graphHomeDir()
39
- const records = liveRepositoryRecords(graphHome)
40
- if (!records.length) return toolResult(
41
- 'VERDICT NOT_CONFIGURED — the global repository registry has no live graphs. Open/build both the backend and client repositories first.',
42
- {status: 'NOT_CONFIGURED', availableRepositories: []},
43
- )
44
-
45
- const backendSelection = selectRecord(records, args.backend)
46
- if (!backendSelection.record) return toolResult(
47
- `VERDICT INVALID_REPOSITORY — ${backendSelection.error}.`,
48
- {status: 'INVALID_REPOSITORY', role: 'backend', ...backendSelection, availableRepositories: records.map((record) => publicRecord(record, safeAlias(record, records)))},
49
- )
50
- const rawClients = Array.isArray(args.clients) ? args.clients.slice(0, 20) : []
51
- if (!rawClients.length) return toolResult(
52
- 'VERDICT INVALID_REPOSITORY — at least one client repository ID or label is required.',
53
- {status: 'INVALID_REPOSITORY', role: 'clients'},
54
- )
55
- const clientRecords = []
56
- for (const selector of rawClients) {
57
- const selected = selectRecord(records, selector)
58
- if (!selected.record) return toolResult(
59
- `VERDICT INVALID_REPOSITORY — ${selected.error}.`,
60
- {status: 'INVALID_REPOSITORY', role: 'client', selector, ...selected},
61
- )
62
- if (!clientRecords.some((record) => record.repositoryId === selected.record.repositoryId)) clientRecords.push(selected.record)
63
- }
64
- if (clientRecords.some((record) => record.repositoryId === backendSelection.record.repositoryId)) return toolResult(
65
- 'VERDICT INVALID_REPOSITORY — backend and client selections must be distinct repositories.',
66
- {status: 'INVALID_REPOSITORY', role: 'clients'},
67
- )
68
-
69
- const backend = backendSelection.record
70
- const backendAlias = safeAlias(backend, records)
71
- const clients = clientRecords.map((record) => ({record, alias: safeAlias(record, records)}))
72
- const reconciled = []
73
- for (const selected of [
74
- {record: backend, alias: backendAlias, role: 'backend'},
75
- ...clients.map(({record, alias}) => ({record, alias, role: 'client'})),
76
- ]) {
77
- reconciled.push(await reconcileGraph(selected.record, selected.alias, selected.role, graphHome))
78
- }
79
- const backendGraph = reconciled[0]
80
- const clientGraphs = reconciled.slice(1)
81
- const reconciliationReasons = reconciled.filter((item) => item.reason).map((item) => item.reason)
82
- const graphReconciliation = reconciled.map((item) => item.publicStatus)
83
- if (!backendGraph.graph || clientGraphs.some((item) => !item.graph)) {
84
- const reasons = reconciliationReasons.length ? reconciliationReasons : ['one or more selected graphs could not be refreshed and loaded']
85
- const completeness = {complete: false, status: 'PARTIAL', reasons}
86
- return toolResult(
87
- `VERDICT PARTIAL — selected repository graphs could not all be refreshed and loaded.\nCompleteness: partial — ${reasons.join('; ')}.`,
88
- {
89
- crossRepoHttpContractV: CROSS_REPO_HTTP_CONTRACT_V,
90
- status: 'PARTIAL',
91
- repositories: {
92
- backend: publicRecord(backend, backendAlias),
93
- clients: clients.map(({record, alias}) => publicRecord(record, alias)),
94
- },
95
- graphReconciliation,
96
- completeness,
97
- },
98
- {completeness, warnings: [{code: 'CROSS_REPO_GRAPH_REFRESH_PARTIAL', message: reasons.join('; ')}]},
99
- )
100
- }
101
-
102
- try {
103
- let analysis = analyzeHttpContracts({
104
- backend: {id: backendAlias, repoRoot: backend.repoPath, graph: backendGraph.graph},
105
- clients: clientGraphs.map((item) => ({id: item.alias, repoRoot: item.record.repoPath, graph: item.graph})),
106
- method: args.method,
107
- path: args.path,
108
- changedFiles: args.changed_files,
109
- includeTests: args.include_tests === true,
110
- clientNames: args.client_names,
111
- wrappers: args.client_wrappers,
112
- autoDiscoverWrappers: args.auto_discover_wrappers !== false,
113
- maxImpactDepth: args.max_impact_depth,
114
- maxEndpoints: args.max_endpoints,
115
- maxMatches: args.max_matches,
116
- maxAffectedFiles: args.max_affected_files,
117
- runtimeValues: args.runtime_config,
118
- })
119
- const selectedTransport = ['all', 'http', 'graphql', 'grpc', 'event'].includes(args.transport) ? args.transport : 'all'
120
- if (!['all', 'http'].includes(selectedTransport)) analysis = {
121
- ...analysis, status: 'complete', completeness: {complete: true, reasons: []}, endpoints: [], uncertain: [],
122
- totals: {...analysis.totals, endpoints: 0, clientCalls: 0, matches: 0, methodMismatches: 0, uncertainCalls: 0, notDeadExternalUse: 0, notDeadExternalHandlers: 0, possibleExternalUse: 0, unknownLiveness: 0},
123
- }
124
- const transportAnalysis = selectedTransport === 'http'
125
- ? {transportContractsV: 2, transport: 'http', status: 'COMPLETE', completeness: {complete: true, reasons: []}, totals: {contracts: 0, matches: 0, uncertain: 0, filesScanned: 0, runtimeObservations: 0, runtimeResolved: 0, runtimeReportsComplete: 0}, contracts: [], uncertain: [], runtimeEvidence: {status: 'NOT_APPLICABLE', reports: [], resolvedUnknowns: 0}}
126
- : analyzeTransportContracts({
127
- backend: {id: backendAlias, repoRoot: backend.repoPath, graph: backendGraph.graph},
128
- clients: clientGraphs.map((item) => ({id: item.alias, repoRoot: item.record.repoPath, graph: item.graph})),
129
- transport: selectedTransport === 'all' ? 'all' : selectedTransport,
130
- includeTests: args.include_tests === true,
131
- maxImpactDepth: args.max_impact_depth,
132
- maxAffectedFiles: args.max_affected_files,
133
- runtimeEvidenceFiles: args.runtime_evidence_files,
134
- runtimeEvidenceMaxAgeHours: args.runtime_evidence_max_age_hours,
135
- })
136
- const verdict = contractVerdict(analysis, transportAnalysis)
137
- const reasons = [...new Set([...reconciliationReasons, ...(analysis.completeness?.reasons || []), ...(transportAnalysis.completeness?.reasons || [])])]
138
- const completeness = {
139
- complete: reasons.length === 0 && analysis.completeness?.complete === true,
140
- status: reasons.length === 0 && analysis.completeness?.complete === true ? 'COMPLETE' : 'PARTIAL',
141
- reasons,
142
- }
143
- const topN = Math.max(1, Math.min(50, Number(args.top_n) || 10))
144
- const ranked = [...analysis.endpoints].sort((left, right) =>
145
- right.callsites.length - left.callsites.length ||
146
- right.affected.files.length - left.affected.files.length ||
147
- left.path.localeCompare(right.path))
148
- const lines = [
149
- contractVerdictLine(verdict, analysis.totals.endpoints + transportAnalysis.totals.contracts),
150
- `Scope: ${backend.label} → ${clients.map(({record}) => record.label).join(', ')}; ${analysis.totals.endpoints} HTTP endpoint(s), ${transportAnalysis.totals.contracts} GraphQL/gRPC/event contract(s), ${analysis.totals.clientCalls} inspected HTTP call(s), ${verdict.uncertainCalls} uncertain.`,
151
- ...ranked.slice(0, topN).flatMap((endpoint) => {
152
- const location = endpoint.file ? ` (${endpoint.backend}:${endpoint.file}${endpoint.line ? `:${endpoint.line}` : ''})` : ''
153
- const callsites = endpoint.callsites.slice(0, 3)
154
- .map((call) => ` caller ${call.clientRepo}:${call.file}:${call.line} (${call.match.confidence}, ${call.match.kind})`)
155
- const screens = endpoint.affected.screens.slice(0, 3)
156
- .map((screen) => ` screen ${screen.client}:${screen.file} (distance ${screen.distance})`)
157
- return [
158
- ` ${endpoint.method} ${endpoint.path}${location} [${endpoint.liveness.status}${endpoint.handler ? `; handler ${endpoint.handler}` : ''}] → ${endpoint.callsites.length} callsite(s), ${endpoint.affected.screens.length} screen(s), ${endpoint.affected.files.length} affected file(s)`,
159
- ...callsites,
160
- ...screens,
161
- ]
162
- }),
163
- // Mismatch-only endpoints rarely rank into top_n (zero callsites), yet they drive the
164
- // *_METHOD_MISMATCH verdicts — always surface them, citing the verdict's own total.
165
- ...(analysis.totals.methodMismatches > 0 ? [
166
- ` Method mismatches (${verdict.methodMismatches} call(s)):`,
167
- ...analysis.endpoints.filter((endpoint) => endpoint.methodMismatches > 0).slice(0, 5).flatMap((endpoint) => [
168
- ` ${endpoint.method} ${endpoint.path} — ${endpoint.methodMismatches} call(s) use a different method`,
169
- ...(endpoint.methodMismatchSites || []).slice(0, 2).map((site) => ` caller ${site.clientRepo}:${site.file}:${site.line} uses ${site.method}`),
170
- ]),
171
- ] : []),
172
- ...transportAnalysis.contracts.filter((contract) => contract.callsites.length).slice(0, topN).map((contract) =>
173
- ` ${contract.transport.toUpperCase()} ${contract.service ? `${contract.service}.` : contract.operation ? `${contract.operation} ` : ''}${contract.name} (${contract.file}:${contract.line}) [${contract.liveness}] → ${contract.callsites.length} callsite(s), ${contract.affected.files.length} affected file(s)`),
174
- completeness.complete
175
- ? 'Completeness: complete within the declared repository graphs, supported static models and fresh revision-bound runtime capture.'
176
- : `Completeness: partial — ${completeness.reasons.join('; ')}.`,
177
- ]
178
- let evidencePage
179
- try {
180
- evidencePage = paginateContractEvidence({
181
- analysis,
182
- transportAnalysis,
183
- args,
184
- fingerprintParts: [
185
- backend.repositoryId,
186
- backendGraph.graph?.graphRevision || null,
187
- ...clientGraphs.flatMap((item) => [item.record.repositoryId, item.graph?.graphRevision || null]),
188
- selectedTransport,
189
- args.method || null,
190
- args.path || null,
191
- Array.isArray(args.changed_files) ? [...args.changed_files].sort() : [],
192
- args.include_tests === true,
193
- ],
194
- })
195
- } catch (error) {
196
- if (!(error instanceof ContractCursorError)) throw error
197
- return toolResult(
198
- `VERDICT INVALID_CURSOR — ${error.message}. Restart from the first page without cursor.`,
199
- {status: 'INVALID_CURSOR', code: error.code, reason: error.message},
200
- {page: {status: 'INVALID_CURSOR'}},
201
- )
202
- }
203
- const transportSummary = {
204
- transportContractsV: transportAnalysis.transportContractsV,
205
- transport: transportAnalysis.transport,
206
- status: transportAnalysis.status,
207
- completeness: transportAnalysis.completeness,
208
- totals: transportAnalysis.totals,
209
- runtimeEvidence: transportAnalysis.runtimeEvidence,
210
- }
211
- const result = {
212
- crossRepoHttpContractV: CROSS_REPO_HTTP_CONTRACT_V,
213
- verdict,
214
- repositories: {
215
- backend: publicRecord(backend, backendAlias),
216
- clients: clients.map(({record, alias}) => publicRecord(record, alias)),
217
- },
218
- httpContractsV: analysis.httpContractsV,
219
- filters: analysis.filters,
220
- limits: analysis.limits,
221
- totals: analysis.totals,
222
- wrapperDiscovery: analysis.wrapperDiscovery,
223
- transportContracts: transportSummary,
224
- evidencePage,
225
- status: completeness.status,
226
- graphReconciliation,
227
- completeness,
228
- }
229
- return toolResult(lines.join('\n'), result, {
230
- completeness,
231
- page: {
232
- detail: evidencePage.detail,
233
- offset: evidencePage.offset,
234
- pageSize: evidencePage.pageSize,
235
- totalItems: evidencePage.totalItems,
236
- returnedItems: evidencePage.returnedItems,
237
- hasMore: evidencePage.hasMore,
238
- nextCursor: evidencePage.nextCursor,
239
- },
240
- warnings: completeness.complete ? [] : [{code: 'CROSS_REPO_ANALYSIS_PARTIAL', message: completeness.reasons.join('; ')}],
241
- })
242
- } catch (error) {
243
- const reason = error instanceof Error ? error.message : 'cross-repository analysis failed'
244
- const completeness = {complete: false, status: 'PARTIAL', reasons: [reason]}
245
- return toolResult(
246
- `VERDICT PARTIAL — ${reason}.`,
247
- {status: 'PARTIAL', graphReconciliation, completeness},
248
- {completeness, warnings: [{code: 'CROSS_REPO_ANALYSIS_PARTIAL', message: reason}]},
249
- )
250
- }
251
- }
@@ -1,222 +0,0 @@
1
- import {isStructuralRelation} from '../graph/relations.js'
2
- import {boundedInteger} from '../bounds.js'
3
- import {isSymbol, labelOf} from './graph-context.mjs'
4
- import {toolResult} from './tool-result.mjs'
5
- import {sourceExcerpt} from './tools-source.mjs'
6
- import {createPathClassifier, hasPathClass} from '../path-classification.js'
7
-
8
- const MAX_LINE_SAMPLES = 5
9
- const CONTEXT_NON_PRODUCT = Object.freeze(['test', 'e2e', 'generated', 'vendored', 'mock', 'story', 'docs', 'benchmark', 'temp'])
10
-
11
- const fileOf = (g, id) => {
12
- const node = g.byId.get(String(id))
13
- return String(node?.source_file || (isSymbol(id) ? String(id).split('#')[0] : id))
14
- }
15
-
16
- function aggregateEdges(g, edges, cap, {
17
- callsiteFile = null, classifier = null, includeClassified = true, productionFirst = false,
18
- } = {}) {
19
- const groups = new Map()
20
- for (const edge of edges || []) {
21
- if (isStructuralRelation(edge.relation) || edge.barrelProxy === true) continue
22
- const id = String(edge.id)
23
- const relation = String(edge.relation || 'references')
24
- const key = `${id}\0${relation}`
25
- let group = groups.get(key)
26
- if (!group) {
27
- const targetFile = fileOf(g, id)
28
- group = {
29
- id, label: labelOf(g, id), relation, count: 0, lines: [],
30
- file: callsiteFile || targetFile,
31
- ...(callsiteFile && callsiteFile !== targetFile ? {targetFile} : {}),
32
- }
33
- groups.set(key, group)
34
- }
35
- group.count++
36
- if (Number.isInteger(edge.line) && group.lines.length < MAX_LINE_SAMPLES && !group.lines.includes(edge.line)) group.lines.push(edge.line)
37
- if (edge.typeOnly === true) group.typeOnly = true
38
- if (edge.compileOnly === true) group.compileOnly = true
39
- }
40
- const all = [...groups.values()]
41
- if (classifier) for (const group of all) {
42
- const info = classifier.explain(group.file, {content: ''})
43
- const classes = CONTEXT_NON_PRODUCT.filter((name) => hasPathClass(info, name))
44
- group.classified = classes.length > 0 || info?.excluded === true
45
- if (classes.length) group.pathClasses = classes
46
- }
47
- const eligible = includeClassified ? all : all.filter((group) => !group.classified)
48
- eligible.sort((left, right) => (productionFirst ? Number(left.classified) - Number(right.classified) : 0)
49
- || right.count - left.count || left.file.localeCompare(right.file) || left.id.localeCompare(right.id))
50
- return {
51
- total: eligible.length,
52
- available: all.length,
53
- suppressed: all.length - eligible.length,
54
- shown: eligible.slice(0, cap),
55
- capped: eligible.length > cap,
56
- }
57
- }
58
-
59
- const sameOrigin = (occurrence, definition) => occurrence.originId === definition.id
60
- || (occurrence.originFile === definition.file && occurrence.originName === definition.name)
61
-
62
- function exactReExportSites(g, definition, cap) {
63
- const occurrences = Array.isArray(g.reExportOccurrences) ? g.reExportOccurrences : []
64
- const exposures = new Map()
65
- if (definition.exported) exposures.set(definition.file, new Set([definition.name]))
66
- const shown = new Map()
67
- const add = (occurrence, exported = occurrence.exported) => {
68
- const key = `${occurrence.file}\0${occurrence.line}\0${exported}\0${occurrence.kind}`
69
- if (shown.has(key)) return false
70
- shown.set(key, {
71
- file: occurrence.file,
72
- line: occurrence.line,
73
- kind: occurrence.kind,
74
- exported,
75
- imported: occurrence.imported,
76
- targetFile: occurrence.targetFile,
77
- typeOnly: occurrence.typeOnly === true,
78
- ...(occurrence.specifier ? {specifier: occurrence.specifier} : {}),
79
- ...(occurrence.originFile ? {originFile: occurrence.originFile, originName: occurrence.originName} : {}),
80
- })
81
- return true
82
- }
83
- for (let pass = 0; pass <= occurrences.length; pass++) {
84
- let changed = false
85
- for (const occurrence of occurrences) {
86
- if (occurrence.kind === 'star') {
87
- const names = exposures.get(occurrence.targetFile)
88
- if (!names) continue
89
- for (const name of names) {
90
- if (name === 'default') continue
91
- changed = add(occurrence, name) || changed
92
- let exported = exposures.get(occurrence.file)
93
- if (!exported) exposures.set(occurrence.file, (exported = new Set()))
94
- const before = exported.size
95
- exported.add(name)
96
- changed = exported.size !== before || changed
97
- }
98
- continue
99
- }
100
- if (!sameOrigin(occurrence, definition)) continue
101
- changed = add(occurrence) || changed
102
- if (occurrence.kind !== 'namespace') {
103
- let exported = exposures.get(occurrence.file)
104
- if (!exported) exposures.set(occurrence.file, (exported = new Set()))
105
- const before = exported.size
106
- exported.add(occurrence.exported)
107
- changed = exported.size !== before || changed
108
- }
109
- }
110
- if (!changed) break
111
- }
112
- const all = [...shown.values()].sort((left, right) => left.file.localeCompare(right.file)
113
- || left.line - right.line || left.exported.localeCompare(right.exported))
114
- return {total: all.length, shown: all.slice(0, cap), capped: all.length > cap}
115
- }
116
-
117
- function linesForGroups(title, groups) {
118
- const suppression = groups.suppressed ? `; ${groups.suppressed} classified container(s) suppressed` : ''
119
- if (!groups.shown.length) return [`${title}: none${suppression}`]
120
- const lines = [`${title}: ${groups.total} container(s)${groups.capped ? ` (${groups.shown.length} shown)` : ''}${suppression}`]
121
- for (const group of groups.shown) {
122
- const sites = group.lines.length ? `:${group.lines.join(',')}` : ''
123
- const destination = group.targetFile ? ` → ${group.targetFile}` : ''
124
- const classified = group.classified ? ` [classified${group.pathClasses?.length ? `:${group.pathClasses.join('+')}` : ''}]` : ''
125
- lines.push(` ${group.count}× ${group.relation} ${group.label} [call site ${group.file}${sites}${destination}]${classified}`)
126
- }
127
- return lines
128
- }
129
-
130
- function textFor(result) {
131
- if (result.status !== 'OK') return result.text || `Context bundle: ${result.status}`
132
- const definition = result.definition
133
- const lines = [
134
- `Context bundle: ${definition.label} [${definition.id}]`,
135
- `Definition: ${definition.file}:${definition.line} (${definition.kind}, ${definition.space} space)`,
136
- `Evidence: ${result.evidence.state}; ${result.references.occurrences} exact reference occurrence(s) in ${result.references.files} file(s).`,
137
- ...linesForGroups('Inbound', result.inbound),
138
- ...linesForGroups('Outbound', result.outbound),
139
- `Re-export sites: ${result.reExports.total}${result.reExports.capped ? ` (${result.reExports.shown.length} shown)` : ''}`,
140
- ]
141
- for (const site of result.reExports.shown) lines.push(` ${site.file}:${site.line} ${site.kind} ${site.imported} → ${site.exported}${site.typeOnly ? ' [type]' : ''}`)
142
- for (const source of result.source) lines.push('', `${source.role} source (${source.file}:${source.startLine}-${source.endLine}):`, source.text)
143
- return lines.join('\n')
144
- }
145
-
146
- export async function tContextBundle(g, args = {}, ctx = {}, inspectSymbol) {
147
- if (typeof inspectSymbol !== 'function') throw new Error('context_bundle requires inspect_symbol support')
148
- const maxRelated = boundedInteger(args.max_related, 10, 1, 30)
149
- const maxReExports = boundedInteger(args.max_reexports, 20, 1, 100)
150
- const maxSourceFiles = boundedInteger(args.max_source_files, 4, 1, 8)
151
- const inspected = await inspectSymbol(g, {
152
- ...args,
153
- max_containers: Math.min(maxRelated, boundedInteger(args.max_containers, 10, 1, 30)),
154
- context_lines: boundedInteger(args.context_lines, 4, 0, 12),
155
- }, ctx)
156
- const inspection = inspected?.result
157
- if (!inspection || inspection.status !== 'OK') return inspected
158
- const definition = {
159
- ...inspection.definition,
160
- name: String(g.byId.get(inspection.definition.id)?.label || '').replace(/\(\)$/, ''),
161
- }
162
- const classifier = createPathClassifier(ctx.repoRoot || null)
163
- const includeClassified = args.include_classified === true
164
- const inbound = aggregateEdges(g, g.inn.get(definition.id), maxRelated, {
165
- classifier, includeClassified, productionFirst: true,
166
- })
167
- const outbound = aggregateEdges(g, g.out.get(definition.id), maxRelated, {callsiteFile: definition.file})
168
- const reExports = exactReExportSites(g, definition, maxReExports)
169
- const source = []
170
- const overlaps = (left, right) => left.file === right.file
171
- && left.startLine <= right.endLine && right.startLine <= left.endLine
172
- const append = (role, excerpt) => {
173
- if (!excerpt || source.length >= maxSourceFiles) return
174
- if (source.some((item) => overlaps(item, excerpt))) return
175
- source.push({role, ...excerpt})
176
- }
177
- append('Definition', inspection.source.definition)
178
- const contextLines = boundedInteger(args.context_lines, 4, 0, 12)
179
- const excerptCandidates = []
180
- const groupExcerpts = (groups, role) => {
181
- const primary = []
182
- const secondary = []
183
- for (const group of groups.shown) for (let index = 0; index < group.lines.length; index++) {
184
- const candidate = {role, excerpt: sourceExcerpt(ctx.repoRoot, group.file, group.lines[index], contextLines)}
185
- ;(index === 0 ? primary : secondary).push(candidate)
186
- }
187
- return [...primary, ...secondary]
188
- }
189
- const outboundExcerpts = groupExcerpts(outbound, 'Outbound call site')
190
- const inboundExcerpts = groupExcerpts(inbound, 'Inbound call site')
191
- for (let index = 0; index < Math.max(outboundExcerpts.length, inboundExcerpts.length); index++) {
192
- if (outboundExcerpts[index]) excerptCandidates.push(outboundExcerpts[index])
193
- if (inboundExcerpts[index]) excerptCandidates.push(inboundExcerpts[index])
194
- }
195
- for (const excerpt of inspection.source.callers || []) excerptCandidates.push({role: 'Reference', excerpt})
196
- const deferred = []
197
- for (const candidate of excerptCandidates) {
198
- const knownFile = source.some((item) => item.file === candidate.excerpt?.file)
199
- if (knownFile && candidate.role !== 'Outbound call site') deferred.push(candidate)
200
- else append(candidate.role, candidate.excerpt)
201
- }
202
- for (const candidate of deferred) append(candidate.role, candidate.excerpt)
203
- const result = {
204
- status: 'OK', definition, evidence: inspection.evidence,
205
- references: {
206
- occurrences: inspection.exact.occurrences,
207
- files: inspection.exact.files,
208
- containers: inspection.exact.containers,
209
- capped: inspection.exact.capped,
210
- },
211
- inbound, outbound, reExports, source,
212
- }
213
- return toolResult(textFor(result), result, {
214
- warnings: inspected.warnings,
215
- completeness: {
216
- status: inspection.evidence.state === 'EXACT' && !inspection.exact.capped && !inbound.capped && !outbound.capped && !reExports.capped ? 'complete' : 'bounded',
217
- relatedLimit: maxRelated,
218
- reExportLimit: maxReExports,
219
- sourceFileLimit: maxSourceFiles,
220
- },
221
- })
222
- }