@mmerterden/multi-agent-pipeline 23.3.0 → 23.4.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 (224) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +25 -6
  3. package/README.tr.md +26 -7
  4. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  5. package/docs/adr/0010-own-code-graph.md +299 -8
  6. package/docs/architecture.md +3 -3
  7. package/docs/ecosystem.md +10 -10
  8. package/docs/engineering.md +4 -4
  9. package/docs/facts.json +8 -8
  10. package/docs/features.md +5 -5
  11. package/docs/performance.md +17 -17
  12. package/install/_dev-only-files.mjs +9 -0
  13. package/install/claude.mjs +28 -2
  14. package/install/templates/claude-hooks.json +32 -1
  15. package/manifest.json +223 -155
  16. package/package.json +11 -3
  17. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  18. package/pipeline/commands/multi-agent/design-check/SKILL.md +2 -2
  19. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  20. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  21. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  22. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  23. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  24. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  25. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  26. package/pipeline/contract/CHANGELOG.md +49 -0
  27. package/pipeline/contract/build.mjs +13 -1
  28. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  29. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  30. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  31. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  32. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  33. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  34. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  35. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  36. package/pipeline/contract/fixtures/runs-running.json +4 -1
  37. package/pipeline/contract/manifest.json +28 -15
  38. package/pipeline/contract/types/index.d.ts +55 -3
  39. package/pipeline/lib/detach-self.mjs +95 -0
  40. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  41. package/pipeline/lib/rotated-log.mjs +93 -0
  42. package/pipeline/lib/tls-trust.mjs +29 -0
  43. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  44. package/pipeline/lib/usage-names.generated.mjs +614 -0
  45. package/pipeline/lib/usage-run-key.mjs +235 -0
  46. package/pipeline/lib/usage-vocab.mjs +210 -0
  47. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  48. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  49. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  50. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  51. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  52. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  53. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  54. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  55. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  56. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  57. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  58. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  59. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  60. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  61. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  62. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  63. package/pipeline/multi-agent-refs/help/en.md +3 -2
  64. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  65. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  66. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  67. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  68. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  69. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  70. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  71. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  72. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  73. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  74. package/pipeline/office/index.html +1207 -233
  75. package/pipeline/office/toolkit.json +1 -1
  76. package/pipeline/rules/outside-the-pipeline.md +1 -1
  77. package/pipeline/schemas/activity.schema.json +23 -0
  78. package/pipeline/schemas/agent-state.schema.json +6 -1
  79. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  80. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  81. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  82. package/pipeline/schemas/code-graph.schema.json +2 -2
  83. package/pipeline/schemas/examples/design-check-config.json +27 -0
  84. package/pipeline/schemas/learning-curve.schema.json +67 -0
  85. package/pipeline/schemas/office-jobs.json +69 -2
  86. package/pipeline/schemas/office-jobs.schema.json +8 -1
  87. package/pipeline/schemas/phases.json +5 -0
  88. package/pipeline/schemas/phases.schema.json +8 -0
  89. package/pipeline/schemas/prefs.schema.json +46 -12
  90. package/pipeline/schemas/runs-index.schema.json +17 -0
  91. package/pipeline/schemas/toolkit-path-params.json +84 -8
  92. package/pipeline/scripts/README.md +1 -0
  93. package/pipeline/scripts/_code-graph.mjs +184 -103
  94. package/pipeline/scripts/_contract-core.mjs +1 -1
  95. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  96. package/pipeline/scripts/_diff-impact.mjs +21 -2
  97. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  98. package/pipeline/scripts/_http-post.mjs +103 -115
  99. package/pipeline/scripts/_safe-read.mjs +57 -0
  100. package/pipeline/scripts/_skill-practices.mjs +26 -0
  101. package/pipeline/scripts/_strip-code.mjs +380 -0
  102. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  103. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  104. package/pipeline/scripts/call-graph/index.mjs +78 -0
  105. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  106. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  107. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  108. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  109. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  110. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  111. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  112. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  113. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  114. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  115. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  116. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  117. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  118. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  119. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  120. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  121. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  122. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  123. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  124. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  125. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  126. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  127. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  128. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  129. package/pipeline/scripts/contract-server.mjs +1 -0
  130. package/pipeline/scripts/feedback-send.mjs +26 -26
  131. package/pipeline/scripts/gate-ledger.mjs +2 -1
  132. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  133. package/pipeline/scripts/graph-affected.mjs +109 -20
  134. package/pipeline/scripts/graph-build.mjs +95 -15
  135. package/pipeline/scripts/graph-export.mjs +272 -0
  136. package/pipeline/scripts/graph-hint.mjs +15 -2
  137. package/pipeline/scripts/graph-query.mjs +305 -26
  138. package/pipeline/scripts/graph-report.mjs +187 -1
  139. package/pipeline/scripts/health-report.mjs +3 -4
  140. package/pipeline/scripts/infra/docs.mjs +317 -0
  141. package/pipeline/scripts/infra/extract.mjs +998 -0
  142. package/pipeline/scripts/infra/graph.mjs +245 -0
  143. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  144. package/pipeline/scripts/job-launch.mjs +67 -2
  145. package/pipeline/scripts/learning-curve.mjs +288 -178
  146. package/pipeline/scripts/log-metric.sh +10 -1
  147. package/pipeline/scripts/note-agent-event.mjs +3 -4
  148. package/pipeline/scripts/note-command-use.mjs +333 -0
  149. package/pipeline/scripts/note-command-use.sh +126 -0
  150. package/pipeline/scripts/note-mcp-call.sh +89 -0
  151. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  152. package/pipeline/scripts/note-session.sh +62 -3
  153. package/pipeline/scripts/note-skill-use.mjs +58 -2
  154. package/pipeline/scripts/office-build.mjs +115 -1
  155. package/pipeline/scripts/office-memory.mjs +14 -5
  156. package/pipeline/scripts/pair.mjs +333 -0
  157. package/pipeline/scripts/pre-push-check.sh +1 -1
  158. package/pipeline/scripts/remote/cbor.mjs +128 -0
  159. package/pipeline/scripts/remote/contract.mjs +98 -0
  160. package/pipeline/scripts/remote/handler.mjs +317 -0
  161. package/pipeline/scripts/remote/handles.mjs +57 -0
  162. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  163. package/pipeline/scripts/remote/listener.mjs +204 -0
  164. package/pipeline/scripts/remote/lockout.mjs +103 -0
  165. package/pipeline/scripts/remote/nonces.mjs +61 -0
  166. package/pipeline/scripts/remote/pairing.mjs +519 -0
  167. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  168. package/pipeline/scripts/remote/store.mjs +188 -0
  169. package/pipeline/scripts/remote/transport.mjs +211 -0
  170. package/pipeline/scripts/remote/verbs.json +70 -0
  171. package/pipeline/scripts/remote/verbs.mjs +217 -0
  172. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  173. package/pipeline/scripts/remote/wire.mjs +364 -0
  174. package/pipeline/scripts/remote-listener.mjs +83 -0
  175. package/pipeline/scripts/route-learn.mjs +4 -4
  176. package/pipeline/scripts/run-kill.mjs +1 -1
  177. package/pipeline/scripts/run-write.mjs +13 -2
  178. package/pipeline/scripts/runs-index.mjs +30 -3
  179. package/pipeline/scripts/search-logs.sh +9 -0
  180. package/pipeline/scripts/session-brief.mjs +458 -0
  181. package/pipeline/scripts/session-brief.sh +130 -0
  182. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  183. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  184. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  185. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  186. package/pipeline/scripts/token-budget-report.mjs +3 -2
  187. package/pipeline/scripts/uninstall.mjs +29 -0
  188. package/pipeline/scripts/usage-access.mjs +16 -31
  189. package/pipeline/scripts/usage-health.mjs +31 -62
  190. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  191. package/pipeline/scripts/usage-register.mjs +39 -29
  192. package/pipeline/scripts/usage-report.mjs +579 -178
  193. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  194. package/pipeline/scripts/write-state.mjs +39 -0
  195. package/pipeline/skills/.skill-manifest.json +21 -17
  196. package/pipeline/skills/.skills-index.json +13 -2
  197. package/pipeline/skills/shared/README.md +5 -4
  198. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  199. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  200. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  201. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  202. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  203. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  204. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  205. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  206. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  207. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  208. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  209. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  210. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  211. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  212. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  213. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  214. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  215. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  216. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  219. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  220. package/pipeline/skills/skills-index.md +3 -2
  221. package/docs/FIGMA_PIPELINE.md +0 -137
  222. package/pipeline/lib/identifier-scan.mjs +0 -156
  223. package/pipeline/scripts/publish-staged.mjs +0 -324
  224. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -0,0 +1,1125 @@
1
+ /**
2
+ * @file resolve.mjs - resolve scanned call chains into `calls` edges.
3
+ *
4
+ * The scanner (scan.mjs) records, per function, the chains it contains and the
5
+ * facts each file declares (types, functions, fields, imports). This module
6
+ * joins them across files. Without a language server and without types on most
7
+ * expressions it resolves what a reader of the source could resolve by name:
8
+ *
9
+ * - the receiver's type from a declaration, a parameter, a field, `self`, a
10
+ * constructor call or the return type of the previous call in the chain
11
+ * - the method on that type, its supertypes, and the extensions that add to it
12
+ * - a call through a protocol or interface to every implementer of the member
13
+ * - a bare call to a method of the enclosing type, a function in the same file,
14
+ * the same package or an imported module, or a constructor
15
+ * - overloads by arity and argument labels; what is left is reported as
16
+ * ambiguous, never picked
17
+ *
18
+ * Every edge records how it was derived (`via`) and a confidence:
19
+ * high a binding was resolved: the callee is in the same file, was named by
20
+ * an import that leads to a file of this repository, is a member of
21
+ * the enclosing type, or is a member of the receiver's declared type
22
+ * (declared in this file, imported, or visible package-wide in a
23
+ * language with package scope). Name equality alone is never high.
24
+ * medium the binding rests on inference: a receiver type that came through a
25
+ * chain of return types or a type found by its bare name, a dispatch
26
+ * to the implementers of a member, or a callee that is the only
27
+ * function of that name in a language whose names are not imported one
28
+ * by one
29
+ * low only the name (and argument count) identifies the callee, several
30
+ * callees remain, or an import was followed but did not reach the
31
+ * definition
32
+ * A name bound by an import that leads to no file of the repository (a package
33
+ * or the standard library) is external and produces no edge, even when the
34
+ * repository declares something with the same name.
35
+ * A receiver whose type is known and not declared in the repository (a library
36
+ * type) produces no edge: guessing a repository method for it would be wrong far
37
+ * more often than right. The exception is a method that an extension in the
38
+ * repository adds to that type: the edge is at most medium, because the SDK's
39
+ * own method of the same name has the same call shape, and high only when the
40
+ * call uses a parameter or label that only the extension declares. An unknown
41
+ * receiver falls back to a method name that is
42
+ * unique in the repository, at low confidence, and never for a name that is
43
+ * common in the standard libraries.
44
+ *
45
+ * @module pipeline/scripts/call-graph/resolve
46
+ */
47
+
48
+ import { profileForPath } from "./profiles.mjs";
49
+
50
+ const RANK = { certain: 4, high: 3, medium: 2, low: 1 };
51
+ const MAX_SUPER_DEPTH = 8;
52
+ const MAX_IMPLEMENTERS = 25;
53
+ const MAX_AMBIGUOUS = 3;
54
+ const GENERIC_NAME_RE = /^[A-Z]\w?$/;
55
+ const EXTERNAL = "?external";
56
+ export const RESOLVE_BUDGET_MS = 120_000;
57
+ const EVENTS_PER_CLOCK_CHECK = 16;
58
+
59
+ const COMMON_NAMES = new Set(
60
+ `get set add remove delete clear contains count size length push pop shift unshift append insert
61
+ map filter reduce forEach each flatMap sorted sort first last min max sum join split trim replace
62
+ find findAll index indexOf slice splice concat keys values entries items has put post patch head
63
+ open close read write send start stop run call apply init new toString toJSON equals hashCode
64
+ compareTo copy clone reset update load save parse format encode decode then catch finally resolve
65
+ reject next done emit on off once log error warn info debug print println test assert expect
66
+ describe it main setup teardown build create make make_ to_string to_owned unwrap expect_err
67
+ iter into from as_ref as_str len is_empty collect clone_from default drop fmt eq ne cmp
68
+ String Array Dictionary Set Optional Result Error
69
+ text json blob arrayBuffer formData clone status ok headers body url type name value key id label title
70
+ click focus blur submit select scroll show hide toggle render mount unmount dispatch subscribe unsubscribe
71
+ publish listen connect disconnect request response handle execute validate check verify register
72
+ toArray toObject toList toSet values keys entries fromJSON toJSONString lastIndexOf startsWith endsWith
73
+ includes some every findIndex fill reverse flat at pad padStart padEnd toUpperCase toLowerCase normalize
74
+ exec match test search then wait sleep delay retry cancel abort flush destroy dispose release acquire`
75
+ .split(/\s+/)
76
+ .filter(Boolean),
77
+ );
78
+
79
+ /**
80
+ * A file is test code by where it sits as well as by its name: a `test`, `tests`,
81
+ * `spec` or `__tests__` directory, a `Tests` directory of a package, or a build
82
+ * target named `...Tests` or `...UITests`.
83
+ */
84
+ const TEST_DIR = /(^|\/)(tests?|specs?|__tests__|__mocks__|Tests|[\w.-]*(UI)?Tests)\//;
85
+ const inTestTree = (p) => TEST_DIR.test(p);
86
+
87
+ const dirOf = (p) => p.slice(0, p.lastIndexOf("/") + 1);
88
+
89
+ function sharedPrefix(a, b) {
90
+ const x = a.split("/");
91
+ const y = b.split("/");
92
+ let n = 0;
93
+ while (n < x.length - 1 && n < y.length - 1 && x[n] === y[n]) n++;
94
+ return n;
95
+ }
96
+
97
+ /** How near declaration path `to` is to the file `from`: higher is nearer. */
98
+ function nearness(from, to) {
99
+ if (from === to) return 1e6;
100
+ if (dirOf(from) === dirOf(to)) return 1e5;
101
+ return sharedPrefix(from, to);
102
+ }
103
+
104
+ /**
105
+ * Pick the nearest of several declarations; null when two are equally near.
106
+ *
107
+ * @param {Array} cands
108
+ * @param {string} from - path of the referencing file
109
+ * @param {(c: object) => string} pathOf
110
+ */
111
+ function nearest(cands, from, pathOf) {
112
+ if (cands.length === 1) return { best: cands[0], tie: false };
113
+ let best = null;
114
+ let bestScore = -1;
115
+ let tie = false;
116
+ for (const c of cands) {
117
+ const score = nearness(from, pathOf(c));
118
+ if (score > bestScore) {
119
+ best = c;
120
+ bestScore = score;
121
+ tie = false;
122
+ } else if (score === bestScore) tie = true;
123
+ }
124
+ return { best, tie };
125
+ }
126
+
127
+ /**
128
+ * Add function nodes and `calls` edges for every file that carries call facts.
129
+ *
130
+ * @param {object} params
131
+ * @param {Map<string, object>} params.extracted - path -> extractFile result
132
+ * @param {Map<string, object>} params.nodes - graph nodes by id, mutated
133
+ * @param {Array} params.edges - graph edges, mutated
134
+ * @param {(p: string) => boolean} params.isTest
135
+ * @param {object} [params.annotations] - id -> fields to add to a node the graph already has, filled in
136
+ * @param {number} [params.budgetMs] - time the resolution may take; a file reached after it, or still being read when it ends, is listed in `unresolved`
137
+ * @param {() => number} [params.now] - clock, injectable for tests
138
+ * @returns {{calls: number, functions: number, unresolved: string[]}} `unresolved` lists the files whose calls were not resolved
139
+ */
140
+ export function addCallEdges({
141
+ extracted,
142
+ nodes,
143
+ edges,
144
+ isTest: isTestByName,
145
+ annotations = {},
146
+ budgetMs = RESOLVE_BUDGET_MS,
147
+ now = Date.now,
148
+ }) {
149
+ const clock = now;
150
+ const isTest = (p) => isTestByName(p) || inTestTree(p);
151
+ const deadline = clock() + budgetMs;
152
+ const unresolved = [];
153
+ const decls = [];
154
+ const fnsByName = new Map();
155
+ const freeByName = new Map();
156
+ const fileFns = new Map();
157
+ const localFns = new Map();
158
+ const fileInfo = new Map();
159
+ const pathsList = [...extracted.keys()];
160
+ let functions = 0;
161
+
162
+ const taken = new Set();
163
+ const nodeFor = (path, f, owner, clash) => {
164
+ const plain = owner ? `${owner}.${f.n}` : f.n;
165
+ const main = nodes.get(`sym:${path}#${f.n}`);
166
+ if (main && main.line === f.l && !taken.has(main.id)) return { id: main.id, fresh: false };
167
+ const bare = `sym:${path}#${plain}`;
168
+ const labels = `(${(f.p || []).map((q) => `${q[0] ?? "_"}:`).join("")})`;
169
+ let id = clash || nodes.has(bare) ? `${bare}${labels}` : bare;
170
+ for (let n = 2; taken.has(id); n++) id = `${bare}${labels}~${n}`;
171
+ return { id, fresh: !nodes.has(id) };
172
+ };
173
+
174
+ for (const [path, data] of extracted) {
175
+ const facts = data.calls;
176
+ if (!facts) continue;
177
+ fileInfo.set(path, { facts, binds: facts.binds || [], lang: facts.lang, test: isTest(path) });
178
+ const list = [];
179
+ fileFns.set(path, list);
180
+ const seenQualified = new Map();
181
+ for (const f of facts.fns) {
182
+ const key = f.o ? `${f.o}.${f.n}` : f.n;
183
+ seenQualified.set(key, (seenQualified.get(key) || 0) + 1);
184
+ }
185
+ for (const f of facts.fns) {
186
+ const owner = f.o || null;
187
+ const clash = seenQualified.get(owner ? `${owner}.${f.n}` : f.n) > 1;
188
+ const { id, fresh } = nodeFor(path, f, owner, clash);
189
+ taken.add(id);
190
+ if (fresh) {
191
+ nodes.set(id, {
192
+ id,
193
+ kind: "symbol",
194
+ name: f.n,
195
+ path,
196
+ line: f.l,
197
+ ...(f.e && f.e > f.l ? { endLine: f.e } : {}),
198
+ symbolKind: owner ? "method" : "function",
199
+ ...(owner ? { owner } : {}),
200
+ isTest: isTest(path),
201
+ nested: true,
202
+ degree: 0,
203
+ });
204
+ edges.push({ from: `file:${path}`, to: id, kind: "defines" });
205
+ } else if (owner) annotations[id] = { owner };
206
+ const F = { ...f, id, path, owner, lang: facts.lang };
207
+ list.push(F);
208
+ functions++;
209
+ if (f.lo) {
210
+ if (!localFns.has(path)) localFns.set(path, []);
211
+ localFns.get(path).push(F);
212
+ continue;
213
+ }
214
+ if (!fnsByName.has(f.n)) fnsByName.set(f.n, []);
215
+ fnsByName.get(f.n).push(F);
216
+ if (!owner) {
217
+ if (!freeByName.has(f.n)) freeByName.set(f.n, []);
218
+ freeByName.get(f.n).push(F);
219
+ }
220
+ }
221
+ for (const t of facts.types) {
222
+ const D = {
223
+ ...t,
224
+ path,
225
+ lang: facts.lang,
226
+ fields: new Map(Object.entries(t.f || {})),
227
+ methods: new Map(),
228
+ id: `sym:${path}#${t.n}`,
229
+ };
230
+ decls.push(D);
231
+ }
232
+ }
233
+
234
+ const partialHost = new Map();
235
+ for (const D of decls) {
236
+ if (!D.partial) continue;
237
+ const host = partialHost.get(D.n);
238
+ if (!host) partialHost.set(D.n, D);
239
+ else D.k = "ext";
240
+ }
241
+
242
+ const byName = new Map();
243
+ for (const D of decls) {
244
+ if (D.k === "ext") continue;
245
+ if (!byName.has(D.n)) byName.set(D.n, []);
246
+ byName.get(D.n).push(D);
247
+ }
248
+ const external = new Map();
249
+ const declFor = (name, fromPath) => {
250
+ const cands = byName.get(name);
251
+ if (!cands) return null;
252
+ const { best, tie } = nearest(cands, fromPath, (d) => d.path);
253
+ return { decl: best, tie };
254
+ };
255
+ const hostFor = (extDecl) => {
256
+ const found = declFor(extDecl.n, extDecl.path);
257
+ if (found && !found.tie) return found.decl;
258
+ if (!external.has(extDecl.n)) {
259
+ external.set(extDecl.n, {
260
+ n: extDecl.n,
261
+ k: "external",
262
+ path: null,
263
+ sup: [],
264
+ fields: new Map(),
265
+ methods: new Map(),
266
+ id: null,
267
+ lang: extDecl.lang,
268
+ ext: true,
269
+ });
270
+ }
271
+ return found ? found.decl : external.get(extDecl.n);
272
+ };
273
+ const hostOfDecl = new Map();
274
+ for (const D of decls) {
275
+ const host = D.k === "ext" ? hostFor(D) : D;
276
+ hostOfDecl.set(D, host);
277
+ if (host !== D) {
278
+ for (const s of D.sup) if (!host.sup.includes(s)) host.sup = [...host.sup, s];
279
+ for (const [k, v] of D.fields) if (!host.fields.has(k)) host.fields.set(k, v);
280
+ }
281
+ }
282
+ const ownerHostCache = new Map();
283
+ const declsAt = new Map();
284
+ for (const d of decls) {
285
+ const key = `${d.path}\0${d.n}`;
286
+ if (!declsAt.has(key)) declsAt.set(key, []);
287
+ declsAt.get(key).push(d);
288
+ }
289
+ const hostForOwner = (F) => {
290
+ const key = `${F.path}\0${F.owner}`;
291
+ const here = declsAt.get(key) || [];
292
+ const shared = here.length > 1;
293
+ if (!shared && ownerHostCache.has(key)) return ownerHostCache.get(key);
294
+ let host;
295
+ const own = shared ? innermostAround(here, F.l) : here.find((d) => d.k !== "ext");
296
+ if (own) host = own;
297
+ else {
298
+ const ext = here[0];
299
+ if (ext) host = hostOfDecl.get(ext);
300
+ else {
301
+ const found = declFor(F.owner, F.path);
302
+ host = found && !found.tie ? found.decl : null;
303
+ if (!host) {
304
+ if (!external.has(F.owner))
305
+ external.set(F.owner, {
306
+ n: F.owner,
307
+ k: "external",
308
+ path: null,
309
+ sup: [],
310
+ fields: new Map(),
311
+ methods: new Map(),
312
+ id: null,
313
+ lang: F.lang,
314
+ ext: true,
315
+ });
316
+ host = external.get(F.owner);
317
+ }
318
+ }
319
+ }
320
+ if (!shared) ownerHostCache.set(key, host);
321
+ return host;
322
+ };
323
+ /** Of several declarations of one name in a file, the one whose span holds line `l`. */
324
+ const innermostAround = (list, l) => {
325
+ const around = list.filter(
326
+ (d) => d.k !== "ext" && d.line !== undefined && d.line <= l && (d.end ?? Infinity) >= l,
327
+ );
328
+ if (!around.length) return list.find((d) => d.k !== "ext");
329
+ return around.reduce((a, b) => (b.line >= a.line ? b : a));
330
+ };
331
+ for (const list of fileFns.values()) {
332
+ for (const F of list) {
333
+ if (!F.owner) continue;
334
+ const host = hostForOwner(F);
335
+ F.host = host;
336
+ if (!host.methods.has(F.n)) host.methods.set(F.n, []);
337
+ host.methods.get(F.n).push(F);
338
+ }
339
+ }
340
+
341
+ const implementers = new Map();
342
+ for (const D of decls) {
343
+ for (const s of D.sup) {
344
+ if (!implementers.has(s)) implementers.set(s, []);
345
+ implementers.get(s).push(hostOfDecl.get(D));
346
+ }
347
+ }
348
+
349
+ const superCache = new Map();
350
+ const structural = [...new Set(decls.map((d) => d.lang))].some((l) => l === "go");
351
+ if (structural) {
352
+ const goHosts = [
353
+ ...new Set(decls.filter((d) => d.lang === "go").map((d) => hostOfDecl.get(d))),
354
+ ];
355
+ for (const I of goHosts) {
356
+ if (I.k !== "interface") continue;
357
+ const need = [...I.methods.keys()];
358
+ if (!need.length) continue;
359
+ for (const C of goHosts) {
360
+ if (C === I || C.k === "interface") continue;
361
+ if (need.every((m) => C.methods.has(m))) {
362
+ if (!implementers.has(I.n)) implementers.set(I.n, []);
363
+ implementers.get(I.n).push(C);
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ const supersOf = (D) => {
370
+ if (superCache.has(D)) return superCache.get(D);
371
+ const out = [];
372
+ for (const s of D.sup || []) {
373
+ const found = scopedDecl(s, D.path || "", D, true);
374
+ if (found?.decl && !found.tie && found.weak !== "low" && found.decl !== D)
375
+ out.push(found.decl);
376
+ }
377
+ superCache.set(D, out);
378
+ return out;
379
+ };
380
+
381
+ const lookupInHierarchy = (D, pick) => {
382
+ const seen = new Set();
383
+ let level = [D];
384
+ for (let depth = 0; depth <= MAX_SUPER_DEPTH && level.length; depth++) {
385
+ const next = [];
386
+ for (const d of level) {
387
+ if (seen.has(d)) continue;
388
+ seen.add(d);
389
+ const r = pick(d);
390
+ if (r) return { value: r, inherited: depth > 0, from: d };
391
+ next.push(...supersOf(d));
392
+ }
393
+ level = next;
394
+ }
395
+ return null;
396
+ };
397
+
398
+ const strictFits = (F, call) => {
399
+ const { n, labels, tc } = call;
400
+ const fits = (k) => k >= F.a[0] && k <= F.a[1];
401
+ if (!fits(n) && !(tc && fits(n + 1))) return false;
402
+ if (labels.length && F.p.length && !F.p.some((q) => q[0] === "**")) {
403
+ const names = new Set(F.p.flatMap((q) => [q[0], q[1]]));
404
+ if (!labels.every((l) => names.has(l))) return false;
405
+ }
406
+ return true;
407
+ };
408
+
409
+ /** JavaScript and TypeScript calls may pass any number of arguments: arity only ranks there. */
410
+ const accepts = (F, call) => (F.lang === "typescript" ? true : strictFits(F, call));
411
+
412
+ /** Callable candidates for a call, the ones whose arity fits first where arity does not decide. */
413
+ const fitting = (list, call) => {
414
+ const ok = list.filter((F) => accepts(F, call));
415
+ if (ok.length < 2) return ok;
416
+ const strict = ok.filter((F) => strictFits(F, call));
417
+ return strict.length ? strict : ok;
418
+ };
419
+
420
+ const preferBodies = (list) => {
421
+ if (list.length < 2) return list;
422
+ const withBody = list.filter((F) => !F.ab);
423
+ return withBody.length ? withBody : list;
424
+ };
425
+
426
+ const methodsOn = (D, name, call) => {
427
+ const r = lookupInHierarchy(D, (d) => {
428
+ const all = d.methods.get(name);
429
+ if (!all) return null;
430
+ const ok = preferBodies(fitting(all, call));
431
+ return ok.length ? ok : null;
432
+ });
433
+ return r ? { fns: r.value, inherited: r.inherited, holder: r.from } : null;
434
+ };
435
+
436
+ const fieldType = (D, name) => {
437
+ const r = lookupInHierarchy(D, (d) => d.fields.get(name) || null);
438
+ return r ? r.value : null;
439
+ };
440
+
441
+ const out = new Map();
442
+ const emit = (from, to, via, conf) => {
443
+ if (!from || !to || from === to) return;
444
+ const key = `${from}\0${to}`;
445
+ const have = out.get(key);
446
+ if (!have || RANK[conf] > RANK[have.confidence])
447
+ out.set(key, { from, to, kind: "calls", via, confidence: conf });
448
+ };
449
+
450
+ const typeState = (name, fromPath, F, owner) => {
451
+ if (!name) return { kind: "unknown" };
452
+ if (F?.g?.includes(name) || owner?.gen?.includes(name) || GENERIC_NAME_RE.test(name))
453
+ return { kind: "unknown" };
454
+ const found = scopedDecl(name, fromPath, owner, true);
455
+ if (found?.external) return { kind: "unknown", external: true };
456
+ if (!found) return { kind: "inst", name, decl: external.get(name) || null };
457
+ return { kind: "inst", name, decl: found.decl, tie: found.tie, weak: found.weak };
458
+ };
459
+
460
+ const moduleCache = new Map();
461
+ const resolveModuleFiles = (from, spec) => {
462
+ const key = `${from}\0${spec}`;
463
+ if (moduleCache.has(key)) return moduleCache.get(key);
464
+ const profile = profileForPath(from);
465
+ const sufs = profile?.moduleSuffixes ? profile.moduleSuffixes(spec, from) : [];
466
+ let hits = [];
467
+ for (const suffix of sufs) {
468
+ const isDir = suffix.endsWith("/");
469
+ hits = pathsList.filter((p) =>
470
+ isDir
471
+ ? dirOf(p) === suffix || dirOf(p).endsWith(`/${suffix}`)
472
+ : p === suffix || p.endsWith(`/${suffix}`),
473
+ );
474
+ if (hits.length) break;
475
+ }
476
+ moduleCache.set(key, hits);
477
+ return hits;
478
+ };
479
+
480
+ /**
481
+ * The files that define `name` as seen through `files`: each file itself, plus
482
+ * the files its `export { name } from` and `export * from` lines lead to.
483
+ */
484
+ const expandReexports = (files, name) => {
485
+ const result = [];
486
+ const seen = new Set();
487
+ const walkFiles = (fs, nm, depth) => {
488
+ for (const f of fs) {
489
+ const key = `${f}\0${nm}`;
490
+ if (seen.has(key)) continue;
491
+ seen.add(key);
492
+ result.push({ path: f, name: nm });
493
+ if (depth >= 4) continue;
494
+ for (const r of fileInfo.get(f)?.facts.rx || []) {
495
+ if (r.m === null) {
496
+ for (const [exp, orig] of r.n) {
497
+ const bind = fileInfo.get(f)?.binds.find((b) => b.l === orig);
498
+ if (exp === nm && bind)
499
+ walkFiles(resolveModuleFiles(f, bind.m), bind.x || orig, depth + 1);
500
+ }
501
+ continue;
502
+ }
503
+ const next = resolveModuleFiles(f, r.m);
504
+ if (r.star) walkFiles(next, nm, depth + 1);
505
+ else for (const [exp, orig] of r.n) if (exp === nm) walkFiles(next, orig, depth + 1);
506
+ }
507
+ }
508
+ };
509
+ walkFiles(files, name, 0);
510
+ return result;
511
+ };
512
+
513
+ const bindCache = new Map();
514
+ /**
515
+ * What the imports of `fromPath` say about `name`: null when no import binds
516
+ * it, otherwise the repository files its module resolves to. Only a language
517
+ * whose modules map to files can call an import external; elsewhere an
518
+ * unresolved import proves nothing.
519
+ */
520
+ const bindInfo = (fromPath, name) => {
521
+ const key = `${fromPath}\0${name}`;
522
+ if (bindCache.has(key)) return bindCache.get(key);
523
+ let info = null;
524
+ const profile = profileForPath(fromPath);
525
+ const binds = fileInfo.get(fromPath)?.binds;
526
+ if (profile?.moduleSuffixes && binds) {
527
+ const found = binds.filter((b) => b.l === name);
528
+ if (found.length) {
529
+ const files = [];
530
+ const add = (spec) => {
531
+ for (const f of resolveModuleFiles(fromPath, spec)) if (!files.includes(f)) files.push(f);
532
+ };
533
+ for (const b of found) {
534
+ add(b.m);
535
+ if (b.alt) add(b.alt);
536
+ }
537
+ info = { files, external: files.length === 0 };
538
+ }
539
+ }
540
+ bindCache.set(key, info);
541
+ return info;
542
+ };
543
+
544
+ const outerDecl = (D) => {
545
+ const c = byName.get(D.outer) || [];
546
+ return c.find((x) => x.path === D.path) || c[0] || null;
547
+ };
548
+
549
+ /** The types whose nested types a bare name inside `owner` may denote. */
550
+ const lexicalTypes = (owner, inherited) => {
551
+ const out = [];
552
+ for (let cur = owner, n = 0; cur && n < 6; n++) {
553
+ out.push(cur);
554
+ cur = cur.outer ? outerDecl(cur) : null;
555
+ }
556
+ if (inherited) for (const c of [...out]) for (const sup of supersOf(c)) out.push(sup);
557
+ return out;
558
+ };
559
+
560
+ const canSee = (profile, fromPath, declPath) => {
561
+ const a = profile.targetOf(fromPath);
562
+ const b = profile.targetOf(declPath);
563
+ if (a.root === b.root) return true;
564
+ if (fileInfo.get(fromPath)?.facts.mods?.includes(b.name)) return true;
565
+ if (a.test && !b.test) {
566
+ const app = a.name.replace(/(UI)?Tests?$/, "");
567
+ return app !== "" && app.toLowerCase() === b.name.toLowerCase();
568
+ }
569
+ return false;
570
+ };
571
+
572
+ /**
573
+ * The type a bare name denotes from `fromPath`, in this order: a type nested
574
+ * in a type that lexically encloses the call, the same file, the files an
575
+ * import names. A platform name stops there. After that only a top-level
576
+ * declaration counts: `weak` is true when the match rests on the name and
577
+ * where the file sits (medium), "low" when the caller's target cannot see the
578
+ * declaration. A nested type is reached from outside only in type position,
579
+ * where a bare spelling is a shortened qualified one, and then at medium.
580
+ */
581
+ const scopedDecl = (name, fromPath, owner = null, typePos = false) => {
582
+ const info = bindInfo(fromPath, name);
583
+ if (info?.external) return { external: true };
584
+ const all = byName.get(name);
585
+ const profile = profileForPath(fromPath);
586
+ const platform = profile?.platformNames.has(name);
587
+ if (!all) return null;
588
+ const lex = owner
589
+ ? lexicalTypes(owner, profile?.id === "java" || profile?.id === "csharp")
590
+ : [];
591
+ const nestedHere = lex.length
592
+ ? all.filter((d) => d.outer && lex.some((c) => c.n === d.outer))
593
+ : [];
594
+ if (nestedHere.length) {
595
+ const { best, tie } = nearest(nestedHere, fromPath, (d) => d.path);
596
+ return { decl: best, tie, weak: tie };
597
+ }
598
+ const top = all.filter((d) => !d.outer);
599
+ const here = top.filter((d) => d.path === fromPath);
600
+ if (here.length) return { decl: here[0], tie: here.length > 1, weak: here.length > 1 };
601
+ if (info) {
602
+ const named = all.filter((d) => info.files.includes(d.path));
603
+ if (named.length) return { decl: named[0], tie: named.length > 1, weak: named.length > 1 };
604
+ }
605
+ if (platform) return { external: true };
606
+ if (!top.length) {
607
+ const nested = typePos ? all.filter((d) => d.outer) : [];
608
+ if (!nested.length) return null;
609
+ const { best, tie } = nearest(nested, fromPath, (d) => d.path);
610
+ return { decl: best, tie, weak: true };
611
+ }
612
+ if (profile?.targetOf) {
613
+ const seen = top.filter((d) => canSee(profile, fromPath, d.path));
614
+ if (!seen.length) {
615
+ const { best, tie } = nearest(top, fromPath, (d) => d.path);
616
+ return { decl: best, tie, weak: "low" };
617
+ }
618
+ const { best, tie } = nearest(seen, fromPath, (d) => d.path);
619
+ const sameTarget = profile.targetOf(fromPath).root === profile.targetOf(best.path).root;
620
+ const sameDir = nearness(fromPath, best.path) >= 1e5;
621
+ return { decl: best, tie, weak: tie || !sameTarget || (seen.length > 1 && !sameDir) };
622
+ }
623
+ const { best, tie } = nearest(top, fromPath, (d) => d.path);
624
+ const sameDir = best.path && nearness(fromPath, best.path) >= 1e5;
625
+ const scoped = profile?.packageScope ? sameDir : !profile?.perNameImports;
626
+ return { decl: best, tie, weak: tie || !scoped };
627
+ };
628
+
629
+ const dispatchTargets = (D, name, call, callerPath, isTestCaller) => {
630
+ const res = [];
631
+ const seen = new Set([D]);
632
+ let level = implementers.get(D.n) || [];
633
+ for (let depth = 0; depth < MAX_SUPER_DEPTH && level.length; depth++) {
634
+ const next = [];
635
+ for (const I of level) {
636
+ if (seen.has(I)) continue;
637
+ seen.add(I);
638
+ const own = preferBodies(fitting(I.methods.get(name) || [], call));
639
+ for (const F of own) res.push(F);
640
+ next.push(...(implementers.get(I.n) || []));
641
+ if (res.length > MAX_IMPLEMENTERS) return res;
642
+ }
643
+ level = next;
644
+ }
645
+ return res.filter((F) => isTestCaller || !fileInfo.get(F.path)?.test);
646
+ };
647
+
648
+ /** The type is declared outside the repository and the repository only extends it. */
649
+ const extensionOnly = (holder, relation) =>
650
+ (holder.ext === true || holder.k === "external") &&
651
+ relation !== "implicit-self" &&
652
+ relation !== "self-receiver";
653
+
654
+ /**
655
+ * Does the call have a shape only the repository's extension has? An extension
656
+ * method that shares its name with a member of the platform type is reached by
657
+ * the platform's own call shape; the call passes every parameter, including an
658
+ * optional one, only when it means the extension (or the extension has no
659
+ * optional parameter at all).
660
+ */
661
+ const usesExtensionShape = (fn, call) => {
662
+ if (fn.a[1] === fn.a[0]) return true;
663
+ const given = call.tc ? call.n + 1 : call.n;
664
+ return given > fn.a[0] && given >= fn.a[1];
665
+ };
666
+
667
+ const ABSTRACT = new Set(["protocol", "interface", "trait", "abstract"]);
668
+ const isVirtual = (holder, fn) =>
669
+ ABSTRACT.has(holder.k) || fn.ab || (implementers.get(holder.n) || []).length > 0;
670
+
671
+ const evalChain = (ctx, steps) => {
672
+ const { F, path, testCaller, profile } = ctx;
673
+ const callerId = F ? F.id : `file:${path}`;
674
+ const ownerDecl = F?.host || null;
675
+ let cur = { kind: "unknown" };
676
+ let conf = "high";
677
+ const target = (fn, via, c) => {
678
+ if (!fn || (fileInfo.get(fn.path)?.test && !testCaller)) return;
679
+ emit(callerId, fn.id, via, c);
680
+ };
681
+ const typeTarget = (D, via, c) => {
682
+ if (!D?.id || !nodes.has(D.id)) return;
683
+ if ((declsAt.get(`${D.path}\0${D.n}`) || []).length > 1 && nodes.get(D.id).line !== D.line)
684
+ return;
685
+ if (nodes.get(D.id).isTest && !testCaller) return;
686
+ emit(callerId, D.id, via, c);
687
+ };
688
+ const pickAmbiguous = (fns, via, c) => {
689
+ if (fns.length === 1) return target(fns[0], via, c);
690
+ if (fns.length <= MAX_AMBIGUOUS)
691
+ for (const fn of fns) target(fn, "ambiguous-overload", "low");
692
+ };
693
+ const callOn = (D, name, call, relation, weak = false) => {
694
+ const hit = methodsOn(D, name, call);
695
+ if (!hit) return null;
696
+ const via =
697
+ relation === "static" ? "static-receiver" : hit.inherited ? "inherited" : relation;
698
+ const c =
699
+ relation === "implicit-self"
700
+ ? "high"
701
+ : weak === "low"
702
+ ? "low"
703
+ : conf === "medium" || weak
704
+ ? "medium"
705
+ : "high";
706
+ if (hit.fns.length === 1) {
707
+ const fn = hit.fns[0];
708
+ const abstractHolder =
709
+ relation !== "super-receiver" && name !== profile.initName && isVirtual(hit.holder, fn);
710
+ const ownShape = !extensionOnly(hit.holder, relation) || usesExtensionShape(fn, call);
711
+ target(
712
+ fn,
713
+ ABSTRACT.has(hit.holder.k) || fn.ab ? "interface-member" : via,
714
+ ownShape || c !== "high" ? c : "medium",
715
+ );
716
+ if (abstractHolder) {
717
+ const impls = dispatchTargets(hit.holder, name, call, path, testCaller);
718
+ if (impls.length <= MAX_IMPLEMENTERS)
719
+ for (const im of impls) target(im, "dispatch", "medium");
720
+ }
721
+ } else pickAmbiguous(hit.fns, via, c);
722
+ const ret = hit.fns.length === 1 ? hit.fns[0] : null;
723
+ return ret;
724
+ };
725
+ const afterCall = (fn, recv) => {
726
+ if (!fn || !fn.r) return { kind: "unknown" };
727
+ const r = fn.r;
728
+ if (r === "Self" || r === "self")
729
+ return recv && recv.kind !== "unknown" ? { ...recv, kind: "inst" } : { kind: "unknown" };
730
+ return typeState(r, fn.path, fn, fn.host);
731
+ };
732
+ const ctorOn = (D, call, via, weak = false) => {
733
+ const c = weak === "low" ? "low" : weak && conf === "high" ? "medium" : conf;
734
+ const inits = fitting(D.methods?.get(profile.initName || "init") || [], call);
735
+ if (inits.length === 1) target(inits[0], via, c);
736
+ else if (inits.length > 1) pickAmbiguous(inits, via, c);
737
+ else typeTarget(D, via, c);
738
+ };
739
+
740
+ for (let si = 0; si < steps.length; si++) {
741
+ const st = steps[si];
742
+ const tag = st[0];
743
+ const call = { n: st[2] ?? 0, labels: st[3] || [], tc: st[4] || 0 };
744
+ if (tag === "s") {
745
+ cur = ownerDecl
746
+ ? { kind: "inst", name: ownerDecl.n, decl: ownerDecl, self: true }
747
+ : { kind: "unknown" };
748
+ } else if (tag === "u") {
749
+ const sup = ownerDecl ? supersOf(ownerDecl)[0] : null;
750
+ cur = sup ? { kind: "inst", name: sup.n, decl: sup, sup: true } : { kind: "unknown" };
751
+ } else if (tag === "k") {
752
+ cur = typeState(st[1], path, F, ownerDecl);
753
+ conf = st[2] === "m" ? "medium" : "high";
754
+ } else if (tag === "x") {
755
+ cur = { kind: "unknown" };
756
+ conf = "medium";
757
+ } else if (tag === "i") {
758
+ const name = st[1];
759
+ if (ctx.locals.has(name)) {
760
+ cur = typeState(ctx.locals.get(name), path, F, ownerDecl);
761
+ if (ctx.weak.has(name) && conf === "high") conf = "medium";
762
+ } else if (ownerDecl && fieldType(ownerDecl, name)) {
763
+ cur = typeState(fieldType(ownerDecl, name), path, F, ownerDecl);
764
+ } else if (ctx.gl[name]) {
765
+ cur = typeState(ctx.gl[name], path, F, ownerDecl);
766
+ } else {
767
+ const bind = ctx.binds.find((b) => b.l === name);
768
+ let resolved = null;
769
+ if (bind) {
770
+ const files = resolveModuleFiles(path, bind.m);
771
+ if (bind.x) {
772
+ const D = files.map((p) => declFor(bind.x, p)).find(Boolean);
773
+ if (D) resolved = { kind: "static", name: bind.x, decl: D.decl };
774
+ else if (bind.alt) {
775
+ const altFiles = resolveModuleFiles(path, bind.alt);
776
+ if (altFiles.length) resolved = { kind: "module", files: altFiles, alias: name };
777
+ }
778
+ if (!resolved && !files.length) resolved = { kind: "unknown", external: true };
779
+ } else {
780
+ resolved = files.length
781
+ ? { kind: "module", files, alias: name }
782
+ : { kind: "unknown", external: true };
783
+ }
784
+ }
785
+ if (!resolved) {
786
+ const found = scopedDecl(name, path, ownerDecl);
787
+ if (found?.external) resolved = { kind: "unknown", external: true };
788
+ else if (found)
789
+ resolved = {
790
+ kind: "static",
791
+ name,
792
+ decl: found.decl,
793
+ tie: found.tie,
794
+ weak: found.weak,
795
+ };
796
+ }
797
+ cur = resolved || { kind: "unknown" };
798
+ }
799
+ } else if (tag === "c") {
800
+ const name = st[1];
801
+ cur = { kind: "unknown" };
802
+ const local = visibleLocalFns(F, path, name, ctx.line);
803
+ if (local.length) {
804
+ const fits = fitting(local, call);
805
+ if (fits.length) {
806
+ const early = fits[0].lv && ctx.line < fits[0].l;
807
+ pickAmbiguous(fits.slice(0, 1), "same-file", early ? "medium" : "high");
808
+ cur = afterCall(fits[0], null);
809
+ continue;
810
+ }
811
+ }
812
+ if (ctx.locals.has(name)) continue;
813
+ if (ctx.vars.has(name)) continue;
814
+ if (bindInfo(path, name)?.external) {
815
+ cur = { kind: "unknown", external: true };
816
+ continue;
817
+ }
818
+ const asType = scopedDecl(name, path, ownerDecl);
819
+ const looksType = /^[A-Z]/.test(name) || profile.bareCallConstructs;
820
+ let done = false;
821
+ if (ownerDecl && profile.implicitSelf) {
822
+ let scope = ownerDecl;
823
+ const chain = [];
824
+ while (scope && chain.length < 4) {
825
+ chain.push(scope);
826
+ scope = scope.outer ? declFor(scope.outer, scope.path)?.decl : null;
827
+ }
828
+ for (const sc of chain) {
829
+ const hit = methodsOn(sc, name, call);
830
+ if (hit) {
831
+ const fn = hit.fns[0];
832
+ if (hit.fns.length === 1) {
833
+ target(fn, hit.inherited ? "inherited" : "implicit-self", "high");
834
+ if (isVirtual(hit.holder, fn))
835
+ for (const im of dispatchTargets(hit.holder, name, call, path, testCaller))
836
+ target(im, "dispatch", "medium");
837
+ cur = afterCall(fn, { kind: "inst", name: sc.n, decl: sc });
838
+ } else pickAmbiguous(hit.fns, "implicit-self", "high");
839
+ done = true;
840
+ break;
841
+ }
842
+ }
843
+ }
844
+ if (!done && asType?.decl && looksType) {
845
+ ctorOn(asType.decl, call, "constructor", asType.weak);
846
+ cur = { kind: "inst", name, decl: asType.decl, tie: asType.tie, weak: asType.weak };
847
+ done = true;
848
+ }
849
+ let importUnreached = false;
850
+ if (!done) {
851
+ const bind = ctx.binds.find((b) => b.l === name && b.x);
852
+ if (bind) {
853
+ const files = resolveModuleFiles(path, bind.m);
854
+ const wanted = bind.d
855
+ ? files.map((f) => fileInfo.get(f)?.facts.def).find(Boolean) || name
856
+ : bind.x || name;
857
+ const reached = expandReexports(files, wanted);
858
+ const cands = fitting(
859
+ (freeByName.get(wanted) || []).filter((f) => files.includes(f.path)),
860
+ call,
861
+ ).concat(
862
+ reached.length > files.length
863
+ ? fitting(
864
+ reached
865
+ .filter((r) => !files.includes(r.path))
866
+ .flatMap((r) =>
867
+ (freeByName.get(r.name) || []).filter((f) => f.path === r.path),
868
+ ),
869
+ call,
870
+ )
871
+ : [],
872
+ );
873
+ if (cands.length) {
874
+ pickAmbiguous(cands, "import", "high");
875
+ cur = afterCall(cands[0], null);
876
+ done = true;
877
+ } else {
878
+ const D = files.map((p) => declFor(wanted, p)).find(Boolean);
879
+ if (D) {
880
+ ctorOn(D.decl, call, "constructor");
881
+ cur = { kind: "inst", name: wanted, decl: D.decl };
882
+ done = true;
883
+ } else if (files.length) importUnreached = true;
884
+ }
885
+ }
886
+ }
887
+ if (!done) {
888
+ const named = freeByName.get(name) || [];
889
+ const cands = preferBodies([
890
+ ...fitting(
891
+ named.filter((f) => f.path === path),
892
+ call,
893
+ ),
894
+ ...named.filter((f) => f.path !== path && strictFits(f, call)),
895
+ ]);
896
+ if (cands.length) {
897
+ const same = cands.filter((f) => f.path === path);
898
+ const pool = same.length ? same : profile.platformNames.has(name) ? [] : cands;
899
+ const { best, tie } = pool.length ? nearest(pool, path, (f) => f.path) : {};
900
+ if (!pool.length) {
901
+ cur = { kind: "unknown", external: true };
902
+ } else if (same.length === 1) {
903
+ target(same[0], "same-file", "high");
904
+ cur = afterCall(same[0], null);
905
+ } else if (!tie) {
906
+ const closeBy = nearness(path, best.path) >= 1e5;
907
+ if (closeBy || pool.length === 1) {
908
+ let via = "unique-name";
909
+ let c = profile.perNameImports ? "low" : "medium";
910
+ if (closeBy) {
911
+ via = profile.packageScope ? "same-package" : "same-directory";
912
+ c = profile.packageScope ? "high" : "low";
913
+ }
914
+ target(best, via, importUnreached ? "low" : c);
915
+ cur = afterCall(best, null);
916
+ }
917
+ } else if (pool.length <= MAX_AMBIGUOUS)
918
+ pickAmbiguous(pool, "ambiguous-overload", "low");
919
+ }
920
+ }
921
+ } else if (tag === "n") {
922
+ const found = scopedDecl(st[1], path, ownerDecl);
923
+ cur = typeState(st[1], path, F, ownerDecl);
924
+ if (found?.decl) ctorOn(found.decl, call, "constructor", found.weak);
925
+ } else if (tag === "f") {
926
+ const name = st[1];
927
+ if (cur.kind === "module") {
928
+ const found = cur.files.map((p) => declFor(name, p)).find(Boolean);
929
+ cur = found ? { kind: "static", name, decl: found.decl } : { kind: "unknown" };
930
+ } else if (cur.decl) {
931
+ const ft = fieldType(cur.decl, name);
932
+ const sub = cur.decl.methods.get(name);
933
+ cur = ft
934
+ ? typeState(ft, cur.decl.path || path, F, cur.decl)
935
+ : sub
936
+ ? { kind: "unknown" }
937
+ : nestedType(cur, name);
938
+ } else
939
+ cur =
940
+ cur.kind === "inst" && cur.name
941
+ ? { kind: "unknown", external: true }
942
+ : { kind: "unknown" };
943
+ if (cur.kind === "unknown" && conf === "high") conf = "medium";
944
+ } else if (tag === "m") {
945
+ const name = st[1];
946
+ const recv = cur;
947
+ if (recv.kind === "module") {
948
+ const cands = expandReexports(recv.files, name).flatMap((r) =>
949
+ fitting(
950
+ (fileFns.get(r.path) || []).filter((f) => !f.owner && !f.lo && f.n === r.name),
951
+ call,
952
+ ),
953
+ );
954
+ if (cands.length) {
955
+ pickAmbiguous(cands, "module-member", "high");
956
+ cur = afterCall(cands[0], null);
957
+ } else {
958
+ const D = recv.files.map((p) => declFor(name, p)).find(Boolean);
959
+ if (D) {
960
+ ctorOn(D.decl, call, "constructor");
961
+ cur = { kind: "inst", name, decl: D.decl };
962
+ } else cur = { kind: "unknown", external: true };
963
+ }
964
+ continue;
965
+ }
966
+ if (recv.decl) {
967
+ const relation = recv.self
968
+ ? "self-receiver"
969
+ : recv.sup
970
+ ? "super-receiver"
971
+ : recv.kind === "static"
972
+ ? "static"
973
+ : conf === "high"
974
+ ? "typed-receiver"
975
+ : "chained-return-type";
976
+ const fn = callOn(recv.decl, name, call, relation, recv.weak);
977
+ if (fn) {
978
+ cur = afterCall(fn, recv);
979
+ if (
980
+ conf === "high" &&
981
+ relation !== "typed-receiver" &&
982
+ relation !== "self-receiver" &&
983
+ relation !== "static"
984
+ )
985
+ conf = "medium";
986
+ } else if (/^[A-Z]/.test(name) && nestedType(recv, name).decl) {
987
+ const nt = nestedType(recv, name);
988
+ ctorOn(nt.decl, call, "constructor", nt.weak);
989
+ cur = { kind: "inst", name, decl: nt.decl };
990
+ } else {
991
+ cur =
992
+ recv.decl.ext || recv.decl.k === "external"
993
+ ? { kind: "unknown", external: true }
994
+ : { kind: "unknown" };
995
+ if (!methodsOn(recv.decl, name, { n: 0, labels: [], tc: 0 }) && !recv.decl.methods.size)
996
+ cur = { kind: "unknown" };
997
+ }
998
+ continue;
999
+ }
1000
+ if (recv.kind === "inst" && recv.name && !recv.decl) {
1001
+ cur = { kind: "unknown", external: true };
1002
+ continue;
1003
+ }
1004
+ if (recv.external) {
1005
+ cur = { kind: "unknown", external: true };
1006
+ continue;
1007
+ }
1008
+ cur = { kind: "unknown" };
1009
+ if (COMMON_NAMES.has(name) || name.length < 3) continue;
1010
+ const cands = (fnsByName.get(name) || []).filter((f) => f.owner && strictFits(f, call));
1011
+ if (cands.length === 1) {
1012
+ target(cands[0], "name-arity", "low");
1013
+ cur = afterCall(cands[0], null);
1014
+ }
1015
+ }
1016
+ }
1017
+ ctx.lastConf = conf;
1018
+ if (cur.external) return EXTERNAL;
1019
+ return cur.kind === "inst" && cur.name ? cur.name : null;
1020
+ };
1021
+
1022
+ /** Local functions declared in a function that encloses (or is) `F`, innermost first. */
1023
+ const visibleLocalFns = (F, path, name, line) => {
1024
+ if (!F) return [];
1025
+ const list = (localFns.get(path) || []).filter(
1026
+ (L) =>
1027
+ L.n === name &&
1028
+ L !== F &&
1029
+ F.l >= L.pl &&
1030
+ (F.e ?? F.l) <= L.pe &&
1031
+ (L.vs === undefined || (line >= L.vs && line <= L.ve)),
1032
+ );
1033
+ if (list.length < 2) return list;
1034
+ const span = (L) => (L.vs === undefined ? L.pe - L.pl : L.ve - L.vs);
1035
+ return list.sort((a, b) => span(a) - span(b));
1036
+ };
1037
+
1038
+ /**
1039
+ * Names the functions around a local function bind (parameters and declarations
1040
+ * anywhere in their bodies): a bare call to one of them inside the local function
1041
+ * is a call of that binding, not of a repository function of the same name.
1042
+ */
1043
+ const inheritedLocals = (F, depth = 0) => {
1044
+ const out = new Map();
1045
+ if (!F.lo || depth > 6) return out;
1046
+ const parent = (fileFns.get(F.path) || []).find(
1047
+ (P) => P !== F && P.l === F.pl && P.e === F.pe && P.l <= F.l,
1048
+ );
1049
+ if (!parent) return out;
1050
+ for (const [n, t] of inheritedLocals(parent, depth + 1)) out.set(n, t);
1051
+ for (const q of parent.p) out.set(q[1], q[2] || null);
1052
+ for (const e of parent.ev || []) if (e[0] === "d" && !out.has(e[1])) out.set(e[1], e[2]);
1053
+ return out;
1054
+ };
1055
+
1056
+ const nestedType = (cur, name) => {
1057
+ const named = (byName.get(name) || []).filter((d) => d.outer === cur.decl?.n);
1058
+ if (!named.length) return { kind: "unknown" };
1059
+ const { best, tie } = nearest(named, cur.decl.path || "", (d) => d.path);
1060
+ return { kind: "static", name, decl: best, tie, weak: tie };
1061
+ };
1062
+
1063
+ let eventsSinceCheck = 0;
1064
+ for (const [path, data] of extracted) {
1065
+ const facts = data.calls;
1066
+ if (!facts) continue;
1067
+ const info = fileInfo.get(path);
1068
+ const profile = profileForPath(path);
1069
+ if (!profile) continue;
1070
+ if (clock() > deadline) {
1071
+ unresolved.push(path);
1072
+ continue;
1073
+ }
1074
+ const fns = fileFns.get(path) || [];
1075
+ const jobs = fns.map((F) => ({ F, ev: F.ev || [] }));
1076
+ if (facts.top?.length) jobs.push({ F: null, ev: facts.top });
1077
+ let outOfTime = false;
1078
+ for (const { F, ev } of jobs) {
1079
+ if (outOfTime) break;
1080
+ const locals = new Map();
1081
+ if (F?.lo) for (const [n, t] of inheritedLocals(F)) locals.set(n, t);
1082
+ if (F) for (const q of F.p) locals.set(q[1], q[2] || null);
1083
+ const ctx = {
1084
+ F,
1085
+ path,
1086
+ locals,
1087
+ weak: new Set(),
1088
+ line: 0,
1089
+ lastConf: "high",
1090
+ gl: facts.gl || {},
1091
+ vars: new Set(facts.vars || []),
1092
+ binds: info.binds,
1093
+ testCaller: info.test,
1094
+ profile,
1095
+ lang: facts.lang,
1096
+ };
1097
+ for (const e of ev) {
1098
+ if (++eventsSinceCheck >= EVENTS_PER_CLOCK_CHECK) {
1099
+ eventsSinceCheck = 0;
1100
+ if (clock() > deadline) {
1101
+ outOfTime = true;
1102
+ unresolved.push(path);
1103
+ break;
1104
+ }
1105
+ }
1106
+ if (e[0] === "d") {
1107
+ locals.set(e[1], e[2]);
1108
+ ctx.weak.delete(e[1]);
1109
+ continue;
1110
+ }
1111
+ const [, line, bind, steps] = e;
1112
+ ctx.line = line;
1113
+ const result = evalChain(ctx, steps);
1114
+ if (bind) {
1115
+ locals.set(bind, result);
1116
+ if (ctx.lastConf === "high") ctx.weak.delete(bind);
1117
+ else ctx.weak.add(bind);
1118
+ }
1119
+ }
1120
+ }
1121
+ }
1122
+
1123
+ for (const e of out.values()) edges.push(e);
1124
+ return { calls: out.size, functions, unresolved };
1125
+ }