@ruverd/julius 0.0.0-stage → 0.24.1

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 (704) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/CREDITS.md +25 -0
  3. package/LICENSE +21 -0
  4. package/PROVENANCE.md +9 -0
  5. package/README.md +229 -2
  6. package/dist/ai/crux.d.ts +60 -0
  7. package/dist/ai/crux.d.ts.map +1 -0
  8. package/dist/ai/crux.js +141 -0
  9. package/dist/ai/crux.js.map +1 -0
  10. package/dist/ai/failure.d.ts +60 -0
  11. package/dist/ai/failure.d.ts.map +1 -0
  12. package/dist/ai/failure.js +86 -0
  13. package/dist/ai/failure.js.map +1 -0
  14. package/dist/ai/llm/anthropic.d.ts +37 -0
  15. package/dist/ai/llm/anthropic.d.ts.map +1 -0
  16. package/dist/ai/llm/anthropic.js +144 -0
  17. package/dist/ai/llm/anthropic.js.map +1 -0
  18. package/dist/ai/llm/factory.d.ts +28 -0
  19. package/dist/ai/llm/factory.d.ts.map +1 -0
  20. package/dist/ai/llm/factory.js +36 -0
  21. package/dist/ai/llm/factory.js.map +1 -0
  22. package/dist/ai/llm/litellm.d.ts +34 -0
  23. package/dist/ai/llm/litellm.d.ts.map +1 -0
  24. package/dist/ai/llm/litellm.js +45 -0
  25. package/dist/ai/llm/litellm.js.map +1 -0
  26. package/dist/ai/llm/openai.d.ts +44 -0
  27. package/dist/ai/llm/openai.d.ts.map +1 -0
  28. package/dist/ai/llm/openai.js +239 -0
  29. package/dist/ai/llm/openai.js.map +1 -0
  30. package/dist/ai/llm/orcarouter.d.ts +34 -0
  31. package/dist/ai/llm/orcarouter.d.ts.map +1 -0
  32. package/dist/ai/llm/orcarouter.js +45 -0
  33. package/dist/ai/llm/orcarouter.js.map +1 -0
  34. package/dist/ai/llm/recover-tool.d.ts +19 -0
  35. package/dist/ai/llm/recover-tool.d.ts.map +1 -0
  36. package/dist/ai/llm/recover-tool.js +109 -0
  37. package/dist/ai/llm/recover-tool.js.map +1 -0
  38. package/dist/ai/llm/types.d.ts +122 -0
  39. package/dist/ai/llm/types.d.ts.map +1 -0
  40. package/dist/ai/llm/types.js +33 -0
  41. package/dist/ai/llm/types.js.map +1 -0
  42. package/dist/ai/providers.d.ts +59 -0
  43. package/dist/ai/providers.d.ts.map +1 -0
  44. package/dist/ai/providers.js +54 -0
  45. package/dist/ai/providers.js.map +1 -0
  46. package/dist/ai/summarize.d.ts +25 -0
  47. package/dist/ai/summarize.d.ts.map +1 -0
  48. package/dist/ai/summarize.js +34 -0
  49. package/dist/ai/summarize.js.map +1 -0
  50. package/dist/ai/synthesize.d.ts +40 -0
  51. package/dist/ai/synthesize.d.ts.map +1 -0
  52. package/dist/ai/synthesize.js +131 -0
  53. package/dist/ai/synthesize.js.map +1 -0
  54. package/dist/app/checkout.d.ts +46 -0
  55. package/dist/app/checkout.d.ts.map +1 -0
  56. package/dist/app/checkout.js +223 -0
  57. package/dist/app/checkout.js.map +1 -0
  58. package/dist/app/events.d.ts +44 -0
  59. package/dist/app/events.d.ts.map +1 -0
  60. package/dist/app/events.js +64 -0
  61. package/dist/app/events.js.map +1 -0
  62. package/dist/app/identity.d.ts +54 -0
  63. package/dist/app/identity.d.ts.map +1 -0
  64. package/dist/app/identity.js +96 -0
  65. package/dist/app/identity.js.map +1 -0
  66. package/dist/app/main.d.ts +2 -0
  67. package/dist/app/main.d.ts.map +1 -0
  68. package/dist/app/main.js +62 -0
  69. package/dist/app/main.js.map +1 -0
  70. package/dist/app/pages.d.ts +56 -0
  71. package/dist/app/pages.d.ts.map +1 -0
  72. package/dist/app/pages.js +193 -0
  73. package/dist/app/pages.js.map +1 -0
  74. package/dist/app/queue.d.ts +40 -0
  75. package/dist/app/queue.d.ts.map +1 -0
  76. package/dist/app/queue.js +68 -0
  77. package/dist/app/queue.js.map +1 -0
  78. package/dist/app/review-process.d.ts +66 -0
  79. package/dist/app/review-process.d.ts.map +1 -0
  80. package/dist/app/review-process.js +200 -0
  81. package/dist/app/review-process.js.map +1 -0
  82. package/dist/app/review-worker.d.ts +2 -0
  83. package/dist/app/review-worker.d.ts.map +1 -0
  84. package/dist/app/review-worker.js +108 -0
  85. package/dist/app/review-worker.js.map +1 -0
  86. package/dist/app/review.d.ts +23 -0
  87. package/dist/app/review.d.ts.map +1 -0
  88. package/dist/app/review.js +142 -0
  89. package/dist/app/review.js.map +1 -0
  90. package/dist/app/server.d.ts +49 -0
  91. package/dist/app/server.d.ts.map +1 -0
  92. package/dist/app/server.js +123 -0
  93. package/dist/app/server.js.map +1 -0
  94. package/dist/ask/ask.d.ts +195 -0
  95. package/dist/ask/ask.d.ts.map +1 -0
  96. package/dist/ask/ask.js +1252 -0
  97. package/dist/ask/ask.js.map +1 -0
  98. package/dist/ask/file-rank.d.ts +72 -0
  99. package/dist/ask/file-rank.d.ts.map +1 -0
  100. package/dist/ask/file-rank.js +160 -0
  101. package/dist/ask/file-rank.js.map +1 -0
  102. package/dist/ask/file-selection.d.ts +22 -0
  103. package/dist/ask/file-selection.d.ts.map +1 -0
  104. package/dist/ask/file-selection.js +66 -0
  105. package/dist/ask/file-selection.js.map +1 -0
  106. package/dist/ask/fuse.d.ts +195 -0
  107. package/dist/ask/fuse.d.ts.map +1 -0
  108. package/dist/ask/fuse.js +344 -0
  109. package/dist/ask/fuse.js.map +1 -0
  110. package/dist/ask/graphrank.d.ts +61 -0
  111. package/dist/ask/graphrank.d.ts.map +1 -0
  112. package/dist/ask/graphrank.js +130 -0
  113. package/dist/ask/graphrank.js.map +1 -0
  114. package/dist/ask/index-file.d.ts +44 -0
  115. package/dist/ask/index-file.d.ts.map +1 -0
  116. package/dist/ask/index-file.js +128 -0
  117. package/dist/ask/index-file.js.map +1 -0
  118. package/dist/bin/julius.d.ts +3 -0
  119. package/dist/bin/julius.d.ts.map +1 -0
  120. package/dist/bin/julius.js +4 -0
  121. package/dist/bin/julius.js.map +1 -0
  122. package/dist/blast/blast-cli.d.ts +35 -0
  123. package/dist/blast/blast-cli.d.ts.map +1 -0
  124. package/dist/blast/blast-cli.js +155 -0
  125. package/dist/blast/blast-cli.js.map +1 -0
  126. package/dist/blast/blast.d.ts +128 -0
  127. package/dist/blast/blast.d.ts.map +1 -0
  128. package/dist/blast/blast.js +383 -0
  129. package/dist/blast/blast.js.map +1 -0
  130. package/dist/blast/diff.d.ts +53 -0
  131. package/dist/blast/diff.d.ts.map +1 -0
  132. package/dist/blast/diff.js +193 -0
  133. package/dist/blast/diff.js.map +1 -0
  134. package/dist/blast/evidence.d.ts +51 -0
  135. package/dist/blast/evidence.d.ts.map +1 -0
  136. package/dist/blast/evidence.js +162 -0
  137. package/dist/blast/evidence.js.map +1 -0
  138. package/dist/blast/modules.d.ts +33 -0
  139. package/dist/blast/modules.d.ts.map +1 -0
  140. package/dist/blast/modules.js +83 -0
  141. package/dist/blast/modules.js.map +1 -0
  142. package/dist/blast/name.d.ts +74 -0
  143. package/dist/blast/name.d.ts.map +1 -0
  144. package/dist/blast/name.js +269 -0
  145. package/dist/blast/name.js.map +1 -0
  146. package/dist/blast/owners.d.ts +85 -0
  147. package/dist/blast/owners.d.ts.map +1 -0
  148. package/dist/blast/owners.js +272 -0
  149. package/dist/blast/owners.js.map +1 -0
  150. package/dist/blast/render.d.ts +46 -0
  151. package/dist/blast/render.d.ts.map +1 -0
  152. package/dist/blast/render.js +422 -0
  153. package/dist/blast/render.js.map +1 -0
  154. package/dist/blast/viz.d.ts +37 -0
  155. package/dist/blast/viz.d.ts.map +1 -0
  156. package/dist/blast/viz.js +180 -0
  157. package/dist/blast/viz.js.map +1 -0
  158. package/dist/brand.d.ts +13 -0
  159. package/dist/brand.d.ts.map +1 -0
  160. package/dist/brand.js +43 -0
  161. package/dist/brand.js.map +1 -0
  162. package/dist/check/learning-edits.d.ts +9 -0
  163. package/dist/check/learning-edits.d.ts.map +1 -0
  164. package/dist/check/learning-edits.js +62 -0
  165. package/dist/check/learning-edits.js.map +1 -0
  166. package/dist/check/local-check.d.ts +104 -0
  167. package/dist/check/local-check.d.ts.map +1 -0
  168. package/dist/check/local-check.js +830 -0
  169. package/dist/check/local-check.js.map +1 -0
  170. package/dist/check/types.d.ts +31 -0
  171. package/dist/check/types.d.ts.map +1 -0
  172. package/dist/check/types.js +2 -0
  173. package/dist/check/types.js.map +1 -0
  174. package/dist/claude/build-progress.d.ts +29 -0
  175. package/dist/claude/build-progress.d.ts.map +1 -0
  176. package/dist/claude/build-progress.js +76 -0
  177. package/dist/claude/build-progress.js.map +1 -0
  178. package/dist/claude/format.d.ts +131 -0
  179. package/dist/claude/format.d.ts.map +1 -0
  180. package/dist/claude/format.js +328 -0
  181. package/dist/claude/format.js.map +1 -0
  182. package/dist/claude/hook-layers.d.ts +8 -0
  183. package/dist/claude/hook-layers.d.ts.map +1 -0
  184. package/dist/claude/hook-layers.js +74 -0
  185. package/dist/claude/hook-layers.js.map +1 -0
  186. package/dist/claude/hooks.d.ts +101 -0
  187. package/dist/claude/hooks.d.ts.map +1 -0
  188. package/dist/claude/hooks.js +849 -0
  189. package/dist/claude/hooks.js.map +1 -0
  190. package/dist/claude/init.d.ts +70 -0
  191. package/dist/claude/init.d.ts.map +1 -0
  192. package/dist/claude/init.js +207 -0
  193. package/dist/claude/init.js.map +1 -0
  194. package/dist/claude/note-signals.d.ts +28 -0
  195. package/dist/claude/note-signals.d.ts.map +1 -0
  196. package/dist/claude/note-signals.js +325 -0
  197. package/dist/claude/note-signals.js.map +1 -0
  198. package/dist/claude/paths.d.ts +9 -0
  199. package/dist/claude/paths.d.ts.map +1 -0
  200. package/dist/claude/paths.js +22 -0
  201. package/dist/claude/paths.js.map +1 -0
  202. package/dist/claude/session-metrics.d.ts +73 -0
  203. package/dist/claude/session-metrics.d.ts.map +1 -0
  204. package/dist/claude/session-metrics.js +209 -0
  205. package/dist/claude/session-metrics.js.map +1 -0
  206. package/dist/claude/settings-merge.d.ts +66 -0
  207. package/dist/claude/settings-merge.d.ts.map +1 -0
  208. package/dist/claude/settings-merge.js +249 -0
  209. package/dist/claude/settings-merge.js.map +1 -0
  210. package/dist/claude/shim-template.d.ts +18 -0
  211. package/dist/claude/shim-template.d.ts.map +1 -0
  212. package/dist/claude/shim-template.js +226 -0
  213. package/dist/claude/shim-template.js.map +1 -0
  214. package/dist/claude/skill-template.d.ts +12 -0
  215. package/dist/claude/skill-template.d.ts.map +1 -0
  216. package/dist/claude/skill-template.js +294 -0
  217. package/dist/claude/skill-template.js.map +1 -0
  218. package/dist/claude/state.d.ts +73 -0
  219. package/dist/claude/state.d.ts.map +1 -0
  220. package/dist/claude/state.js +33 -0
  221. package/dist/claude/state.js.map +1 -0
  222. package/dist/claude/stats.d.ts +5 -0
  223. package/dist/claude/stats.d.ts.map +1 -0
  224. package/dist/claude/stats.js +24 -0
  225. package/dist/claude/stats.js.map +1 -0
  226. package/dist/claude/statusline.d.ts +14 -0
  227. package/dist/claude/statusline.d.ts.map +1 -0
  228. package/dist/claude/statusline.js +45 -0
  229. package/dist/claude/statusline.js.map +1 -0
  230. package/dist/claude/sync-run.d.ts +3 -0
  231. package/dist/claude/sync-run.d.ts.map +1 -0
  232. package/dist/claude/sync-run.js +46 -0
  233. package/dist/claude/sync-run.js.map +1 -0
  234. package/dist/claude/tally.d.ts +50 -0
  235. package/dist/claude/tally.d.ts.map +1 -0
  236. package/dist/claude/tally.js +211 -0
  237. package/dist/claude/tally.js.map +1 -0
  238. package/dist/cli-epilogue.d.ts +12 -0
  239. package/dist/cli-epilogue.d.ts.map +1 -0
  240. package/dist/cli-epilogue.js +55 -0
  241. package/dist/cli-epilogue.js.map +1 -0
  242. package/dist/cli-meta.d.ts +45 -0
  243. package/dist/cli-meta.d.ts.map +1 -0
  244. package/dist/cli-meta.js +145 -0
  245. package/dist/cli-meta.js.map +1 -0
  246. package/dist/cli-picker.d.ts +129 -0
  247. package/dist/cli-picker.d.ts.map +1 -0
  248. package/dist/cli-picker.js +432 -0
  249. package/dist/cli-picker.js.map +1 -0
  250. package/dist/cli.d.ts +3 -0
  251. package/dist/cli.d.ts.map +1 -0
  252. package/dist/cli.js +2213 -0
  253. package/dist/cli.js.map +1 -0
  254. package/dist/cloud/diff.d.ts +20 -0
  255. package/dist/cloud/diff.d.ts.map +1 -0
  256. package/dist/cloud/diff.js +59 -0
  257. package/dist/cloud/diff.js.map +1 -0
  258. package/dist/cloud/nudge.d.ts +66 -0
  259. package/dist/cloud/nudge.d.ts.map +1 -0
  260. package/dist/cloud/nudge.js +268 -0
  261. package/dist/cloud/nudge.js.map +1 -0
  262. package/dist/cloud/workspace-sync.d.ts +58 -0
  263. package/dist/cloud/workspace-sync.d.ts.map +1 -0
  264. package/dist/cloud/workspace-sync.js +268 -0
  265. package/dist/cloud/workspace-sync.js.map +1 -0
  266. package/dist/cloud/workspace.d.ts +159 -0
  267. package/dist/cloud/workspace.d.ts.map +1 -0
  268. package/dist/cloud/workspace.js +134 -0
  269. package/dist/cloud/workspace.js.map +1 -0
  270. package/dist/context/build.d.ts +52 -0
  271. package/dist/context/build.d.ts.map +1 -0
  272. package/dist/context/build.js +362 -0
  273. package/dist/context/build.js.map +1 -0
  274. package/dist/context/check.d.ts +42 -0
  275. package/dist/context/check.d.ts.map +1 -0
  276. package/dist/context/check.js +162 -0
  277. package/dist/context/check.js.map +1 -0
  278. package/dist/context/map-dir.d.ts +4 -0
  279. package/dist/context/map-dir.d.ts.map +1 -0
  280. package/dist/context/map-dir.js +6 -0
  281. package/dist/context/map-dir.js.map +1 -0
  282. package/dist/context/node-file.d.ts +109 -0
  283. package/dist/context/node-file.d.ts.map +1 -0
  284. package/dist/context/node-file.js +362 -0
  285. package/dist/context/node-file.js.map +1 -0
  286. package/dist/context/price.d.ts +49 -0
  287. package/dist/context/price.d.ts.map +1 -0
  288. package/dist/context/price.js +83 -0
  289. package/dist/context/price.js.map +1 -0
  290. package/dist/context/savings.d.ts +26 -0
  291. package/dist/context/savings.d.ts.map +1 -0
  292. package/dist/context/savings.js +59 -0
  293. package/dist/context/savings.js.map +1 -0
  294. package/dist/economy/cli.d.ts +3 -0
  295. package/dist/economy/cli.d.ts.map +1 -0
  296. package/dist/economy/cli.js +52 -0
  297. package/dist/economy/cli.js.map +1 -0
  298. package/dist/economy/delivery.d.ts +49 -0
  299. package/dist/economy/delivery.d.ts.map +1 -0
  300. package/dist/economy/delivery.js +176 -0
  301. package/dist/economy/delivery.js.map +1 -0
  302. package/dist/economy/index.d.ts +68 -0
  303. package/dist/economy/index.d.ts.map +1 -0
  304. package/dist/economy/index.js +524 -0
  305. package/dist/economy/index.js.map +1 -0
  306. package/dist/engine.d.ts +83 -0
  307. package/dist/engine.d.ts.map +1 -0
  308. package/dist/engine.js +122 -0
  309. package/dist/engine.js.map +1 -0
  310. package/dist/evaluation/index.d.ts +41 -0
  311. package/dist/evaluation/index.d.ts.map +1 -0
  312. package/dist/evaluation/index.js +61 -0
  313. package/dist/evaluation/index.js.map +1 -0
  314. package/dist/graph/bindings.d.ts +64 -0
  315. package/dist/graph/bindings.d.ts.map +1 -0
  316. package/dist/graph/bindings.js +713 -0
  317. package/dist/graph/bindings.js.map +1 -0
  318. package/dist/graph/build.d.ts +88 -0
  319. package/dist/graph/build.d.ts.map +1 -0
  320. package/dist/graph/build.js +375 -0
  321. package/dist/graph/build.js.map +1 -0
  322. package/dist/graph/cards.d.ts +46 -0
  323. package/dist/graph/cards.d.ts.map +1 -0
  324. package/dist/graph/cards.js +280 -0
  325. package/dist/graph/cards.js.map +1 -0
  326. package/dist/graph/check.d.ts +25 -0
  327. package/dist/graph/check.d.ts.map +1 -0
  328. package/dist/graph/check.js +192 -0
  329. package/dist/graph/check.js.map +1 -0
  330. package/dist/graph/container.d.ts +63 -0
  331. package/dist/graph/container.d.ts.map +1 -0
  332. package/dist/graph/container.js +190 -0
  333. package/dist/graph/container.js.map +1 -0
  334. package/dist/graph/enrich.d.ts +62 -0
  335. package/dist/graph/enrich.d.ts.map +1 -0
  336. package/dist/graph/enrich.js +253 -0
  337. package/dist/graph/enrich.js.map +1 -0
  338. package/dist/graph/extract-cache.d.ts +101 -0
  339. package/dist/graph/extract-cache.d.ts.map +1 -0
  340. package/dist/graph/extract-cache.js +199 -0
  341. package/dist/graph/extract-cache.js.map +1 -0
  342. package/dist/graph/extract.d.ts +85 -0
  343. package/dist/graph/extract.d.ts.map +1 -0
  344. package/dist/graph/extract.js +2376 -0
  345. package/dist/graph/extract.js.map +1 -0
  346. package/dist/graph/fingerprint.d.ts +76 -0
  347. package/dist/graph/fingerprint.d.ts.map +1 -0
  348. package/dist/graph/fingerprint.js +160 -0
  349. package/dist/graph/fingerprint.js.map +1 -0
  350. package/dist/graph/generic.d.ts +74 -0
  351. package/dist/graph/generic.d.ts.map +1 -0
  352. package/dist/graph/generic.js +580 -0
  353. package/dist/graph/generic.js.map +1 -0
  354. package/dist/graph/invariants.d.ts +33 -0
  355. package/dist/graph/invariants.d.ts.map +1 -0
  356. package/dist/graph/invariants.js +52 -0
  357. package/dist/graph/invariants.js.map +1 -0
  358. package/dist/graph/load.d.ts +29 -0
  359. package/dist/graph/load.d.ts.map +1 -0
  360. package/dist/graph/load.js +97 -0
  361. package/dist/graph/load.js.map +1 -0
  362. package/dist/graph/lsp/client.d.ts +43 -0
  363. package/dist/graph/lsp/client.d.ts.map +1 -0
  364. package/dist/graph/lsp/client.js +179 -0
  365. package/dist/graph/lsp/client.js.map +1 -0
  366. package/dist/graph/lsp/enrich.d.ts +11 -0
  367. package/dist/graph/lsp/enrich.d.ts.map +1 -0
  368. package/dist/graph/lsp/enrich.js +155 -0
  369. package/dist/graph/lsp/enrich.js.map +1 -0
  370. package/dist/graph/lsp/registry.d.ts +15 -0
  371. package/dist/graph/lsp/registry.d.ts.map +1 -0
  372. package/dist/graph/lsp/registry.js +46 -0
  373. package/dist/graph/lsp/registry.js.map +1 -0
  374. package/dist/graph/map.d.ts +107 -0
  375. package/dist/graph/map.d.ts.map +1 -0
  376. package/dist/graph/map.js +239 -0
  377. package/dist/graph/map.js.map +1 -0
  378. package/dist/graph/native.d.ts +38 -0
  379. package/dist/graph/native.d.ts.map +1 -0
  380. package/dist/graph/native.js +169 -0
  381. package/dist/graph/native.js.map +1 -0
  382. package/dist/graph/queries/c.scm +13 -0
  383. package/dist/graph/queries/c_sharp.scm +19 -0
  384. package/dist/graph/queries/clojure.scm +58 -0
  385. package/dist/graph/queries/cpp.scm +23 -0
  386. package/dist/graph/queries/dart.scm +42 -0
  387. package/dist/graph/queries/elixir.scm +54 -0
  388. package/dist/graph/queries/java.scm +20 -0
  389. package/dist/graph/queries/kotlin.scm +43 -0
  390. package/dist/graph/queries/lua.scm +36 -0
  391. package/dist/graph/queries/nix.scm +32 -0
  392. package/dist/graph/queries/php.scm +40 -0
  393. package/dist/graph/queries/ruby.scm +65 -0
  394. package/dist/graph/queries/rust.scm +41 -0
  395. package/dist/graph/queries/scala.scm +66 -0
  396. package/dist/graph/queries/solidity.scm +43 -0
  397. package/dist/graph/queries/swift.scm +51 -0
  398. package/dist/graph/refresh.d.ts +49 -0
  399. package/dist/graph/refresh.d.ts.map +1 -0
  400. package/dist/graph/refresh.js +255 -0
  401. package/dist/graph/refresh.js.map +1 -0
  402. package/dist/graph/relations.d.ts +14 -0
  403. package/dist/graph/relations.d.ts.map +1 -0
  404. package/dist/graph/relations.js +8 -0
  405. package/dist/graph/relations.js.map +1 -0
  406. package/dist/graph/resolve.d.ts +17 -0
  407. package/dist/graph/resolve.d.ts.map +1 -0
  408. package/dist/graph/resolve.js +654 -0
  409. package/dist/graph/resolve.js.map +1 -0
  410. package/dist/graph/root.d.ts +11 -0
  411. package/dist/graph/root.d.ts.map +1 -0
  412. package/dist/graph/root.js +40 -0
  413. package/dist/graph/root.js.map +1 -0
  414. package/dist/graph/scopes.d.ts +42 -0
  415. package/dist/graph/scopes.d.ts.map +1 -0
  416. package/dist/graph/scopes.js +342 -0
  417. package/dist/graph/scopes.js.map +1 -0
  418. package/dist/graph/seed.d.ts +38 -0
  419. package/dist/graph/seed.d.ts.map +1 -0
  420. package/dist/graph/seed.js +226 -0
  421. package/dist/graph/seed.js.map +1 -0
  422. package/dist/graph/source-files.d.ts +40 -0
  423. package/dist/graph/source-files.d.ts.map +1 -0
  424. package/dist/graph/source-files.js +85 -0
  425. package/dist/graph/source-files.js.map +1 -0
  426. package/dist/graph/traverse-cli.d.ts +55 -0
  427. package/dist/graph/traverse-cli.d.ts.map +1 -0
  428. package/dist/graph/traverse-cli.js +189 -0
  429. package/dist/graph/traverse-cli.js.map +1 -0
  430. package/dist/graph/traverse.d.ts +112 -0
  431. package/dist/graph/traverse.d.ts.map +1 -0
  432. package/dist/graph/traverse.js +192 -0
  433. package/dist/graph/traverse.js.map +1 -0
  434. package/dist/graph/types.d.ts +78 -0
  435. package/dist/graph/types.d.ts.map +1 -0
  436. package/dist/graph/types.js +14 -0
  437. package/dist/graph/types.js.map +1 -0
  438. package/dist/graph/workspace-cli.d.ts +48 -0
  439. package/dist/graph/workspace-cli.d.ts.map +1 -0
  440. package/dist/graph/workspace-cli.js +102 -0
  441. package/dist/graph/workspace-cli.js.map +1 -0
  442. package/dist/graph/workspace.d.ts +135 -0
  443. package/dist/graph/workspace.d.ts.map +1 -0
  444. package/dist/graph/workspace.js +598 -0
  445. package/dist/graph/workspace.js.map +1 -0
  446. package/dist/graph/write.d.ts +13 -0
  447. package/dist/graph/write.d.ts.map +1 -0
  448. package/dist/graph/write.js +86 -0
  449. package/dist/graph/write.js.map +1 -0
  450. package/dist/hosts/antigravity.d.ts +8 -0
  451. package/dist/hosts/antigravity.d.ts.map +1 -0
  452. package/dist/hosts/antigravity.js +42 -0
  453. package/dist/hosts/antigravity.js.map +1 -0
  454. package/dist/hosts/claude-global.d.ts +36 -0
  455. package/dist/hosts/claude-global.d.ts.map +1 -0
  456. package/dist/hosts/claude-global.js +153 -0
  457. package/dist/hosts/claude-global.js.map +1 -0
  458. package/dist/hosts/codex-hooks.d.ts +11 -0
  459. package/dist/hosts/codex-hooks.d.ts.map +1 -0
  460. package/dist/hosts/codex-hooks.js +80 -0
  461. package/dist/hosts/codex-hooks.js.map +1 -0
  462. package/dist/hosts/config-write.d.ts +36 -0
  463. package/dist/hosts/config-write.d.ts.map +1 -0
  464. package/dist/hosts/config-write.js +64 -0
  465. package/dist/hosts/config-write.js.map +1 -0
  466. package/dist/hosts/cursor-hooks.d.ts +21 -0
  467. package/dist/hosts/cursor-hooks.d.ts.map +1 -0
  468. package/dist/hosts/cursor-hooks.js +103 -0
  469. package/dist/hosts/cursor-hooks.js.map +1 -0
  470. package/dist/hosts/init.d.ts +26 -0
  471. package/dist/hosts/init.d.ts.map +1 -0
  472. package/dist/hosts/init.js +82 -0
  473. package/dist/hosts/init.js.map +1 -0
  474. package/dist/hosts/install.d.ts +12 -0
  475. package/dist/hosts/install.d.ts.map +1 -0
  476. package/dist/hosts/install.js +347 -0
  477. package/dist/hosts/install.js.map +1 -0
  478. package/dist/hosts/instructions.d.ts +7 -0
  479. package/dist/hosts/instructions.d.ts.map +1 -0
  480. package/dist/hosts/instructions.js +71 -0
  481. package/dist/hosts/instructions.js.map +1 -0
  482. package/dist/hosts/investigation-instructions.d.ts +2 -0
  483. package/dist/hosts/investigation-instructions.d.ts.map +1 -0
  484. package/dist/hosts/investigation-instructions.js +2 -0
  485. package/dist/hosts/investigation-instructions.js.map +1 -0
  486. package/dist/hosts/mcp-config.d.ts +59 -0
  487. package/dist/hosts/mcp-config.d.ts.map +1 -0
  488. package/dist/hosts/mcp-config.js +229 -0
  489. package/dist/hosts/mcp-config.js.map +1 -0
  490. package/dist/hosts/plan.d.ts +32 -0
  491. package/dist/hosts/plan.d.ts.map +1 -0
  492. package/dist/hosts/plan.js +77 -0
  493. package/dist/hosts/plan.js.map +1 -0
  494. package/dist/hosts/registry.d.ts +35 -0
  495. package/dist/hosts/registry.d.ts.map +1 -0
  496. package/dist/hosts/registry.js +157 -0
  497. package/dist/hosts/registry.js.map +1 -0
  498. package/dist/hosts/retract.d.ts +47 -0
  499. package/dist/hosts/retract.d.ts.map +1 -0
  500. package/dist/hosts/retract.js +541 -0
  501. package/dist/hosts/retract.js.map +1 -0
  502. package/dist/hosts/sections.d.ts +46 -0
  503. package/dist/hosts/sections.d.ts.map +1 -0
  504. package/dist/hosts/sections.js +126 -0
  505. package/dist/hosts/sections.js.map +1 -0
  506. package/dist/index.d.ts +43 -0
  507. package/dist/index.d.ts.map +1 -0
  508. package/dist/index.js +33 -0
  509. package/dist/index.js.map +1 -0
  510. package/dist/ingest/fs.d.ts +79 -0
  511. package/dist/ingest/fs.d.ts.map +1 -0
  512. package/dist/ingest/fs.js +307 -0
  513. package/dist/ingest/fs.js.map +1 -0
  514. package/dist/init-guard.d.ts +11 -0
  515. package/dist/init-guard.d.ts.map +1 -0
  516. package/dist/init-guard.js +21 -0
  517. package/dist/init-guard.js.map +1 -0
  518. package/dist/investigation/index.d.ts +57 -0
  519. package/dist/investigation/index.d.ts.map +1 -0
  520. package/dist/investigation/index.js +346 -0
  521. package/dist/investigation/index.js.map +1 -0
  522. package/dist/mcp/compact.d.ts +9 -0
  523. package/dist/mcp/compact.d.ts.map +1 -0
  524. package/dist/mcp/compact.js +133 -0
  525. package/dist/mcp/compact.js.map +1 -0
  526. package/dist/mcp/instructions.d.ts +5 -0
  527. package/dist/mcp/instructions.d.ts.map +1 -0
  528. package/dist/mcp/instructions.js +57 -0
  529. package/dist/mcp/instructions.js.map +1 -0
  530. package/dist/mcp/server.d.ts +7 -0
  531. package/dist/mcp/server.d.ts.map +1 -0
  532. package/dist/mcp/server.js +128 -0
  533. package/dist/mcp/server.js.map +1 -0
  534. package/dist/mcp/tool-names.d.ts +20 -0
  535. package/dist/mcp/tool-names.d.ts.map +1 -0
  536. package/dist/mcp/tool-names.js +36 -0
  537. package/dist/mcp/tool-names.js.map +1 -0
  538. package/dist/mcp/tools.d.ts +22 -0
  539. package/dist/mcp/tools.d.ts.map +1 -0
  540. package/dist/mcp/tools.js +300 -0
  541. package/dist/mcp/tools.js.map +1 -0
  542. package/dist/notes/ask-notes.d.ts +8 -0
  543. package/dist/notes/ask-notes.d.ts.map +1 -0
  544. package/dist/notes/ask-notes.js +19 -0
  545. package/dist/notes/ask-notes.js.map +1 -0
  546. package/dist/notes/branches.d.ts +102 -0
  547. package/dist/notes/branches.d.ts.map +1 -0
  548. package/dist/notes/branches.js +304 -0
  549. package/dist/notes/branches.js.map +1 -0
  550. package/dist/notes/cold-start.d.ts +177 -0
  551. package/dist/notes/cold-start.d.ts.map +1 -0
  552. package/dist/notes/cold-start.js +537 -0
  553. package/dist/notes/cold-start.js.map +1 -0
  554. package/dist/notes/edit-overlap.d.ts +62 -0
  555. package/dist/notes/edit-overlap.d.ts.map +1 -0
  556. package/dist/notes/edit-overlap.js +202 -0
  557. package/dist/notes/edit-overlap.js.map +1 -0
  558. package/dist/notes/git-facts.d.ts +21 -0
  559. package/dist/notes/git-facts.d.ts.map +1 -0
  560. package/dist/notes/git-facts.js +121 -0
  561. package/dist/notes/git-facts.js.map +1 -0
  562. package/dist/notes/home.d.ts +87 -0
  563. package/dist/notes/home.d.ts.map +1 -0
  564. package/dist/notes/home.js +430 -0
  565. package/dist/notes/home.js.map +1 -0
  566. package/dist/notes/learning-fields.d.ts +102 -0
  567. package/dist/notes/learning-fields.d.ts.map +1 -0
  568. package/dist/notes/learning-fields.js +217 -0
  569. package/dist/notes/learning-fields.js.map +1 -0
  570. package/dist/notes/note-gate.d.ts +42 -0
  571. package/dist/notes/note-gate.d.ts.map +1 -0
  572. package/dist/notes/note-gate.js +181 -0
  573. package/dist/notes/note-gate.js.map +1 -0
  574. package/dist/notes/notes.d.ts +214 -0
  575. package/dist/notes/notes.d.ts.map +1 -0
  576. package/dist/notes/notes.js +591 -0
  577. package/dist/notes/notes.js.map +1 -0
  578. package/dist/notes/pr-reviews.d.ts +108 -0
  579. package/dist/notes/pr-reviews.d.ts.map +1 -0
  580. package/dist/notes/pr-reviews.js +325 -0
  581. package/dist/notes/pr-reviews.js.map +1 -0
  582. package/dist/notes/repo-julius.d.ts +18 -0
  583. package/dist/notes/repo-julius.d.ts.map +1 -0
  584. package/dist/notes/repo-julius.js +111 -0
  585. package/dist/notes/repo-julius.js.map +1 -0
  586. package/dist/notes/session-cost.d.ts +35 -0
  587. package/dist/notes/session-cost.d.ts.map +1 -0
  588. package/dist/notes/session-cost.js +276 -0
  589. package/dist/notes/session-cost.js.map +1 -0
  590. package/dist/search/grep-cli.d.ts +37 -0
  591. package/dist/search/grep-cli.d.ts.map +1 -0
  592. package/dist/search/grep-cli.js +119 -0
  593. package/dist/search/grep-cli.js.map +1 -0
  594. package/dist/search/grep.d.ts +60 -0
  595. package/dist/search/grep.d.ts.map +1 -0
  596. package/dist/search/grep.js +176 -0
  597. package/dist/search/grep.js.map +1 -0
  598. package/dist/search/ignored-code.d.ts +9 -0
  599. package/dist/search/ignored-code.d.ts.map +1 -0
  600. package/dist/search/ignored-code.js +73 -0
  601. package/dist/search/ignored-code.js.map +1 -0
  602. package/dist/skills/skills.d.ts +118 -0
  603. package/dist/skills/skills.d.ts.map +1 -0
  604. package/dist/skills/skills.js +370 -0
  605. package/dist/skills/skills.js.map +1 -0
  606. package/dist/telemetry/contract.d.ts +103 -0
  607. package/dist/telemetry/contract.d.ts.map +1 -0
  608. package/dist/telemetry/contract.js +270 -0
  609. package/dist/telemetry/contract.js.map +1 -0
  610. package/dist/telemetry/flush.d.ts +21 -0
  611. package/dist/telemetry/flush.d.ts.map +1 -0
  612. package/dist/telemetry/flush.js +85 -0
  613. package/dist/telemetry/flush.js.map +1 -0
  614. package/dist/telemetry/gate.d.ts +30 -0
  615. package/dist/telemetry/gate.d.ts.map +1 -0
  616. package/dist/telemetry/gate.js +81 -0
  617. package/dist/telemetry/gate.js.map +1 -0
  618. package/dist/telemetry/identity.d.ts +40 -0
  619. package/dist/telemetry/identity.d.ts.map +1 -0
  620. package/dist/telemetry/identity.js +80 -0
  621. package/dist/telemetry/identity.js.map +1 -0
  622. package/dist/telemetry/index.d.ts +18 -0
  623. package/dist/telemetry/index.d.ts.map +1 -0
  624. package/dist/telemetry/index.js +16 -0
  625. package/dist/telemetry/index.js.map +1 -0
  626. package/dist/telemetry/key.d.ts +4 -0
  627. package/dist/telemetry/key.d.ts.map +1 -0
  628. package/dist/telemetry/key.js +4 -0
  629. package/dist/telemetry/key.js.map +1 -0
  630. package/dist/telemetry/notice.d.ts +19 -0
  631. package/dist/telemetry/notice.d.ts.map +1 -0
  632. package/dist/telemetry/notice.js +93 -0
  633. package/dist/telemetry/notice.js.map +1 -0
  634. package/dist/telemetry/queue.d.ts +35 -0
  635. package/dist/telemetry/queue.d.ts.map +1 -0
  636. package/dist/telemetry/queue.js +162 -0
  637. package/dist/telemetry/queue.js.map +1 -0
  638. package/dist/telemetry/send.d.ts +19 -0
  639. package/dist/telemetry/send.d.ts.map +1 -0
  640. package/dist/telemetry/send.js +84 -0
  641. package/dist/telemetry/send.js.map +1 -0
  642. package/dist/telemetry/sessions.d.ts +25 -0
  643. package/dist/telemetry/sessions.d.ts.map +1 -0
  644. package/dist/telemetry/sessions.js +104 -0
  645. package/dist/telemetry/sessions.js.map +1 -0
  646. package/dist/telemetry/track.d.ts +62 -0
  647. package/dist/telemetry/track.d.ts.map +1 -0
  648. package/dist/telemetry/track.js +142 -0
  649. package/dist/telemetry/track.js.map +1 -0
  650. package/dist/upkeep-run.d.ts +15 -0
  651. package/dist/upkeep-run.d.ts.map +1 -0
  652. package/dist/upkeep-run.js +71 -0
  653. package/dist/upkeep-run.js.map +1 -0
  654. package/dist/upkeep.d.ts +125 -0
  655. package/dist/upkeep.d.ts.map +1 -0
  656. package/dist/upkeep.js +255 -0
  657. package/dist/upkeep.js.map +1 -0
  658. package/dist/util/browser.d.ts +3 -0
  659. package/dist/util/browser.d.ts.map +1 -0
  660. package/dist/util/browser.js +14 -0
  661. package/dist/util/browser.js.map +1 -0
  662. package/dist/util/front-matter.d.ts +19 -0
  663. package/dist/util/front-matter.d.ts.map +1 -0
  664. package/dist/util/front-matter.js +21 -0
  665. package/dist/util/front-matter.js.map +1 -0
  666. package/dist/util/id.d.ts +7 -0
  667. package/dist/util/id.d.ts.map +1 -0
  668. package/dist/util/id.js +14 -0
  669. package/dist/util/id.js.map +1 -0
  670. package/dist/util/paths.d.ts +29 -0
  671. package/dist/util/paths.d.ts.map +1 -0
  672. package/dist/util/paths.js +71 -0
  673. package/dist/util/paths.js.map +1 -0
  674. package/dist/util/source.d.ts +4 -0
  675. package/dist/util/source.d.ts.map +1 -0
  676. package/dist/util/source.js +12 -0
  677. package/dist/util/source.js.map +1 -0
  678. package/dist/util/spinner.d.ts +15 -0
  679. package/dist/util/spinner.d.ts.map +1 -0
  680. package/dist/util/spinner.js +52 -0
  681. package/dist/util/spinner.js.map +1 -0
  682. package/dist/util/state.d.ts +100 -0
  683. package/dist/util/state.d.ts.map +1 -0
  684. package/dist/util/state.js +186 -0
  685. package/dist/util/state.js.map +1 -0
  686. package/dist/viewer/app.js +2 -0
  687. package/dist/viewer/index.html +49 -0
  688. package/dist/viewer/style.css +154 -0
  689. package/dist/viz/assemble.d.ts +83 -0
  690. package/dist/viz/assemble.d.ts.map +1 -0
  691. package/dist/viz/assemble.js +101 -0
  692. package/dist/viz/assemble.js.map +1 -0
  693. package/dist/viz/export.d.ts +39 -0
  694. package/dist/viz/export.d.ts.map +1 -0
  695. package/dist/viz/export.js +98 -0
  696. package/dist/viz/export.js.map +1 -0
  697. package/dist/viz/serve.d.ts +12 -0
  698. package/dist/viz/serve.d.ts.map +1 -0
  699. package/dist/viz/serve.js +129 -0
  700. package/dist/viz/serve.js.map +1 -0
  701. package/docs/assets/context-benchmark.svg +31 -0
  702. package/docs/assets/julius-hero.png +0 -0
  703. package/docs/upstream-changelog.md +785 -0
  704. package/package.json +138 -4
@@ -0,0 +1,1252 @@
1
+ /**
2
+ * `julius ask "<task>"` — the ACTIVE channel.
3
+ *
4
+ * One tool that routes a plain-words query to the right graph and returns a lean,
5
+ * ranked context pack (prose + exact `file:line` + related), never raw JSON and
6
+ * never whole files:
7
+ *
8
+ * - Structural intent ("what calls X", "callers of X", "what does X import")
9
+ * → walk the wiring graph's edges and return the neighbour symbols with spans.
10
+ * - Everything else → lexical rank over concept nodes (prose) and wiring symbols
11
+ * (name + signature + summary), returning the best few with pointers.
12
+ *
13
+ * v1 is deterministic and $0 (term-overlap scoring, no LLM, no embeddings). The
14
+ * output is markdown so it drops straight into an agent's context.
15
+ */
16
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
17
+ import { join, resolve } from "node:path";
18
+ import { matter } from "../util/front-matter.js";
19
+ import { contextDirFor } from "../context/node-file.js";
20
+ import { withSavings, savingsFor, savingsLine } from "../context/savings.js";
21
+ import { loadGraphCached, loadAskIndexCached } from "../graph/load.js";
22
+ import { assertPrefixIndexed, pathUnderPrefix, scopeLabel, scopeOf, scopesHereClause, scopesOfGraph, } from "../graph/scopes.js";
23
+ import { normalizePathPrefix } from "../util/paths.js";
24
+ import { resolveSymbol } from "../graph/traverse.js";
25
+ import { combineComparableScopes, rankScopesAndFuse, } from "./fuse.js";
26
+ import { rankFilesBounded, } from "./file-rank.js";
27
+ import { fileFirstRoundRobin, roundRobinQueues } from "./file-selection.js";
28
+ import { personalizedPageRank, personalizedPageRankPrepared, preparePageRankPartitions, } from "./graphrank.js";
29
+ import { readSourceFile } from "../util/source.js";
30
+ import { counts, tokenize } from "./index-file.js";
31
+ import { cmd, tag } from "../brand.js";
32
+ import { formatNoteHits, learningSavingsLine } from "../notes/notes.js";
33
+ /** Max source lines to inline per hit — a definition longer than this is
34
+ * truncated with a marker, so one giant function can't blow up the pack. */
35
+ const MAX_SPAN_LINES = 80;
36
+ /** First real prose line of a node body (skips headings, markers, blanks). */
37
+ function firstProse(body) {
38
+ for (const raw of body.split("\n")) {
39
+ const line = raw.trim();
40
+ if (!line || line.startsWith("#") || line.startsWith("<!--") || line.startsWith("-"))
41
+ continue;
42
+ return line;
43
+ }
44
+ return "";
45
+ }
46
+ function loadCorpus(outDir) {
47
+ const concepts = [];
48
+ if (existsSync(outDir)) {
49
+ for (const entry of readdirSync(outDir)) {
50
+ if (!entry.endsWith(".md") || entry === "INDEX.md")
51
+ continue;
52
+ const parsed = matter(readFileSync(join(outDir, entry), "utf8"));
53
+ const fm = parsed.data;
54
+ const sources = Array.isArray(fm.sources)
55
+ ? fm.sources.map((s) => s.path)
56
+ : [];
57
+ const related = Array.isArray(fm.links)
58
+ ? fm.links.map((l) => l.to)
59
+ : [];
60
+ const snippet = firstProse(parsed.content);
61
+ concepts.push({
62
+ slug: String(fm.slug ?? entry.replace(/\.md$/, "")),
63
+ name: String(fm.name ?? ""),
64
+ sources,
65
+ related,
66
+ snippet,
67
+ text: `${fm.name ?? ""} ${snippet} ${sources.join(" ")}`,
68
+ });
69
+ }
70
+ }
71
+ return { concepts, graph: loadGraphCached(outDir), askIndex: loadAskIndexCached(outDir) };
72
+ }
73
+ /** Score a document's token counts against the query counts (name field
74
+ * pre-weighted by caller). Each shared term is weighted by its inverse document
75
+ * frequency (`idf`), so a word that appears in many nodes — "overlay" across a
76
+ * whole widget subsystem, or a repeated word in a pasted issue body — counts for
77
+ * far less than a rare, discriminating identifier ("scrolling"). Without idf,
78
+ * pure term-frequency lets an incidental common word dominate the ranking; this
79
+ * is the lexical half of the keyword-collision fix (graph-rank is the other). */
80
+ /** Test files rarely answer "how does X work" / "where is Y" — they mirror the
81
+ * real symbol's tokens, so a test can out-score the definition on a lexical tie
82
+ * and land as the top hit (observed: an `ask` returning a `Test…` function first,
83
+ * sending the agent to the wrong file). A multiplicative de-rank keeps tests in
84
+ * the results (they still matter for "where are the tests") but below the real
85
+ * definition. Covers Go (`_test.go`), JS/TS (`.test.` / `.spec.`), and test dirs. */
86
+ export function isTestPath(path) {
87
+ return /(^|\/)(tests?|__tests__|spec)\/|(_test|\.test|\.spec)\.[a-z]+$|(^|\/)(test_[^/]+|conftest)\.py$/i.test(path || "");
88
+ }
89
+ const TEST_RANK_PENALTY = 0.35;
90
+ function score(query, doc, idf) {
91
+ let s = 0;
92
+ for (const [t, qn] of query) {
93
+ const dn = doc.get(t);
94
+ if (dn)
95
+ s += qn * dn * (idf.get(t) ?? 1);
96
+ }
97
+ return s;
98
+ }
99
+ /** Inverse document frequency over the scored corpus. `df` counts how many
100
+ * documents (concept nodes + symbol nodes) contain each token; N is the corpus
101
+ * size. `log(1 + N/(1+df))` is the smoothed standard form: monotonically
102
+ * decreasing in df, always positive, ~0 extra weight for a token in every doc. */
103
+ function idfFromDf(df, n) {
104
+ const idf = new Map();
105
+ for (const [t, d] of df)
106
+ idf.set(t, Math.log(1 + n / (1 + d)));
107
+ return idf;
108
+ }
109
+ function computeIdf(docBags) {
110
+ const df = new Map();
111
+ for (const bag of docBags)
112
+ for (const t of bag)
113
+ df.set(t, (df.get(t) ?? 0) + 1);
114
+ return idfFromDf(df, docBags.length);
115
+ }
116
+ /** Same idf as {@link computeIdf}, but the symbol half of `df` and the doc
117
+ * count come from the build-time sidecar instead of tokenizing the corpus
118
+ * live; only the concept bags (always tokenized live — there are only dozens)
119
+ * are folded in here, the same way `computeIdf` would fold them into the full
120
+ * docBags array. `df` is a commutative sum and `n` is the same total document
121
+ * count either way, so this produces byte-identical idf values to `computeIdf`
122
+ * run over concept-bags + live-tokenized-symbol-bags. */
123
+ function computeIdfFromIndex(index, conceptBags) {
124
+ const df = new Map(index.df);
125
+ for (const bag of conceptBags)
126
+ for (const t of bag)
127
+ df.set(t, (df.get(t) ?? 0) + 1);
128
+ return idfFromDf(df, index.docCount + conceptBags.length);
129
+ }
130
+ /** BM25 term score for a document field, used for the (potentially large) body
131
+ * field. Unlike raw term-frequency, BM25 saturates repeated occurrences (`k1`)
132
+ * and normalizes by document length (`b`, against the corpus-average length
133
+ * `avgdl`), so a big definition — a sprawling test class — can't outrank a
134
+ * tight, on-point function merely by containing more words. Standard params. */
135
+ function bm25(query, doc, idf, dl, avgdl) {
136
+ const k1 = 1.2;
137
+ const b = 0.75;
138
+ const norm = k1 * (1 - b + (b * dl) / (avgdl || 1));
139
+ let s = 0;
140
+ for (const t of query.keys()) {
141
+ const tf = doc.get(t);
142
+ if (tf)
143
+ s += (idf.get(t) ?? 1) * ((tf * (k1 + 1)) / (tf + norm));
144
+ }
145
+ return s;
146
+ }
147
+ /** Exact query terms awarded by the existing lexical fields. Bounded ranking uses
148
+ * presence only: raw name/path/BM25 magnitudes cannot enter the file residual. */
149
+ function matchedLexicalTerms(query, name, path, body) {
150
+ const terms = new Set();
151
+ for (const term of query.keys())
152
+ if (name.has(term) || path.has(term) || body.has(term))
153
+ terms.add(term);
154
+ return terms;
155
+ }
156
+ /** NAME-only query terms behind file-level strong coverage. This intentionally
157
+ * mirrors {@link strongShare}'s plural folding while excluding file nodes at
158
+ * the call site. */
159
+ function matchedStrongTerms(query, name) {
160
+ const terms = new Set();
161
+ for (const term of query.keys())
162
+ if (hasTerm(name, term))
163
+ terms.add(term);
164
+ return terms;
165
+ }
166
+ // ── Structural intent ──────────────────────────────────────────────────────
167
+ const INCOMING = /\b(caller|callers|calls?\s+into|who\s+calls|what\s+calls|called\s+by|used\s+by|uses)\b/;
168
+ const OUTGOING = /\b(callee|callees|what\s+does\s+\w+\s+call|calls\s+what|imports?|depends\s+on)\b/;
169
+ const INCOMING_RELS = ["calls", "references", "implements", "extends"];
170
+ const OUTGOING_RELS = ["calls", "references", "imports", "implements", "extends"];
171
+ /** Split a prose query into word-like tokens, keeping dots so a qualified name
172
+ * ("Cache.get") or package-qualified name ("pkg.Fn") survives as one token —
173
+ * `resolveSymbol`'s own suffix/last-segment matching handles the rest. */
174
+ function subjectWords(query) {
175
+ return [...new Set(query.split(/[^A-Za-z0-9_.]+/).filter(Boolean))];
176
+ }
177
+ /** Resolve the query's structural subject via {@link resolveSymbol}, trying
178
+ * each word longest-first — the intended subject of a structural query is
179
+ * usually the most specific (longest) identifier-shaped word, never a short
180
+ * verb like "calls" — until one resolves. `tried` is the word that was tried
181
+ * last regardless of outcome, so a caller can name *something* in a fallthrough
182
+ * note even when nothing resolved (e.g. `subjects.length === 0`). This is what
183
+ * makes a qualified/dotted subject like `Cache.get` resolve, where the old
184
+ * plain name-equality lookup (`findSubject`) never matched it.
185
+ *
186
+ * `inPrefix`, when given, filters each word's `resolveSymbol` matches down to
187
+ * nodes under that path prefix BEFORE checking whether any survived — same
188
+ * "narrow the subject resolution" semantics `callers`/`callees`/`impact --in`
189
+ * already have (segment-aware here, via `pathUnderPrefix`). A word that
190
+ * resolves globally but has nothing under the prefix does NOT count as a
191
+ * match; the next (shorter) word is tried instead, same as an unresolved word
192
+ * today — and if nothing survives for ANY word, `subjects.length === 0`
193
+ * naturally falls through to the existing loud fallthrough note. */
194
+ function findSubjectNodes(query, graph, inPrefix) {
195
+ const words = subjectWords(query).sort((a, b) => b.length - a.length);
196
+ for (const w of words) {
197
+ let nodes = resolveSymbol(graph, w);
198
+ if (inPrefix)
199
+ nodes = nodes.filter((n) => pathUnderPrefix(n.path, inPrefix));
200
+ if (nodes.length > 0)
201
+ return { nodes, tried: w };
202
+ }
203
+ return { nodes: [], tried: words[0] ?? query };
204
+ }
205
+ function fallthroughNoteFor(subject) {
206
+ return (`structural index: no entries for '${subject}' — showing lexical matches; ` +
207
+ `for precise edges try ${cmd("julius callers")} '${subject}', or ${cmd("julius grep")} '${subject}' for every reference (loosen the pattern if it returns nothing)`);
208
+ }
209
+ function structural(query, graph, limit, inPrefix) {
210
+ const wantsIn = INCOMING.test(query);
211
+ const wantsOut = OUTGOING.test(query);
212
+ if (!wantsIn && !wantsOut)
213
+ return null;
214
+ const { nodes: subjects, tried } = findSubjectNodes(query, graph, inPrefix);
215
+ if (subjects.length === 0)
216
+ return { fallthroughNote: fallthroughNoteFor(tried) };
217
+ const ids = new Set(subjects.map((n) => n.id));
218
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
219
+ const outgoing = wantsOut && !wantsIn; // "what does X call / import" — else default to callers
220
+ const rels = new Set(outgoing ? OUTGOING_RELS : INCOMING_RELS);
221
+ const hits = [];
222
+ const seen = new Set();
223
+ for (const e of graph.edges) {
224
+ if (!rels.has(e.relation))
225
+ continue;
226
+ const anchor = outgoing ? e.source : e.target;
227
+ const other = outgoing ? e.target : e.source;
228
+ if (!ids.has(anchor) || seen.has(other + e.relation))
229
+ continue;
230
+ seen.add(other + e.relation);
231
+ const node = byId.get(other);
232
+ hits.push({
233
+ kind: outgoing ? "callee" : "caller",
234
+ title: node ? node.name : other, // unresolved import target → raw module string
235
+ pointer: node ? `${node.path}:${node.span}` : other,
236
+ snippet: node?.summary?.split("\n")[0].trim() ?? node?.signature ?? "",
237
+ relation: e.relation,
238
+ score: 1,
239
+ });
240
+ }
241
+ // Subject resolved but the graph has no indexed edges for it — same "loud,
242
+ // never a bare empty" contract as `julius callers`/`callees` — fall through
243
+ // to lexical rather than returning a structural result with zero hits.
244
+ if (hits.length === 0)
245
+ return { fallthroughNote: fallthroughNoteFor(subjects[0].name) };
246
+ hits.sort((a, b) => a.pointer.localeCompare(b.pointer));
247
+ return {
248
+ result: {
249
+ query,
250
+ mode: "structural",
251
+ subject: subjects[0].name,
252
+ hits: hits.slice(0, limit),
253
+ note: outgoing
254
+ ? `outgoing edges from ${subjects[0].name}`
255
+ : `callers / references of ${subjects[0].name}`,
256
+ },
257
+ };
258
+ }
259
+ // ── Lexical rank ─────────────────────────────────────────────────────────────
260
+ /** How much a node's graph-centrality (0..1) can lift its blended score. A
261
+ * lexically-perfect node scores 1.0 on the lexical axis; a graph weight of 0.5
262
+ * lets connectivity reorder near-ties and separate a connected hit from an
263
+ * isolated same-word collision, without letting structure override a clear
264
+ * lexical winner. */
265
+ const GRAPH_WEIGHT = 0.5;
266
+ /** A node the query never word-matched is pulled into the results only if the
267
+ * walk gives it at least this share of the top node's mass — i.e. it is
268
+ * genuinely central to the matched cluster, not incidentally reachable. This is
269
+ * what surfaces the config/helper a task depends on but didn't name. */
270
+ const RESCUE_FLOOR = 0.15;
271
+ /** Term presence with plural folding — "packs" finds "pack" and vice versa, so
272
+ * a natural-language plural doesn't read as a miss against identifier tokens. */
273
+ function hasTerm(f, t) {
274
+ return f.has(t) || f.has(`${t}s`) || (t.endsWith("s") && f.has(t.slice(0, -1)));
275
+ }
276
+ /** Idf-weighted share (0..1) of the query a document matches: each query term
277
+ * counts by its rarity, so this separates task prompts from chatter in a way a
278
+ * raw term count can't. A conversational prompt's words are either off-corpus
279
+ * (rare → heavy, unmatched → sinks the ratio) or generic code words ("list",
280
+ * "write": common → near-weightless even when they collide with a symbol name);
281
+ * a task prompt matches exactly its rare, discriminating identifiers. Terms the
282
+ * corpus has never seen take `dfltIdf` (the df=0 weight). */
283
+ /** The match-STRENGTH share behind `coverageStrong`: idf-weighted share of the
284
+ * query matched in the node's NAME field ONLY. The PATH field is deliberately
285
+ * excluded — a coincidental generic directory (`gateway/`) or file basename
286
+ * (`gateway.ts`) in an unrelated repo would otherwise clear the strength gate
287
+ * and float that repo to the top; an on-topic path-organized repo is still
288
+ * rescued by the broad-coverage HIGH_FLOOR clause instead. For the same reason
289
+ * a `kind:"file"` node contributes zero strength: its `name` is a basename (a
290
+ * path component), not a symbol name, so a file whose basename happens to share
291
+ * a query word is not a strong match. */
292
+ export function strongShare(q, node, doc, idf, dfltIdf) {
293
+ if (node.kind === "file")
294
+ return 0;
295
+ return matchedIdfShare(q, [doc.name], idf, dfltIdf);
296
+ }
297
+ function matchedIdfShare(q, fields, idf, dfltIdf) {
298
+ let matched = 0;
299
+ let total = 0;
300
+ for (const t of q.keys()) {
301
+ const w = idf.get(t) ?? dfltIdf;
302
+ total += w;
303
+ if (fields.some((f) => hasTerm(f, t)))
304
+ matched += w;
305
+ }
306
+ return total > 0 ? matched / total : 0;
307
+ }
308
+ /** Normalized query-term IDF mass used by file-level union coverage. Presence
309
+ * comes from the exact term-contribution maps, so plural folding cannot
310
+ * manufacture evidence that the lexical scorer did not award. */
311
+ function normalizedQueryWeights(q, idf, dfltIdf) {
312
+ let total = 0;
313
+ for (const t of q.keys())
314
+ total += idf.get(t) ?? dfltIdf;
315
+ if (total <= 0)
316
+ return new Map();
317
+ return new Map([...q.keys()].map((term) => [term, (idf.get(term) ?? dfltIdf) / total]));
318
+ }
319
+ function lexical(query, corpus, limit, graphRank, inPrefix, fileFirst = true, fileComplement = false, fileTopLock = false, includeRankingMetadata = false) {
320
+ // Binary query terms: a word repeated in a pasted issue body counts once, so a
321
+ // ranty description can't linearly amplify an incidental word.
322
+ const q = new Map([...counts(tokenize(query)).keys()].map((t) => [t, 1]));
323
+ const graph = corpus.graph;
324
+ // Test-file de-ranking is query-aware: a query that ASKS about tests wants test
325
+ // files on top, so it gets no penalty; every other query wants the real
326
+ // definition first. This stops a test that merely contains the query's literals
327
+ // (e.g. `TestDownloadStall` matching "download stall") from outranking the
328
+ // source it exercises — the "tests ranked above the actual code" trap.
329
+ const wantsTests = /\b(tests?|specs?|coverage|assert(?:ion)?s?|fixtures?|mocks?)\b/i.test(query);
330
+ const testFactor = (path) => (!wantsTests && isTestPath(path) ? TEST_RANK_PENALTY : 1);
331
+ // ── Pass 1: tokenize every scored field once, and collect per-document token
332
+ // bags so IDF can down-weight words that occur across the whole corpus. `--in`
333
+ // drops a concept unless at least one of its sources falls under the prefix —
334
+ // filtering happens here, before any scoring, so a narrowed query never sees
335
+ // an unrelated concept from outside the prefix. ──
336
+ const conceptDocs = corpus.concepts
337
+ .filter((c) => !inPrefix || c.sources.some((p) => pathUnderPrefix(p, inPrefix)))
338
+ .map((c) => ({
339
+ c,
340
+ name: counts(tokenize(c.name)),
341
+ body: counts(tokenize(c.text)),
342
+ }));
343
+ // A build-time sidecar (`.cache/ask-index.json`) is usable only when it covers
344
+ // every node in the current graph: `docs.length === graph.nodes.length` is a
345
+ // cheap staleness guard (an id-level check below catches a same-count but
346
+ // mismatched set, e.g. a hand-edited or corrupt sidecar). Anything short of
347
+ // that — missing, unparseable, unknown version, wrong count, mismatched ids —
348
+ // falls back to live tokenization so results never depend on the sidecar
349
+ // existing; see `readAskIndex`'s own null-on-anything-off contract.
350
+ //
351
+ // `--in` does NOT disable the sidecar here: `writeGraph` strips `body_text`
352
+ // from every node it serializes (see `write.ts`) — the sidecar's per-doc
353
+ // `docs[].body` bags are the ONLY place a symbol's body tokens survive on a
354
+ // graph loaded from disk. Bypassing the sidecar under `--in` would silently
355
+ // empty out `body` for every node (falling back to `n.body_text ?? ""`,
356
+ // always `""` post-slim-serialization), losing every body-only match under
357
+ // the filtered prefix. What DOES need bypassing under `--in` is the
358
+ // sidecar's GLOBAL `df`/`docCount`/`avgBodyLen` — those cover the whole
359
+ // corpus, not the filtered subset — so each read of those three fields below
360
+ // is separately gated on `!inPrefix`, while the per-doc bags (used to build
361
+ // `symbolDocs` right after this) are used unconditionally.
362
+ let docById = null;
363
+ if (corpus.askIndex && graph && corpus.askIndex.docs.length === graph.nodes.length) {
364
+ const map = new Map(corpus.askIndex.docs.map((d) => [d.id, d]));
365
+ if (graph.nodes.every((n) => map.has(n.id)))
366
+ docById = map;
367
+ }
368
+ const askIndex = docById ? corpus.askIndex : null;
369
+ // Symbols AND file nodes are scored: a symbol's body_text is its definition;
370
+ // a file's body_text is the module-level residual (imports/constants not in
371
+ // any symbol). Including files closes the recall gap where a gold file's only
372
+ // query-relevant text lives outside every function/class. `--in` filters the
373
+ // node set here, at the very top, before any scoring — every downstream stat
374
+ // (idf, avgdl, candidates, the per-scope partition below) then naturally
375
+ // reflects only the filtered set with no other code needing to know about it.
376
+ const graphNodes = inPrefix ? (graph?.nodes ?? []).filter((n) => pathUnderPrefix(n.path, inPrefix)) : (graph?.nodes ?? []);
377
+ const symbolDocs = graphNodes.map((n) => {
378
+ const d = docById?.get(n.id);
379
+ if (d)
380
+ return { n, name: new Map(d.name), path: new Map(d.path), body: new Map(d.body) };
381
+ return {
382
+ n,
383
+ name: counts(tokenize(n.name)),
384
+ path: counts(tokenize(n.path)),
385
+ // The body (indexed at build) joins the signature + summary as the low-weight
386
+ // body field, so a term that appears only in the code — not the name/signature
387
+ // — still makes the node findable. IDF (from these same bags) keeps a word
388
+ // common across many bodies from dominating. `body_text` is absent on every
389
+ // node loaded from a wiring.json written after the slim-serialization change
390
+ // (it's stripped there — see `write.ts`) as well as on file nodes and
391
+ // pre-body_text graphs; `?? ""` degrades gracefully to signature+summary
392
+ // only, it never crashes on the missing field.
393
+ body: counts(tokenize(`${n.signature ?? ""} ${n.summary ?? ""} ${n.body_text ?? ""}`)),
394
+ };
395
+ });
396
+ const conceptBags = conceptDocs.map((d) => new Set([...d.name.keys(), ...d.body.keys()]));
397
+ // IDF must see the SAME inputs either way: with a sidecar, its `df` (stored
398
+ // WITHOUT concepts) plus these live concept bags reproduces exactly what
399
+ // `computeIdf` below would compute from concept+symbol bags tokenized live.
400
+ // `askIndex.df` is a corpus-GLOBAL count, so `--in` can't use it — the
401
+ // filtered doc set needs its own idf, computed from (already-filtered)
402
+ // `symbolDocs`' own bags, regardless of where those bags came from.
403
+ const idf = askIndex && !inPrefix
404
+ ? computeIdfFromIndex(askIndex, conceptBags)
405
+ : computeIdf([...conceptBags, ...symbolDocs.map((d) => new Set([...d.name.keys(), ...d.path.keys(), ...d.body.keys()]))]);
406
+ // Per-hit idf-weighted coverage, kept out of the public AskHit shape; only
407
+ // the top hit's value survives, as `coverage` on the result. The df=0 weight
408
+ // mirrors idfFromDf's formula at df=0 for whichever corpus size idf was
409
+ // computed from. Same `--in` reasoning as `idf` above: `askIndex.docCount`
410
+ // is global.
411
+ const nDocs = askIndex && !inPrefix
412
+ ? askIndex.docCount + conceptBags.length
413
+ : conceptBags.length + symbolDocs.length;
414
+ const dfltIdf = Math.log(1 + nDocs);
415
+ const matchedOf = new Map();
416
+ // Parallel to matchedOf, but over NAME+PATH only (body dropped) — the
417
+ // match-strength signal exported as `coverageStrong`.
418
+ const matchedStrongOf = new Map();
419
+ // Final listwise selection groups code hits by exact source path. Concepts
420
+ // use singleton pseudo-groups so they remain ordinary ranked candidates
421
+ // without masquerading as every file listed in their sources.
422
+ const selectionGroupOf = new Map();
423
+ // ── Concepts (prose nodes; not in the wiring graph) ──
424
+ const conceptHits = [];
425
+ let maxConcept = 0;
426
+ for (const { c, name, body } of conceptDocs) {
427
+ const total = score(q, name, idf) * 3 + score(q, body, idf);
428
+ if (total > 0) {
429
+ maxConcept = Math.max(maxConcept, total);
430
+ const hit = {
431
+ kind: "concept",
432
+ title: c.name || c.slug,
433
+ pointer: c.sources.join(", ") || c.slug,
434
+ snippet: c.snippet,
435
+ related: c.related,
436
+ score: total,
437
+ };
438
+ matchedOf.set(hit, matchedIdfShare(q, [name, body], idf, dfltIdf));
439
+ matchedStrongOf.set(hit, matchedIdfShare(q, [name], idf, dfltIdf)); // concepts have no path field
440
+ // A concept is one singleton partition even if two source entries reuse
441
+ // the same slug; include its stable encounter index to prevent accidental
442
+ // grouping by frontmatter alone.
443
+ selectionGroupOf.set(hit, `concept:${c.slug}:${conceptHits.length}`);
444
+ conceptHits.push(hit);
445
+ }
446
+ }
447
+ // ── Symbols (wiring graph): lexical score per node, keyed by id ──
448
+ const byId = new Map((graph?.nodes ?? []).map((n) => [n.id, n]));
449
+ const bodyLen = (m) => {
450
+ let s = 0;
451
+ for (const v of m.values())
452
+ s += v;
453
+ return s;
454
+ };
455
+ const docsById = new Map(symbolDocs.map((d) => [d.n.id, d]));
456
+ const symbolHits = [];
457
+ const baselineSymbolHits = [];
458
+ const baselineHitById = new Map();
459
+ const fileQueueHitsByGroup = new Map();
460
+ const baselineQueueHitsByGroup = new Map();
461
+ const fileGroups = [];
462
+ const needsFileQueues = fileComplement && (fileTopLock || includeRankingMetadata);
463
+ const makeSymbolHit = (id, hitScore, scope) => {
464
+ const n = byId.get(id);
465
+ if (!n)
466
+ return null;
467
+ const hit = {
468
+ kind: "symbol",
469
+ title: `${n.name} · ${n.kind}`,
470
+ pointer: n.kind === "file" ? n.path : `${n.path}:${n.span}`,
471
+ snippet: n.summary?.split("\n")[0].trim() ?? n.signature ?? "",
472
+ score: hitScore,
473
+ ...(scope === undefined ? {} : { scope }),
474
+ };
475
+ const d = docsById.get(id);
476
+ matchedOf.set(hit, d ? matchedIdfShare(q, [d.name, d.path, d.body], idf, dfltIdf) : 0);
477
+ matchedStrongOf.set(hit, d ? strongShare(q, n, d, idf, dfltIdf) : 0);
478
+ selectionGroupOf.set(hit, `file:${n.path}`);
479
+ return hit;
480
+ };
481
+ const symbolTitle = (id) => {
482
+ const n = byId.get(id);
483
+ return n ? `${n.name} · ${n.kind}` : id;
484
+ };
485
+ // The single-vs-multi-scope branch keys on `scopesOfGraph` ONLY: one scope
486
+ // (or no graph) keeps the original local scoring path.
487
+ const scopes = graph ? scopesOfGraph(graph) : null;
488
+ let scopeMeta;
489
+ // The BM25 length prior, corpus-global like `idf`/`dfltIdf` above. Hoisted out
490
+ // of the single-scope branch so BOTH paths score against the same statistics
491
+ // — that shared basis is half of what makes multi-scope scores comparable
492
+ // (see fuse.ts's module header). Under `--in`, the sidecar's `avgBodyLen`
493
+ // covers the whole corpus and must not be reused for the filtered set.
494
+ const avgBodyLen = askIndex && !inPrefix
495
+ ? askIndex.avgBodyLen
496
+ : symbolDocs.length
497
+ ? symbolDocs.reduce((a, d) => a + bodyLen(d.body), 0) / symbolDocs.length
498
+ : 0;
499
+ // Populated only for bounded file ranking. The baseline path pays no allocation
500
+ // or matched-term tracking cost, and their scalar lexical path remains exact.
501
+ const rawLexicalById = new Map();
502
+ const matchedTermsById = new Map();
503
+ const matchedStrongTermsById = new Map();
504
+ const fileQueryWeights = fileComplement
505
+ ? normalizedQueryWeights(q, idf, dfltIdf)
506
+ : new Map();
507
+ const spanStart = (span) => {
508
+ const match = span.match(/^L(\d+)-L\d+$/);
509
+ return match ? Number(match[1]) : Number.POSITIVE_INFINITY;
510
+ };
511
+ if (scopes && scopes.length > 1) {
512
+ // ── Multi-scope repo: partition by sub-project and walk each subgraph
513
+ // separately — so the big scope can't drown the small one — but score every
514
+ // scope against the repo-wide statistics, so the results stay comparable and
515
+ // can be ordered by score. Same scoring functions and blend as the
516
+ // single-scope path; the combination itself lives in fuse.ts. ──
517
+ const byScope = new Map();
518
+ const scopeById = new Map();
519
+ for (const d of symbolDocs) {
520
+ const s = scopeOf(d.n.path, scopes).prefix;
521
+ scopeById.set(d.n.id, s);
522
+ const list = byScope.get(s);
523
+ if (list)
524
+ list.push(d);
525
+ else
526
+ byScope.set(s, [d]);
527
+ }
528
+ // Lazily build every scope's PageRank topology in one node/edge pass. The
529
+ // old nodeFilter path rebuilt the full repo adjacency once per matching
530
+ // scope; on large multi-project repos that turned one query into hundreds
531
+ // of full graph scans before the participation gate could run. Waiting for
532
+ // the first walk keeps no-match and graphRank:false queries edge-scan free.
533
+ let pageRankByScope;
534
+ let collapsedComponents = [];
535
+ let collapsedComponentById;
536
+ let collapsedFileByRepresentative;
537
+ const fusion = rankScopesAndFuse([...byScope.keys()].sort(), {
538
+ lex: (s) => {
539
+ const docs = byScope.get(s);
540
+ // Repo-wide IDF and length prior — the SAME `idf`/`avgBodyLen` the
541
+ // single-scope path uses. Scoring each scope against its own corpus
542
+ // (as this did before #117) made a term worth a different amount in
543
+ // every scope, so the resulting scores could not be compared and the
544
+ // combined order had to fall back on rank. Only the PARTITION is
545
+ // per-scope now; the statistics are global.
546
+ const out = new Map();
547
+ for (const { n, name, path, body } of docs) {
548
+ const factor = testFactor(n.path);
549
+ const total = (score(q, name, idf) * 3 +
550
+ score(q, path, idf) * 2 +
551
+ bm25(q, body, idf, bodyLen(body), avgBodyLen)) *
552
+ factor;
553
+ if (total > 0) {
554
+ out.set(n.id, total);
555
+ if (fileComplement) {
556
+ rawLexicalById.set(n.id, total);
557
+ matchedTermsById.set(n.id, matchedLexicalTerms(q, name, path, body));
558
+ if (n.kind !== "file")
559
+ matchedStrongTermsById.set(n.id, matchedStrongTerms(q, name));
560
+ }
561
+ }
562
+ }
563
+ return out;
564
+ },
565
+ // Body-only suppression: does any doc in this scope carry a query term
566
+ // in an identifier (name) or its path, rather than only in prose?
567
+ hasIdentifierMatch: (s) => (byScope.get(s) ?? []).some(({ name, path }) => {
568
+ for (const t of q.keys())
569
+ if (hasTerm(name, t) || hasTerm(path, t))
570
+ return true;
571
+ return false;
572
+ }),
573
+ walk: (s, seeds) => {
574
+ if (!graphRank)
575
+ return new Map();
576
+ pageRankByScope ??= preparePageRankPartitions(graph, (id) => scopeById.get(id));
577
+ const topology = pageRankByScope?.get(s);
578
+ return topology
579
+ ? personalizedPageRankPrepared(topology, seeds)
580
+ : new Map();
581
+ },
582
+ rankFactor: (_s, id) => testFactor(byId.get(id)?.path ?? ""),
583
+ collapseCandidates: fileComplement
584
+ ? (candidates) => {
585
+ collapsedComponents = [...candidates];
586
+ collapsedComponentById = new Map(candidates.map((candidate) => [candidate.id, candidate]));
587
+ const fileCandidates = candidates.map((candidate) => {
588
+ const n = byId.get(candidate.id);
589
+ const rawLexical = rawLexicalById.get(candidate.id) ?? 0;
590
+ return {
591
+ id: candidate.id,
592
+ file: n?.path ?? "",
593
+ kind: n?.kind === "file" ? "file" : "symbol",
594
+ rawLexical,
595
+ lexical: candidate.lexical,
596
+ graph: candidate.graph,
597
+ rankFactor: candidate.rankFactor,
598
+ baselineScore: candidate.score,
599
+ baselineTieKey: symbolTitle(candidate.id),
600
+ matchedTerms: matchedTermsById.get(candidate.id) ?? new Set(),
601
+ matchedStrongTerms: matchedStrongTermsById.get(candidate.id) ?? new Set(),
602
+ eligible: Boolean(n && n.kind !== "file" && rawLexical > 0),
603
+ spanStart: n ? spanStart(n.span) : undefined,
604
+ };
605
+ });
606
+ const rankedFiles = rankFilesBounded(fileCandidates, fileQueryWeights);
607
+ collapsedFileByRepresentative = new Map(rankedFiles.map((file) => [file.representative.id, file]));
608
+ return rankedFiles.map((file) => {
609
+ const component = collapsedComponentById.get(file.representative.id);
610
+ return {
611
+ id: file.representative.id,
612
+ scope: component.scope,
613
+ score: file.score,
614
+ };
615
+ });
616
+ }
617
+ : undefined,
618
+ }, GRAPH_WEIGHT, RESCUE_FLOOR);
619
+ if (needsFileQueues) {
620
+ const baselineFusion = combineComparableScopes(collapsedComponents.map(({ id, scope, score }) => ({ id, scope, score })));
621
+ const baselineScoreById = new Map(baselineFusion.ranked.map((ranked) => [ranked.id, ranked.score]));
622
+ const baselineDisplayOrder = (a, b) => b.score - a.score || symbolTitle(a.id).localeCompare(symbolTitle(b.id));
623
+ let baselineTopRanked = baselineFusion.ranked[0];
624
+ for (const ranked of baselineFusion.ranked.slice(1))
625
+ if (baselineTopRanked && baselineDisplayOrder(ranked, baselineTopRanked) < 0)
626
+ baselineTopRanked = ranked;
627
+ const baselineHitsToBuild = includeRankingMetadata
628
+ ? [...baselineFusion.ranked].sort(baselineDisplayOrder)
629
+ : baselineTopRanked
630
+ ? [baselineTopRanked]
631
+ : [];
632
+ for (const ranked of baselineHitsToBuild) {
633
+ const hit = makeSymbolHit(ranked.id, ranked.score, ranked.scope);
634
+ if (hit) {
635
+ baselineSymbolHits.push(hit);
636
+ baselineHitById.set(ranked.id, hit);
637
+ }
638
+ }
639
+ for (const ranked of fusion.ranked) {
640
+ const file = collapsedFileByRepresentative?.get(ranked.id);
641
+ if (!file)
642
+ continue;
643
+ const materializeFileQueue = () => file.queue.flatMap((member, index) => {
644
+ const component = collapsedComponentById?.get(member.id);
645
+ if (index > 0) {
646
+ const baselineHit = baselineHitById.get(member.id);
647
+ if (baselineHit)
648
+ return [baselineHit];
649
+ }
650
+ const hit = makeSymbolHit(member.id, index === 0
651
+ ? ranked.score
652
+ : baselineScoreById.get(member.id) ?? member.baselineScore, component?.scope ?? ranked.scope);
653
+ return hit ? [hit] : [];
654
+ });
655
+ const materializeBaselineQueue = () => file.queue.flatMap((member) => {
656
+ const hit = makeSymbolHit(member.id, baselineScoreById.get(member.id) ?? member.baselineScore, collapsedComponentById?.get(member.id)?.scope ?? ranked.scope);
657
+ return hit ? [hit] : [];
658
+ });
659
+ const hits = includeRankingMetadata
660
+ ? materializeFileQueue()
661
+ : (() => {
662
+ const leader = file.queue[0];
663
+ if (!leader)
664
+ return [];
665
+ const hit = makeSymbolHit(leader.id, ranked.score, collapsedComponentById?.get(leader.id)?.scope ?? ranked.scope);
666
+ return hit ? [hit] : [];
667
+ })();
668
+ if (hits.length === 0)
669
+ continue;
670
+ const group = {
671
+ key: `file:${file.file}`,
672
+ hits,
673
+ coverage: file.unionCoverage,
674
+ coverageStrong: file.unionStrongCoverage,
675
+ };
676
+ fileQueueHitsByGroup.set(group.key, materializeFileQueue);
677
+ baselineQueueHitsByGroup.set(group.key, materializeBaselineQueue);
678
+ fileGroups.push(group);
679
+ symbolHits.push(hits[0]);
680
+ }
681
+ }
682
+ else {
683
+ for (const ranked of fusion.ranked) {
684
+ const hit = makeSymbolHit(ranked.id, ranked.score, ranked.scope);
685
+ if (hit)
686
+ symbolHits.push(hit);
687
+ }
688
+ }
689
+ // Label + footer only when federation actually happened (or a scope was
690
+ // gated out and is worth mentioning) — a query matching one scope of a
691
+ // multi-scope repo reads exactly like today.
692
+ if (fusion.federated.length > 1 || fusion.alsoMatched.length > 0)
693
+ scopeMeta = { federated: fusion.federated, alsoMatched: fusion.alsoMatched };
694
+ }
695
+ else {
696
+ // Single-scope: the pre-scopes ranking path, byte-identical output when
697
+ // `--in` is absent (Task 3's regression guarantee: `askIndex && !inPrefix`
698
+ // reduces to plain `askIndex` when `inPrefix` is undefined). `avgBodyLen` is
699
+ // now defined once above and shared with the multi-scope branch.
700
+ const lex = new Map(); // node id → lexical score (>0 only)
701
+ let maxLex = 0;
702
+ for (const { n, name, path, body } of symbolDocs) {
703
+ // Name and path are short identifiers → plain idf-weighted overlap; the body
704
+ // is length-normalized via BM25 so long definitions don't win on bulk.
705
+ const factor = testFactor(n.path);
706
+ const total = (score(q, name, idf) * 3 +
707
+ score(q, path, idf) * 2 +
708
+ bm25(q, body, idf, bodyLen(body), avgBodyLen)) *
709
+ factor;
710
+ if (total > 0) {
711
+ lex.set(n.id, total);
712
+ maxLex = Math.max(maxLex, total);
713
+ if (fileComplement) {
714
+ rawLexicalById.set(n.id, total);
715
+ matchedTermsById.set(n.id, matchedLexicalTerms(q, name, path, body));
716
+ if (n.kind !== "file")
717
+ matchedStrongTermsById.set(n.id, matchedStrongTerms(q, name));
718
+ }
719
+ }
720
+ }
721
+ // ── Graph-rank: let connectivity to the matched set reorder and rescue ──
722
+ // `--in` restricts the walk itself, not just the seeds: without a nodeFilter
723
+ // here, a RESCUE_FLOOR-qualifying neighbour OUTSIDE the prefix could still
724
+ // surface, defeating the "filters before scoring" contract.
725
+ const pr = graphRank && graph && lex.size > 0
726
+ ? personalizedPageRank(graph, lex, inPrefix ? { nodeFilter: (id) => pathUnderPrefix(byId.get(id)?.path ?? "", inPrefix) } : {})
727
+ : new Map();
728
+ // Candidate symbols = everything the query word-matched, plus nodes the walk
729
+ // found strongly central even without a word match (RESCUE_FLOOR).
730
+ const candidates = new Set(lex.keys());
731
+ for (const [id, p] of pr)
732
+ if (p >= RESCUE_FLOOR)
733
+ candidates.add(id);
734
+ const singleCandidates = [];
735
+ for (const id of candidates) {
736
+ const n = byId.get(id);
737
+ if (!n)
738
+ continue;
739
+ const lexical = maxLex > 0 ? (lex.get(id) ?? 0) / maxLex : 0;
740
+ const graphScore = pr.get(id) ?? 0;
741
+ const rankFactor = testFactor(n.path);
742
+ // Apply the test penalty after normalization too. Applying it only to the
743
+ // raw lexical score is not enough: if a test is still the strongest raw
744
+ // match, dividing by maxLex restores it to 1.0 and erases the de-rank.
745
+ const baseline = (lexical + GRAPH_WEIGHT * graphScore) * rankFactor;
746
+ if (baseline <= 0)
747
+ continue;
748
+ singleCandidates.push({ id, n, lexical, graph: graphScore, rankFactor, baseline });
749
+ }
750
+ const candidateById = fileComplement
751
+ ? new Map(singleCandidates.map((candidate) => [candidate.id, candidate]))
752
+ : undefined;
753
+ const rankedFiles = fileComplement
754
+ ? rankFilesBounded(singleCandidates.map((candidate) => {
755
+ const rawLexical = rawLexicalById.get(candidate.id) ?? 0;
756
+ return {
757
+ id: candidate.id,
758
+ file: candidate.n.path,
759
+ kind: candidate.n.kind === "file" ? "file" : "symbol",
760
+ rawLexical,
761
+ lexical: candidate.lexical,
762
+ graph: candidate.graph,
763
+ rankFactor: candidate.rankFactor,
764
+ baselineScore: candidate.baseline,
765
+ baselineTieKey: symbolTitle(candidate.id),
766
+ matchedTerms: matchedTermsById.get(candidate.id) ?? new Set(),
767
+ matchedStrongTerms: matchedStrongTermsById.get(candidate.id) ?? new Set(),
768
+ eligible: candidate.n.kind !== "file" && rawLexical > 0,
769
+ spanStart: spanStart(candidate.n.span),
770
+ };
771
+ }), fileQueryWeights)
772
+ : undefined;
773
+ if (needsFileQueues && rankedFiles) {
774
+ const baselineCandidateOrder = (a, b) => b.baseline - a.baseline ||
775
+ `${a.n.name} · ${a.n.kind}`.localeCompare(`${b.n.name} · ${b.n.kind}`);
776
+ let baselineTopCandidate = singleCandidates[0];
777
+ for (const candidate of singleCandidates.slice(1))
778
+ if (baselineTopCandidate && baselineCandidateOrder(candidate, baselineTopCandidate) < 0)
779
+ baselineTopCandidate = candidate;
780
+ const baselineCandidatesToBuild = includeRankingMetadata
781
+ ? [...singleCandidates].sort(baselineCandidateOrder)
782
+ : baselineTopCandidate
783
+ ? [baselineTopCandidate]
784
+ : [];
785
+ for (const candidate of baselineCandidatesToBuild) {
786
+ const hit = makeSymbolHit(candidate.id, candidate.baseline);
787
+ if (hit) {
788
+ baselineSymbolHits.push(hit);
789
+ baselineHitById.set(candidate.id, hit);
790
+ }
791
+ }
792
+ for (const file of rankedFiles) {
793
+ const materializeFileQueue = () => file.queue.flatMap((member, index) => {
794
+ if (index > 0) {
795
+ const baselineHit = baselineHitById.get(member.id);
796
+ if (baselineHit)
797
+ return [baselineHit];
798
+ }
799
+ const hit = makeSymbolHit(member.id, index === 0 ? file.score : member.baselineScore);
800
+ return hit ? [hit] : [];
801
+ });
802
+ const materializeBaselineQueue = () => file.queue.flatMap((member) => {
803
+ const hit = makeSymbolHit(member.id, member.baselineScore);
804
+ return hit ? [hit] : [];
805
+ });
806
+ const hits = includeRankingMetadata
807
+ ? materializeFileQueue()
808
+ : (() => {
809
+ const leader = file.queue[0];
810
+ if (!leader)
811
+ return [];
812
+ const hit = makeSymbolHit(leader.id, file.score);
813
+ return hit ? [hit] : [];
814
+ })();
815
+ if (hits.length === 0)
816
+ continue;
817
+ const group = {
818
+ key: `file:${file.file}`,
819
+ hits,
820
+ coverage: file.unionCoverage,
821
+ coverageStrong: file.unionStrongCoverage,
822
+ };
823
+ fileQueueHitsByGroup.set(group.key, materializeFileQueue);
824
+ baselineQueueHitsByGroup.set(group.key, materializeBaselineQueue);
825
+ fileGroups.push(group);
826
+ symbolHits.push(hits[0]);
827
+ }
828
+ }
829
+ else if (rankedFiles) {
830
+ for (const file of rankedFiles) {
831
+ const candidate = candidateById?.get(file.representative.id);
832
+ const hit = candidate ? makeSymbolHit(candidate.id, file.score) : null;
833
+ if (hit)
834
+ symbolHits.push(hit);
835
+ }
836
+ }
837
+ else {
838
+ for (const candidate of singleCandidates) {
839
+ const hit = makeSymbolHit(candidate.id, candidate.baseline);
840
+ if (hit)
841
+ symbolHits.push(hit);
842
+ }
843
+ }
844
+ }
845
+ // Concepts and symbols live on comparable 0..~1.5 scales so they merge fairly:
846
+ // concept scores are normalized to their own max; symbol scores use the
847
+ // lexical-normalized + graph-weighted blend.
848
+ for (const h of conceptHits)
849
+ h.score = maxConcept > 0 ? h.score / maxConcept : 0;
850
+ const scored = [...conceptHits, ...symbolHits];
851
+ scored.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
852
+ const baselineScored = needsFileQueues
853
+ ? [...conceptHits, ...baselineSymbolHits].sort((a, b) => b.score - a.score || a.title.localeCompare(b.title))
854
+ : scored;
855
+ const conceptGroups = conceptHits.map((hit, index) => ({
856
+ key: selectionGroupOf.get(hit) ?? `concept:${index}`,
857
+ hits: [hit],
858
+ coverage: matchedOf.get(hit) ?? 0,
859
+ coverageStrong: matchedStrongOf.get(hit) ?? 0,
860
+ }));
861
+ const unlockedGroups = [...conceptGroups, ...fileGroups].sort((a, b) => b.hits[0].score - a.hits[0].score ||
862
+ a.hits[0].title.localeCompare(b.hits[0].title));
863
+ const sameHit = (a, b) => a.kind === b.kind && a.pointer === b.pointer && a.title === b.title;
864
+ let projectedGroups = unlockedGroups;
865
+ let lockedGroupKey;
866
+ if (fileTopLock && fileFirst && baselineScored[0]) {
867
+ const baselineTop = baselineScored[0];
868
+ const key = selectionGroupOf.get(baselineTop) ?? "locked:top";
869
+ lockedGroupKey = key;
870
+ const existing = unlockedGroups.find((group) => group.key === key);
871
+ const baselineQueue = includeRankingMetadata || limit > unlockedGroups.length
872
+ ? baselineQueueHitsByGroup.get(key)?.() ?? baselineScored.filter((hit) => (selectionGroupOf.get(hit) ?? "") === key)
873
+ : [];
874
+ const locked = existing
875
+ ? {
876
+ ...existing,
877
+ hits: [
878
+ baselineTop,
879
+ ...baselineQueue.filter((hit) => !sameHit(hit, baselineTop)),
880
+ ],
881
+ }
882
+ : {
883
+ key,
884
+ hits: baselineQueue.length ? baselineQueue : [baselineTop],
885
+ coverage: matchedOf.get(baselineTop) ?? 0,
886
+ coverageStrong: matchedStrongOf.get(baselineTop) ?? 0,
887
+ };
888
+ projectedGroups = [
889
+ locked,
890
+ ...unlockedGroups.filter((group) => group.key !== key),
891
+ ];
892
+ }
893
+ // Ranking always sees the complete candidate universe, but a normal bounded
894
+ // request usually needs only one leader per file. Materialize secondary span
895
+ // queues only when the requested output can actually reach a second round.
896
+ if (fileTopLock &&
897
+ fileFirst &&
898
+ !includeRankingMetadata &&
899
+ limit > projectedGroups.length) {
900
+ projectedGroups = projectedGroups.map((group) => {
901
+ if (group.key === lockedGroupKey)
902
+ return group;
903
+ const materialize = fileQueueHitsByGroup.get(group.key);
904
+ return materialize ? { ...group, hits: materialize() } : group;
905
+ });
906
+ }
907
+ // File-aware ranking feeds latent groups to the existing file-first frontier.
908
+ // Leaders are listed first so every file/concept emits once before any
909
+ // secondary span; each group's remaining queue retains baseline order.
910
+ const selected = fileTopLock && fileFirst
911
+ ? roundRobinQueues(projectedGroups.map((group) => group.hits), limit)
912
+ : fileFirst
913
+ ? fileFirstRoundRobin(scored.map((hit, index) => ({
914
+ group: selectionGroupOf.get(hit) ?? `ungrouped:${index}`,
915
+ value: hit,
916
+ })), limit)
917
+ : scored;
918
+ const top = selected[0] ?? scored[0];
919
+ if (fileTopLock && top?.scope && scopeMeta) {
920
+ scopeMeta = {
921
+ federated: [...new Set([top.scope, ...scopeMeta.federated])],
922
+ alsoMatched: scopeMeta.alsoMatched.filter((match) => match.scope !== top.scope),
923
+ };
924
+ }
925
+ const ranking = includeRankingMetadata && needsFileQueues
926
+ ? {
927
+ groups: unlockedGroups.slice(0, limit).map((group) => ({
928
+ ...group,
929
+ hits: group.hits.slice(0, limit),
930
+ baselineHits: baselineScored
931
+ .filter((hit) => selectionGroupOf.get(hit) === group.key)
932
+ .slice(0, limit),
933
+ })),
934
+ baseline: baselineScored.slice(0, limit).map((hit, index) => ({
935
+ group: selectionGroupOf.get(hit) ?? `ungrouped:${index}`,
936
+ hit,
937
+ })),
938
+ baselineCoverage: baselineScored[0]
939
+ ? matchedOf.get(baselineScored[0]) ?? 0
940
+ : undefined,
941
+ baselineCoverageStrong: baselineScored[0]
942
+ ? matchedStrongOf.get(baselineScored[0]) ?? 0
943
+ : undefined,
944
+ }
945
+ : undefined;
946
+ return {
947
+ query,
948
+ mode: scored.length ? "lexical" : "empty",
949
+ hits: selected.slice(0, limit),
950
+ scopes: scopeMeta,
951
+ coverage: top && q.size > 0 ? matchedOf.get(top) ?? 0 : undefined,
952
+ coverageStrong: top && q.size > 0 ? matchedStrongOf.get(top) ?? 0 : undefined,
953
+ ...(ranking ? { ranking } : {}),
954
+ // Zero hits on a genuinely multi-scope graph names the scopes that exist,
955
+ // so a query that missed everywhere still tells the caller where to look.
956
+ note: scored.length
957
+ ? undefined
958
+ : `no matching nodes — try different words, or \`${cmd("julius build")}\` if the code map is empty${scopesHereClause(scopes ?? [])}`,
959
+ };
960
+ }
961
+ /** Parse a `path:Lx-Ly` pointer into its parts, or null if it isn't one
962
+ * (concept multi-path lists and raw import strings return null). */
963
+ function parseSpan(pointer) {
964
+ const m = pointer.match(/^(.*):L(\d+)-L(\d+)$/);
965
+ if (!m)
966
+ return null;
967
+ return { path: m[1], from: Number(m[2]), to: Number(m[3]) };
968
+ }
969
+ /** Read the source lines [from, to] (1-indexed, inclusive) of `path` under `root`,
970
+ * capped at {@link MAX_SPAN_LINES}. Returns null if the file can't be read. */
971
+ function sliceSpan(root, path, from, to) {
972
+ try {
973
+ const source = readSourceFile(join(root, path));
974
+ if (source === null)
975
+ return null; // unsupported encoding (e.g. UTF-16BE)
976
+ const lines = source.split("\n");
977
+ const start = Math.max(1, from);
978
+ const end = Math.min(lines.length, to);
979
+ const slice = lines.slice(start - 1, end);
980
+ if (slice.length > MAX_SPAN_LINES) {
981
+ const head = slice.slice(0, MAX_SPAN_LINES);
982
+ head.push(`… (+${slice.length - MAX_SPAN_LINES} more lines; open ${path}:L${start}-L${end})`);
983
+ return head.join("\n");
984
+ }
985
+ return slice.join("\n");
986
+ }
987
+ catch {
988
+ return null;
989
+ }
990
+ }
991
+ /** Attach inlined source to every hit whose pointer is a real `path:span`.
992
+ * Crux-first: when the graph carries an LLM-chosen crux for the hit's node and
993
+ * `full` is off, inline that ≤8-line excerpt (with an escalation marker) rather
994
+ * than the whole definition — most hits only need the decision point, and the
995
+ * marker tells the agent exactly how to get the rest when this one doesn't. */
996
+ function inlineSource(root, hits, graph, full) {
997
+ const cruxByPointer = new Map();
998
+ if (!full && graph) {
999
+ for (const n of graph.nodes)
1000
+ if (n.crux?.code)
1001
+ cruxByPointer.set(`${n.path}:${n.span}`, n.crux.code);
1002
+ }
1003
+ for (const h of hits) {
1004
+ const s = parseSpan(h.pointer);
1005
+ if (!s)
1006
+ continue;
1007
+ const crux = cruxByPointer.get(h.pointer);
1008
+ if (crux) {
1009
+ h.code = `${crux}\n… (crux — full definition at ${h.pointer}; rerun with --full)`;
1010
+ continue;
1011
+ }
1012
+ const code = sliceSpan(root, s.path, s.from, s.to);
1013
+ if (code)
1014
+ h.code = code;
1015
+ }
1016
+ }
1017
+ /** Every repo-relative file path a set of hits points into (dedup). A symbol
1018
+ * pointer is `path:span`; a concept pointer is a comma-joined path list. */
1019
+ function hitFiles(hits) {
1020
+ const files = new Set();
1021
+ for (const h of hits) {
1022
+ const span = parseSpan(h.pointer);
1023
+ if (span) {
1024
+ files.add(span.path);
1025
+ continue;
1026
+ }
1027
+ for (const p of h.pointer.split(",").map((s) => s.trim()))
1028
+ if (p && !p.includes(" "))
1029
+ files.add(p);
1030
+ }
1031
+ return files;
1032
+ }
1033
+ /** Baseline = whole size of the files these hits cover, read from the sizes the
1034
+ * build stored on each file node. Zero when the graph predates the `chars` field
1035
+ * (a pre-upgrade index) — the caller then just omits the estimate. */
1036
+ function baselineFor(hits, graph) {
1037
+ if (!graph)
1038
+ return undefined;
1039
+ return savingsFor(graph, hitFiles(hits));
1040
+ }
1041
+ /** Answer a query from the julius/ graph at `dir`. Deterministic, $0. */
1042
+ export function ask(dir, query, opts = {}) {
1043
+ const root = resolve(dir);
1044
+ const outDir = contextDirFor(root, opts.contextDir);
1045
+ const limit = opts.limit ?? 8;
1046
+ const corpus = loadCorpus(outDir);
1047
+ const graphRank = opts.graphRank ?? true;
1048
+ const fileFirst = opts.fileFirst ?? true;
1049
+ // The production path uses bounded file scoring plus an exact baseline top lock.
1050
+ // Internal/raw callers can still request the baseline by disabling
1051
+ // file-first selection. A top lock is projected only on a file-first list.
1052
+ const fileTopLock = opts.fileTopLock ?? fileFirst;
1053
+ const fileComplement = (opts.fileComplement ?? false) || fileTopLock;
1054
+ // Normalized ONCE, up front, and this value used everywhere below
1055
+ // (validation, filtering, structural). `ask --in frontend/` must work exactly
1056
+ // like `--in frontend` — `scopeLabel`/the footer's own `--in <scope>/`
1057
+ // suggestion always includes the slash, so rejecting it would make the tool's
1058
+ // own suggested next command fail — and `--in frontend\sub` must work too,
1059
+ // because that is what a Windows shell's tab-completion produces.
1060
+ const inPrefix = opts.in ? normalizePathPrefix(opts.in) : undefined;
1061
+ // `--in` validated up front, before any mode runs.
1062
+ if (inPrefix && corpus.graph)
1063
+ assertPrefixIndexed(corpus.graph, inPrefix);
1064
+ let result;
1065
+ if (corpus.graph) {
1066
+ const outcome = structural(query, corpus.graph, limit, inPrefix);
1067
+ if (outcome && "result" in outcome) {
1068
+ result = outcome.result;
1069
+ }
1070
+ else {
1071
+ result = lexical(query, corpus, limit, graphRank, inPrefix, fileFirst, fileComplement, fileTopLock, opts.includeRankingMetadata ?? false);
1072
+ // A structural-intent query that couldn't be answered structurally still
1073
+ // gets a prominent note on the lexical fallback result — never silent.
1074
+ if (outcome && "fallthroughNote" in outcome) {
1075
+ result.note = result.note ? `${outcome.fallthroughNote}\n${result.note}` : outcome.fallthroughNote;
1076
+ }
1077
+ }
1078
+ }
1079
+ else {
1080
+ result = lexical(query, corpus, limit, graphRank, inPrefix, fileFirst, fileComplement, fileTopLock, opts.includeRankingMetadata ?? false);
1081
+ }
1082
+ if (opts.source) {
1083
+ inlineSource(root, result.hits, corpus.graph, opts.full ?? false);
1084
+ if (result.ranking) {
1085
+ const internalHits = [
1086
+ ...result.ranking.groups.flatMap((group) => group.hits),
1087
+ ...result.ranking.groups.flatMap((group) => group.baselineHits ?? []),
1088
+ ...result.ranking.baseline.map((entry) => entry.hit),
1089
+ ];
1090
+ inlineSource(root, [...new Set(internalHits)], corpus.graph, opts.full ?? false);
1091
+ }
1092
+ // The pack is truly substitutive only in retriever mode (spans inlined), so
1093
+ // the "vs reading whole files" estimate is only honest here.
1094
+ result.saved = baselineFor(result.hits, corpus.graph);
1095
+ }
1096
+ return result;
1097
+ }
1098
+ /** Signatures-only view of one file, straight from the wiring graph — the
1099
+ * cheapest way to understand a file's API surface (~10× less than reading it).
1100
+ * `file` is matched as an exact repo-relative path, then as a basename. */
1101
+ export function skeleton(dir, file, opts = {}) {
1102
+ const outDir = contextDirFor(resolve(dir), opts.contextDir);
1103
+ const graph = loadGraphCached(outDir);
1104
+ if (!graph)
1105
+ return { file, entries: [], note: `no wiring graph — run \`${cmd("julius build")}\` first` };
1106
+ let defs = graph.nodes.filter((n) => n.kind !== "file" && n.path === file);
1107
+ if (!defs.length) {
1108
+ const matches = new Set(graph.nodes.filter((n) => n.path === file || n.path.endsWith(`/${file}`)).map((n) => n.path));
1109
+ if (matches.size > 1)
1110
+ return { file, entries: [], note: `ambiguous — matches: ${[...matches].sort().join(", ")}` };
1111
+ const [path] = matches;
1112
+ if (path)
1113
+ defs = graph.nodes.filter((n) => n.kind !== "file" && n.path === path);
1114
+ }
1115
+ if (!defs.length)
1116
+ return { file, entries: [], note: "no definitions indexed for this file" };
1117
+ const startLine = (span) => Number(span.match(/^L(\d+)/)?.[1] ?? 0);
1118
+ defs.sort((a, b) => startLine(a.span) - startLine(b.span));
1119
+ return {
1120
+ file: defs[0].path,
1121
+ entries: defs.map((n) => ({
1122
+ name: n.name,
1123
+ kind: n.kind,
1124
+ span: n.span,
1125
+ signature: n.signature,
1126
+ summary: n.summary?.split("\n")[0].trim() || undefined,
1127
+ })),
1128
+ saved: savingsFor(graph, [defs[0].path]),
1129
+ };
1130
+ }
1131
+ /** Render a {@link SkeletonResult} as compact markdown. */
1132
+ export function formatSkeleton(r) {
1133
+ const head = `${cmd("julius skeleton")} — ${r.file}`;
1134
+ if (!r.entries.length)
1135
+ return `${head}\n\n${r.note ?? "no definitions."}\n`;
1136
+ const lines = r.entries.map((e) => {
1137
+ const sig = e.signature ? ` ${e.signature}` : "";
1138
+ const sum = e.summary ? ` — ${e.summary}` : "";
1139
+ return `- ${e.span} ${e.kind} ${e.name}${sig}${sum}`;
1140
+ });
1141
+ const body = `${head}\n${lines.join("\n")}`;
1142
+ return withSavings(body, r.saved) + "\n";
1143
+ }
1144
+ /** Rough tokens for a byte length (≈ 4 chars/token; good enough for an estimate). */
1145
+ function toTokens(chars) {
1146
+ return Math.round(chars / 4);
1147
+ }
1148
+ /** Render an {@link AskResult} as a compact markdown context pack. */
1149
+ export function formatAsk(r) {
1150
+ const head = `${cmd("julius ask")} — "${r.query}" (${r.mode})`;
1151
+ // The note prints as its own prominent line(s) right under the header —
1152
+ // above every hit — so a loud structural-fallthrough note (or the
1153
+ // no-structural-edges / no-lexical-match note) can never be missed by only
1154
+ // being embedded inline in the header parenthetical. Only a genuine
1155
+ // fallthrough/warning line (from `fallthroughNoteFor`, always prefixed
1156
+ // "structural index:") gets the ⚠ marker; the benign structural header note
1157
+ // ("callers / references of X" / "outgoing edges from X") prints plain —
1158
+ // it's informational, not a warning.
1159
+ const noteBlock = r.note
1160
+ ? r.note
1161
+ .split("\n")
1162
+ .map((l) => (l.startsWith("structural index:") ? `⚠ ${l}` : l))
1163
+ .join("\n")
1164
+ : "";
1165
+ // Notes go first: a decision a past session already made, or an approach it
1166
+ // already ruled out, changes how the code below should be read.
1167
+ const teamNotes = r.notes?.length
1168
+ ? formatNoteHits(r.notes)
1169
+ : r.notesChecked
1170
+ ? ["· no learnings about this yet", ""]
1171
+ : [];
1172
+ const learned = r.notes?.length ? learningSavingsLine(r.notes) : null;
1173
+ if (learned)
1174
+ teamNotes.push(learned, "");
1175
+ if (r.notesHint)
1176
+ teamNotes.push(r.notesHint, "");
1177
+ if (r.hits.length === 0) {
1178
+ if (r.notes?.length)
1179
+ return `${head}\n\n${teamNotes.join("\n").trimEnd()}\n\n${noteBlock || "no code matches."}${escalationNudge(r)}\n`;
1180
+ return `${head}\n\n${noteBlock || "no matches."}${escalationNudge(r)}\n`;
1181
+ }
1182
+ const lines = noteBlock ? [head, "", noteBlock, "", ...teamNotes] : [head, "", ...teamNotes];
1183
+ if (r.mode === "structural") {
1184
+ for (const h of r.hits) {
1185
+ const tail = h.snippet ? ` — ${h.snippet}` : "";
1186
+ lines.push(`- ${h.title} ${h.pointer} (${h.relation})${tail}`);
1187
+ if (h.code)
1188
+ lines.push("", "```", h.code, "```", "");
1189
+ }
1190
+ }
1191
+ else {
1192
+ r.hits.forEach((h, i) => {
1193
+ // Multi-scope results label each hit with its sub-project (root scope
1194
+ // "" stays unlabeled) so a reviewer can tell WHICH codebase answered.
1195
+ const label = r.scopes && h.scope ? `[${h.scope}/] ` : "";
1196
+ lines.push(`${i + 1}. ${label}${h.title} [${h.kind}]`);
1197
+ lines.push(` ${h.pointer}`);
1198
+ if (h.snippet)
1199
+ lines.push(` ${h.snippet}`);
1200
+ if (h.related?.length)
1201
+ lines.push(` related: ${h.related.join(", ")}`);
1202
+ if (h.code)
1203
+ lines.push("", "```", h.code, "```");
1204
+ lines.push("");
1205
+ });
1206
+ lines.push(...scopeFooterLines(r));
1207
+ }
1208
+ const body = lines.join("\n").trimEnd();
1209
+ const savings = askSavingsLine(r, body);
1210
+ return (savings ? `${savings}\n\n${body}` : body) + escalationNudge(r) + "\n";
1211
+ }
1212
+ /** When a lexical `ask` returns thin/no results, the productive next move is a
1213
+ * different TOOL, not a re-phrased ask — re-asking is the "over-ask" trap that
1214
+ * inflates cost. Surface the escalation in the output so the agent switches to
1215
+ * grep/skeleton/callers instead. Silent when the result is already rich (>3
1216
+ * hits) or in structural mode (a resolved who-calls IS the answer). */
1217
+ function escalationNudge(r) {
1218
+ if ((r.mode !== "lexical" && r.mode !== "empty") || r.hits.length > 3)
1219
+ return "";
1220
+ const n = r.hits.length;
1221
+ return (`\n\n${tag()} ${n === 0 ? "no hits" : `only ${n} hit${n === 1 ? "" : "s"}`} — don't re-ask with new wording; switch tool: ` +
1222
+ `\`${cmd("julius grep")} "<literal>"\` for every occurrence · \`${cmd("julius skeleton")} <file>\` for a file's full API · \`${cmd("julius callers")} <symbol>\` for who-uses.`);
1223
+ }
1224
+ /** The one-line token-saving estimate `ask` prepends in retriever mode, so the
1225
+ * agent gets the number for free in the tool output — no extra work on its end.
1226
+ * `packChars` is measured from the rendered body: exactly what the agent reads.
1227
+ * Header, not footer, for the reason documented on `withSavings`: a trailing
1228
+ * line dies to `head -N` and to host output truncation. */
1229
+ function askSavingsLine(r, body) {
1230
+ return savingsLine(body, r.saved);
1231
+ }
1232
+ /** Multi-scope footer: answers a reviewer's two questions — "which
1233
+ * sub-projects did this pack come from?" (`matched in:`, displayed-hit counts,
1234
+ * biggest first) and "did anything else match that I should know about?"
1235
+ * (`also matched:` for scopes gated out of fusion, with the flag to narrow).
1236
+ * Empty (zero output) whenever the result isn't a federated multi-scope one. */
1237
+ function scopeFooterLines(r) {
1238
+ if (!r.scopes)
1239
+ return [];
1240
+ const perScope = new Map();
1241
+ for (const h of r.hits)
1242
+ if (h.scope !== undefined)
1243
+ perScope.set(h.scope, (perScope.get(h.scope) ?? 0) + 1);
1244
+ const parts = [...perScope]
1245
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
1246
+ .map(([s, c]) => `${scopeLabel(s)} (${c})`);
1247
+ const out = parts.length ? [`matched in: ${parts.join(" · ")}`] : [];
1248
+ for (const m of r.scopes.alsoMatched)
1249
+ out.push(`also matched: ${scopeLabel(m.scope)} — narrow with --in ${scopeLabel(m.scope)}`);
1250
+ return out;
1251
+ }
1252
+ //# sourceMappingURL=ask.js.map